mirror of
https://github.com/SigNoz/signoz.git
synced 2026-11-25 17:50:55 +00:00
Compare commits
5 Commits
keystone-p
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6921b40467 | ||
|
|
d655a8998b | ||
|
|
70ab9c2321 | ||
|
|
e085decc05 | ||
|
|
415a74938b |
@@ -296,6 +296,8 @@
|
||||
// Bans msw imports in *.stories.tsx; handlers/mock data belong in the sibling .stories.mocks.tsx
|
||||
"signoz/no-direct-react-router-import": "error",
|
||||
// Steers call sites to the src/lib/router facade (allowlisted in overrides below)
|
||||
"signoz/no-builder-ai-query-access": "error",
|
||||
// Steers AI slot access to lib/query/builderSlot (allowlisted in overrides below)
|
||||
"no-restricted-globals": [
|
||||
"error",
|
||||
{
|
||||
@@ -560,6 +562,8 @@
|
||||
"no-restricted-globals": "off",
|
||||
// Tests need raw localStorage/sessionStorage to seed DOM state for isolation
|
||||
"signoz/no-zustand-getstate-in-hooks": "off",
|
||||
"signoz/no-builder-ai-query-access": "off",
|
||||
// Fixtures build and assert on the raw AI slot
|
||||
"@typescript-eslint/no-explicit-any": "off", // Tests often need any for mocks/stubs
|
||||
"@typescript-eslint/explicit-module-boundary-types": "off", // Return types not required in tests
|
||||
"@typescript-eslint/explicit-function-return-type": "off" // Same as above rule, don't need to care about return type
|
||||
@@ -616,6 +620,20 @@
|
||||
"rules": {
|
||||
"signoz/no-direct-react-router-import": "off"
|
||||
}
|
||||
},
|
||||
{
|
||||
// builderSlot owns the AI slot; the rest normalise its wire shape or test whether it exists, which the helpers hide
|
||||
"files": [
|
||||
"src/lib/query/builderSlot.ts",
|
||||
"src/hooks/queryBuilder/normalizeCompositeQuery.ts",
|
||||
"src/hooks/queryBuilder/useGetCompositeQueryParam.ts",
|
||||
"src/providers/QueryBuilder.tsx",
|
||||
"src/pages/DashboardPage/DashboardContainer/PanelEditor/hooks/usePanelKindChange.ts",
|
||||
"src/pages/DashboardPage/DashboardContainer/Panels/utils/seedBuilderForMode.ts"
|
||||
],
|
||||
"rules": {
|
||||
"signoz/no-builder-ai-query-access": "off"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ import i18n from '../src/ReactI18';
|
||||
// `src/index.tsx` does this at boot: without it `@monaco-editor/react` falls back
|
||||
// to its loader default and pulls Monaco from cdn.jsdelivr.net, which msw does
|
||||
// not report because the requests look like static assets.
|
||||
import '../src/lib/monaco/setup';
|
||||
import '../src/lib/monaco/loader';
|
||||
|
||||
import '../src/styles.scss';
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ const config: Config.InitialOptions = {
|
||||
coverageReporters: ['text', 'cobertura', 'html', 'json-summary'],
|
||||
collectCoverageFrom: ['src/**/*.{ts,tsx}'],
|
||||
moduleFileExtensions: ['ts', 'tsx', 'js', 'json'],
|
||||
modulePathIgnorePatterns: ['dist'],
|
||||
modulePathIgnorePatterns: ['<rootDir>/dist/'],
|
||||
moduleNameMapper: {
|
||||
'\\.(png|jpg|jpeg|gif|svg|webp|avif|ico|bmp|tiff)$':
|
||||
'<rootDir>/__mocks__/fileMock.ts',
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import { ruleTester } from './rule-tester.mjs';
|
||||
|
||||
const message =
|
||||
'from lib/query/builderSlot instead of accessing builder_ai_query';
|
||||
|
||||
await ruleTester({
|
||||
rule: 'no-builder-ai-query-access',
|
||||
valid: [
|
||||
{
|
||||
name: 'reading through the slot helper',
|
||||
code: 'export const data = getActiveBuilder(query).queryData;',
|
||||
},
|
||||
{
|
||||
name: 'reading the builder slot',
|
||||
code: 'export const data = query.builder.queryData;',
|
||||
},
|
||||
{
|
||||
name: 'building a query with the AI slot',
|
||||
code: 'export const next = { ...query, builder_ai_query: builder };',
|
||||
},
|
||||
{
|
||||
name: 'generated enum member',
|
||||
code:
|
||||
'export const type = Querybuildertypesv5QueryTypeDTO.builder_ai_query;',
|
||||
},
|
||||
{
|
||||
name: 'type position',
|
||||
code: "export type Slot = Query['builder_ai_query'];",
|
||||
},
|
||||
],
|
||||
invalid: [
|
||||
{
|
||||
name: 'picking the slot by query type',
|
||||
code:
|
||||
'export const data =\n\tquery.queryType === EQueryType.AI_QUERY_BUILDER\n\t\t? query.builder_ai_query?.queryData\n\t\t: query.builder.queryData;',
|
||||
errors: [{ message, line: 3 }],
|
||||
},
|
||||
{
|
||||
name: 'optional chaining',
|
||||
code: 'export const slot = query?.builder_ai_query;',
|
||||
errors: [{ message, line: 1 }],
|
||||
},
|
||||
{
|
||||
name: 'writing the slot',
|
||||
code: 'query.builder_ai_query = builder;',
|
||||
errors: [{ message, line: 1 }],
|
||||
},
|
||||
{
|
||||
name: 'bracket access',
|
||||
code: "export const slot = query['builder_ai_query'];",
|
||||
errors: [{ message, line: 1 }],
|
||||
},
|
||||
{
|
||||
name: 'destructuring',
|
||||
code: 'export const { builder_ai_query: slot } = query;',
|
||||
errors: [{ message, line: 1 }],
|
||||
},
|
||||
],
|
||||
});
|
||||
51
frontend/plugins/rules/no-builder-ai-query-access.mjs
Normal file
51
frontend/plugins/rules/no-builder-ai-query-access.mjs
Normal file
@@ -0,0 +1,51 @@
|
||||
const SLOT = 'builder_ai_query';
|
||||
|
||||
function isSlotKey(key, computed) {
|
||||
if (key.type === 'Literal') {
|
||||
return key.value === SLOT;
|
||||
}
|
||||
return !computed && key.type === 'Identifier' && key.name === SLOT;
|
||||
}
|
||||
|
||||
// Generated enums like Querybuildertypesv5QueryTypeDTO.builder_ai_query are not queries
|
||||
function isGeneratedEnum(object) {
|
||||
return object.type === 'Identifier' && /^[A-Z]/.test(object.name);
|
||||
}
|
||||
|
||||
export default {
|
||||
meta: {
|
||||
type: 'suggestion',
|
||||
docs: {
|
||||
description:
|
||||
'Disallow direct builder_ai_query access; use the lib/query/builderSlot helpers',
|
||||
category: 'Query Builder',
|
||||
},
|
||||
schema: [],
|
||||
messages: {
|
||||
useSlotHelper:
|
||||
'Use getActiveBuilder, getBuilderBySlotKey or replaceBuilderBySlotKey from lib/query/builderSlot instead of accessing builder_ai_query directly.',
|
||||
},
|
||||
},
|
||||
create(context) {
|
||||
return {
|
||||
MemberExpression(node) {
|
||||
if (
|
||||
isSlotKey(node.property, node.computed) &&
|
||||
!isGeneratedEnum(node.object)
|
||||
) {
|
||||
context.report({ node, messageId: 'useSlotHelper' });
|
||||
}
|
||||
},
|
||||
ObjectPattern(node) {
|
||||
node.properties.forEach((property) => {
|
||||
if (
|
||||
property.type === 'Property' &&
|
||||
isSlotKey(property.key, property.computed)
|
||||
) {
|
||||
context.report({ node: property, messageId: 'useSlotHelper' });
|
||||
}
|
||||
});
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -20,6 +20,7 @@ import noDirectReactRouterImport from './rules/no-direct-react-router-import.mjs
|
||||
import noTextCss from './rules/no-text-css.mjs';
|
||||
import requireDisableReason from './rules/require-disable-reason.mjs';
|
||||
import noDomNodeAccess from './rules/no-dom-node-access.mjs';
|
||||
import noBuilderAiQueryAccess from './rules/no-builder-ai-query-access.mjs';
|
||||
|
||||
export default {
|
||||
meta: {
|
||||
@@ -41,5 +42,6 @@ export default {
|
||||
'no-text-css': noTextCss,
|
||||
'require-disable-reason': requireDisableReason,
|
||||
'no-dom-node-access': noDomNodeAccess,
|
||||
'no-builder-ai-query-access': noBuilderAiQueryAccess,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -117,6 +117,8 @@
|
||||
"log_based_alert_desc": "Send a notification when a condition occurs in the logs data.",
|
||||
"traces_based_alert": "Trace-based Alert",
|
||||
"traces_based_alert_desc": "Send a notification when a condition occurs in the traces data.",
|
||||
"ai_traces_based_alert": "AI Trace-based Alert",
|
||||
"ai_traces_based_alert_desc": "Send a notification when a condition occurs in AI and LLM traces.",
|
||||
"exceptions_based_alert": "Exceptions-based Alert",
|
||||
"exceptions_based_alert_desc": "Send a notification when a condition occurs in the exceptions data.",
|
||||
"field_unit": "Threshold unit",
|
||||
|
||||
@@ -121,6 +121,8 @@
|
||||
"log_based_alert_desc": "Send a notification when a condition occurs in the logs data.",
|
||||
"traces_based_alert": "Trace-based Alert",
|
||||
"traces_based_alert_desc": "Send a notification when a condition occurs in the traces data.",
|
||||
"ai_traces_based_alert": "AI Trace-based Alert",
|
||||
"ai_traces_based_alert_desc": "Send a notification when a condition occurs in AI and LLM traces.",
|
||||
"exceptions_based_alert": "Exceptions-based Alert",
|
||||
"exceptions_based_alert_desc": "Send a notification when a condition occurs in the exceptions data.",
|
||||
"field_unit": "Threshold unit",
|
||||
|
||||
17
frontend/src/constants/__tests__/alerts.test.ts
Normal file
17
frontend/src/constants/__tests__/alerts.test.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
import { RuletypesAlertTypeDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import { dataSourceForAlertType } from '../alerts';
|
||||
|
||||
describe('dataSourceForAlertType', () => {
|
||||
it.each([
|
||||
[RuletypesAlertTypeDTO.METRIC_BASED_ALERT, DataSource.METRICS],
|
||||
[RuletypesAlertTypeDTO.LOGS_BASED_ALERT, DataSource.LOGS],
|
||||
[RuletypesAlertTypeDTO.TRACES_BASED_ALERT, DataSource.TRACES],
|
||||
[RuletypesAlertTypeDTO.EXCEPTIONS_BASED_ALERT, DataSource.TRACES],
|
||||
[RuletypesAlertTypeDTO.AI_TRACES_BASED_ALERT, DataSource.TRACES],
|
||||
[undefined, DataSource.METRICS],
|
||||
])('maps %s to %s', (alertType, dataSource) => {
|
||||
expect(dataSourceForAlertType(alertType)).toBe(dataSource);
|
||||
});
|
||||
});
|
||||
@@ -8,6 +8,7 @@ export const ALERTS_DATA_SOURCE_MAP: Record<AlertTypes, DataSource> = {
|
||||
[AlertTypes.LOGS_BASED_ALERT]: DataSource.LOGS,
|
||||
[AlertTypes.TRACES_BASED_ALERT]: DataSource.TRACES,
|
||||
[AlertTypes.EXCEPTIONS_BASED_ALERT]: DataSource.TRACES,
|
||||
[AlertTypes.AI_TRACES_BASED_ALERT]: DataSource.TRACES,
|
||||
};
|
||||
|
||||
export function dataSourceForAlertType(
|
||||
@@ -18,6 +19,7 @@ export function dataSourceForAlertType(
|
||||
return DataSource.LOGS;
|
||||
case RuletypesAlertTypeDTO.TRACES_BASED_ALERT:
|
||||
case RuletypesAlertTypeDTO.EXCEPTIONS_BASED_ALERT:
|
||||
case RuletypesAlertTypeDTO.AI_TRACES_BASED_ALERT:
|
||||
return DataSource.TRACES;
|
||||
default:
|
||||
return DataSource.METRICS;
|
||||
|
||||
@@ -5,7 +5,7 @@ import { Popover } from 'antd';
|
||||
import LogsIcon from 'assets/AlertHistory/LogsIcon';
|
||||
import ROUTES from 'constants/routes';
|
||||
import { useIsDarkMode } from 'hooks/useDarkMode';
|
||||
import { DraftingCompass } from '@signozhq/icons';
|
||||
import { Brain, DraftingCompass } from '@signozhq/icons';
|
||||
|
||||
import './AlertPopover.styles.scss';
|
||||
|
||||
@@ -13,14 +13,17 @@ type Props = {
|
||||
children: React.ReactNode;
|
||||
relatedTracesLink?: string;
|
||||
relatedLogsLink?: string;
|
||||
relatedAITracesLink?: string;
|
||||
};
|
||||
|
||||
function PopoverContent({
|
||||
relatedTracesLink,
|
||||
relatedLogsLink,
|
||||
relatedAITracesLink,
|
||||
}: {
|
||||
relatedTracesLink?: Props['relatedTracesLink'];
|
||||
relatedLogsLink?: Props['relatedLogsLink'];
|
||||
relatedAITracesLink?: Props['relatedAITracesLink'];
|
||||
}): JSX.Element {
|
||||
const isDarkMode = useIsDarkMode();
|
||||
return (
|
||||
@@ -52,18 +55,35 @@ function PopoverContent({
|
||||
<div className="text">View Traces</div>
|
||||
</AppLink>
|
||||
)}
|
||||
{!!relatedAITracesLink && (
|
||||
<AppLink
|
||||
to={`${ROUTES.AI_OBSERVABILITY_EXPLORER}?${relatedAITracesLink}`}
|
||||
className="contributor-row-popover-buttons__button"
|
||||
data-testid="alert-popover-view-ai-traces"
|
||||
>
|
||||
<div className="icon">
|
||||
<Brain
|
||||
size={14}
|
||||
color={isDarkMode ? Color.BG_VANILLA_400 : Color.TEXT_INK_400}
|
||||
/>
|
||||
</div>
|
||||
<div className="text">View AI Traces</div>
|
||||
</AppLink>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
PopoverContent.defaultProps = {
|
||||
relatedTracesLink: '',
|
||||
relatedLogsLink: '',
|
||||
relatedAITracesLink: '',
|
||||
};
|
||||
|
||||
function AlertPopover({
|
||||
children,
|
||||
relatedTracesLink,
|
||||
relatedLogsLink,
|
||||
relatedAITracesLink,
|
||||
}: Props): JSX.Element {
|
||||
return (
|
||||
<div className="alert-popover-trigger-action">
|
||||
@@ -77,6 +97,7 @@ function AlertPopover({
|
||||
<PopoverContent
|
||||
relatedTracesLink={relatedTracesLink}
|
||||
relatedLogsLink={relatedLogsLink}
|
||||
relatedAITracesLink={relatedAITracesLink}
|
||||
/>
|
||||
}
|
||||
trigger="click"
|
||||
@@ -90,23 +111,27 @@ function AlertPopover({
|
||||
AlertPopover.defaultProps = {
|
||||
relatedTracesLink: '',
|
||||
relatedLogsLink: '',
|
||||
relatedAITracesLink: '',
|
||||
};
|
||||
|
||||
type ConditionalAlertPopoverProps = {
|
||||
relatedTracesLink: string;
|
||||
relatedLogsLink: string;
|
||||
relatedAITracesLink: string;
|
||||
children: React.ReactNode;
|
||||
};
|
||||
export function ConditionalAlertPopover({
|
||||
children,
|
||||
relatedTracesLink,
|
||||
relatedLogsLink,
|
||||
relatedAITracesLink,
|
||||
}: ConditionalAlertPopoverProps): JSX.Element {
|
||||
if (relatedTracesLink || relatedLogsLink) {
|
||||
if (relatedTracesLink || relatedLogsLink || relatedAITracesLink) {
|
||||
return (
|
||||
<AlertPopover
|
||||
relatedTracesLink={relatedTracesLink}
|
||||
relatedLogsLink={relatedLogsLink}
|
||||
relatedAITracesLink={relatedAITracesLink}
|
||||
>
|
||||
{children}
|
||||
</AlertPopover>
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
import ROUTES from 'constants/routes';
|
||||
import { render, screen, userEvent } from 'tests/test-utils';
|
||||
|
||||
import { ConditionalAlertPopover } from '../AlertPopover';
|
||||
|
||||
const AI_TRACES_LINK = 'compositeQuery=ai&startTime=1&endTime=2';
|
||||
const TRACES_LINK = 'compositeQuery=traces&startTime=1&endTime=2';
|
||||
const TRIGGER_TEST_ID = 'popover-trigger';
|
||||
|
||||
const renderPopover = (links: {
|
||||
relatedTracesLink?: string;
|
||||
relatedLogsLink?: string;
|
||||
relatedAITracesLink?: string;
|
||||
}): void => {
|
||||
render(
|
||||
<ConditionalAlertPopover
|
||||
relatedTracesLink={links.relatedTracesLink ?? ''}
|
||||
relatedLogsLink={links.relatedLogsLink ?? ''}
|
||||
relatedAITracesLink={links.relatedAITracesLink ?? ''}
|
||||
>
|
||||
<button type="button" data-testid={TRIGGER_TEST_ID}>
|
||||
open
|
||||
</button>
|
||||
</ConditionalAlertPopover>,
|
||||
);
|
||||
};
|
||||
|
||||
describe('ConditionalAlertPopover', () => {
|
||||
it('links an AI traces alert to the AI observability explorer', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderPopover({ relatedAITracesLink: AI_TRACES_LINK });
|
||||
|
||||
await user.click(screen.getByTestId(TRIGGER_TEST_ID));
|
||||
|
||||
const link = await screen.findByTestId('alert-popover-view-ai-traces');
|
||||
expect(link).toHaveTextContent('View AI Traces');
|
||||
expect(link).toHaveAttribute(
|
||||
'href',
|
||||
`${ROUTES.AI_OBSERVABILITY_EXPLORER}?${AI_TRACES_LINK}`,
|
||||
);
|
||||
expect(
|
||||
screen.queryByTestId('alert-popover-view-traces'),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('keeps traces alerts on the traces explorer', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderPopover({ relatedTracesLink: TRACES_LINK });
|
||||
|
||||
await user.click(screen.getByTestId(TRIGGER_TEST_ID));
|
||||
|
||||
await expect(
|
||||
screen.findByTestId('alert-popover-view-traces'),
|
||||
).resolves.toHaveAttribute(
|
||||
'href',
|
||||
`${ROUTES.TRACES_EXPLORER}?${TRACES_LINK}`,
|
||||
);
|
||||
expect(
|
||||
screen.queryByTestId('alert-popover-view-ai-traces'),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders no popover without any link', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderPopover({});
|
||||
|
||||
await user.click(screen.getByTestId(TRIGGER_TEST_ID));
|
||||
|
||||
expect(
|
||||
screen.queryByTestId('alert-popover-view-ai-traces'),
|
||||
).not.toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByTestId('alert-popover-view-traces'),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -31,6 +31,7 @@ function TopContributorsRows({
|
||||
<ConditionalAlertPopover
|
||||
relatedTracesLink={record.relatedTracesLink}
|
||||
relatedLogsLink={record.relatedLogsLink}
|
||||
relatedAITracesLink={record.relatedAITracesLink}
|
||||
>
|
||||
<div>
|
||||
<AlertLabels labels={labels} />
|
||||
@@ -47,6 +48,7 @@ function TopContributorsRows({
|
||||
<ConditionalAlertPopover
|
||||
relatedTracesLink={record.relatedTracesLink}
|
||||
relatedLogsLink={record.relatedLogsLink}
|
||||
relatedAITracesLink={record.relatedAITracesLink}
|
||||
>
|
||||
<div className="top-contributors-progress">
|
||||
<Progress
|
||||
@@ -67,6 +69,7 @@ function TopContributorsRows({
|
||||
<ConditionalAlertPopover
|
||||
relatedTracesLink={record.relatedTracesLink}
|
||||
relatedLogsLink={record.relatedLogsLink}
|
||||
relatedAITracesLink={record.relatedAITracesLink}
|
||||
>
|
||||
<div
|
||||
className="total-contribution"
|
||||
|
||||
@@ -27,6 +27,7 @@ function TopContributorsRenderer({
|
||||
labels: labelsArrayToObject(contributor.labels),
|
||||
relatedLogsLink: contributor.relatedLogsLink ?? '',
|
||||
relatedTracesLink: contributor.relatedTracesLink ?? '',
|
||||
relatedAITracesLink: contributor.relatedAITracesLink ?? '',
|
||||
}));
|
||||
}, [data?.data]);
|
||||
|
||||
|
||||
@@ -69,6 +69,7 @@ function TimelineTableContent(): JSX.Element {
|
||||
labels: labelsArrayToObject(item.labels),
|
||||
relatedLogsLink: item.relatedLogsLink,
|
||||
relatedTracesLink: item.relatedTracesLink,
|
||||
relatedAITracesLink: item.relatedAITracesLink,
|
||||
};
|
||||
});
|
||||
|
||||
|
||||
@@ -49,7 +49,11 @@ export const timelineTableColumns = ({
|
||||
width: 140,
|
||||
align: 'right',
|
||||
render: (_, record): JSX.Element => {
|
||||
if (!record.relatedTracesLink && !record.relatedLogsLink) {
|
||||
if (
|
||||
!record.relatedTracesLink &&
|
||||
!record.relatedLogsLink &&
|
||||
!record.relatedAITracesLink
|
||||
) {
|
||||
return (
|
||||
<Tooltip title="No links available for this item">
|
||||
<Button type="text" ghost disabled data-testid="timeline-row-actions">
|
||||
@@ -63,6 +67,7 @@ export const timelineTableColumns = ({
|
||||
<ConditionalAlertPopover
|
||||
relatedTracesLink={record.relatedTracesLink ?? ''}
|
||||
relatedLogsLink={record.relatedLogsLink ?? ''}
|
||||
relatedAITracesLink={record.relatedAITracesLink ?? ''}
|
||||
>
|
||||
<Button type="text" ghost data-testid="timeline-row-actions">
|
||||
<Ellipsis className="dropdown-icon" size="md" />
|
||||
|
||||
@@ -93,6 +93,7 @@ describe('Alert history navigations keep the expression', () => {
|
||||
count: fingerprint,
|
||||
relatedLogsLink: '',
|
||||
relatedTracesLink: '',
|
||||
relatedAITracesLink: '',
|
||||
}));
|
||||
render(
|
||||
<>
|
||||
|
||||
@@ -1,9 +1,21 @@
|
||||
import {
|
||||
initialFormulaBuilderFormValues,
|
||||
initialQueriesMap,
|
||||
initialQueryAIWithType,
|
||||
} from 'constants/queryBuilder';
|
||||
import { getActiveBuilder } from 'lib/query/builderSlot';
|
||||
import { Query } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { QueryFunction } from 'types/api/v5/queryRange';
|
||||
import { EQueryType } from 'types/common/dashboard';
|
||||
|
||||
import { INITIAL_CRITICAL_THRESHOLD } from '../../context/constants';
|
||||
import { Threshold } from '../../context/types';
|
||||
|
||||
import { getSmallestDeviation, syncAnomalyFunction } from '../utils';
|
||||
import {
|
||||
getQueryNames,
|
||||
getSmallestDeviation,
|
||||
syncAnomalyFunction,
|
||||
} from '../utils';
|
||||
|
||||
const timeShift: QueryFunction = { name: 'timeShift', args: [{ value: 3600 }] };
|
||||
const anomaly = (
|
||||
@@ -56,3 +68,46 @@ describe('getSmallestDeviation', () => {
|
||||
expect(getSmallestDeviation(thresholds)).toBe(expected);
|
||||
});
|
||||
});
|
||||
|
||||
const tracesQuery = initialQueriesMap.traces;
|
||||
const formula = { ...initialFormulaBuilderFormValues, queryName: 'F1' };
|
||||
|
||||
describe('getQueryNames', () => {
|
||||
it('lists the Query Builder queries and formulas', () => {
|
||||
const query: Query = {
|
||||
...tracesQuery,
|
||||
builder: { ...tracesQuery.builder, queryFormulas: [formula] },
|
||||
};
|
||||
|
||||
expect(getQueryNames(query)).toStrictEqual([
|
||||
{ label: 'A', value: 'A' },
|
||||
{ label: 'F1', value: 'F1' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('lists the AI queries and formulas from the AI slot', () => {
|
||||
const query: Query = {
|
||||
...tracesQuery,
|
||||
queryType: EQueryType.AI_QUERY_BUILDER,
|
||||
builder: { ...tracesQuery.builder, queryData: [] },
|
||||
builder_ai_query: {
|
||||
...getActiveBuilder(initialQueryAIWithType),
|
||||
queryFormulas: [formula],
|
||||
},
|
||||
};
|
||||
|
||||
expect(getQueryNames(query)).toStrictEqual([
|
||||
{ label: 'A', value: 'A' },
|
||||
{ label: 'F1', value: 'F1' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('lists nothing for an AI query whose AI slot is missing', () => {
|
||||
const query: Query = {
|
||||
...tracesQuery,
|
||||
queryType: EQueryType.AI_QUERY_BUILDER,
|
||||
};
|
||||
|
||||
expect(getQueryNames(query)).toStrictEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
} from 'container/CreateAlert/context/types';
|
||||
import { getSelectedQueryOptions } from 'container/FormAlertRules/utils';
|
||||
import { useSafeNavigate } from 'hooks/useSafeNavigate';
|
||||
import { getActiveBuilder } from 'lib/query/builderSlot';
|
||||
import { ArrowRight } from '@signozhq/icons';
|
||||
import { IUser } from 'providers/App/types';
|
||||
import { Query } from 'types/api/queryBuilder/queryBuilderData';
|
||||
@@ -26,22 +27,23 @@ import { Threshold } from '../context/types';
|
||||
import { RoutingPolicyBannerProps } from './types';
|
||||
|
||||
export function getQueryNames(currentQuery: Query): BaseOptionType[] {
|
||||
const builder = getActiveBuilder(currentQuery);
|
||||
const involvedQueriesInTraceOperator = getInvolvedQueriesInTraceOperator(
|
||||
currentQuery.builder.queryTraceOperator,
|
||||
builder.queryTraceOperator,
|
||||
);
|
||||
const getBuilderQueryNames = (): SelectProps['options'] => [
|
||||
...(getSelectedQueryOptions(builder.queryData)?.filter(
|
||||
(option) => !involvedQueriesInTraceOperator.includes(option.value as string),
|
||||
) || []),
|
||||
...(getSelectedQueryOptions(builder.queryFormulas) || []),
|
||||
...(getSelectedQueryOptions(builder.queryTraceOperator) || []),
|
||||
];
|
||||
const queryConfig: Record<EQueryType, () => SelectProps['options']> = {
|
||||
[EQueryType.QUERY_BUILDER]: () => [
|
||||
...(getSelectedQueryOptions(currentQuery.builder.queryData)?.filter(
|
||||
(option) =>
|
||||
!involvedQueriesInTraceOperator.includes(option.value as string),
|
||||
) || []),
|
||||
...(getSelectedQueryOptions(currentQuery.builder.queryFormulas) || []),
|
||||
...(getSelectedQueryOptions(currentQuery.builder.queryTraceOperator) || []),
|
||||
],
|
||||
[EQueryType.QUERY_BUILDER]: getBuilderQueryNames,
|
||||
[EQueryType.PROM]: () => getSelectedQueryOptions(currentQuery.promql),
|
||||
[EQueryType.CLICKHOUSE]: () =>
|
||||
getSelectedQueryOptions(currentQuery.clickhouse_sql),
|
||||
[EQueryType.AI_QUERY_BUILDER]: () => [],
|
||||
[EQueryType.AI_QUERY_BUILDER]: getBuilderQueryNames,
|
||||
};
|
||||
|
||||
return queryConfig[currentQuery.queryType]?.() || [];
|
||||
|
||||
@@ -2,6 +2,7 @@ import { useCallback, useMemo } from 'react';
|
||||
import { Input } from '@signozhq/ui/input';
|
||||
import classNames from 'classnames';
|
||||
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import { getActiveBuilder } from 'lib/query/builderSlot';
|
||||
import { useAlertRuleOptional } from 'providers/Alert';
|
||||
import { Labels } from 'types/api/alerts/def';
|
||||
|
||||
@@ -18,7 +19,7 @@ function CreateAlertHeader(): JSX.Element {
|
||||
|
||||
const groupByLabels = useMemo(() => {
|
||||
const labels = new Array<string>();
|
||||
currentQuery.builder.queryData.forEach((query) => {
|
||||
getActiveBuilder(currentQuery).queryData.forEach((query) => {
|
||||
query.groupBy.forEach((groupBy) => {
|
||||
labels.push(groupBy.key);
|
||||
});
|
||||
|
||||
@@ -1,11 +1,17 @@
|
||||
import { fireEvent, render, screen } from '@testing-library/react';
|
||||
import { initialQueryAIWithType } from 'constants/queryBuilder';
|
||||
import { defaultPostableAlertRuleV2 } from 'container/CreateAlert/constants';
|
||||
import { getCreateAlertLocalStateFromAlertDef } from 'container/CreateAlert/utils';
|
||||
import { getActiveBuilder } from 'lib/query/builderSlot';
|
||||
import { mockAppLocation } from 'tests/router-mocks';
|
||||
import { fireEvent, render, screen, userEvent } from 'tests/test-utils';
|
||||
import { AlertTypes } from 'types/api/alerts/alertTypes';
|
||||
import type { Query } from 'types/api/queryBuilder/queryBuilderData';
|
||||
|
||||
import * as rulesHook from '../../../../api/generated/services/rules';
|
||||
import * as createAlertContext from '../../context';
|
||||
import { CreateAlertProvider } from '../../context';
|
||||
import type { ICreateAlertContextProps } from '../../context/types';
|
||||
import { createMockAlertContextState } from '../../EvaluationSettings/__tests__/testUtils';
|
||||
import CreateAlertHeader from '../CreateAlertHeader';
|
||||
|
||||
jest.spyOn(rulesHook, 'useCreateRule').mockReturnValue({
|
||||
@@ -93,4 +99,47 @@ describe('CreateAlertHeader', () => {
|
||||
screen.getByPlaceholderText(ENTER_ALERT_RULE_NAME_PLACEHOLDER),
|
||||
).toHaveValue('TEST_ALERT');
|
||||
});
|
||||
|
||||
it('should reject a label key used as a group by in an AI query', async () => {
|
||||
const user = userEvent.setup();
|
||||
const mockSetAlertState = jest.fn() as jest.MockedFunction<
|
||||
ICreateAlertContextProps['setAlertState']
|
||||
>;
|
||||
const alertStateSpy = jest
|
||||
.spyOn(createAlertContext, 'useCreateAlertState')
|
||||
.mockReturnValue(
|
||||
createMockAlertContextState({
|
||||
alertType: AlertTypes.AI_TRACES_BASED_ALERT,
|
||||
setAlertState: mockSetAlertState,
|
||||
}),
|
||||
);
|
||||
const aiBuilder = getActiveBuilder(initialQueryAIWithType);
|
||||
const aiQuery: Query = {
|
||||
...initialQueryAIWithType,
|
||||
builder_ai_query: {
|
||||
...aiBuilder,
|
||||
queryData: [
|
||||
{
|
||||
...aiBuilder.queryData[0],
|
||||
groupBy: [{ key: 'service.name', type: 'resource' }],
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
render(<CreateAlertHeader />, undefined, {
|
||||
queryBuilderOverrides: { currentQuery: aiQuery },
|
||||
});
|
||||
await user.click(screen.getByTestId('alert-add-label-button'));
|
||||
await user.type(
|
||||
screen.getByTestId('alert-add-label-input'),
|
||||
'service.name:foo{Enter}',
|
||||
);
|
||||
|
||||
expect(mockSetAlertState).not.toHaveBeenCalledWith(
|
||||
expect.objectContaining({ type: 'SET_ALERT_LABELS' }),
|
||||
);
|
||||
|
||||
alertStateSpy.mockRestore();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
import { UniversalYAxisUnit } from 'components/YAxisUnitSelector/types';
|
||||
import { initialQueriesMap } from 'constants/queryBuilder';
|
||||
import { RuletypesAlertTypeDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import {
|
||||
initialQueriesMap,
|
||||
initialQueryAIWithType,
|
||||
} from 'constants/queryBuilder';
|
||||
import {
|
||||
INITIAL_ADVANCED_OPTIONS_STATE,
|
||||
INITIAL_ALERT_STATE,
|
||||
@@ -16,6 +20,7 @@ import {
|
||||
} from 'container/CreateAlert/context/types';
|
||||
import { createMockAlertContextState } from 'container/CreateAlert/EvaluationSettings/__tests__/testUtils';
|
||||
import { AlertTypes } from 'types/api/alerts/alertTypes';
|
||||
import { toPostableRuleDTO } from 'types/api/alerts/convert';
|
||||
import { EQueryType } from 'types/common/dashboard';
|
||||
|
||||
import { BuildCreateAlertRulePayloadArgs } from '../types';
|
||||
@@ -573,6 +578,42 @@ describe('Footer utils', () => {
|
||||
expect(props.ruleType).toBe('promql_rule');
|
||||
});
|
||||
|
||||
describe('for an AI traces alert', () => {
|
||||
const aiArgs: BuildCreateAlertRulePayloadArgs = {
|
||||
...INITIAL_BUILD_CREATE_ALERT_RULE_PAYLOAD_ARGS,
|
||||
alertType: AlertTypes.AI_TRACES_BASED_ALERT,
|
||||
query: {
|
||||
...initialQueriesMap.traces,
|
||||
queryType: EQueryType.AI_QUERY_BUILDER,
|
||||
builder: { ...initialQueriesMap.traces.builder, queryData: [] },
|
||||
builder_ai_query: initialQueryAIWithType.builder_ai_query,
|
||||
},
|
||||
};
|
||||
|
||||
it('sends the AI slot as builder_ai_query envelopes under the builder query type', () => {
|
||||
const props = buildCreateThresholdAlertRulePayload(aiArgs);
|
||||
const { compositeQuery } = props.condition;
|
||||
|
||||
expect(compositeQuery.queryType).toBe(EQueryType.QUERY_BUILDER);
|
||||
expect(compositeQuery.queries).toHaveLength(1);
|
||||
expect(compositeQuery.queries?.[0]).toMatchObject({
|
||||
type: 'builder_ai_query',
|
||||
spec: { name: 'A', signal: 'traces' },
|
||||
});
|
||||
expect(props.alertType).toBe(AlertTypes.AI_TRACES_BASED_ALERT);
|
||||
expect(props.ruleType).toBe('threshold_rule');
|
||||
expect(props.condition.selectedQueryName).toBe(
|
||||
aiArgs.thresholdState.selectedQuery,
|
||||
);
|
||||
});
|
||||
|
||||
it('keeps the AI alert type in the posted rule', () => {
|
||||
const dto = toPostableRuleDTO(buildCreateThresholdAlertRulePayload(aiArgs));
|
||||
|
||||
expect(dto.alertType).toBe(RuletypesAlertTypeDTO.AI_TRACES_BASED_ALERT);
|
||||
});
|
||||
});
|
||||
|
||||
// Backward compatibility: a rule loaded with a legacy op/matchType
|
||||
// serialization ("1", ">", "eq", "above_or_equal", ...) must round-trip
|
||||
// back to the backend unchanged when the user hasn't touched those
|
||||
|
||||
@@ -2,6 +2,7 @@ import { RuletypesRuleTypeDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { UniversalYAxisUnit } from 'components/YAxisUnitSelector/types';
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import { mapQueryDataToApi } from 'lib/newQueryBuilder/queryBuilderMappers/mapQueryDataToApi';
|
||||
import { foldAISlot } from 'lib/query/builderSlot';
|
||||
import {
|
||||
AlertTypes,
|
||||
BasicThreshold,
|
||||
@@ -224,8 +225,9 @@ export function buildCreateThresholdAlertRulePayload(
|
||||
evaluationWindow,
|
||||
advancedOptions,
|
||||
notificationSettings,
|
||||
query,
|
||||
query: authoredQuery,
|
||||
} = args;
|
||||
const query = foldAISlot(authoredQuery);
|
||||
|
||||
const compositeQuery = compositeQueryToQueryEnvelope({
|
||||
builderQueries: {
|
||||
|
||||
@@ -3,6 +3,7 @@ import { Select, Tooltip } from 'antd';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import { Info } from '@signozhq/icons';
|
||||
import { getActiveBuilder } from 'lib/query/builderSlot';
|
||||
|
||||
import { ALL_SELECTED_VALUE } from '../constants';
|
||||
import { useCreateAlertState } from '../context';
|
||||
@@ -18,14 +19,13 @@ function MultipleNotifications(): JSX.Element {
|
||||
[notificationSettings.multipleNotifications],
|
||||
);
|
||||
|
||||
const { queryData } = getActiveBuilder(currentQuery);
|
||||
|
||||
const spaceAggregationOptions = useMemo(() => {
|
||||
const allGroupBys = currentQuery.builder.queryData?.reduce<string[]>(
|
||||
(acc, query) => {
|
||||
const groupByKeys = query.groupBy?.map((groupBy) => groupBy.key) || [];
|
||||
return [...acc, ...groupByKeys];
|
||||
},
|
||||
[],
|
||||
);
|
||||
const allGroupBys = queryData.reduce<string[]>((acc, query) => {
|
||||
const groupByKeys = query.groupBy?.map((groupBy) => groupBy.key) || [];
|
||||
return [...acc, ...groupByKeys];
|
||||
}, []);
|
||||
const uniqueGroupBys = [...new Set(allGroupBys)];
|
||||
const options = uniqueGroupBys.map((key) => ({
|
||||
label: key,
|
||||
@@ -44,7 +44,7 @@ function MultipleNotifications(): JSX.Element {
|
||||
];
|
||||
}
|
||||
return options;
|
||||
}, [currentQuery.builder.queryData, isAllOptionSelected]);
|
||||
}, [queryData, isAllOptionSelected]);
|
||||
|
||||
const isMultipleNotificationsEnabled = spaceAggregationOptions.length > 0;
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { render, screen, userEvent } from 'tests/test-utils';
|
||||
import { ALL_SELECTED_VALUE } from 'container/CreateAlert/constants';
|
||||
import * as createAlertContext from 'container/CreateAlert/context';
|
||||
import {
|
||||
@@ -7,6 +6,9 @@ import {
|
||||
INITIAL_NOTIFICATION_SETTINGS_STATE,
|
||||
} from 'container/CreateAlert/context/constants';
|
||||
import { createMockAlertContextState } from 'container/CreateAlert/EvaluationSettings/__tests__/testUtils';
|
||||
import { initialQueryAIWithType } from 'constants/queryBuilder';
|
||||
import { getActiveBuilder } from 'lib/query/builderSlot';
|
||||
import type { Query } from 'types/api/queryBuilder/queryBuilderData';
|
||||
|
||||
import MultipleNotifications from '../MultipleNotifications';
|
||||
|
||||
@@ -142,6 +144,36 @@ describe('MultipleNotifications', () => {
|
||||
expect(select).toHaveAttribute(ARIA_DISABLED_ATTR, FALSE);
|
||||
});
|
||||
|
||||
it('should list the group by fields of an AI query', async () => {
|
||||
const user = userEvent.setup();
|
||||
const aiBuilder = getActiveBuilder(initialQueryAIWithType);
|
||||
const aiQuery: Query = {
|
||||
...initialQueryAIWithType,
|
||||
builder_ai_query: {
|
||||
...aiBuilder,
|
||||
queryData: [
|
||||
{
|
||||
...aiBuilder.queryData[0],
|
||||
queryName: TEST_QUERY,
|
||||
groupBy: [{ key: 'gen_ai.request.model', type: 'tag' }],
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
useQueryBuilder.mockReturnValue({ currentQuery: aiQuery });
|
||||
|
||||
render(<MultipleNotifications />);
|
||||
|
||||
const select = screen.getByRole(COMBOBOX_ROLE);
|
||||
expect(select).toHaveAttribute(ARIA_DISABLED_ATTR, FALSE);
|
||||
await user.click(select);
|
||||
expect(
|
||||
screen
|
||||
.getAllByTestId('multiple-notifications-select-option')
|
||||
.map((option) => option.textContent),
|
||||
).toStrictEqual(['All', 'gen_ai.request.model']);
|
||||
});
|
||||
|
||||
it('should render unique group by options from all queries', async () => {
|
||||
useQueryBuilder.mockReturnValue({
|
||||
currentQuery: {
|
||||
|
||||
@@ -11,6 +11,7 @@ import ChartPreviewComponent from 'container/FormAlertRules/ChartPreview';
|
||||
import PlotTag from 'components/PlotTag/PlotTag';
|
||||
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import useGetYAxisUnit from 'hooks/useGetYAxisUnit';
|
||||
import { isBuilderQueryType } from 'lib/query/builderSlot';
|
||||
import { AppState } from 'store/reducers';
|
||||
import { AlertTypes } from 'types/api/alerts/alertTypes';
|
||||
import { AlertDef } from 'types/api/alerts/def';
|
||||
@@ -120,8 +121,7 @@ function ChartPreview({
|
||||
|
||||
return (
|
||||
<div className="chart-preview-container">
|
||||
{currentQuery.queryType === EQueryType.QUERY_BUILDER &&
|
||||
renderQBChartPreview()}
|
||||
{isBuilderQueryType(currentQuery.queryType) && renderQBChartPreview()}
|
||||
{currentQuery.queryType === EQueryType.PROM &&
|
||||
renderPromAndChQueryChartPreview()}
|
||||
{currentQuery.queryType === EQueryType.CLICKHOUSE &&
|
||||
|
||||
@@ -12,6 +12,7 @@ import { getMetricNameFromQueryData } from 'hooks/useGetYAxisUnit';
|
||||
import useUrlQuery from 'hooks/useUrlQuery';
|
||||
import {
|
||||
BarChart,
|
||||
Brain,
|
||||
DraftingCompass,
|
||||
FileText,
|
||||
ScrollText,
|
||||
@@ -125,6 +126,11 @@ function QuerySection(): JSX.Element {
|
||||
icon: <DraftingCompass size={14} data-testid="traces-view" />,
|
||||
value: AlertTypes.TRACES_BASED_ALERT,
|
||||
},
|
||||
{
|
||||
label: 'AI Traces',
|
||||
icon: <Brain size={14} data-testid="ai-traces-view" />,
|
||||
value: AlertTypes.AI_TRACES_BASED_ALERT,
|
||||
},
|
||||
{
|
||||
label: 'Exceptions',
|
||||
icon: <FileText size={14} data-testid="exceptions-view" />,
|
||||
|
||||
@@ -224,6 +224,29 @@ describe('ChartPreview', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('renders the chart preview when query type is AI_QUERY_BUILDER', () => {
|
||||
useQueryBuilder.mockReturnValue({
|
||||
...mockUseQueryBuilder,
|
||||
currentQuery: {
|
||||
...mockUseQueryBuilder.currentQuery,
|
||||
queryType: EQueryType.AI_QUERY_BUILDER,
|
||||
},
|
||||
stagedQuery: {
|
||||
queryType: EQueryType.AI_QUERY_BUILDER,
|
||||
unit: REQUESTS_PER_SEC,
|
||||
},
|
||||
});
|
||||
|
||||
renderChartPreview();
|
||||
|
||||
expect(
|
||||
screen.getByTestId(CHART_PREVIEW_COMPONENT_TEST_ID),
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByTestId(QUERY_TYPE_TEST_ID)).toHaveTextContent(
|
||||
EQueryType.AI_QUERY_BUILDER,
|
||||
);
|
||||
});
|
||||
|
||||
it('uses default panel type when panelType is not provided', () => {
|
||||
useQueryBuilder.mockReturnValue({
|
||||
...mockUseQueryBuilder,
|
||||
|
||||
@@ -146,9 +146,11 @@ const METRICS_TEXT = 'Metrics';
|
||||
const QUERY_BUILDER_TEXT = 'query_builder';
|
||||
const LOGS_TEXT = 'Logs';
|
||||
const TRACES_TEXT = 'Traces';
|
||||
const AI_TRACES_TEXT = 'AI Traces';
|
||||
const ACTIVE_TAB_CLASS = 'active-tab';
|
||||
const METRICS_TAB_TEST_ID = `query-section-tab-${AlertTypes.METRICS_BASED_ALERT}`;
|
||||
const LOGS_TAB_TEST_ID = `query-section-tab-${AlertTypes.LOGS_BASED_ALERT}`;
|
||||
const AI_TRACES_TAB_TEST_ID = `query-section-tab-${AlertTypes.AI_TRACES_BASED_ALERT}`;
|
||||
|
||||
describe('QuerySection', () => {
|
||||
const { useQueryBuilder } = jest.requireMock(
|
||||
@@ -359,6 +361,35 @@ describe('QuerySection', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('renders the AI traces alert type tab', () => {
|
||||
renderQuerySection();
|
||||
|
||||
expect(screen.getByTestId(AI_TRACES_TAB_TEST_ID)).toHaveTextContent(
|
||||
AI_TRACES_TEXT,
|
||||
);
|
||||
expect(screen.getByTestId('ai-traces-view')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('loads the AI default into the AI slot when the AI traces tab is clicked', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderQuerySection();
|
||||
|
||||
await user.click(screen.getByTestId(AI_TRACES_TAB_TEST_ID));
|
||||
|
||||
const [query, params] =
|
||||
mockUseQueryBuilder.redirectWithQueryBuilderData.mock.calls[0];
|
||||
|
||||
expect(params).toStrictEqual({
|
||||
[QueryParams.alertType]: AlertTypes.AI_TRACES_BASED_ALERT,
|
||||
[QueryParams.ruleType]: RuletypesRuleTypeDTO.threshold_rule,
|
||||
});
|
||||
expect(query.queryType).toBe(EQueryType.AI_QUERY_BUILDER);
|
||||
expect(query.builder.queryData).toHaveLength(0);
|
||||
expect(query.builder_ai_query.queryData[0].dataSource).toBe(
|
||||
DataSource.TRACES,
|
||||
);
|
||||
});
|
||||
|
||||
it('updates the query data when the query type changes from query_builder to promql', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderQuerySection();
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
import { UniversalYAxisUnit } from 'components/YAxisUnitSelector/types';
|
||||
import { initialQueriesMap } from 'constants/queryBuilder';
|
||||
import {
|
||||
initialQueriesMap,
|
||||
initialQueryAIWithType,
|
||||
} from 'constants/queryBuilder';
|
||||
import { ALERTS_DATA_SOURCE_MAP } from 'constants/alerts';
|
||||
import {
|
||||
aiTraceAlertDefaults,
|
||||
alertDefaults,
|
||||
anamolyAlertDefaults,
|
||||
exceptionAlertDefaults,
|
||||
@@ -9,6 +14,8 @@ import {
|
||||
} from 'container/CreateAlertRule/defaults';
|
||||
import dayjs from 'dayjs';
|
||||
import { AlertTypes } from 'types/api/alerts/alertTypes';
|
||||
import { EQueryType } from 'types/common/dashboard';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import {
|
||||
INITIAL_ADVANCED_OPTIONS_STATE,
|
||||
@@ -131,6 +138,16 @@ describe('CreateAlert Context Utils', () => {
|
||||
expect(result).toBe(AlertTypes.TRACES_BASED_ALERT);
|
||||
});
|
||||
|
||||
it('should return AI_TRACES_BASED_ALERT for an AI query', () => {
|
||||
const result = getInitialAlertType({
|
||||
...initialQueriesMap.traces,
|
||||
queryType: EQueryType.AI_QUERY_BUILDER,
|
||||
builder: { ...initialQueriesMap.traces.builder, queryData: [] },
|
||||
builder_ai_query: initialQueryAIWithType.builder_ai_query,
|
||||
});
|
||||
expect(result).toBe(AlertTypes.AI_TRACES_BASED_ALERT);
|
||||
});
|
||||
|
||||
it('should return METRICS_BASED_ALERT for unknown data source', () => {
|
||||
const queryWithUnknownDataSource = {
|
||||
...initialQueriesMap.metrics,
|
||||
@@ -170,12 +187,37 @@ describe('CreateAlert Context Utils', () => {
|
||||
expect(result).toBe(alertDefaults);
|
||||
});
|
||||
|
||||
it('should return aiTraceAlertDefaults for AI_TRACES_BASED_ALERT', () => {
|
||||
const result = buildInitialAlertDef(AlertTypes.AI_TRACES_BASED_ALERT);
|
||||
expect(result).toBe(aiTraceAlertDefaults);
|
||||
});
|
||||
|
||||
it('should return alertDefaults for unknown alert type', () => {
|
||||
const result = buildInitialAlertDef('UNKNOWN' as AlertTypes);
|
||||
expect(result).toBe(alertDefaults);
|
||||
});
|
||||
});
|
||||
|
||||
describe('aiTraceAlertDefaults', () => {
|
||||
const { compositeQuery } = aiTraceAlertDefaults.condition;
|
||||
|
||||
it('should be an AI traces alert', () => {
|
||||
expect(aiTraceAlertDefaults.alertType).toBe(
|
||||
AlertTypes.AI_TRACES_BASED_ALERT,
|
||||
);
|
||||
expect(ALERTS_DATA_SOURCE_MAP[AlertTypes.AI_TRACES_BASED_ALERT]).toBe(
|
||||
DataSource.TRACES,
|
||||
);
|
||||
});
|
||||
|
||||
it('should start on the AI query type with an AI traces query', () => {
|
||||
expect(compositeQuery.queryType).toBe(EQueryType.AI_QUERY_BUILDER);
|
||||
expect(compositeQuery.builderQueries?.A).toMatchObject({
|
||||
dataSource: DataSource.TRACES,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('getInitialAlertTypeFromURL', () => {
|
||||
it('should return ANOMALY_BASED_ALERT when ruleType is anomaly_rule', () => {
|
||||
const params = new URLSearchParams('?ruleType=anomaly_rule');
|
||||
|
||||
@@ -2,12 +2,14 @@ import { UTC_TIMEZONE } from 'components/CustomTimePicker/timezoneUtils';
|
||||
import { UniversalYAxisUnit } from 'components/YAxisUnitSelector/types';
|
||||
import { QueryParams } from 'constants/query';
|
||||
import {
|
||||
aiTraceAlertDefaults,
|
||||
alertDefaults,
|
||||
anamolyAlertDefaults,
|
||||
exceptionAlertDefaults,
|
||||
logAlertDefaults,
|
||||
traceAlertDefaults,
|
||||
} from 'container/CreateAlertRule/defaults';
|
||||
import { isAIQueryType } from 'lib/query/builderSlot';
|
||||
import { AlertTypes } from 'types/api/alerts/alertTypes';
|
||||
import { AlertDef } from 'types/api/alerts/def';
|
||||
import { Query } from 'types/api/queryBuilder/queryBuilderData';
|
||||
@@ -67,9 +69,12 @@ export const alertCreationReducer = (
|
||||
}
|
||||
};
|
||||
|
||||
export function getInitialAlertType(currentQuery: Query): AlertTypes {
|
||||
export function getInitialAlertType(currentQuery: Query | null): AlertTypes {
|
||||
if (currentQuery && isAIQueryType(currentQuery.queryType)) {
|
||||
return AlertTypes.AI_TRACES_BASED_ALERT;
|
||||
}
|
||||
const dataSource =
|
||||
currentQuery.builder.queryData?.[0]?.dataSource || DataSource.METRICS;
|
||||
currentQuery?.builder.queryData?.[0]?.dataSource || DataSource.METRICS;
|
||||
switch (dataSource) {
|
||||
case DataSource.METRICS:
|
||||
return AlertTypes.METRICS_BASED_ALERT;
|
||||
@@ -92,6 +97,8 @@ export function buildInitialAlertDef(alertType: AlertTypes): AlertDef {
|
||||
return exceptionAlertDefaults;
|
||||
case AlertTypes.ANOMALY_BASED_ALERT:
|
||||
return anamolyAlertDefaults;
|
||||
case AlertTypes.AI_TRACES_BASED_ALERT:
|
||||
return aiTraceAlertDefaults;
|
||||
case AlertTypes.METRICS_BASED_ALERT:
|
||||
return alertDefaults;
|
||||
default:
|
||||
@@ -101,7 +108,7 @@ export function buildInitialAlertDef(alertType: AlertTypes): AlertDef {
|
||||
|
||||
export function getInitialAlertTypeFromURL(
|
||||
urlSearchParams: URLSearchParams,
|
||||
currentQuery: Query,
|
||||
currentQuery: Query | null,
|
||||
): AlertTypes {
|
||||
const ruleType = urlSearchParams.get(QueryParams.ruleType);
|
||||
if (ruleType === 'anomaly_rule') {
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { fireEvent, render, screen } from '@testing-library/react';
|
||||
import {
|
||||
LicensePlatform,
|
||||
LicenseResModel,
|
||||
} from 'types/api/licensesV3/getActive';
|
||||
import { getAppContextMockState } from 'container/RoutingPolicies/__tests__/testUtils';
|
||||
import * as appHooks from 'providers/App/App';
|
||||
import { fireEvent, render, screen, userEvent } from 'tests/test-utils';
|
||||
import { AlertTypes } from 'types/api/alerts/alertTypes';
|
||||
|
||||
import SelectAlertType from '..';
|
||||
@@ -15,6 +15,8 @@ const CLOUD_LICENSE = {
|
||||
platform: LicensePlatform.CLOUD,
|
||||
} as LicenseResModel;
|
||||
|
||||
const AI_CARD_TEST_ID = `alert-type-card-${AlertTypes.AI_TRACES_BASED_ALERT}`;
|
||||
|
||||
describe('SelectAlertType', () => {
|
||||
const mockOnSelect = jest.fn();
|
||||
|
||||
@@ -35,6 +37,9 @@ describe('SelectAlertType', () => {
|
||||
expect(screen.getByText('log_based_alert')).toBeInTheDocument();
|
||||
expect(screen.getByText('traces_based_alert')).toBeInTheDocument();
|
||||
expect(screen.getByText('exceptions_based_alert')).toBeInTheDocument();
|
||||
expect(screen.getByTestId(AI_CARD_TEST_ID)).toHaveTextContent(
|
||||
'ai_traces_based_alert',
|
||||
);
|
||||
expect(screen.getByText('anomaly_based_alert')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
@@ -58,6 +63,9 @@ describe('SelectAlertType', () => {
|
||||
expect(screen.getByText('log_based_alert')).toBeInTheDocument();
|
||||
expect(screen.getByText('traces_based_alert')).toBeInTheDocument();
|
||||
expect(screen.getByText('exceptions_based_alert')).toBeInTheDocument();
|
||||
expect(screen.getByTestId(AI_CARD_TEST_ID)).toHaveTextContent(
|
||||
'ai_traces_based_alert',
|
||||
);
|
||||
expect(screen.queryByText('anomaly_based_alert')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
@@ -112,4 +120,61 @@ describe('SelectAlertType', () => {
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
it('should call onSelect with AI traces based alert type', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<SelectAlertType onSelect={mockOnSelect} />);
|
||||
await user.click(screen.getByTestId(AI_CARD_TEST_ID));
|
||||
|
||||
expect(mockOnSelect).toHaveBeenCalledWith(
|
||||
AlertTypes.AI_TRACES_BASED_ALERT,
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
it('should ask for a new tab when the AI traces card is modifier-clicked', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<SelectAlertType onSelect={mockOnSelect} />);
|
||||
await user.keyboard('{Meta>}');
|
||||
await user.click(screen.getByTestId(AI_CARD_TEST_ID));
|
||||
await user.keyboard('{/Meta}');
|
||||
|
||||
expect(mockOnSelect).toHaveBeenCalledWith(
|
||||
AlertTypes.AI_TRACES_BASED_ALERT,
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it('should mark the AI traces card as beta', () => {
|
||||
render(<SelectAlertType onSelect={mockOnSelect} />);
|
||||
|
||||
expect(
|
||||
screen.getByTestId(`alert-type-beta-${AlertTypes.AI_TRACES_BASED_ALERT}`),
|
||||
).toHaveTextContent('Beta');
|
||||
});
|
||||
|
||||
it('should not show the sample alert link on the AI traces card', () => {
|
||||
render(<SelectAlertType onSelect={mockOnSelect} />);
|
||||
|
||||
expect(
|
||||
screen.queryByTestId(
|
||||
`alert-type-sample-link-${AlertTypes.AI_TRACES_BASED_ALERT}`,
|
||||
),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should place the AI traces card after the traces card', () => {
|
||||
render(<SelectAlertType onSelect={mockOnSelect} />);
|
||||
const order = screen
|
||||
.getAllByTestId(/^alert-type-card-/)
|
||||
.map((card) => card.getAttribute('data-testid'));
|
||||
|
||||
expect(order).toStrictEqual([
|
||||
`alert-type-card-${AlertTypes.METRICS_BASED_ALERT}`,
|
||||
`alert-type-card-${AlertTypes.LOGS_BASED_ALERT}`,
|
||||
`alert-type-card-${AlertTypes.TRACES_BASED_ALERT}`,
|
||||
`alert-type-card-${AlertTypes.AI_TRACES_BASED_ALERT}`,
|
||||
`alert-type-card-${AlertTypes.EXCEPTIONS_BASED_ALERT}`,
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -23,6 +23,12 @@ export const getOptionList = (
|
||||
selection: AlertTypes.TRACES_BASED_ALERT,
|
||||
description: t('traces_based_alert_desc'),
|
||||
},
|
||||
{
|
||||
title: t('ai_traces_based_alert'),
|
||||
selection: AlertTypes.AI_TRACES_BASED_ALERT,
|
||||
description: t('ai_traces_based_alert_desc'),
|
||||
isBeta: true,
|
||||
},
|
||||
{
|
||||
title: t('exceptions_based_alert'),
|
||||
selection: AlertTypes.EXCEPTIONS_BASED_ALERT,
|
||||
|
||||
@@ -50,7 +50,7 @@ function SelectAlertType({ onSelect }: SelectAlertTypeProps): JSX.Element {
|
||||
}
|
||||
|
||||
function handleSampleAlertClick(option: AlertTypes): void {
|
||||
logEvent('Alert: Sample alert link clicked', {
|
||||
void logEvent('Alert: Sample alert link clicked', {
|
||||
dataSource: ALERTS_DATA_SOURCE_MAP[option],
|
||||
link: getSampleAlertUrl(option),
|
||||
page: 'New alert data source selection page',
|
||||
@@ -59,39 +59,49 @@ function SelectAlertType({ onSelect }: SelectAlertTypeProps): JSX.Element {
|
||||
const renderOptions = useMemo(
|
||||
() => (
|
||||
<>
|
||||
{optionList.map((option: OptionType) => (
|
||||
<AlertTypeCard
|
||||
key={option.selection}
|
||||
title={option.title}
|
||||
extra={
|
||||
option.isBeta ? (
|
||||
<Badge variant="solid" color="primary">
|
||||
Beta
|
||||
</Badge>
|
||||
) : undefined
|
||||
}
|
||||
onClick={(e): void => {
|
||||
onSelect(option.selection, isModifierKeyPressed(e));
|
||||
}}
|
||||
data-testid={`alert-type-card-${option.selection}`}
|
||||
>
|
||||
{option.description}{' '}
|
||||
<Typography.Link
|
||||
variant="paragraph"
|
||||
size="base"
|
||||
weight="regular"
|
||||
textOverflow="wrap"
|
||||
href={getSampleAlertUrl(option.selection)}
|
||||
target="_blank"
|
||||
{optionList.map((option: OptionType) => {
|
||||
const sampleAlertUrl = getSampleAlertUrl(option.selection);
|
||||
return (
|
||||
<AlertTypeCard
|
||||
key={option.selection}
|
||||
title={option.title}
|
||||
extra={
|
||||
option.isBeta ? (
|
||||
<Badge
|
||||
variant="solid"
|
||||
color="primary"
|
||||
testId={`alert-type-beta-${option.selection}`}
|
||||
>
|
||||
Beta
|
||||
</Badge>
|
||||
) : undefined
|
||||
}
|
||||
onClick={(e): void => {
|
||||
e.stopPropagation();
|
||||
handleSampleAlertClick(option.selection);
|
||||
onSelect(option.selection, isModifierKeyPressed(e));
|
||||
}}
|
||||
data-testid={`alert-type-card-${option.selection}`}
|
||||
>
|
||||
Click here to see how to create a sample alert.
|
||||
</Typography.Link>{' '}
|
||||
</AlertTypeCard>
|
||||
))}
|
||||
{option.description}{' '}
|
||||
{sampleAlertUrl ? (
|
||||
<Typography.Link
|
||||
variant="paragraph"
|
||||
size="base"
|
||||
weight="regular"
|
||||
textOverflow="wrap"
|
||||
href={sampleAlertUrl}
|
||||
target="_blank"
|
||||
onClick={(e): void => {
|
||||
e.stopPropagation();
|
||||
handleSampleAlertClick(option.selection);
|
||||
}}
|
||||
testId={`alert-type-sample-link-${option.selection}`}
|
||||
>
|
||||
Click here to see how to create a sample alert.
|
||||
</Typography.Link>
|
||||
) : null}{' '}
|
||||
</AlertTypeCard>
|
||||
);
|
||||
})}
|
||||
</>
|
||||
),
|
||||
[onSelect, optionList],
|
||||
|
||||
@@ -1,17 +1,21 @@
|
||||
import { fireEvent, screen } from '@testing-library/react';
|
||||
import {
|
||||
LicensePlatform,
|
||||
LicenseResModel,
|
||||
} from 'types/api/licensesV3/getActive';
|
||||
import { QueryParams } from 'constants/query';
|
||||
import { initialQueriesMap } from 'constants/queryBuilder';
|
||||
import ROUTES from 'constants/routes';
|
||||
import {
|
||||
initialQueriesMap,
|
||||
initialQueryAIWithType,
|
||||
} from 'constants/queryBuilder';
|
||||
import { getAppContextMockState } from 'container/RoutingPolicies/__tests__/testUtils';
|
||||
import * as useCompositeQueryParamHooks from 'hooks/queryBuilder/useGetCompositeQueryParam';
|
||||
import * as navigateHooks from 'hooks/useSafeNavigate';
|
||||
import * as useUrlQueryHooks from 'hooks/useUrlQuery';
|
||||
import * as appHooks from 'providers/App/App';
|
||||
import { render } from 'tests/test-utils';
|
||||
import { fireEvent, render, screen, userEvent } from 'tests/test-utils';
|
||||
import { AlertTypes } from 'types/api/alerts/alertTypes';
|
||||
import { EQueryType } from 'types/common/dashboard';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import CreateAlertRule from '../index';
|
||||
@@ -31,9 +35,9 @@ jest.mock('container/CreateAlert', () => ({
|
||||
alertType: AlertTypes;
|
||||
}): JSX.Element {
|
||||
return (
|
||||
<div>
|
||||
<div data-testid="create-alert-mock">
|
||||
<h1>Create Alert V2</h1>
|
||||
<p>{alertType}</p>
|
||||
<p data-testid="create-alert-mock-type">{alertType}</p>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
@@ -58,6 +62,7 @@ const mockSafeNavigate = jest.fn();
|
||||
const mockDeleteUrlQuery = jest.fn();
|
||||
|
||||
const CREATE_ALERT_V2_TEXT = 'Create Alert V2';
|
||||
const AI_TRACES_ALERT_PARAMS = `ruleType=threshold_rule&alertType=${AlertTypes.AI_TRACES_BASED_ALERT}`;
|
||||
|
||||
describe('CreateAlertRule', () => {
|
||||
beforeEach(() => {
|
||||
@@ -136,6 +141,20 @@ describe('CreateAlertRule', () => {
|
||||
expect(screen.getByText(AlertTypes.LOGS_BASED_ALERT)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should open an AI traces alert for an AI query when no alertType is in the URL', () => {
|
||||
mockGetUrlQuery.mockReturnValue(null);
|
||||
useCompositeQueryParamSpy.mockReturnValue({
|
||||
...initialQueriesMap.traces,
|
||||
queryType: EQueryType.AI_QUERY_BUILDER,
|
||||
builder: { ...initialQueriesMap.traces.builder, queryData: [] },
|
||||
builder_ai_query: initialQueryAIWithType.builder_ai_query,
|
||||
});
|
||||
render(<CreateAlertRule />);
|
||||
expect(screen.getByTestId('create-alert-mock-type')).toHaveTextContent(
|
||||
AlertTypes.AI_TRACES_BASED_ALERT,
|
||||
);
|
||||
});
|
||||
|
||||
it('should use alertType from URL over compositeQuery dataSource', () => {
|
||||
mockGetUrlQuery.mockImplementation((key: string) => {
|
||||
if (key === QueryParams.alertType) {
|
||||
@@ -211,6 +230,28 @@ describe('CreateAlertRule', () => {
|
||||
expect(mockSafeNavigate).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should navigate with threshold alert params for AI traces alert', async () => {
|
||||
const user = userEvent.setup();
|
||||
mockToString.mockReturnValue(AI_TRACES_ALERT_PARAMS);
|
||||
render(<CreateAlertRule />);
|
||||
await user.click(
|
||||
screen.getByTestId(`alert-type-card-${AlertTypes.AI_TRACES_BASED_ALERT}`),
|
||||
);
|
||||
|
||||
expect(mockSetUrlQuery).toHaveBeenCalledWith(
|
||||
QueryParams.ruleType,
|
||||
'threshold_rule',
|
||||
);
|
||||
expect(mockSetUrlQuery).toHaveBeenCalledWith(
|
||||
QueryParams.alertType,
|
||||
AlertTypes.AI_TRACES_BASED_ALERT,
|
||||
);
|
||||
expect(mockSafeNavigate).toHaveBeenCalledWith(
|
||||
`${ROUTES.ALERTS_NEW}?${AI_TRACES_ALERT_PARAMS}`,
|
||||
{ newTab: false },
|
||||
);
|
||||
});
|
||||
|
||||
it('should navigate with threshold alert params for exceptions alert', () => {
|
||||
render(<CreateAlertRule />);
|
||||
fireEvent.click(screen.getByText('exceptions_based_alert'));
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
import { AlertTypes } from 'types/api/alerts/alertTypes';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
export const ALERT_TYPE_VS_SOURCE_MAPPING = {
|
||||
[DataSource.LOGS]: AlertTypes.LOGS_BASED_ALERT,
|
||||
[DataSource.METRICS]: AlertTypes.METRICS_BASED_ALERT,
|
||||
[DataSource.TRACES]: AlertTypes.TRACES_BASED_ALERT,
|
||||
};
|
||||
@@ -1,46 +0,0 @@
|
||||
import { AlertTypes } from 'types/api/alerts/alertTypes';
|
||||
|
||||
// since we don't have a card in alert creation for anomaly based alert
|
||||
|
||||
export const ALERT_TYPE_URL_MAP: Record<
|
||||
AlertTypes,
|
||||
{ selection: string; creation: string }
|
||||
> = {
|
||||
[AlertTypes.METRICS_BASED_ALERT]: {
|
||||
selection:
|
||||
'https://signoz.io/docs/alerts-management/metrics-based-alerts/?utm_source=product&utm_medium=alert-source-selection-page#examples',
|
||||
creation:
|
||||
'https://signoz.io/docs/alerts-management/metrics-based-alerts/?utm_source=product&utm_medium=alert-creation-page',
|
||||
},
|
||||
[AlertTypes.LOGS_BASED_ALERT]: {
|
||||
selection:
|
||||
'https://signoz.io/docs/alerts-management/log-based-alerts/?utm_source=product&utm_medium=alert-source-selection-page#examples',
|
||||
creation:
|
||||
'https://signoz.io/docs/alerts-management/log-based-alerts/?utm_source=product&utm_medium=alert-creation-page',
|
||||
},
|
||||
[AlertTypes.TRACES_BASED_ALERT]: {
|
||||
selection:
|
||||
'https://signoz.io/docs/alerts-management/trace-based-alerts/?utm_source=product&utm_medium=alert-source-selection-page#examples',
|
||||
creation:
|
||||
'https://signoz.io/docs/alerts-management/trace-based-alerts/?utm_source=product&utm_medium=alert-creation-page',
|
||||
},
|
||||
[AlertTypes.EXCEPTIONS_BASED_ALERT]: {
|
||||
selection:
|
||||
'https://signoz.io/docs/alerts-management/exceptions-based-alerts/?utm_source=product&utm_medium=alert-source-selection-page#examples',
|
||||
creation:
|
||||
'https://signoz.io/docs/alerts-management/exceptions-based-alerts/?utm_source=product&utm_medium=alert-creation-page',
|
||||
},
|
||||
[AlertTypes.ANOMALY_BASED_ALERT]: {
|
||||
selection: 'https://signoz.io/docs/alerts-management/anomaly-based-alerts/',
|
||||
creation:
|
||||
'https://signoz.io/docs/alerts-management/anomaly-based-alerts/?utm_source=product&utm_medium=alert-creation-page',
|
||||
},
|
||||
};
|
||||
|
||||
export const ALERT_TYPE_TO_TITLE: Record<AlertTypes, string> = {
|
||||
[AlertTypes.METRICS_BASED_ALERT]: 'metric_based_alert',
|
||||
[AlertTypes.LOGS_BASED_ALERT]: 'log_based_alert',
|
||||
[AlertTypes.TRACES_BASED_ALERT]: 'traces_based_alert',
|
||||
[AlertTypes.EXCEPTIONS_BASED_ALERT]: 'exceptions_based_alert',
|
||||
[AlertTypes.ANOMALY_BASED_ALERT]: 'anomaly_based_alert',
|
||||
};
|
||||
@@ -1,9 +1,11 @@
|
||||
import { RuletypesRuleTypeDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import {
|
||||
initialQueryAIWithType,
|
||||
initialQueryBuilderFormValuesMap,
|
||||
initialQueryPromQLData,
|
||||
PANEL_TYPES,
|
||||
} from 'constants/queryBuilder';
|
||||
import { getActiveBuilder } from 'lib/query/builderSlot';
|
||||
import { AlertTypes } from 'types/api/alerts/alertTypes';
|
||||
import {
|
||||
AlertDef,
|
||||
@@ -195,10 +197,26 @@ export const exceptionAlertDefaults: AlertDef = {
|
||||
alert: '',
|
||||
};
|
||||
|
||||
export const aiTraceAlertDefaults: AlertDef = {
|
||||
...traceAlertDefaults,
|
||||
alertType: AlertTypes.AI_TRACES_BASED_ALERT,
|
||||
condition: {
|
||||
...traceAlertDefaults.condition,
|
||||
compositeQuery: {
|
||||
...traceAlertDefaults.condition.compositeQuery,
|
||||
builderQueries: {
|
||||
A: getActiveBuilder(initialQueryAIWithType).queryData[0],
|
||||
},
|
||||
queryType: EQueryType.AI_QUERY_BUILDER,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
export const ALERT_TYPE_BREADCRUMB_TITLE: Record<AlertTypes, string> = {
|
||||
[AlertTypes.ANOMALY_BASED_ALERT]: 'Anomaly-Based Alert',
|
||||
[AlertTypes.METRICS_BASED_ALERT]: 'Metric-Based Alert',
|
||||
[AlertTypes.LOGS_BASED_ALERT]: 'Log-Based Alert',
|
||||
[AlertTypes.TRACES_BASED_ALERT]: 'Traces-Based Alert',
|
||||
[AlertTypes.EXCEPTIONS_BASED_ALERT]: 'Exceptions-Based Alert',
|
||||
[AlertTypes.AI_TRACES_BASED_ALERT]: 'AI Traces-Based Alert',
|
||||
};
|
||||
|
||||
@@ -8,6 +8,7 @@ import HeaderRightSection from 'components/HeaderRightSection/HeaderRightSection
|
||||
import { QueryParams } from 'constants/query';
|
||||
import ROUTES from 'constants/routes';
|
||||
import CreateAlert from 'container/CreateAlert';
|
||||
import { getInitialAlertTypeFromURL } from 'container/CreateAlert/context/utils';
|
||||
import DateTimeSelector from 'container/TopNav/DateTimeSelectionV2';
|
||||
import { useGetCompositeQueryParam } from 'hooks/queryBuilder/useGetCompositeQueryParam';
|
||||
import { useSafeNavigate } from 'hooks/useSafeNavigate';
|
||||
@@ -16,7 +17,6 @@ import { AlertListTabs } from 'pages/AlertList/types';
|
||||
import { GalleryVerticalEnd, Pyramid } from '@signozhq/icons';
|
||||
import { AlertTypes } from 'types/api/alerts/alertTypes';
|
||||
|
||||
import { ALERT_TYPE_VS_SOURCE_MAPPING } from './config';
|
||||
import { ALERT_TYPE_BREADCRUMB_TITLE } from './defaults';
|
||||
import SelectAlertType from './SelectAlertType';
|
||||
|
||||
@@ -39,19 +39,10 @@ function CreateRules(): JSX.Element {
|
||||
}
|
||||
}, [isTypeSelectionMode]);
|
||||
|
||||
const alertType = useMemo(() => {
|
||||
if (ruleTypeFromURL === RuletypesRuleTypeDTO.anomaly_rule) {
|
||||
return AlertTypes.ANOMALY_BASED_ALERT;
|
||||
}
|
||||
if (!alertTypeFromURL) {
|
||||
const dataSource = compositeQuery?.builder.queryData?.[0]?.dataSource;
|
||||
if (dataSource) {
|
||||
return ALERT_TYPE_VS_SOURCE_MAPPING[dataSource];
|
||||
}
|
||||
return AlertTypes.METRICS_BASED_ALERT;
|
||||
}
|
||||
return alertTypeFromURL as AlertTypes;
|
||||
}, [alertTypeFromURL, ruleTypeFromURL, compositeQuery?.builder.queryData]);
|
||||
const alertType = useMemo(
|
||||
() => getInitialAlertTypeFromURL(queryParams, compositeQuery),
|
||||
[queryParams, compositeQuery],
|
||||
);
|
||||
|
||||
const handleTabChange = useCallback(
|
||||
(tab: string): void => {
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { useMemo } from 'react';
|
||||
import { useShareBuilderUrl } from 'hooks/queryBuilder/useShareBuilderUrl';
|
||||
import { mapQueryDataFromApi } from 'lib/newQueryBuilder/queryBuilderMappers/mapQueryDataFromApi';
|
||||
import { AlertTypes, PostableAlertRuleV2 } from 'types/api/alerts/alertTypes';
|
||||
|
||||
import AlertCondition from '../CreateAlert/AlertCondition';
|
||||
@@ -9,6 +8,7 @@ import Footer from '../CreateAlert/Footer';
|
||||
import NotificationSettings from '../CreateAlert/NotificationSettings';
|
||||
import QuerySection from '../CreateAlert/QuerySection';
|
||||
import { Spinner } from '../CreateAlert/utils';
|
||||
import { getEditAlertQuery } from './utils';
|
||||
|
||||
import '../CreateAlert/CreateAlert.styles.scss';
|
||||
|
||||
@@ -23,9 +23,10 @@ function EditAlert({
|
||||
}: EditAlertProps): JSX.Element {
|
||||
const currentQueryToRedirect = useMemo(() => {
|
||||
const basicAlertDef = buildInitialAlertDef(alertType);
|
||||
return mapQueryDataFromApi(
|
||||
return getEditAlertQuery(
|
||||
initialAlert?.condition.compositeQuery ||
|
||||
basicAlertDef.condition.compositeQuery,
|
||||
alertType,
|
||||
);
|
||||
}, [initialAlert, alertType]);
|
||||
|
||||
|
||||
82
frontend/src/container/EditAlert/__tests__/utils.test.ts
Normal file
82
frontend/src/container/EditAlert/__tests__/utils.test.ts
Normal file
@@ -0,0 +1,82 @@
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import { INITIAL_ALERT_THRESHOLD_STATE } from 'container/CreateAlert/context/constants';
|
||||
import { createMockAlertContextState } from 'container/CreateAlert/EvaluationSettings/__tests__/testUtils';
|
||||
import { buildCreateThresholdAlertRulePayload } from 'container/CreateAlert/Footer/utils';
|
||||
import { AlertTypes } from 'types/api/alerts/alertTypes';
|
||||
import { ICompositeMetricQuery } from 'types/api/alerts/compositeQuery';
|
||||
import { QueryEnvelope } from 'types/api/v5/queryRange';
|
||||
import { EQueryType } from 'types/common/dashboard';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import { getEditAlertQuery } from '../utils';
|
||||
|
||||
const savedQuery = (
|
||||
type: 'builder_query' | 'builder_ai_query',
|
||||
): ICompositeMetricQuery => ({
|
||||
queryType: EQueryType.QUERY_BUILDER,
|
||||
panelType: PANEL_TYPES.TIME_SERIES,
|
||||
unit: undefined,
|
||||
queries: [
|
||||
{
|
||||
type,
|
||||
spec: {
|
||||
name: 'A',
|
||||
signal: 'traces',
|
||||
aggregations: [{ expression: 'count()' }],
|
||||
},
|
||||
} as QueryEnvelope,
|
||||
],
|
||||
});
|
||||
|
||||
describe('getEditAlertQuery', () => {
|
||||
it('opens a saved AI traces alert in the AI slot', () => {
|
||||
const query = getEditAlertQuery(
|
||||
savedQuery('builder_ai_query'),
|
||||
AlertTypes.AI_TRACES_BASED_ALERT,
|
||||
);
|
||||
|
||||
expect(query.queryType).toBe(EQueryType.AI_QUERY_BUILDER);
|
||||
expect(query.builder.queryData).toHaveLength(0);
|
||||
expect(query.builder_ai_query?.queryData[0]).toMatchObject({
|
||||
queryName: 'A',
|
||||
dataSource: DataSource.TRACES,
|
||||
});
|
||||
});
|
||||
|
||||
it('opens a saved traces alert unchanged', () => {
|
||||
const query = getEditAlertQuery(
|
||||
savedQuery('builder_query'),
|
||||
AlertTypes.TRACES_BASED_ALERT,
|
||||
);
|
||||
|
||||
expect(query.queryType).toBe(EQueryType.QUERY_BUILDER);
|
||||
expect(query.builder.queryData[0].queryName).toBe('A');
|
||||
expect(query.builder_ai_query).toBeUndefined();
|
||||
});
|
||||
|
||||
it('saves an unchanged AI traces alert back as builder_ai_query envelopes', () => {
|
||||
const state = createMockAlertContextState();
|
||||
const payload = buildCreateThresholdAlertRulePayload({
|
||||
alertType: AlertTypes.AI_TRACES_BASED_ALERT,
|
||||
basicAlertState: state.alertState,
|
||||
thresholdState: INITIAL_ALERT_THRESHOLD_STATE,
|
||||
advancedOptions: state.advancedOptions,
|
||||
evaluationWindow: state.evaluationWindow,
|
||||
notificationSettings: state.notificationSettings,
|
||||
query: getEditAlertQuery(
|
||||
savedQuery('builder_ai_query'),
|
||||
AlertTypes.AI_TRACES_BASED_ALERT,
|
||||
),
|
||||
});
|
||||
|
||||
expect(payload.condition.compositeQuery.queryType).toBe(
|
||||
EQueryType.QUERY_BUILDER,
|
||||
);
|
||||
expect(payload.condition.compositeQuery.queries).toStrictEqual([
|
||||
expect.objectContaining({
|
||||
type: 'builder_ai_query',
|
||||
spec: expect.objectContaining({ name: 'A', signal: 'traces' }),
|
||||
}),
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,10 @@
|
||||
import { RuletypesAlertTypeDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { dataSourceForAlertType } from 'constants/alerts';
|
||||
import { initialQueryBuilderFormValuesMap } from 'constants/queryBuilder';
|
||||
import { mapQueryDataFromApi } from 'lib/newQueryBuilder/queryBuilderMappers/mapQueryDataFromApi';
|
||||
import { unfoldAISlot } from 'lib/query/builderSlot';
|
||||
import { AlertTypes } from 'types/api/alerts/alertTypes';
|
||||
import { ICompositeMetricQuery } from 'types/api/alerts/compositeQuery';
|
||||
import { Query } from 'types/api/queryBuilder/queryBuilderData';
|
||||
|
||||
export function sanitizeDefaultAlertQuery(
|
||||
@@ -13,3 +17,14 @@ export function sanitizeDefaultAlertQuery(
|
||||
}
|
||||
return query;
|
||||
}
|
||||
|
||||
/** A saved AI traces rule comes back as a builder query; the editor holds it in the AI slot. */
|
||||
export function getEditAlertQuery(
|
||||
compositeQuery: ICompositeMetricQuery,
|
||||
alertType: AlertTypes,
|
||||
): Query {
|
||||
const query = mapQueryDataFromApi(compositeQuery);
|
||||
return alertType === AlertTypes.AI_TRACES_BASED_ALERT
|
||||
? unfoldAISlot(query)
|
||||
: query;
|
||||
}
|
||||
|
||||
24
frontend/src/container/FormAlertRules/AIQuerySection.tsx
Normal file
24
frontend/src/container/FormAlertRules/AIQuerySection.tsx
Normal file
@@ -0,0 +1,24 @@
|
||||
import { QueryBuilderV2 } from 'components/QueryBuilderV2/QueryBuilderV2';
|
||||
import { ENTITY_VERSION_V5 } from 'constants/app';
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
interface AIQuerySectionProps {
|
||||
panelType: PANEL_TYPES;
|
||||
}
|
||||
|
||||
function AIQuerySection({ panelType }: AIQuerySectionProps): JSX.Element {
|
||||
return (
|
||||
<QueryBuilderV2
|
||||
panelType={panelType}
|
||||
config={{
|
||||
queryVariant: 'static',
|
||||
initialDataSource: DataSource.TRACES,
|
||||
}}
|
||||
showTraceOperator={false}
|
||||
version={ENTITY_VERSION_V5}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export default AIQuerySection;
|
||||
@@ -29,6 +29,7 @@ import { useResizeObserver } from 'hooks/useDimensions';
|
||||
import useUrlQuery from 'hooks/useUrlQuery';
|
||||
import GetMinMax from 'lib/getMinMax';
|
||||
import getTimeString from 'lib/getTimeString';
|
||||
import { getActiveBuilder } from 'lib/query/builderSlot';
|
||||
import { navigate } from 'lib/router/navigation';
|
||||
import { LegendPosition } from 'lib/uPlotV2/components/types';
|
||||
import { isEmpty } from 'lodash-es';
|
||||
@@ -157,10 +158,10 @@ function ChartPreview({
|
||||
query.clickhouse_sql[0].query?.length > 0
|
||||
);
|
||||
case EQueryType.QUERY_BUILDER:
|
||||
return (
|
||||
query.builder.queryData.length > 0 &&
|
||||
query.builder.queryData[0].queryName !== ''
|
||||
);
|
||||
case EQueryType.AI_QUERY_BUILDER: {
|
||||
const { queryData } = getActiveBuilder(query);
|
||||
return queryData.length > 0 && queryData[0].queryName !== '';
|
||||
}
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -13,10 +13,11 @@ import RunQueryBtn from 'container/QueryBuilder/components/RunQueryBtn/RunQueryB
|
||||
import { useKeyboardHotkeys } from 'hooks/hotkeys/useKeyboardHotkeys';
|
||||
import { useIsDarkMode } from 'hooks/useDarkMode';
|
||||
import { isEmpty } from 'lodash-es';
|
||||
import { Atom, Terminal } from '@signozhq/icons';
|
||||
import { Atom, Brain, Terminal } from '@signozhq/icons';
|
||||
import { AlertTypes } from 'types/api/alerts/alertTypes';
|
||||
import { EQueryType } from 'types/common/dashboard';
|
||||
|
||||
import AIQuerySection from './AIQuerySection';
|
||||
import ChQuerySection from './ChQuerySection';
|
||||
import PromqlSection from './PromqlSection';
|
||||
|
||||
@@ -149,6 +150,29 @@ function QuerySection({
|
||||
},
|
||||
];
|
||||
|
||||
const aiTabs = [
|
||||
{
|
||||
label: (
|
||||
<Tooltip title="AI Query Builder">
|
||||
<Button className="nav-btns" data-testid="ai-query-builder-tab">
|
||||
<Brain size={14} />
|
||||
<Typography
|
||||
variant="paragraph"
|
||||
size="base"
|
||||
weight="regular"
|
||||
color="inherit"
|
||||
as="span"
|
||||
textOverflow="wrap"
|
||||
>
|
||||
AI Query Builder
|
||||
</Typography>
|
||||
</Button>
|
||||
</Tooltip>
|
||||
),
|
||||
key: EQueryType.AI_QUERY_BUILDER,
|
||||
},
|
||||
];
|
||||
|
||||
useEffect(() => {
|
||||
if (isAnomalyDetection && queryCategory !== EQueryType.QUERY_BUILDER) {
|
||||
setQueryCategory(EQueryType.QUERY_BUILDER);
|
||||
@@ -262,6 +286,7 @@ function QuerySection({
|
||||
case AlertTypes.TRACES_BASED_ALERT:
|
||||
case AlertTypes.LOGS_BASED_ALERT:
|
||||
case AlertTypes.EXCEPTIONS_BASED_ALERT:
|
||||
case AlertTypes.AI_TRACES_BASED_ALERT:
|
||||
return (
|
||||
<div className="alert-tabs">
|
||||
<Tabs
|
||||
@@ -287,7 +312,7 @@ function QuerySection({
|
||||
/>
|
||||
</span>
|
||||
}
|
||||
items={tabs}
|
||||
items={typ === AlertTypes.AI_TRACES_BASED_ALERT ? aiTabs : tabs}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
@@ -326,6 +351,9 @@ function QuerySection({
|
||||
if (c === EQueryType.QUERY_BUILDER) {
|
||||
return renderMetricUI();
|
||||
}
|
||||
if (c === EQueryType.AI_QUERY_BUILDER) {
|
||||
return <AIQuerySection panelType={panelType} />;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
import type { ComponentProps } from 'react';
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import { render, screen } from 'tests/test-utils';
|
||||
import { AlertTypes } from 'types/api/alerts/alertTypes';
|
||||
import type { QueryBuilderProps } from 'container/QueryBuilder/QueryBuilder.interfaces';
|
||||
import type { useKeyboardHotkeys } from 'hooks/hotkeys/useKeyboardHotkeys';
|
||||
import { EQueryType } from 'types/common/dashboard';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import QuerySection from '../QuerySection';
|
||||
|
||||
const mockQueryBuilderV2 = jest.fn() as jest.MockedFunction<
|
||||
(props: QueryBuilderProps) => void
|
||||
>;
|
||||
|
||||
jest.mock('components/QueryBuilderV2/QueryBuilderV2', () => ({
|
||||
QueryBuilderV2: (props: QueryBuilderProps): JSX.Element => {
|
||||
mockQueryBuilderV2(props);
|
||||
return <div data-testid="query-builder-v2" />;
|
||||
},
|
||||
}));
|
||||
|
||||
jest.mock('hooks/hotkeys/useKeyboardHotkeys', () => ({
|
||||
useKeyboardHotkeys: (): ReturnType<typeof useKeyboardHotkeys> => ({
|
||||
registerShortcut: jest.fn() as jest.MockedFunction<
|
||||
ReturnType<typeof useKeyboardHotkeys>['registerShortcut']
|
||||
>,
|
||||
deregisterShortcut: jest.fn() as jest.MockedFunction<
|
||||
ReturnType<typeof useKeyboardHotkeys>['deregisterShortcut']
|
||||
>,
|
||||
}),
|
||||
}));
|
||||
|
||||
jest.mock('../ChQuerySection', () => ({
|
||||
__esModule: true,
|
||||
default: (): JSX.Element => <div data-testid="clickhouse-section" />,
|
||||
}));
|
||||
|
||||
jest.mock('../PromqlSection', () => ({
|
||||
__esModule: true,
|
||||
default: (): JSX.Element => <div data-testid="promql-section" />,
|
||||
}));
|
||||
|
||||
type QuerySectionProps = ComponentProps<typeof QuerySection>;
|
||||
|
||||
const renderQuerySection = (
|
||||
alertType: AlertTypes,
|
||||
queryCategory: EQueryType,
|
||||
): void => {
|
||||
render(
|
||||
<QuerySection
|
||||
queryCategory={queryCategory}
|
||||
setQueryCategory={
|
||||
jest.fn() as jest.MockedFunction<QuerySectionProps['setQueryCategory']>
|
||||
}
|
||||
alertType={alertType}
|
||||
runQuery={jest.fn() as jest.MockedFunction<QuerySectionProps['runQuery']>}
|
||||
isLoadingQueries={false}
|
||||
handleCancelQuery={
|
||||
jest.fn() as jest.MockedFunction<QuerySectionProps['handleCancelQuery']>
|
||||
}
|
||||
panelType={PANEL_TYPES.TIME_SERIES}
|
||||
ruleId=""
|
||||
/>,
|
||||
);
|
||||
};
|
||||
|
||||
describe('FormAlertRules QuerySection', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
it('shows only the AI Query Builder tab for an AI traces alert', () => {
|
||||
renderQuerySection(
|
||||
AlertTypes.AI_TRACES_BASED_ALERT,
|
||||
EQueryType.AI_QUERY_BUILDER,
|
||||
);
|
||||
|
||||
expect(screen.getByTestId('ai-query-builder-tab')).toHaveTextContent(
|
||||
'AI Query Builder',
|
||||
);
|
||||
expect(screen.queryByTestId('query-builder-tab')).not.toBeInTheDocument();
|
||||
expect(screen.queryByTestId('clickhouse-tab')).not.toBeInTheDocument();
|
||||
expect(screen.queryByTestId('promql-tab')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('pins the AI Query Builder to traces', () => {
|
||||
renderQuerySection(
|
||||
AlertTypes.AI_TRACES_BASED_ALERT,
|
||||
EQueryType.AI_QUERY_BUILDER,
|
||||
);
|
||||
|
||||
expect(screen.getByTestId('query-builder-v2')).toBeInTheDocument();
|
||||
expect(mockQueryBuilderV2).toHaveBeenLastCalledWith(
|
||||
expect.objectContaining({
|
||||
config: expect.objectContaining({
|
||||
initialDataSource: DataSource.TRACES,
|
||||
queryVariant: 'static',
|
||||
}),
|
||||
showTraceOperator: false,
|
||||
}),
|
||||
);
|
||||
expect(mockQueryBuilderV2.mock.lastCall?.[0]).not.toHaveProperty(
|
||||
'signalSourceChangeEnabled',
|
||||
);
|
||||
});
|
||||
|
||||
it('keeps the traces alert tabs without the AI tab', () => {
|
||||
renderQuerySection(AlertTypes.TRACES_BASED_ALERT, EQueryType.QUERY_BUILDER);
|
||||
|
||||
expect(screen.getByTestId('query-builder-tab')).toHaveTextContent(
|
||||
'Query Builder',
|
||||
);
|
||||
expect(screen.getByTestId('clickhouse-tab')).toHaveTextContent(
|
||||
'ClickHouse Query',
|
||||
);
|
||||
expect(screen.queryByTestId('ai-query-builder-tab')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('keeps the metrics alert tabs without the AI tab', () => {
|
||||
renderQuerySection(AlertTypes.METRICS_BASED_ALERT, EQueryType.QUERY_BUILDER);
|
||||
|
||||
expect(screen.getByTestId('query-builder-tab')).toHaveTextContent(
|
||||
'Query Builder',
|
||||
);
|
||||
expect(screen.getByTestId('clickhouse-tab')).toHaveTextContent(
|
||||
'ClickHouse Query',
|
||||
);
|
||||
expect(screen.getByTestId('promql-tab')).toHaveTextContent('PromQL');
|
||||
expect(screen.queryByTestId('ai-query-builder-tab')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -13,7 +13,7 @@ import store from 'store';
|
||||
import APIError from 'types/api/error';
|
||||
import { installTranslationResilience } from 'translation-resilience';
|
||||
|
||||
import 'lib/monaco/setup';
|
||||
import 'lib/monaco/loader';
|
||||
|
||||
import './ReactI18';
|
||||
|
||||
|
||||
51
frontend/src/lib/monaco/__tests__/loader.test.ts
Normal file
51
frontend/src/lib/monaco/__tests__/loader.test.ts
Normal file
@@ -0,0 +1,51 @@
|
||||
import type { loader as Loader } from '@monaco-editor/react';
|
||||
|
||||
const mockMonaco = { editor: {} };
|
||||
const mockLazyRetry = jest.fn();
|
||||
|
||||
jest.mock('../setup', () => ({ monaco: mockMonaco }));
|
||||
jest.mock('utils/lazyWithRetries', () => ({
|
||||
lazyRetry: (load: () => Promise<unknown>): Promise<unknown> =>
|
||||
mockLazyRetry(load),
|
||||
}));
|
||||
|
||||
async function loadPatchedLoader(): Promise<typeof Loader> {
|
||||
let patched!: typeof Loader;
|
||||
await jest.isolateModulesAsync(async () => {
|
||||
({ loader: patched } = await import('@monaco-editor/react'));
|
||||
await import('../loader');
|
||||
});
|
||||
return patched;
|
||||
}
|
||||
|
||||
describe('lazy monaco loader', () => {
|
||||
beforeEach(() => {
|
||||
mockLazyRetry.mockImplementation((load: () => Promise<unknown>) => load());
|
||||
});
|
||||
|
||||
it('rejects a canceled init with the cancelation error', async () => {
|
||||
const loader = await loadPatchedLoader();
|
||||
const init = loader.init();
|
||||
init.cancel();
|
||||
|
||||
await expect(init).rejects.toMatchObject({ type: 'cancelation' });
|
||||
});
|
||||
|
||||
it('resolves with the bundled instance without adding a CDN script', async () => {
|
||||
const loader = await loadPatchedLoader();
|
||||
|
||||
await expect(loader.init()).resolves.toBe(mockMonaco);
|
||||
// oxlint-disable-next-line signoz/no-dom-node-access -- script elements have no role to query by
|
||||
expect(document.querySelector('script')).toBeNull();
|
||||
});
|
||||
|
||||
it('imports Monaco again on the next init after a failed load', async () => {
|
||||
const loader = await loadPatchedLoader();
|
||||
const chunkError = new Error('Failed to fetch dynamically imported module');
|
||||
mockLazyRetry.mockRejectedValueOnce(chunkError);
|
||||
|
||||
await expect(loader.init()).rejects.toBe(chunkError);
|
||||
await expect(loader.init()).resolves.toBe(mockMonaco);
|
||||
expect(mockLazyRetry).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
37
frontend/src/lib/monaco/loader.ts
Normal file
37
frontend/src/lib/monaco/loader.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import { loader } from '@monaco-editor/react';
|
||||
import { lazyRetry } from 'utils/lazyWithRetries';
|
||||
|
||||
type LoaderInit = typeof loader.init;
|
||||
type CancelableMonaco = ReturnType<LoaderInit>;
|
||||
|
||||
const CANCELATION = {
|
||||
type: 'cancelation',
|
||||
msg: 'operation is manually canceled',
|
||||
};
|
||||
|
||||
const initLoader: LoaderInit = loader.init;
|
||||
let monacoLoaded: Promise<void> | undefined;
|
||||
|
||||
// monaco-editor is about a third of the entry chunk, so it loads on the first editor
|
||||
// mount instead of with the app. Every editor goes through @monaco-editor/react, whose
|
||||
// components call `loader.init()` on mount; handing the loader the bundled instance
|
||||
// before the original init runs keeps it from fetching Monaco from the CDN.
|
||||
loader.init = (): CancelableMonaco => {
|
||||
monacoLoaded ??= lazyRetry(() => import('./setup'))
|
||||
.then(({ monaco }) => loader.config({ monaco }))
|
||||
.catch((error) => {
|
||||
monacoLoaded = undefined;
|
||||
throw error;
|
||||
});
|
||||
let canceled = false;
|
||||
const promise = monacoLoaded.then(() => {
|
||||
if (canceled) {
|
||||
throw CANCELATION;
|
||||
}
|
||||
return initLoader();
|
||||
}) as CancelableMonaco;
|
||||
promise.cancel = (): void => {
|
||||
canceled = true;
|
||||
};
|
||||
return promise;
|
||||
};
|
||||
@@ -1,4 +1,3 @@
|
||||
import { loader } from '@monaco-editor/react';
|
||||
import * as monaco from 'monaco-editor';
|
||||
import EditorWorker from 'monaco-editor/esm/vs/editor/editor.worker?worker';
|
||||
import JsonWorker from 'monaco-editor/esm/vs/language/json/json.worker?worker';
|
||||
@@ -18,4 +17,4 @@ self.MonacoEnvironment = {
|
||||
},
|
||||
};
|
||||
|
||||
loader.config({ monaco });
|
||||
export { monaco };
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
/* eslint-disable sonarjs/cognitive-complexity */
|
||||
import { initialQueryState } from 'constants/queryBuilder';
|
||||
import { isAIQueryType } from 'lib/query/builderSlot';
|
||||
import { ICompositeMetricQuery } from 'types/api/alerts/compositeQuery';
|
||||
import {
|
||||
IBuilderFormula,
|
||||
@@ -24,6 +25,15 @@ import { v4 as uuid } from 'uuid';
|
||||
|
||||
import { transformQueryBuilderDataModel } from '../transformQueryBuilderDataModel';
|
||||
|
||||
/** An AI-typed composite authors in the AI slot; every other type keeps `builder`. */
|
||||
const toBuilderSlots = (
|
||||
builder: Query['builder'],
|
||||
queryType: EQueryType,
|
||||
): Pick<Query, 'builder' | 'builder_ai_query'> =>
|
||||
isAIQueryType(queryType)
|
||||
? { builder: transformQueryBuilderDataModel({}), builder_ai_query: builder }
|
||||
: { builder };
|
||||
|
||||
const mapQueryFromV5 = (compositeQuery: ICompositeMetricQuery): Query => {
|
||||
const builderQueries: Record<
|
||||
string,
|
||||
@@ -38,7 +48,7 @@ const mapQueryFromV5 = (compositeQuery: ICompositeMetricQuery): Query => {
|
||||
> = {};
|
||||
const promQueries: IPromQLQuery[] = [];
|
||||
const clickhouseQueries: IClickHouseQuery[] = [];
|
||||
const isAIQuery = compositeQuery.queryType === EQueryType.AI_QUERY_BUILDER;
|
||||
const isAIQuery = isAIQueryType(compositeQuery.queryType);
|
||||
|
||||
compositeQuery.queries?.forEach((q) => {
|
||||
const spec = q.spec as BuilderQuery | PromQuery | ClickHouseQuery;
|
||||
@@ -98,8 +108,7 @@ const mapQueryFromV5 = (compositeQuery: ICompositeMetricQuery): Query => {
|
||||
builderQueryTypes,
|
||||
);
|
||||
return {
|
||||
builder: isAIQuery ? transformQueryBuilderDataModel({}) : builder,
|
||||
...(isAIQuery && { builder_ai_query: builder }),
|
||||
...toBuilderSlots(builder, compositeQuery.queryType),
|
||||
promql: promQueries,
|
||||
clickhouse_sql: clickhouseQueries,
|
||||
queryType: compositeQuery.queryType,
|
||||
@@ -129,7 +138,7 @@ const mapQueryFromV3 = (compositeQuery: ICompositeMetricQuery): Query => {
|
||||
: initialQueryState.clickhouse_sql;
|
||||
|
||||
return {
|
||||
builder,
|
||||
...toBuilderSlots(builder, compositeQuery.queryType),
|
||||
promql: promql as IPromQLQuery[],
|
||||
clickhouse_sql: clickhouseSql as IClickHouseQuery[],
|
||||
queryType: compositeQuery.queryType,
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
isAIQueryType,
|
||||
isBuilderQueryType,
|
||||
foldAISlot,
|
||||
unfoldAISlot,
|
||||
toSlotQuery,
|
||||
} from 'lib/query/builderSlot';
|
||||
import type { Query } from 'types/api/queryBuilder/queryBuilderData';
|
||||
@@ -129,3 +130,38 @@ describe('toSlotQuery', () => {
|
||||
expect(restored.builder_ai_query).toBe(refined.builder);
|
||||
});
|
||||
});
|
||||
|
||||
describe('unfoldAISlot', () => {
|
||||
const wireQuery = foldAISlot({
|
||||
...baseQuery,
|
||||
queryType: EQueryType.AI_QUERY_BUILDER,
|
||||
builder_ai_query: aiBuilder,
|
||||
});
|
||||
|
||||
it('moves a builder query into the AI slot under the AI type, tags dropped', () => {
|
||||
const result = unfoldAISlot(wireQuery);
|
||||
|
||||
expect(result.queryType).toBe(EQueryType.AI_QUERY_BUILDER);
|
||||
expect(result.builder.queryData).toHaveLength(0);
|
||||
expect(result.builder_ai_query?.queryData[0].queryName).toBe('A');
|
||||
expect(
|
||||
result.builder_ai_query?.queryData[0].builderQueryType,
|
||||
).toBeUndefined();
|
||||
});
|
||||
|
||||
it('round-trips with foldAISlot', () => {
|
||||
expect(foldAISlot(unfoldAISlot(wireQuery))).toStrictEqual(wireQuery);
|
||||
});
|
||||
|
||||
it('leaves ClickHouse, PromQL and AI-typed queries untouched', () => {
|
||||
const promql: Query = { ...baseQuery, queryType: EQueryType.PROM };
|
||||
const aiTyped: Query = {
|
||||
...baseQuery,
|
||||
queryType: EQueryType.AI_QUERY_BUILDER,
|
||||
builder_ai_query: aiBuilder,
|
||||
};
|
||||
|
||||
expect(unfoldAISlot(promql)).toBe(promql);
|
||||
expect(unfoldAISlot(aiTyped)).toBe(aiTyped);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Querybuildertypesv5QueryTypeDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { omit } from 'lodash-es';
|
||||
import type {
|
||||
Query,
|
||||
QueryState,
|
||||
@@ -72,6 +73,24 @@ export function toSlotQuery(requestQuery: Query, slotQuery: Query): Query {
|
||||
};
|
||||
}
|
||||
|
||||
/** The reverse of `foldAISlot`: a builder query moves into the AI slot under the AI type, untagged. */
|
||||
export function unfoldAISlot(query: Query): Query {
|
||||
if (query.queryType !== EQueryType.QUERY_BUILDER) {
|
||||
return query;
|
||||
}
|
||||
return {
|
||||
...query,
|
||||
queryType: EQueryType.AI_QUERY_BUILDER,
|
||||
builder: EMPTY_BUILDER,
|
||||
builder_ai_query: {
|
||||
...query.builder,
|
||||
queryData: query.builder.queryData.map((queryData) =>
|
||||
omit(queryData, 'builderQueryType'),
|
||||
),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** The builder at `slotKey`; an unused AI slot holds none. */
|
||||
export function getBuilderBySlotKey(
|
||||
state: QueryState,
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import { PrecisionOption } from 'components/Graph/types';
|
||||
import { getToolTipValue } from 'components/Graph/yAxisConfig';
|
||||
import { DATE_TIME_FORMATS } from 'constants/dateTimeFormats';
|
||||
import dayjs from 'dayjs';
|
||||
import { formatRowLabel } from 'lib/uPlotV2/plugins/HeatmapPlugin/geometry';
|
||||
import {
|
||||
createBucketValueFormatter,
|
||||
formatRowLabel,
|
||||
} from 'lib/uPlotV2/plugins/HeatmapPlugin/geometry';
|
||||
import {
|
||||
HeatmapSeries,
|
||||
HeatmapYAxis,
|
||||
@@ -71,8 +73,9 @@ export function formatBucketLabel({
|
||||
if (!bucket) {
|
||||
return '';
|
||||
}
|
||||
return formatRowLabel(bucket, (value) =>
|
||||
getToolTipValue(String(value), yAxisUnit, decimalPrecision),
|
||||
return formatRowLabel(
|
||||
bucket,
|
||||
createBucketValueFormatter(yAxisUnit, decimalPrecision),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -106,8 +109,10 @@ export function buildBucketRows({
|
||||
yAxisUnit?: string;
|
||||
decimalPrecision?: PrecisionOption;
|
||||
}): HeatmapBucketRow[] {
|
||||
const formatBucketValue = (value: number): string =>
|
||||
getToolTipValue(String(value), yAxisUnit, decimalPrecision);
|
||||
const formatBucketValue = createBucketValueFormatter(
|
||||
yAxisUnit,
|
||||
decimalPrecision,
|
||||
);
|
||||
|
||||
const rows: HeatmapBucketRow[] = [];
|
||||
for (let offset = NEIGHBOUR_SPAN; offset >= -NEIGHBOUR_SPAN; offset -= 1) {
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
import type uPlot from 'uplot';
|
||||
|
||||
import { createVariableWidthBarsPathBuilder } from '../variableWidthBars';
|
||||
|
||||
class FakePath2D {
|
||||
rects: number[][] = [];
|
||||
|
||||
rect(x: number, y: number, width: number, height: number): void {
|
||||
this.rects.push([x, y, width, height]);
|
||||
}
|
||||
}
|
||||
|
||||
/** 10 px per unit on both axes; y grows downward from 100. */
|
||||
const fakePlot: Partial<uPlot> = {
|
||||
valToPos: (value: number, scaleKey: string): number =>
|
||||
scaleKey === 'x' ? value * 10 : 100 - value * 10,
|
||||
ctx: {} as CanvasRenderingContext2D,
|
||||
};
|
||||
const plot = fakePlot as uPlot;
|
||||
|
||||
type Fills = Map<CanvasRenderingContext2D['fillStyle'], Path2D>;
|
||||
|
||||
function fillsOf(paths: ReturnType<uPlot.Series.PathBuilder>): Fills {
|
||||
const fill = paths?.fill;
|
||||
if (!(fill instanceof Map)) {
|
||||
throw new Error('expected a fill per style');
|
||||
}
|
||||
return fill;
|
||||
}
|
||||
|
||||
function rectsOf(path: Path2D | undefined): number[][] {
|
||||
if (!(path instanceof FakePath2D)) {
|
||||
throw new Error('expected a FakePath2D');
|
||||
}
|
||||
return path.rects;
|
||||
}
|
||||
|
||||
describe('createVariableWidthBarsPathBuilder', () => {
|
||||
const originalPath2D = globalThis.Path2D;
|
||||
|
||||
beforeAll(() => {
|
||||
Object.defineProperty(globalThis, 'Path2D', {
|
||||
value: FakePath2D,
|
||||
configurable: true,
|
||||
});
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
Object.defineProperty(globalThis, 'Path2D', {
|
||||
value: originalPath2D,
|
||||
configurable: true,
|
||||
});
|
||||
});
|
||||
|
||||
function build(
|
||||
pattern: CanvasPattern | null = null,
|
||||
): ReturnType<uPlot.Series.PathBuilder> {
|
||||
return createVariableWidthBarsPathBuilder({
|
||||
getBars: () => [
|
||||
{ x0: 0, x1: 1, y0: 0, y1: 2, hatched: false },
|
||||
{ x0: 1, x1: 4, y0: 0, y1: 5, hatched: false },
|
||||
{ x0: 4, x1: 6, y0: 1, y1: 3, hatched: true },
|
||||
],
|
||||
fill: '#ff0000',
|
||||
hatchedFill: '#ff000066',
|
||||
getHatchPattern: () => pattern,
|
||||
gapPx: 2,
|
||||
})(plot, 1, 0, 0);
|
||||
}
|
||||
|
||||
it('draws each bar at its own width, inset by half the gap', () => {
|
||||
const fills = fillsOf(build());
|
||||
|
||||
expect(rectsOf(fills.get('#ff0000'))).toStrictEqual([
|
||||
[1, 80, 8, 20],
|
||||
[11, 50, 28, 50],
|
||||
]);
|
||||
});
|
||||
|
||||
it('draws hatched bars in their own fill, with the pattern on top', () => {
|
||||
const pattern = {} as CanvasPattern;
|
||||
const fills = fillsOf(build(pattern));
|
||||
|
||||
expect([...fills.keys()]).toStrictEqual(['#ff0000', '#ff000066', pattern]);
|
||||
expect(rectsOf(fills.get(pattern))).toStrictEqual([[41, 70, 18, 20]]);
|
||||
});
|
||||
it('reads a fill callback on every draw', () => {
|
||||
let fill = '#ff0000';
|
||||
const builder = createVariableWidthBarsPathBuilder({
|
||||
getBars: () => [{ x0: 0, x1: 1, y0: 0, y1: 1, hatched: false }],
|
||||
fill: () => fill,
|
||||
hatchedFill: '#00ff00',
|
||||
getHatchPattern: () => null,
|
||||
gapPx: 0,
|
||||
});
|
||||
|
||||
const first = fillsOf(builder(plot, 1, 0, 0));
|
||||
fill = '#0000ff';
|
||||
const second = fillsOf(builder(plot, 1, 0, 0));
|
||||
|
||||
expect([...first.keys()]).toStrictEqual(['#ff0000']);
|
||||
expect([...second.keys()]).toStrictEqual(['#0000ff']);
|
||||
});
|
||||
|
||||
it('keeps solid bars when the hatched fill is the same colour', () => {
|
||||
const fills = fillsOf(
|
||||
createVariableWidthBarsPathBuilder({
|
||||
getBars: () => [
|
||||
{ x0: 0, x1: 1, y0: 0, y1: 1, hatched: false },
|
||||
{ x0: 1, x1: 2, y0: 0, y1: 1, hatched: true },
|
||||
],
|
||||
fill: 'red',
|
||||
hatchedFill: 'red',
|
||||
getHatchPattern: () => null,
|
||||
gapPx: 0,
|
||||
})(plot, 1, 0, 0),
|
||||
);
|
||||
|
||||
expect(rectsOf(fills.get('red'))).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('hatches only overflow bars when both fills are the same colour', () => {
|
||||
const pattern = {} as CanvasPattern;
|
||||
const fills = fillsOf(
|
||||
createVariableWidthBarsPathBuilder({
|
||||
getBars: () => [
|
||||
{ x0: 0, x1: 1, y0: 0, y1: 1, hatched: false },
|
||||
{ x0: 1, x1: 2, y0: 0, y1: 1, hatched: true },
|
||||
],
|
||||
fill: 'red',
|
||||
hatchedFill: 'red',
|
||||
getHatchPattern: () => pattern,
|
||||
gapPx: 0,
|
||||
})(plot, 1, 0, 0),
|
||||
);
|
||||
|
||||
expect(rectsOf(fills.get(pattern))).toStrictEqual([[10, 90, 10, 10]]);
|
||||
});
|
||||
});
|
||||
88
frontend/src/lib/uPlotV2/paths/variableWidthBars.ts
Normal file
88
frontend/src/lib/uPlotV2/paths/variableWidthBars.ts
Normal file
@@ -0,0 +1,88 @@
|
||||
import uPlot from 'uplot';
|
||||
|
||||
/** A bar in scale space. Unlike uPlot's own bars, each one carries its own width. */
|
||||
export interface VariableWidthBar {
|
||||
x0: number;
|
||||
x1: number;
|
||||
y0: number;
|
||||
y1: number;
|
||||
/** Drawn in `hatchedFill` with the hatch pattern on top. */
|
||||
hatched: boolean;
|
||||
}
|
||||
|
||||
/** A fill, or one read on every draw (e.g. to dim a series on hover). */
|
||||
type BarFill = string | (() => string);
|
||||
|
||||
/** Bars narrower than this, in CSS pixels, keep no gap between them. */
|
||||
const MIN_WIDTH_FOR_GAP_PX = 3;
|
||||
|
||||
/**
|
||||
* Draws `[x0, x1] × [y0, y1]` rects on the `x` and `y` scales. uPlot's bar builder
|
||||
* assumes one width for every bar, which a bucket axis with uneven bounds breaks.
|
||||
*
|
||||
* `getBars` runs on every redraw, so a caller can derive the bars from the plot's
|
||||
* current state (e.g. which series are shown).
|
||||
*/
|
||||
export function createVariableWidthBarsPathBuilder({
|
||||
getBars,
|
||||
fill,
|
||||
hatchedFill,
|
||||
getHatchPattern,
|
||||
gapPx,
|
||||
}: {
|
||||
getBars: (uPlotInstance: uPlot, seriesIdx: number) => VariableWidthBar[];
|
||||
fill: BarFill;
|
||||
hatchedFill: BarFill;
|
||||
getHatchPattern: (ctx: CanvasRenderingContext2D) => CanvasPattern | null;
|
||||
/** Space between neighbouring bars, in CSS pixels. */
|
||||
gapPx: number;
|
||||
}): uPlot.Series.PathBuilder {
|
||||
return (uPlotInstance, seriesIdx): uPlot.Series.Paths => {
|
||||
const solidFill = resolveFill(fill);
|
||||
const overflowFill = resolveFill(hatchedFill);
|
||||
const solidPath = new Path2D();
|
||||
// The hatch overlays only overflow bars, so they keep a path of their own even
|
||||
// when one colour fill covers both (a Map keyed by fill holds one path a fill).
|
||||
const hatchedPath = new Path2D();
|
||||
const isSharedFill = overflowFill === solidFill;
|
||||
const inset = (gapPx * uPlot.pxRatio) / 2;
|
||||
const minWidthForGap = MIN_WIDTH_FOR_GAP_PX * uPlot.pxRatio;
|
||||
let hasHatched = false;
|
||||
|
||||
getBars(uPlotInstance, seriesIdx).forEach((bar) => {
|
||||
const left = uPlotInstance.valToPos(bar.x0, 'x', true);
|
||||
const right = uPlotInstance.valToPos(bar.x1, 'x', true);
|
||||
const top = uPlotInstance.valToPos(bar.y1, 'y', true);
|
||||
const bottom = uPlotInstance.valToPos(bar.y0, 'y', true);
|
||||
const width = right - left;
|
||||
const gap = width > minWidthForGap ? inset : 0;
|
||||
const rect = [left + gap, top, width - 2 * gap, bottom - top] as const;
|
||||
if (!bar.hatched || isSharedFill) {
|
||||
solidPath.rect(...rect);
|
||||
}
|
||||
if (bar.hatched) {
|
||||
hatchedPath.rect(...rect);
|
||||
hasHatched = true;
|
||||
}
|
||||
});
|
||||
|
||||
const fills = new Map<CanvasRenderingContext2D['fillStyle'], Path2D>([
|
||||
[solidFill, solidPath],
|
||||
]);
|
||||
if (hasHatched) {
|
||||
if (!isSharedFill) {
|
||||
fills.set(overflowFill, hatchedPath);
|
||||
}
|
||||
const pattern = getHatchPattern(uPlotInstance.ctx);
|
||||
if (pattern) {
|
||||
fills.set(pattern, hatchedPath);
|
||||
}
|
||||
}
|
||||
|
||||
return { stroke: null, fill: fills, clip: null, band: null, flags: 0 };
|
||||
};
|
||||
}
|
||||
|
||||
function resolveFill(fill: BarFill): string {
|
||||
return typeof fill === 'function' ? fill() : fill;
|
||||
}
|
||||
@@ -1,3 +1,6 @@
|
||||
import { PrecisionOption } from 'components/Graph/types';
|
||||
import { getToolTipValue } from 'components/Graph/yAxisConfig';
|
||||
|
||||
import { HeatmapAxisScale, HeatmapRow, HeatmapYAxis } from './types';
|
||||
|
||||
/** Used when the ratio cannot be inferred, i.e. a single boundary. */
|
||||
@@ -335,6 +338,15 @@ export function resolveColumnIndex(
|
||||
return xValue < timestamps[candidate] + width ? candidate : null;
|
||||
}
|
||||
|
||||
/** Formats a bucket bound, or any value on the bucketed axis, in its unit. */
|
||||
export function createBucketValueFormatter(
|
||||
unit?: string,
|
||||
decimalPrecision?: PrecisionOption,
|
||||
): (value: number) => string {
|
||||
return (value: number): string =>
|
||||
getToolTipValue(String(value), unit, decimalPrecision);
|
||||
}
|
||||
|
||||
/** The open-ended rows are labelled by their one real boundary; the synthetic
|
||||
* edge is a drawing device, not a value. */
|
||||
export function formatRowLabel(
|
||||
|
||||
@@ -51,6 +51,7 @@ export default function TooltipPlugin({
|
||||
canPinTooltip = false,
|
||||
pinKey = DEFAULT_PIN_TOOLTIP_KEY,
|
||||
onClick,
|
||||
shouldPinOnClick,
|
||||
portalRoot: portalRootProp,
|
||||
}: TooltipPluginProps): JSX.Element | null {
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
@@ -59,6 +60,8 @@ export default function TooltipPlugin({
|
||||
const layoutRef = useRef<TooltipLayoutInfo>();
|
||||
const renderRef = useRef(render);
|
||||
renderRef.current = render;
|
||||
const shouldPinOnClickRef = useRef(shouldPinOnClick);
|
||||
shouldPinOnClickRef.current = shouldPinOnClick;
|
||||
const [portalRoot, setPortalRoot] = useState<HTMLElement>(
|
||||
portalRootProp ??
|
||||
(document.fullscreenElement as HTMLElement) ??
|
||||
@@ -378,6 +381,15 @@ export default function TooltipPlugin({
|
||||
controller.focusedSeriesIndex != null
|
||||
) {
|
||||
const clickData = buildClickData(event, plot);
|
||||
if (canPinTooltip && shouldPinOnClickRef.current?.(clickData)) {
|
||||
controller.clickData = clickData;
|
||||
controller.pinned = true;
|
||||
logEvent(Events.TOOLTIP_PINNED, {
|
||||
id: config.getId(),
|
||||
});
|
||||
scheduleRender(true);
|
||||
return;
|
||||
}
|
||||
onClick?.(clickData);
|
||||
}
|
||||
};
|
||||
@@ -388,7 +400,7 @@ export default function TooltipPlugin({
|
||||
const handleInit = (u: uPlot): void => {
|
||||
controller.plot = u;
|
||||
updateState({ hasPlot: true });
|
||||
if (onClick) {
|
||||
if (onClick || shouldPinOnClick) {
|
||||
overClickHandler = handleOverClick;
|
||||
u.over.addEventListener('click', overClickHandler);
|
||||
}
|
||||
|
||||
@@ -60,6 +60,8 @@ export interface TooltipPluginProps {
|
||||
pinKey?: string;
|
||||
/** Called when the user clicks the uPlot overlay. Receives resolved click data. */
|
||||
onClick?: (clickData: ChartClickData) => void;
|
||||
/** With `canPinTooltip`, a click it returns true for pins the tooltip instead of calling `onClick`. */
|
||||
shouldPinOnClick?: (clickData: ChartClickData) => boolean;
|
||||
syncMode?: DashboardCursorSync;
|
||||
syncKey?: string;
|
||||
syncMetadata?: TooltipSyncMetadata;
|
||||
|
||||
@@ -8,6 +8,7 @@ import TooltipPlugin from '../TooltipPlugin/TooltipPlugin';
|
||||
import {
|
||||
DashboardCursorSync,
|
||||
DEFAULT_PIN_TOOLTIP_KEY,
|
||||
type TooltipPluginProps,
|
||||
} from '../TooltipPlugin/types';
|
||||
|
||||
// Avoid depending on the full uPlot + onClickPlugin behaviour in these tests.
|
||||
@@ -620,6 +621,57 @@ describe('TooltipPlugin', () => {
|
||||
|
||||
// ---- Keyboard pin edge cases ------------------------------------------------
|
||||
|
||||
describe('pin on click', () => {
|
||||
it('pins on a click shouldPinOnClick accepts, instead of calling onClick', async () => {
|
||||
const config = createConfigMock();
|
||||
const onClick = jest.fn() as jest.MockedFunction<
|
||||
NonNullable<TooltipPluginProps['onClick']>
|
||||
>;
|
||||
const shouldPinOnClick = jest.fn() as jest.MockedFunction<
|
||||
NonNullable<TooltipPluginProps['shouldPinOnClick']>
|
||||
>;
|
||||
shouldPinOnClick.mockReturnValue(true);
|
||||
const fakePlot = renderAndActivateHover(config, undefined, {
|
||||
canPinTooltip: true,
|
||||
onClick,
|
||||
shouldPinOnClick,
|
||||
});
|
||||
|
||||
act(() => {
|
||||
fakePlot.over.dispatchEvent(new MouseEvent('click', { bubbles: true }));
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('tooltip-plugin-container').dataset.pinned).toBe(
|
||||
'true',
|
||||
);
|
||||
});
|
||||
expect(shouldPinOnClick).toHaveBeenCalledTimes(1);
|
||||
expect(onClick).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('calls onClick for a click shouldPinOnClick declines', () => {
|
||||
const config = createConfigMock();
|
||||
const onClick = jest.fn() as jest.MockedFunction<
|
||||
NonNullable<TooltipPluginProps['onClick']>
|
||||
>;
|
||||
const fakePlot = renderAndActivateHover(config, undefined, {
|
||||
canPinTooltip: true,
|
||||
onClick,
|
||||
shouldPinOnClick: () => false,
|
||||
});
|
||||
|
||||
act(() => {
|
||||
fakePlot.over.dispatchEvent(new MouseEvent('click', { bubbles: true }));
|
||||
});
|
||||
|
||||
expect(onClick).toHaveBeenCalledTimes(1);
|
||||
expect(
|
||||
screen.getByTestId('tooltip-plugin-container').dataset.pinned,
|
||||
).not.toBe('true');
|
||||
});
|
||||
});
|
||||
|
||||
describe('keyboard pin edge cases', () => {
|
||||
it('does not pin when cursor coordinates are negative (cursor off-screen)', () => {
|
||||
const config = createConfigMock();
|
||||
|
||||
@@ -33,6 +33,7 @@ export default function ChartWrapper({
|
||||
canPinTooltip = false,
|
||||
pinKey,
|
||||
onClick,
|
||||
shouldPinOnClick,
|
||||
syncMode,
|
||||
syncKey,
|
||||
syncFilterMode,
|
||||
@@ -139,6 +140,7 @@ export default function ChartWrapper({
|
||||
canPinTooltip={canPinTooltip}
|
||||
pinKey={pinKey}
|
||||
onClick={onClick}
|
||||
shouldPinOnClick={shouldPinOnClick}
|
||||
syncMode={syncMode}
|
||||
maxWidth={Math.max(
|
||||
TOOLTIP_MIN_WIDTH,
|
||||
|
||||
@@ -0,0 +1,329 @@
|
||||
import { useCallback, useMemo } from 'react';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import Legend from 'lib/uPlotV2/components/Legend/Legend';
|
||||
import {
|
||||
LegendPosition,
|
||||
type TooltipRenderArgs,
|
||||
} from 'lib/uPlotV2/components/types';
|
||||
import { createBucketValueFormatter } from 'lib/uPlotV2/plugins/HeatmapPlugin/geometry';
|
||||
import type { LegendItem } from 'lib/uPlotV2/config/types';
|
||||
import { StackMode } from 'lib/uPlotV2/config/types';
|
||||
import ChartWrapper from 'lib/visualization/charts/ChartWrapper/ChartWrapper';
|
||||
import { resolveBoundaryPrecision } from 'lib/visualization/charts/Heatmap/utils';
|
||||
import { DistributionChartProps } from 'lib/visualization/charts/types';
|
||||
import { useLegendVisibility } from 'lib/visualization/hooks/useLegendVisibility';
|
||||
import type { LegendLayout } from 'lib/visualization/layout/ChartLayout/ChartLayout';
|
||||
|
||||
import { resolveOtherColor } from 'lib/visualization/charts/utils/otherGroup';
|
||||
|
||||
import { resolveSeriesColor } from './colors';
|
||||
import DistributionTooltip from './components/DistributionTooltip/DistributionTooltip';
|
||||
import { buildDistributionConfig } from './config';
|
||||
import {
|
||||
clampDistributionXAxis,
|
||||
cropDistributionXAxis,
|
||||
resolveDistributionBars,
|
||||
resolveDistributionXAxis,
|
||||
sumVisibleCounts,
|
||||
} from './layout';
|
||||
import { computeDistributionPercentiles } from './percentiles';
|
||||
import { groupIntoOther, resolveMaxDrawnGroups } from './topGroups';
|
||||
import { DistributionYScale } from './types';
|
||||
import { useDistributionBarClick } from './useDistributionBarClick';
|
||||
|
||||
import { prepareDistributionChartData } from './utils';
|
||||
|
||||
/** Rough share of the panel width the plot gets, for fitting side-by-side bars. */
|
||||
const PLOT_SHARE = 0.9;
|
||||
const PLOT_SHARE_WITH_RIGHT_LEGEND = 0.65;
|
||||
/** Vertical space the Other notice takes out of the container. */
|
||||
const NOTICE_HEIGHT = 20;
|
||||
const NO_PERCENTILES: readonly number[] = Object.freeze([]);
|
||||
|
||||
export default function Distribution({
|
||||
id,
|
||||
buckets,
|
||||
series,
|
||||
width,
|
||||
height,
|
||||
isDarkMode,
|
||||
xMin,
|
||||
xMax,
|
||||
yScale = DistributionYScale.Linear,
|
||||
stack = StackMode.Normal,
|
||||
xAxisUnit,
|
||||
decimalPrecision,
|
||||
customColors,
|
||||
percentiles = NO_PERCENTILES,
|
||||
onBarClick,
|
||||
showLegend = true,
|
||||
legendPosition = LegendPosition.BOTTOM,
|
||||
showTooltip = true,
|
||||
canPinTooltip = false,
|
||||
renderTooltipFooter,
|
||||
tooltipPortalRoot,
|
||||
layoutChildren,
|
||||
'data-testid': testId,
|
||||
}: DistributionChartProps): JSX.Element {
|
||||
const labels = useMemo(() => series.map((entry) => entry.label), [series]);
|
||||
const counts = useMemo(() => series.map((entry) => entry.counts), [series]);
|
||||
|
||||
const { visibleKeys, focusedSeriesIndex, onLegendAction } =
|
||||
useLegendVisibility({ keys: labels, indexOffset: 1, id });
|
||||
|
||||
const visible = useMemo(
|
||||
() => labels.map((label) => visibleKeys.includes(label)),
|
||||
[labels, visibleKeys],
|
||||
);
|
||||
|
||||
const colors = useMemo(
|
||||
() =>
|
||||
labels.map((label) => resolveSeriesColor(label, isDarkMode, customColors)),
|
||||
[labels, isDarkMode, customColors],
|
||||
);
|
||||
|
||||
const { xAxis, totals } = useMemo(() => {
|
||||
const fullXAxis = resolveDistributionXAxis(buckets);
|
||||
const visibleTotals = sumVisibleCounts(
|
||||
counts,
|
||||
visible,
|
||||
fullXAxis.rows.length,
|
||||
);
|
||||
// An explicit max may reach past the last occupied bucket; only auto-crop without one.
|
||||
const croppedXAxis =
|
||||
xMax === undefined
|
||||
? cropDistributionXAxis(fullXAxis, visibleTotals)
|
||||
: fullXAxis;
|
||||
return {
|
||||
xAxis: clampDistributionXAxis(croppedXAxis, xMin, xMax),
|
||||
totals: visibleTotals,
|
||||
};
|
||||
}, [buckets, xMin, xMax, counts, visible]);
|
||||
|
||||
// Over the visible groups combined, so a legend toggle moves them without a refetch.
|
||||
const markers = useMemo(
|
||||
() => computeDistributionPercentiles({ xAxis, totals, percentiles }),
|
||||
[xAxis, totals, percentiles],
|
||||
);
|
||||
|
||||
const isLogY =
|
||||
yScale === DistributionYScale.Log && stack !== StackMode.Percent;
|
||||
|
||||
// The legend lists every group; the plot draws the largest and sums the rest into
|
||||
// Other, so a toggle re-ranks without a refetch.
|
||||
const drawn = useMemo(
|
||||
() =>
|
||||
groupIntoOther({
|
||||
labels,
|
||||
counts,
|
||||
colors,
|
||||
visible,
|
||||
maxGroups: resolveMaxDrawnGroups({
|
||||
stack,
|
||||
xAxis,
|
||||
plotWidth:
|
||||
width *
|
||||
(legendPosition === LegendPosition.RIGHT
|
||||
? PLOT_SHARE_WITH_RIGHT_LEGEND
|
||||
: PLOT_SHARE),
|
||||
}),
|
||||
otherColor: resolveOtherColor(isDarkMode),
|
||||
}),
|
||||
[
|
||||
labels,
|
||||
counts,
|
||||
colors,
|
||||
visible,
|
||||
stack,
|
||||
xAxis,
|
||||
width,
|
||||
legendPosition,
|
||||
isDarkMode,
|
||||
],
|
||||
);
|
||||
|
||||
const layout = useMemo(
|
||||
() =>
|
||||
resolveDistributionBars({
|
||||
xAxis,
|
||||
counts: drawn.counts,
|
||||
stack,
|
||||
isLogY,
|
||||
}),
|
||||
[xAxis, drawn, stack, isLogY],
|
||||
);
|
||||
|
||||
const boundaryPrecision = useMemo(
|
||||
() =>
|
||||
resolveBoundaryPrecision({
|
||||
yAxis: xAxis,
|
||||
yAxisUnit: xAxisUnit,
|
||||
decimalPrecision,
|
||||
}),
|
||||
[xAxis, xAxisUnit, decimalPrecision],
|
||||
);
|
||||
|
||||
const formatBound = useMemo(
|
||||
() => createBucketValueFormatter(xAxisUnit, boundaryPrecision),
|
||||
[xAxisUnit, boundaryPrecision],
|
||||
);
|
||||
|
||||
const config = useMemo(
|
||||
() =>
|
||||
buildDistributionConfig({
|
||||
id,
|
||||
xAxis,
|
||||
layout,
|
||||
labels: drawn.labels,
|
||||
colors: drawn.colors,
|
||||
stack,
|
||||
isLogY,
|
||||
isDarkMode,
|
||||
markers,
|
||||
xAxisUnit,
|
||||
decimalPrecision: boundaryPrecision,
|
||||
}),
|
||||
[
|
||||
id,
|
||||
xAxis,
|
||||
layout,
|
||||
drawn,
|
||||
stack,
|
||||
isLogY,
|
||||
isDarkMode,
|
||||
markers,
|
||||
xAxisUnit,
|
||||
boundaryPrecision,
|
||||
],
|
||||
);
|
||||
|
||||
const otherMembers = useMemo(
|
||||
() =>
|
||||
drawn.otherSourceIndexes.map((source) => ({
|
||||
sourceIndex: source,
|
||||
label: series[source].label,
|
||||
color: colors[source],
|
||||
counts: series[source].counts,
|
||||
})),
|
||||
[drawn, series, colors],
|
||||
);
|
||||
|
||||
const {
|
||||
onClick: handleClick,
|
||||
shouldPinOnClick,
|
||||
onOtherMemberClick,
|
||||
} = useDistributionBarClick({
|
||||
xAxis,
|
||||
layout,
|
||||
drawn,
|
||||
series,
|
||||
colors,
|
||||
onBarClick,
|
||||
});
|
||||
|
||||
const renderTooltip = useCallback(
|
||||
(args: TooltipRenderArgs): React.ReactNode => (
|
||||
<DistributionTooltip
|
||||
id={id}
|
||||
uPlotInstance={args.uPlotInstance}
|
||||
isPinned={args.isPinned}
|
||||
dismiss={args.dismiss}
|
||||
xAxis={xAxis}
|
||||
layout={layout}
|
||||
labels={drawn.labels}
|
||||
colors={drawn.colors}
|
||||
counts={drawn.counts}
|
||||
otherMembers={otherMembers}
|
||||
onOtherMemberClick={onOtherMemberClick}
|
||||
formatBound={formatBound}
|
||||
renderTooltipFooter={renderTooltipFooter}
|
||||
/>
|
||||
),
|
||||
[
|
||||
id,
|
||||
xAxis,
|
||||
layout,
|
||||
drawn,
|
||||
otherMembers,
|
||||
onOtherMemberClick,
|
||||
formatBound,
|
||||
renderTooltipFooter,
|
||||
],
|
||||
);
|
||||
|
||||
const data = useMemo(
|
||||
() => prepareDistributionChartData(xAxis, drawn.counts),
|
||||
[xAxis, drawn],
|
||||
);
|
||||
|
||||
const legendItems = useMemo<LegendItem[]>(
|
||||
() =>
|
||||
labels.map((label, index) => ({
|
||||
seriesIndex: index + 1,
|
||||
label,
|
||||
color: colors[index],
|
||||
show: visible[index],
|
||||
})),
|
||||
[labels, colors, visible],
|
||||
);
|
||||
|
||||
const groupLegend = useCallback(
|
||||
({ averageLegendWidth, showSearch }: LegendLayout): React.ReactNode => (
|
||||
<Legend
|
||||
items={legendItems}
|
||||
position={legendPosition}
|
||||
averageLegendWidth={averageLegendWidth}
|
||||
showSearch={showSearch}
|
||||
itemLabel="groups"
|
||||
focusedSeriesIndex={focusedSeriesIndex}
|
||||
onAction={onLegendAction}
|
||||
/>
|
||||
),
|
||||
[legendItems, legendPosition, focusedSeriesIndex, onLegendAction],
|
||||
);
|
||||
|
||||
return (
|
||||
<ChartWrapper
|
||||
config={config}
|
||||
data={data}
|
||||
width={width}
|
||||
height={
|
||||
drawn.otherSourceIndexes.length > 0
|
||||
? Math.max(0, height - NOTICE_HEIGHT)
|
||||
: height
|
||||
}
|
||||
legendConfig={{ position: legendPosition }}
|
||||
showLegend={showLegend}
|
||||
customLegend={groupLegend}
|
||||
legendLabels={labels}
|
||||
showTooltip={showTooltip}
|
||||
canPinTooltip={canPinTooltip}
|
||||
decimalPrecision={decimalPrecision}
|
||||
customTooltip={renderTooltip}
|
||||
onClick={handleClick}
|
||||
shouldPinOnClick={shouldPinOnClick}
|
||||
contentFooter={
|
||||
drawn.otherSourceIndexes.length > 0 && (
|
||||
<Typography
|
||||
variant="paragraph"
|
||||
as="div"
|
||||
size="small"
|
||||
weight="regular"
|
||||
color="secondary"
|
||||
textOverflow="wrap"
|
||||
paddingX={4}
|
||||
paddingY={2}
|
||||
testId="distribution-other-notice"
|
||||
>
|
||||
Showing top {drawn.labels.length - 1} of {drawn.visibleGroupCount} groups;
|
||||
the rest are summed into Other.
|
||||
</Typography>
|
||||
)
|
||||
}
|
||||
renderTooltipFooter={renderTooltipFooter}
|
||||
tooltipPortalRoot={tooltipPortalRoot}
|
||||
layoutChildren={layoutChildren}
|
||||
data-testid={testId}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
import type React from 'react';
|
||||
import type { LegendItem } from 'lib/uPlotV2/config/types';
|
||||
import { StackMode } from 'lib/uPlotV2/config/types';
|
||||
import { render, screen, userEvent } from 'tests/test-utils';
|
||||
|
||||
import Distribution from '../Distribution';
|
||||
import type { DistributionSeries } from '../types';
|
||||
|
||||
// The shared Legend virtualises its items; render them all so they are queryable.
|
||||
jest.mock('react-virtuoso', () => ({
|
||||
VirtuosoGrid: ({
|
||||
data,
|
||||
itemContent,
|
||||
}: {
|
||||
data: LegendItem[];
|
||||
itemContent: (index: number, item: LegendItem) => React.ReactNode;
|
||||
}): JSX.Element => (
|
||||
<div>
|
||||
{data.map((item, index) => (
|
||||
<div key={item.seriesIndex}>{itemContent(index, item)}</div>
|
||||
))}
|
||||
</div>
|
||||
),
|
||||
}));
|
||||
|
||||
const BUCKETS = [5, 10, 100, 1000];
|
||||
|
||||
const SERIES: DistributionSeries[] = [
|
||||
{ label: 'service.name=cart', counts: [3, 40, 12, 1, 0] },
|
||||
{ label: 'service.name=checkout', counts: [1, 10, 30, 6, 2] },
|
||||
];
|
||||
|
||||
function renderDistribution(
|
||||
props: Partial<React.ComponentProps<typeof Distribution>> = {},
|
||||
): ReturnType<typeof render> {
|
||||
return render(
|
||||
<Distribution
|
||||
id="panel-1"
|
||||
buckets={BUCKETS}
|
||||
series={SERIES}
|
||||
width={800}
|
||||
height={400}
|
||||
isDarkMode
|
||||
data-testid="distribution"
|
||||
{...props}
|
||||
/>,
|
||||
);
|
||||
}
|
||||
|
||||
describe('Distribution', () => {
|
||||
// Legend items count from 1, as uPlot's data series do.
|
||||
const CART = 1;
|
||||
const CHECKOUT = 2;
|
||||
|
||||
// The selection persists under the panel id, which every case here shares.
|
||||
beforeEach(() => localStorage.clear());
|
||||
|
||||
function legendItem(seriesIndex: number): HTMLElement {
|
||||
return screen.getByTestId(`legend-item-${seriesIndex}`);
|
||||
}
|
||||
|
||||
it('lists every group in the legend, all shown', () => {
|
||||
renderDistribution();
|
||||
|
||||
expect(legendItem(CART)).toHaveAttribute('aria-checked', 'true');
|
||||
expect(legendItem(CHECKOUT)).toHaveAttribute('aria-checked', 'true');
|
||||
});
|
||||
|
||||
it('isolates a group when its row is clicked', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderDistribution();
|
||||
|
||||
await user.click(legendItem(CART));
|
||||
|
||||
expect(legendItem(CART)).toHaveAttribute('aria-checked', 'true');
|
||||
expect(legendItem(CHECKOUT)).toHaveAttribute('aria-checked', 'false');
|
||||
});
|
||||
|
||||
it('hides only that group when its marker is clicked', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderDistribution();
|
||||
|
||||
await user.click(screen.getByTestId(`legend-marker-${CHECKOUT}`));
|
||||
|
||||
expect(legendItem(CHECKOUT)).toHaveAttribute('aria-checked', 'false');
|
||||
expect(legendItem(CART)).toHaveAttribute('aria-checked', 'true');
|
||||
});
|
||||
it('sums groups past the side-by-side cap into Other, with a notice', () => {
|
||||
renderDistribution({
|
||||
stack: StackMode.None,
|
||||
series: Array.from({ length: 12 }, (_, index) => ({
|
||||
label: `group-${index}`,
|
||||
counts: [index, 1, 1, 0, 0],
|
||||
})),
|
||||
});
|
||||
|
||||
expect(screen.getByTestId('distribution-other-notice')).toHaveTextContent(
|
||||
'Showing top 9 of 12 groups; the rest are summed into Other.',
|
||||
);
|
||||
// The legend still lists every group, so any can be isolated.
|
||||
expect(legendItem(1)).toHaveAttribute('aria-label', 'group-0');
|
||||
});
|
||||
|
||||
it('stacks every group, with no Other', () => {
|
||||
renderDistribution({
|
||||
series: Array.from({ length: 12 }, (_, index) => ({
|
||||
label: `group-${index}`,
|
||||
counts: [index, 1, 1, 0, 0],
|
||||
})),
|
||||
});
|
||||
|
||||
expect(
|
||||
screen.queryByTestId('distribution-other-notice'),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows no notice when every group fits', () => {
|
||||
renderDistribution();
|
||||
|
||||
expect(
|
||||
screen.queryByTestId('distribution-other-notice'),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,130 @@
|
||||
import { StackMode } from 'lib/uPlotV2/config/types';
|
||||
import type uPlot from 'uplot';
|
||||
|
||||
import { resolveDistributionBars, resolveDistributionXAxis } from '../layout';
|
||||
import { buildDistributionConfig } from '../config';
|
||||
|
||||
// Buckets ≤ 10, (10, 20], (20, 40], > 40 in slots [0, 1] … [3, 4]. Only (10, 20] is occupied.
|
||||
const xAxis = resolveDistributionXAxis([10, 20, 40]);
|
||||
const counts = [
|
||||
[0, 4, 0, 0],
|
||||
[0, 6, 0, 0],
|
||||
];
|
||||
|
||||
function setCursorHook(drawnCounts = counts): (u: uPlot) => void {
|
||||
const config = buildDistributionConfig({
|
||||
id: 'panel-1',
|
||||
xAxis,
|
||||
layout: resolveDistributionBars({
|
||||
xAxis,
|
||||
counts: drawnCounts,
|
||||
stack: StackMode.Normal,
|
||||
isLogY: false,
|
||||
}),
|
||||
labels: drawnCounts.map((_, index) => `group-${index}`),
|
||||
colors: drawnCounts.map(() => '#ff0000'),
|
||||
stack: StackMode.Normal,
|
||||
isLogY: false,
|
||||
isDarkMode: true,
|
||||
markers: [],
|
||||
}).getConfig();
|
||||
const [hook] = config.hooks?.setCursor ?? [];
|
||||
return hook as (u: uPlot) => void;
|
||||
}
|
||||
|
||||
/** Pixels are values, so the cursor sits at `(left, top)` in scale space. */
|
||||
function plotAt(
|
||||
left: number,
|
||||
top: number,
|
||||
): {
|
||||
u: uPlot;
|
||||
setSeries: jest.MockedFunction<uPlot['setSeries']>;
|
||||
redraw: jest.MockedFunction<uPlot['redraw']>;
|
||||
} {
|
||||
const setSeries = jest.fn() as jest.MockedFunction<uPlot['setSeries']>;
|
||||
const redraw = jest.fn() as jest.MockedFunction<uPlot['redraw']>;
|
||||
const plot: Partial<uPlot> = {
|
||||
cursor: { left, top },
|
||||
posToVal: (position: number) => position,
|
||||
setSeries,
|
||||
redraw,
|
||||
};
|
||||
return { u: plot as uPlot, setSeries, redraw };
|
||||
}
|
||||
|
||||
describe('buildDistributionConfig cursor', () => {
|
||||
it('turns off drag-to-zoom', () => {
|
||||
const config = buildDistributionConfig({
|
||||
id: 'panel-1',
|
||||
xAxis,
|
||||
layout: resolveDistributionBars({
|
||||
xAxis,
|
||||
counts,
|
||||
stack: StackMode.Normal,
|
||||
isLogY: false,
|
||||
}),
|
||||
labels: ['group-0', 'group-1'],
|
||||
colors: ['#ff0000', '#ff0000'],
|
||||
stack: StackMode.Normal,
|
||||
isLogY: false,
|
||||
isDarkMode: true,
|
||||
markers: [],
|
||||
}).getConfig();
|
||||
|
||||
expect(config.cursor?.drag).toMatchObject({ x: false, y: false });
|
||||
});
|
||||
});
|
||||
|
||||
describe('buildDistributionConfig setCursor', () => {
|
||||
// TooltipPlugin only shows a tooltip for a focused series.
|
||||
it('focuses the group under the cursor, 1-based as uPlot counts series', () => {
|
||||
const { u, setSeries, redraw } = plotAt(1.5, 8);
|
||||
|
||||
setCursorHook()(u);
|
||||
|
||||
expect(setSeries).toHaveBeenCalledWith(2, { focus: true });
|
||||
expect(redraw).toHaveBeenCalledWith(true, false);
|
||||
});
|
||||
|
||||
it('focuses the nearest group above the stack, dimming the rest', () => {
|
||||
const { u, setSeries, redraw } = plotAt(1.5, 50);
|
||||
|
||||
setCursorHook()(u);
|
||||
|
||||
expect(setSeries).toHaveBeenCalledWith(2, { focus: true });
|
||||
expect(redraw).toHaveBeenCalledWith(true, false);
|
||||
});
|
||||
|
||||
it('keeps a tooltip over an empty bucket without dimming any group', () => {
|
||||
const hook = setCursorHook();
|
||||
const { u, setSeries, redraw } = plotAt(1.5, 8);
|
||||
hook(u);
|
||||
redraw.mockClear();
|
||||
|
||||
u.cursor.left = 2.5;
|
||||
u.cursor.top = 1;
|
||||
hook(u);
|
||||
|
||||
expect(setSeries).toHaveBeenLastCalledWith(1, { focus: true });
|
||||
expect(redraw).toHaveBeenCalledWith(true, false);
|
||||
});
|
||||
|
||||
it('focuses nothing off the plot', () => {
|
||||
const hook = setCursorHook();
|
||||
const { u, setSeries } = plotAt(1.5, 8);
|
||||
hook(u);
|
||||
|
||||
u.cursor.left = -1;
|
||||
hook(u);
|
||||
|
||||
expect(setSeries).toHaveBeenLastCalledWith(null, { focus: true });
|
||||
});
|
||||
|
||||
it('focuses nothing over an empty bucket when every group is hidden', () => {
|
||||
const { u, setSeries } = plotAt(2.5, 1);
|
||||
|
||||
setCursorHook([])(u);
|
||||
|
||||
expect(setSeries).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,58 @@
|
||||
import {
|
||||
layoutMarkerLabels,
|
||||
resolveHoveredMarker,
|
||||
} from '../drawPercentileMarkers';
|
||||
|
||||
describe('resolveHoveredMarker', () => {
|
||||
const areas = [
|
||||
{
|
||||
x: 100,
|
||||
badges: [
|
||||
{ left: 92, right: 108, top: 0, bottom: 16 },
|
||||
{ left: 92, right: 108, top: 184, bottom: 200 },
|
||||
],
|
||||
},
|
||||
{
|
||||
x: 120,
|
||||
badges: [{ left: 112, right: 128, top: 18, bottom: 34 }],
|
||||
},
|
||||
];
|
||||
|
||||
it('picks the line nearest x within the tolerance', () => {
|
||||
expect(resolveHoveredMarker(areas, 103, 100, 4)).toBe(0);
|
||||
expect(resolveHoveredMarker(areas, 117, 100, 4)).toBe(1);
|
||||
expect(resolveHoveredMarker(areas, 110, 100, 4)).toBeNull();
|
||||
});
|
||||
|
||||
it('picks the marker whose badge is under the cursor', () => {
|
||||
expect(resolveHoveredMarker(areas, 107, 190, 4)).toBe(0);
|
||||
expect(resolveHoveredMarker(areas, 126, 20, 4)).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('layoutMarkerLabels', () => {
|
||||
it('keeps labels that fit on the first row', () => {
|
||||
expect(
|
||||
layoutMarkerLabels(
|
||||
[
|
||||
{ x: 0, width: 20 },
|
||||
{ x: 40, width: 20 },
|
||||
],
|
||||
4,
|
||||
),
|
||||
).toStrictEqual([0, 0]);
|
||||
});
|
||||
|
||||
it('drops a label that would overlap to the next free row', () => {
|
||||
expect(
|
||||
layoutMarkerLabels(
|
||||
[
|
||||
{ x: 30, width: 20 },
|
||||
{ x: 0, width: 20 },
|
||||
{ x: 10, width: 20 },
|
||||
],
|
||||
4,
|
||||
),
|
||||
).toStrictEqual([0, 0, 1]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,294 @@
|
||||
import { StackMode } from 'lib/uPlotV2/config/types';
|
||||
|
||||
import {
|
||||
clampDistributionXAxis,
|
||||
cropDistributionXAxis,
|
||||
resolveDistributionBars,
|
||||
resolveDistributionXAxis,
|
||||
resolveNearestSeries,
|
||||
sumVisibleCounts,
|
||||
thinLabelledSplits,
|
||||
} from '../layout';
|
||||
|
||||
function widths(edges: number[]): number[] {
|
||||
return edges.slice(1).map((edge, index) => edge - edges[index]);
|
||||
}
|
||||
|
||||
describe('resolveDistributionXAxis', () => {
|
||||
it('lays N bounds out as N + 1 buckets, overflow last', () => {
|
||||
const axis = resolveDistributionXAxis([10, 20, 30]);
|
||||
|
||||
expect(axis.rows).toHaveLength(4);
|
||||
expect(axis.rows[0].isUnderflow).toBe(true);
|
||||
expect(axis.rows[3]).toMatchObject({ lower: 30, isOverflow: true });
|
||||
expect(axis.edges).toHaveLength(5);
|
||||
});
|
||||
|
||||
it('gives every bucket the same width, ticks on the bounds', () => {
|
||||
const axis = resolveDistributionXAxis([0, 5, 10, 25, 1000]);
|
||||
|
||||
expect(widths(axis.edges)).toStrictEqual([1, 1, 1, 1, 1, 1]);
|
||||
expect(axis.splits).toStrictEqual([1, 2, 3, 4, 5]);
|
||||
expect(axis.overflowSplit).toBe(6);
|
||||
expect(axis.toBucketValue(3.5)).toBe(17.5);
|
||||
});
|
||||
});
|
||||
|
||||
describe('cropDistributionXAxis', () => {
|
||||
it('stops one bucket past the last occupied one', () => {
|
||||
const axis = resolveDistributionXAxis([1, 2, 3, 4]);
|
||||
|
||||
const cropped = cropDistributionXAxis(axis, [1, 5, 0, 0, 0]);
|
||||
|
||||
expect(cropped.max).toBe(3);
|
||||
expect(cropped.overflowSplit).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('clampDistributionXAxis', () => {
|
||||
// Buckets ≤ 10, (10, 20], (20, 40], (40, 80], > 80 in slots [0, 1] … [4, 5].
|
||||
const axis = resolveDistributionXAxis([10, 20, 40, 80]);
|
||||
|
||||
it('keeps every bucket without a range', () => {
|
||||
expect(clampDistributionXAxis(axis)).toStrictEqual(axis);
|
||||
});
|
||||
|
||||
it('hides buckets wholly outside the range, keeping straddling ones whole', () => {
|
||||
const clamped = clampDistributionXAxis(axis, 20, 50);
|
||||
|
||||
expect([clamped.min, clamped.max]).toStrictEqual([2, 4]);
|
||||
expect(clamped.overflowSplit).toBeNull();
|
||||
});
|
||||
|
||||
it('keeps the overflow tick while the overflow bucket shows', () => {
|
||||
const clamped = clampDistributionXAxis(axis, 15);
|
||||
|
||||
expect([clamped.min, clamped.max]).toStrictEqual([1, 5]);
|
||||
expect(clamped.overflowSplit).toBe(5);
|
||||
});
|
||||
|
||||
it('keeps one bucket when the range misses them all', () => {
|
||||
const clamped = clampDistributionXAxis(axis, 1000);
|
||||
|
||||
expect([clamped.min, clamped.max]).toStrictEqual([4, 5]);
|
||||
});
|
||||
|
||||
it('narrows an already cropped axis, never widening it', () => {
|
||||
const cropped = cropDistributionXAxis(axis, [1, 5, 0, 0, 0]);
|
||||
|
||||
expect(clampDistributionXAxis(cropped, 15).max).toBe(cropped.max);
|
||||
});
|
||||
});
|
||||
|
||||
describe('sumVisibleCounts', () => {
|
||||
it('adds only the visible series', () => {
|
||||
expect(
|
||||
sumVisibleCounts(
|
||||
[
|
||||
[1, 2],
|
||||
[10, 20],
|
||||
[100, 200],
|
||||
],
|
||||
[true, false, true],
|
||||
2,
|
||||
),
|
||||
).toStrictEqual([101, 202]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolveDistributionBars', () => {
|
||||
const xAxis = resolveDistributionXAxis([1, 2]);
|
||||
const counts = [
|
||||
[4, 6, 0],
|
||||
[1, 3, 2],
|
||||
];
|
||||
|
||||
it('sizes the count axis by the buckets left in the window', () => {
|
||||
// Buckets ≤ 1, (1, 2], > 2; a max of 1 keeps only the first.
|
||||
const { yMax } = resolveDistributionBars({
|
||||
xAxis: clampDistributionXAxis(xAxis, undefined, 1),
|
||||
counts: [[4, 1000, 0]],
|
||||
stack: StackMode.Normal,
|
||||
isLogY: false,
|
||||
});
|
||||
|
||||
expect(yMax).toBe(4);
|
||||
});
|
||||
|
||||
it('stacks series in each bucket under normal', () => {
|
||||
const { rects, yMax } = resolveDistributionBars({
|
||||
xAxis,
|
||||
counts,
|
||||
stack: StackMode.Normal,
|
||||
isLogY: false,
|
||||
});
|
||||
|
||||
expect(rects[0].map(({ y0, y1 }) => [y0, y1])).toStrictEqual([
|
||||
[0, 4],
|
||||
[0, 6],
|
||||
]);
|
||||
expect(rects[1].map(({ y0, y1 }) => [y0, y1])).toStrictEqual([
|
||||
[4, 5],
|
||||
[6, 9],
|
||||
[0, 2],
|
||||
]);
|
||||
expect(yMax).toBe(9);
|
||||
});
|
||||
|
||||
it('marks the overflow bucket hatched', () => {
|
||||
const { rects } = resolveDistributionBars({
|
||||
xAxis,
|
||||
counts,
|
||||
stack: StackMode.Normal,
|
||||
isLogY: false,
|
||||
});
|
||||
|
||||
expect(rects[1].map(({ hatched }) => hatched)).toStrictEqual([
|
||||
false,
|
||||
false,
|
||||
true,
|
||||
]);
|
||||
});
|
||||
|
||||
it('stacks shares of each bucket under percent', () => {
|
||||
const { rects, yMax } = resolveDistributionBars({
|
||||
xAxis,
|
||||
counts,
|
||||
stack: StackMode.Percent,
|
||||
isLogY: false,
|
||||
});
|
||||
|
||||
expect(rects[0][0]).toMatchObject({ y0: 0, y1: 80 });
|
||||
expect(rects[1][0]).toMatchObject({ y0: 80, y1: 100 });
|
||||
expect(yMax).toBe(100);
|
||||
});
|
||||
|
||||
it('splits the bucket width between series under none', () => {
|
||||
const { rects, yMax } = resolveDistributionBars({
|
||||
xAxis,
|
||||
counts,
|
||||
stack: StackMode.None,
|
||||
isLogY: false,
|
||||
});
|
||||
|
||||
expect(rects[0][0]).toMatchObject({ x0: 0, x1: 0.5, y0: 0, y1: 4 });
|
||||
expect(rects[1][0]).toMatchObject({ x0: 0.5, x1: 1, y0: 0, y1: 1 });
|
||||
expect(yMax).toBe(6);
|
||||
});
|
||||
|
||||
it('starts bars at the log base and skips zero counts', () => {
|
||||
const { rects, yMin } = resolveDistributionBars({
|
||||
xAxis,
|
||||
counts,
|
||||
stack: StackMode.Normal,
|
||||
isLogY: true,
|
||||
});
|
||||
|
||||
expect(yMin).toBe(0.1);
|
||||
expect(rects[0].map(({ y0 }) => y0)).toStrictEqual([0.1, 0.1]);
|
||||
expect(rects[0].map(({ bucketIndex }) => bucketIndex)).toStrictEqual([0, 1]);
|
||||
});
|
||||
|
||||
it.each([StackMode.Normal, StackMode.None])(
|
||||
'draws a single observation on a log axis (%s)',
|
||||
(stack) => {
|
||||
const { rects } = resolveDistributionBars({
|
||||
xAxis,
|
||||
counts: [[1, 0, 0]],
|
||||
stack,
|
||||
isLogY: true,
|
||||
});
|
||||
|
||||
expect(rects[0].map(({ y0, y1 }) => [y0, y1])).toStrictEqual([[0.1, 1]]);
|
||||
},
|
||||
);
|
||||
|
||||
it('finds the log base over more counts than a call takes arguments', () => {
|
||||
const { yMin } = resolveDistributionBars({
|
||||
xAxis,
|
||||
counts: Array.from({ length: 300 }, (_, series) =>
|
||||
Array.from({ length: 1000 }, (_unused, bucket) =>
|
||||
series === 7 && bucket === 9 ? 0.5 : 2,
|
||||
),
|
||||
),
|
||||
stack: StackMode.None,
|
||||
isLogY: true,
|
||||
});
|
||||
|
||||
expect(yMin).toBe(0.01);
|
||||
});
|
||||
|
||||
it('puts the log base a decade under the smallest fractional count', () => {
|
||||
const { yMin } = resolveDistributionBars({
|
||||
xAxis,
|
||||
counts: [[0.25, 3, 0]],
|
||||
stack: StackMode.Normal,
|
||||
isLogY: true,
|
||||
});
|
||||
|
||||
expect(yMin).toBe(0.01);
|
||||
});
|
||||
});
|
||||
|
||||
describe('thinLabelledSplits', () => {
|
||||
it('keeps labels that clear each other by the gap', () => {
|
||||
expect(
|
||||
thinLabelledSplits({
|
||||
positions: [0, 50, 100],
|
||||
widths: [20, 20, 20],
|
||||
gap: 10,
|
||||
}),
|
||||
).toStrictEqual([0, 1, 2]);
|
||||
});
|
||||
|
||||
it('drops a wide label that would touch its neighbour, keeping the rightmost', () => {
|
||||
// 16.67 mins-wide labels 60 px apart: each needs 70 px of centre distance.
|
||||
expect(
|
||||
thinLabelledSplits({
|
||||
positions: [0, 60, 120, 180],
|
||||
widths: [60, 60, 60, 60],
|
||||
gap: 10,
|
||||
}),
|
||||
).toStrictEqual([1, 3]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolveNearestSeries', () => {
|
||||
// Buckets ≤ 10, (10, 20], (20, 40], > 40 in slots [0, 1] … [3, 4].
|
||||
const xAxis = resolveDistributionXAxis([10, 20, 40]);
|
||||
const counts = [
|
||||
[0, 4, 0, 0],
|
||||
[0, 6, 0, 0],
|
||||
];
|
||||
const stacked = resolveDistributionBars({
|
||||
xAxis,
|
||||
counts,
|
||||
stack: StackMode.Normal,
|
||||
isLogY: false,
|
||||
});
|
||||
|
||||
it('names the group whose bar is under the point', () => {
|
||||
expect(resolveNearestSeries(stacked, 1, 1.5, 2)).toBe(0);
|
||||
expect(resolveNearestSeries(stacked, 1, 1.5, 8)).toBe(1);
|
||||
});
|
||||
|
||||
it('takes the vertically nearest group off the bars, as a bar chart does', () => {
|
||||
expect(resolveNearestSeries(stacked, 1, 1.5, 50)).toBe(1);
|
||||
});
|
||||
|
||||
it('is null over an empty bucket', () => {
|
||||
expect(resolveNearestSeries(stacked, 2, 2.5, 1)).toBeNull();
|
||||
});
|
||||
|
||||
it('picks the sub-bar under the cursor side by side', () => {
|
||||
const sideBySide = resolveDistributionBars({
|
||||
xAxis,
|
||||
counts,
|
||||
stack: StackMode.None,
|
||||
isLogY: false,
|
||||
});
|
||||
|
||||
expect(resolveNearestSeries(sideBySide, 1, 1.25, 50)).toBe(0);
|
||||
expect(resolveNearestSeries(sideBySide, 1, 1.75, 1)).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,105 @@
|
||||
import { resolveDistributionXAxis } from '../layout';
|
||||
import {
|
||||
computeDistributionPercentiles,
|
||||
formatPercentileBadge,
|
||||
formatPercentileName,
|
||||
formatPercentileValue,
|
||||
groupPercentileMarkers,
|
||||
} from '../percentiles';
|
||||
|
||||
// Buckets ≤ 10, (10, 20], (20, 40], > 40 in slots [0, 1] … [3, 4].
|
||||
const xAxis = resolveDistributionXAxis([10, 20, 40]);
|
||||
|
||||
describe('computeDistributionPercentiles', () => {
|
||||
it('interpolates inside the bucket holding the rank, as histogram_quantile does', () => {
|
||||
const markers = computeDistributionPercentiles({
|
||||
xAxis,
|
||||
totals: [10, 20, 10, 0],
|
||||
percentiles: [50, 90],
|
||||
});
|
||||
|
||||
expect(markers.map(({ value }) => value)).toStrictEqual([15, 32]);
|
||||
expect(markers.every(({ isOverflow }) => !isOverflow)).toBe(true);
|
||||
});
|
||||
|
||||
it('places the marker the same fraction across the bucket on the axis', () => {
|
||||
const [p50] = computeDistributionPercentiles({
|
||||
xAxis,
|
||||
totals: [10, 20, 10, 0],
|
||||
percentiles: [50],
|
||||
});
|
||||
|
||||
expect(p50.axisValue).toBe(1.5);
|
||||
});
|
||||
|
||||
it('starts the lowest bucket at zero', () => {
|
||||
const [p10] = computeDistributionPercentiles({
|
||||
xAxis,
|
||||
totals: [10, 20, 10, 0],
|
||||
percentiles: [10],
|
||||
});
|
||||
|
||||
expect(p10.value).toBe(4);
|
||||
});
|
||||
|
||||
it('reports a percentile in overflow as above the last bound, at its left edge', () => {
|
||||
const [p99] = computeDistributionPercentiles({
|
||||
xAxis,
|
||||
totals: [0, 0, 10, 10],
|
||||
percentiles: [99],
|
||||
});
|
||||
|
||||
expect(p99).toMatchObject({ value: 40, axisValue: 3, isOverflow: true });
|
||||
});
|
||||
|
||||
it('marks nothing when every count is zero', () => {
|
||||
expect(
|
||||
computeDistributionPercentiles({
|
||||
xAxis,
|
||||
totals: [0, 0, 0, 0],
|
||||
percentiles: [50],
|
||||
}),
|
||||
).toStrictEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('formatPercentileName', () => {
|
||||
it('keeps fractional percentile names short', () => {
|
||||
expect(formatPercentileName(99.9)).toBe('p99.9');
|
||||
expect(formatPercentileName(50)).toBe('p50');
|
||||
});
|
||||
});
|
||||
|
||||
describe('percentile marker groups', () => {
|
||||
const formatBound = (value: number): string => `${value} ms`;
|
||||
const p50 = { percentile: 50, value: 15, axisValue: 1.5, isOverflow: false };
|
||||
const p99 = { percentile: 99, value: 40, axisValue: 3, isOverflow: true };
|
||||
const p90 = { percentile: 90, value: 40, axisValue: 3, isOverflow: true };
|
||||
|
||||
it('groups markers on the same spot, lowest percentile first', () => {
|
||||
expect(groupPercentileMarkers([p50, p99, p90])).toStrictEqual([
|
||||
[p50],
|
||||
[p90, p99],
|
||||
]);
|
||||
});
|
||||
|
||||
it('names a group by its lowest percentile', () => {
|
||||
expect(formatPercentileBadge([p50])).toBe('p50');
|
||||
expect(formatPercentileBadge([p90, p99])).toBe('p90+');
|
||||
});
|
||||
|
||||
it('shows the estimate, or the overflow bound once for the group', () => {
|
||||
expect(formatPercentileValue([p50], formatBound)).toBe('p50 ≈ 15 ms');
|
||||
expect(formatPercentileValue([p90, p99], formatBound)).toBe(
|
||||
'p90, p99 > 40 ms',
|
||||
);
|
||||
});
|
||||
|
||||
it('keeps an estimate ending at the overflow edge apart from the overflow', () => {
|
||||
const p90AtEdge = { ...p90, isOverflow: false };
|
||||
|
||||
expect(formatPercentileValue([p90AtEdge, p99], formatBound)).toBe(
|
||||
'p90 ≈ 40 ms, p99 > 40 ms',
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,135 @@
|
||||
import { StackMode } from 'lib/uPlotV2/config/types';
|
||||
import { OTHER_GROUP_LABEL } from 'lib/visualization/charts/utils/otherGroup';
|
||||
|
||||
import { resolveDistributionXAxis } from '../layout';
|
||||
import {
|
||||
groupIntoOther,
|
||||
resolveClickedGroup,
|
||||
MAX_SIDE_BY_SIDE_GROUPS,
|
||||
resolveMaxDrawnGroups,
|
||||
} from '../topGroups';
|
||||
|
||||
describe('resolveMaxDrawnGroups', () => {
|
||||
// Four equal buckets plus underflow and overflow: six slots of one unit each.
|
||||
const xAxis = resolveDistributionXAxis([1, 2, 3, 4, 5]);
|
||||
|
||||
it('draws every group when stacked or percent', () => {
|
||||
expect(
|
||||
resolveMaxDrawnGroups({ stack: StackMode.Normal, xAxis, plotWidth: 60 }),
|
||||
).toBe(Number.POSITIVE_INFINITY);
|
||||
expect(
|
||||
resolveMaxDrawnGroups({ stack: StackMode.Percent, xAxis, plotWidth: 60 }),
|
||||
).toBe(Number.POSITIVE_INFINITY);
|
||||
});
|
||||
|
||||
it('caps side by side at the fixed limit, however wide', () => {
|
||||
expect(
|
||||
resolveMaxDrawnGroups({ stack: StackMode.None, xAxis, plotWidth: 6000 }),
|
||||
).toBe(MAX_SIDE_BY_SIDE_GROUPS);
|
||||
});
|
||||
|
||||
it('fits side by side so the narrowest bar stays 3 px wide', () => {
|
||||
// 120 px over six slots: 20 px a bucket, six 3 px bars.
|
||||
expect(
|
||||
resolveMaxDrawnGroups({ stack: StackMode.None, xAxis, plotWidth: 120 }),
|
||||
).toBe(6);
|
||||
expect(
|
||||
resolveMaxDrawnGroups({ stack: StackMode.None, xAxis, plotWidth: 6 }),
|
||||
).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('groupIntoOther', () => {
|
||||
const args = {
|
||||
labels: ['a', 'b', 'c', 'd'],
|
||||
counts: [
|
||||
[1, 1],
|
||||
[5, 5],
|
||||
[2, 0],
|
||||
[3, 3],
|
||||
],
|
||||
colors: ['#a', '#b', '#c', '#d'],
|
||||
visible: [true, true, true, true],
|
||||
otherColor: '#999',
|
||||
};
|
||||
|
||||
it('draws every visible group when they fit', () => {
|
||||
const drawn = groupIntoOther({ ...args, maxGroups: 4 });
|
||||
|
||||
expect(drawn.labels).toStrictEqual(['a', 'b', 'c', 'd']);
|
||||
expect(drawn.otherSourceIndexes).toStrictEqual([]);
|
||||
});
|
||||
|
||||
it('keeps the largest, in legend order, and sums the rest exactly', () => {
|
||||
const drawn = groupIntoOther({ ...args, maxGroups: 3 });
|
||||
|
||||
expect(drawn.labels).toStrictEqual(['b', 'd', OTHER_GROUP_LABEL]);
|
||||
expect(drawn.sourceIndexes).toStrictEqual([1, 3, null]);
|
||||
expect(drawn.counts[2]).toStrictEqual([3, 1]);
|
||||
expect(drawn.colors[2]).toBe('#999');
|
||||
expect(drawn).toMatchObject({
|
||||
otherSourceIndexes: [0, 2],
|
||||
visibleGroupCount: 4,
|
||||
});
|
||||
});
|
||||
|
||||
it('re-ranks without hidden groups, which never reach Other', () => {
|
||||
const drawn = groupIntoOther({
|
||||
...args,
|
||||
visible: [true, false, true, true],
|
||||
maxGroups: 2,
|
||||
});
|
||||
|
||||
expect(drawn.labels).toStrictEqual(['d', OTHER_GROUP_LABEL]);
|
||||
expect(drawn.sourceIndexes).toStrictEqual([3, null]);
|
||||
expect(drawn.counts[1]).toStrictEqual([3, 1]);
|
||||
expect(drawn.visibleGroupCount).toBe(3);
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolveClickedGroup', () => {
|
||||
const series = ['a', 'b', 'c'].map((label) => ({
|
||||
label,
|
||||
counts: [label === 'a' ? 5 : 1],
|
||||
}));
|
||||
const drawn = groupIntoOther({
|
||||
labels: ['a', 'b', 'c'],
|
||||
counts: series.map(({ counts }) => counts),
|
||||
colors: ['#a', '#b', '#c'],
|
||||
visible: [true, true, true],
|
||||
maxGroups: 2,
|
||||
otherColor: '#999',
|
||||
});
|
||||
|
||||
it('maps a drawn bar back to its source group and colour', () => {
|
||||
expect(resolveClickedGroup(drawn, 0, series)).toStrictEqual({
|
||||
series: series[0],
|
||||
color: '#a',
|
||||
});
|
||||
});
|
||||
|
||||
it('refuses Other and empty space', () => {
|
||||
expect(resolveClickedGroup(drawn, 1, series)).toBeNull();
|
||||
expect(resolveClickedGroup(drawn, null, series)).toBeNull();
|
||||
});
|
||||
|
||||
it('maps by source index, not label, when groups share a legend', () => {
|
||||
const twins = [
|
||||
{ label: 'Other', groupLabels: { pod: 'a' }, counts: [1] },
|
||||
{ label: 'Other', groupLabels: { pod: 'b' }, counts: [2] },
|
||||
];
|
||||
const drawnTwins = groupIntoOther({
|
||||
labels: twins.map(({ label }) => label),
|
||||
counts: twins.map(({ counts }) => counts),
|
||||
colors: ['#a', '#b'],
|
||||
visible: [true, true],
|
||||
maxGroups: 2,
|
||||
otherColor: '#999',
|
||||
});
|
||||
|
||||
expect(resolveClickedGroup(drawnTwins, 1, twins)).toStrictEqual({
|
||||
series: twins[1],
|
||||
color: '#b',
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,118 @@
|
||||
import { StackMode } from 'lib/uPlotV2/config/types';
|
||||
import type { ChartClickData } from 'lib/uPlotV2/plugins/TooltipPlugin/types';
|
||||
import { renderHook } from 'tests/test-utils';
|
||||
|
||||
import { resolveDistributionBars, resolveDistributionXAxis } from '../layout';
|
||||
import { groupIntoOther } from '../topGroups';
|
||||
import type { DistributionSeries, UseDistributionBarClickArgs } from '../types';
|
||||
import { useDistributionBarClick } from '../useDistributionBarClick';
|
||||
|
||||
// Buckets ≤ 10, (10, 20], (20, 40], > 40. In (10, 20], `a` stacks 0–5 and Other
|
||||
// (`b` + `c`) 5–8.
|
||||
const xAxis = resolveDistributionXAxis([10, 20, 40]);
|
||||
const series: DistributionSeries[] = [
|
||||
{ label: 'a', counts: [0, 5, 0, 0] },
|
||||
{ label: 'b', counts: [0, 2, 0, 0] },
|
||||
{ label: 'c', counts: [0, 1, 0, 0] },
|
||||
];
|
||||
const colors = ['#a', '#b', '#c'];
|
||||
const drawn = groupIntoOther({
|
||||
labels: series.map(({ label }) => label),
|
||||
counts: series.map(({ counts }) => counts),
|
||||
colors,
|
||||
visible: [true, true, true],
|
||||
maxGroups: 2,
|
||||
otherColor: '#999',
|
||||
});
|
||||
const layout = resolveDistributionBars({
|
||||
xAxis,
|
||||
counts: drawn.counts,
|
||||
stack: StackMode.Normal,
|
||||
isLogY: false,
|
||||
});
|
||||
|
||||
const clickAt = (xValue: number, yValue: number): ChartClickData => ({
|
||||
xValue,
|
||||
yValue,
|
||||
focusedSeries: null,
|
||||
clickedDataTimestamp: 0,
|
||||
mouseX: 0,
|
||||
mouseY: 0,
|
||||
absoluteMouseX: 40,
|
||||
absoluteMouseY: 60,
|
||||
});
|
||||
|
||||
describe('useDistributionBarClick', () => {
|
||||
it('pins on a click over Other, and only there', () => {
|
||||
const { result } = renderHook(() =>
|
||||
useDistributionBarClick({ xAxis, layout, drawn, series, colors }),
|
||||
);
|
||||
|
||||
expect(result.current.shouldPinOnClick?.(clickAt(1.5, 6.5))).toBe(true);
|
||||
expect(result.current.shouldPinOnClick?.(clickAt(1.5, 2))).toBe(false);
|
||||
});
|
||||
|
||||
it('drills into a drawn group, never into Other', () => {
|
||||
const onBarClick = jest.fn() as jest.MockedFunction<
|
||||
NonNullable<UseDistributionBarClickArgs['onBarClick']>
|
||||
>;
|
||||
const { result } = renderHook(() =>
|
||||
useDistributionBarClick({
|
||||
xAxis,
|
||||
layout,
|
||||
drawn,
|
||||
series,
|
||||
colors,
|
||||
onBarClick,
|
||||
}),
|
||||
);
|
||||
|
||||
result.current.onClick?.(clickAt(1.5, 6.5));
|
||||
result.current.onClick?.(clickAt(1.5, 2));
|
||||
|
||||
expect(onBarClick).toHaveBeenCalledTimes(1);
|
||||
expect(onBarClick).toHaveBeenCalledWith({
|
||||
series: series[0],
|
||||
color: '#a',
|
||||
coordinates: { x: 40, y: 60 },
|
||||
});
|
||||
});
|
||||
|
||||
it('pins nothing when no group is summed into Other', () => {
|
||||
const { result } = renderHook(() =>
|
||||
useDistributionBarClick({
|
||||
xAxis,
|
||||
layout,
|
||||
drawn: { ...drawn, otherSourceIndexes: [] },
|
||||
series,
|
||||
colors,
|
||||
}),
|
||||
);
|
||||
|
||||
expect(result.current.shouldPinOnClick).toBeUndefined();
|
||||
});
|
||||
|
||||
it('drills into a group picked out of Other, with its own colour', () => {
|
||||
const onBarClick = jest.fn() as jest.MockedFunction<
|
||||
NonNullable<UseDistributionBarClickArgs['onBarClick']>
|
||||
>;
|
||||
const { result } = renderHook(() =>
|
||||
useDistributionBarClick({
|
||||
xAxis,
|
||||
layout,
|
||||
drawn,
|
||||
series,
|
||||
colors,
|
||||
onBarClick,
|
||||
}),
|
||||
);
|
||||
|
||||
result.current.onOtherMemberClick?.(2, { x: 5, y: 6 });
|
||||
|
||||
expect(onBarClick).toHaveBeenCalledWith({
|
||||
series: series[2],
|
||||
color: '#c',
|
||||
coordinates: { x: 5, y: 6 },
|
||||
});
|
||||
});
|
||||
});
|
||||
23
frontend/src/lib/visualization/charts/Distribution/colors.ts
Normal file
23
frontend/src/lib/visualization/charts/Distribution/colors.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
import { themeColors } from 'constants/theme';
|
||||
import { generateColor } from 'lib/uPlotLib/utils/generateColor';
|
||||
import { toAlphaHex } from 'lib/uPlotV2/utils/fillOpacity';
|
||||
|
||||
const HEX_COLOR = /^#[0-9a-f]{6}$/i;
|
||||
|
||||
export function withOpacity(color: string, opacity: number): string {
|
||||
return HEX_COLOR.test(color) ? `${color}${toAlphaHex(opacity)}` : color;
|
||||
}
|
||||
|
||||
export function resolveSeriesColor(
|
||||
label: string,
|
||||
isDarkMode: boolean,
|
||||
customColors?: Record<string, string>,
|
||||
): string {
|
||||
return (
|
||||
customColors?.[label] ??
|
||||
generateColor(
|
||||
label,
|
||||
isDarkMode ? themeColors.chartcolors : themeColors.lightModeColor,
|
||||
)
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
// Same surface as the shared and heatmap tooltips.
|
||||
.container {
|
||||
--gutter: 14px;
|
||||
--row-inset: 6px;
|
||||
|
||||
font-family: 'Inter';
|
||||
font-size: 12px;
|
||||
background: var(--l2-background);
|
||||
-webkit-font-smoothing: antialiased;
|
||||
color: var(--l2-foreground);
|
||||
border-radius: 6px;
|
||||
border: 1px solid var(--l2-border);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-width: 240px;
|
||||
|
||||
&.pinned {
|
||||
border-color: var(--ring);
|
||||
}
|
||||
}
|
||||
|
||||
.divider {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 1px;
|
||||
background-color: var(--l2-border);
|
||||
}
|
||||
|
||||
// Same as the heatmap tooltip's bucket row.
|
||||
.title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--spacing-2);
|
||||
padding: var(--spacing-6) var(--gutter);
|
||||
}
|
||||
|
||||
.titleBucket,
|
||||
.titleCount {
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--font-size-xs);
|
||||
font-weight: 700;
|
||||
letter-spacing: -0.01em;
|
||||
color: var(--popover-foreground);
|
||||
white-space: nowrap;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.titleSeparator {
|
||||
flex: 1;
|
||||
border-width: 0.5px;
|
||||
border-style: dashed;
|
||||
border-color: currentColor;
|
||||
min-width: 24px;
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
// Same inset as the time-series tooltip's active row.
|
||||
.activeItem {
|
||||
padding: 0 var(--spacing-4) var(--spacing-4);
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
import { useCallback, useMemo } from 'react';
|
||||
import type { MouseEvent as ReactMouseEvent } from 'react';
|
||||
import cx from 'classnames';
|
||||
import TooltipItem from 'lib/uPlotV2/components/Tooltip/components/TooltipItem/TooltipItem';
|
||||
import TooltipList from 'lib/uPlotV2/components/Tooltip/components/TooltipList/TooltipList';
|
||||
import TooltipPinnedBadge from 'lib/uPlotV2/components/Tooltip/components/TooltipPinnedBadge/TooltipPinnedBadge';
|
||||
import GroupedTooltipFooter from 'lib/visualization/panels/components/GroupedTooltipFooter';
|
||||
import {
|
||||
formatRowLabel,
|
||||
resolveRowIndex,
|
||||
} from 'lib/uPlotV2/plugins/HeatmapPlugin/geometry';
|
||||
|
||||
import { resolveNearestSeries } from '../../layout';
|
||||
import {
|
||||
buildDistributionTooltipItems,
|
||||
buildOtherMemberItems,
|
||||
} from './distributionTooltipContent';
|
||||
import { DistributionTooltipProps } from './types';
|
||||
|
||||
import Styles from './DistributionTooltip.module.scss';
|
||||
|
||||
/**
|
||||
* Laid out like the time-series tooltip: the hovered group above the divider, every
|
||||
* group below it, largest first. Over Other, the list is the groups Other sums, as
|
||||
* on Pie. The bucket comes from the live cursor, not uPlot's `cursor.idx`: that
|
||||
* snaps to the nearest bucket centre, which on uneven widths is often the neighbour.
|
||||
*/
|
||||
export default function DistributionTooltip({
|
||||
id,
|
||||
uPlotInstance,
|
||||
xAxis,
|
||||
layout,
|
||||
labels,
|
||||
colors,
|
||||
counts,
|
||||
otherMembers,
|
||||
onOtherMemberClick,
|
||||
formatBound,
|
||||
isPinned,
|
||||
dismiss,
|
||||
renderTooltipFooter,
|
||||
}: DistributionTooltipProps): JSX.Element | null {
|
||||
// Read outside the memo: uPlot mutates the same instance on every move.
|
||||
const { left = -10, top = -10 } = uPlotInstance.cursor;
|
||||
|
||||
const hover = useMemo(() => {
|
||||
if (left < 0 || top < 0) {
|
||||
return null;
|
||||
}
|
||||
const x = uPlotInstance.posToVal(left, 'x');
|
||||
const bucket = resolveRowIndex(xAxis.edges, x);
|
||||
if (bucket === null) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
bucket,
|
||||
series: resolveNearestSeries(
|
||||
layout,
|
||||
bucket,
|
||||
x,
|
||||
uPlotInstance.posToVal(top, 'y'),
|
||||
),
|
||||
};
|
||||
}, [left, top, uPlotInstance, xAxis, layout]);
|
||||
|
||||
// Other is drawn last.
|
||||
const otherIndex = otherMembers.length > 0 ? labels.length - 1 : null;
|
||||
const isOtherHovered = otherIndex !== null && hover?.series === otherIndex;
|
||||
|
||||
const content = useMemo(() => {
|
||||
if (!hover) {
|
||||
return null;
|
||||
}
|
||||
const { active, items } = buildDistributionTooltipItems({
|
||||
labels,
|
||||
colors,
|
||||
counts,
|
||||
bucket: hover.bucket,
|
||||
hoveredSeries: hover.series,
|
||||
formatLabel: (label, series) =>
|
||||
series === otherIndex ? `${label} (${otherMembers.length})` : label,
|
||||
});
|
||||
const total = items.reduce((sum, item) => sum + item.value, 0);
|
||||
if (!isOtherHovered) {
|
||||
return { active, items, total, members: [] };
|
||||
}
|
||||
const members = buildOtherMemberItems({
|
||||
members: otherMembers,
|
||||
bucket: hover.bucket,
|
||||
});
|
||||
return {
|
||||
active,
|
||||
items: members.map(({ item }) => item),
|
||||
total,
|
||||
members,
|
||||
};
|
||||
}, [hover, labels, colors, counts, otherIndex, otherMembers, isOtherHovered]);
|
||||
|
||||
// The menu opens where the tooltip was, which closes first.
|
||||
const handleMemberClick = useCallback(
|
||||
(index: number, event: ReactMouseEvent): void => {
|
||||
const rect = (event.currentTarget as Element)
|
||||
.closest('[data-distribution-tooltip]')
|
||||
?.getBoundingClientRect();
|
||||
const member = content?.members[index];
|
||||
dismiss();
|
||||
if (member) {
|
||||
onOtherMemberClick?.(member.sourceIndex, {
|
||||
x: rect?.left ?? event.clientX,
|
||||
y: rect?.top ?? event.clientY,
|
||||
});
|
||||
}
|
||||
},
|
||||
[content, dismiss, onOtherMemberClick],
|
||||
);
|
||||
|
||||
if (!hover || !content) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const canPickMember = isOtherHovered && isPinned && !!onOtherMemberClick;
|
||||
// As in the shared tooltip, a lone row that is the active one collapses into it.
|
||||
const shouldShowList =
|
||||
content.items.length > 1 ||
|
||||
(content.items.length === 1 && content.active === null);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cx(Styles.container, { [Styles.pinned]: isPinned })}
|
||||
data-pinned={isPinned}
|
||||
data-distribution-tooltip
|
||||
data-testid="distribution-tooltip"
|
||||
>
|
||||
<div className={Styles.title}>
|
||||
<span
|
||||
className={Styles.titleBucket}
|
||||
data-testid="distribution-tooltip-range"
|
||||
>
|
||||
{formatRowLabel(xAxis.rows[hover.bucket], formatBound)}
|
||||
</span>
|
||||
<span className={Styles.titleSeparator} />
|
||||
<span
|
||||
className={Styles.titleCount}
|
||||
data-testid="distribution-tooltip-total"
|
||||
>
|
||||
{content.total.toLocaleString()}
|
||||
</span>
|
||||
{isPinned && <TooltipPinnedBadge />}
|
||||
</div>
|
||||
|
||||
{content.active && (
|
||||
<div className={Styles.activeItem}>
|
||||
<TooltipItem
|
||||
item={content.active}
|
||||
isItemActive
|
||||
containerTestId="distribution-tooltip-active"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{shouldShowList && content.active && <span className={Styles.divider} />}
|
||||
|
||||
{shouldShowList && (
|
||||
<TooltipList
|
||||
id={id}
|
||||
content={content.items}
|
||||
onItemClick={canPickMember ? handleMemberClick : undefined}
|
||||
/>
|
||||
)}
|
||||
|
||||
{isOtherHovered ? (
|
||||
<GroupedTooltipFooter
|
||||
isGroup
|
||||
isPinned={isPinned}
|
||||
canDrilldown={!!onOtherMemberClick}
|
||||
onUnpin={dismiss}
|
||||
/>
|
||||
) : (
|
||||
renderTooltipFooter?.({ isPinned, dismiss })
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
import { StackMode } from 'lib/uPlotV2/config/types';
|
||||
import {
|
||||
resolveDistributionBars,
|
||||
resolveDistributionXAxis,
|
||||
} from 'lib/visualization/charts/Distribution/layout';
|
||||
import { render, screen, userEvent, within } from 'tests/test-utils';
|
||||
import type uPlot from 'uplot';
|
||||
|
||||
import DistributionTooltip from '../DistributionTooltip';
|
||||
|
||||
// Virtuoso only renders a window in jsdom; render every row.
|
||||
jest.mock('react-virtuoso', () => ({
|
||||
Virtuoso: ({
|
||||
data,
|
||||
itemContent,
|
||||
'data-testid': testId,
|
||||
}: {
|
||||
data: unknown[];
|
||||
itemContent: (index: number, item: unknown) => React.ReactNode;
|
||||
'data-testid'?: string;
|
||||
}): JSX.Element => (
|
||||
<div data-testid={testId}>
|
||||
{data.map((item, index) => (
|
||||
// eslint-disable-next-line react/no-array-index-key
|
||||
<div key={index}>{itemContent(index, item)}</div>
|
||||
))}
|
||||
</div>
|
||||
),
|
||||
}));
|
||||
import type { DistributionTooltipProps } from '../types';
|
||||
|
||||
// Buckets ≤ 10, (10, 20], (20, 40], > 40 in slots [0, 1] … [3, 4].
|
||||
const xAxis = resolveDistributionXAxis([10, 20, 40]);
|
||||
const counts = [
|
||||
[1, 4, 2, 0],
|
||||
[0, 6, 1, 1],
|
||||
];
|
||||
const layout = resolveDistributionBars({
|
||||
xAxis,
|
||||
counts,
|
||||
stack: StackMode.Normal,
|
||||
isLogY: false,
|
||||
});
|
||||
|
||||
/** Pixels are values: the cursor at (1.5, 2) is over the first group in (10, 20]. */
|
||||
function plotAt(left: number, top: number): uPlot {
|
||||
const plot: Partial<uPlot> = {
|
||||
cursor: { left, top },
|
||||
posToVal: (position: number) => position,
|
||||
};
|
||||
return plot as uPlot;
|
||||
}
|
||||
|
||||
function renderTooltip(
|
||||
uPlotInstance: uPlot,
|
||||
overrides: Partial<DistributionTooltipProps> = {},
|
||||
): void {
|
||||
render(
|
||||
<DistributionTooltip
|
||||
id="panel-1"
|
||||
uPlotInstance={uPlotInstance}
|
||||
isPinned={false}
|
||||
dismiss={jest.fn()}
|
||||
xAxis={xAxis}
|
||||
layout={layout}
|
||||
labels={['{service.name="cart"}', '{service.name="checkout"}']}
|
||||
colors={['#f00', '#0f0']}
|
||||
counts={counts}
|
||||
otherMembers={[]}
|
||||
formatBound={(value): string => `${value} ms`}
|
||||
{...overrides}
|
||||
/>,
|
||||
);
|
||||
}
|
||||
|
||||
/** The second drawn group is Other, summing `ad` and `quote`. */
|
||||
const withOther: Partial<DistributionTooltipProps> = {
|
||||
labels: ['{service.name="cart"}', 'Other'],
|
||||
otherMembers: [
|
||||
{
|
||||
sourceIndex: 3,
|
||||
label: '{service.name="ad"}',
|
||||
color: '#00f',
|
||||
counts: [0, 4, 1, 0],
|
||||
},
|
||||
{
|
||||
sourceIndex: 5,
|
||||
label: '{service.name="quote"}',
|
||||
color: '#ff0',
|
||||
counts: [0, 2, 0, 1],
|
||||
},
|
||||
],
|
||||
};
|
||||
/** In (10, 20], above cart's 4: over Other. */
|
||||
const overOther = (): uPlot => plotAt(1.5, 7);
|
||||
|
||||
describe('DistributionTooltip', () => {
|
||||
const listRows = (): string[] =>
|
||||
within(screen.getByTestId('uplot-tooltip-list'))
|
||||
.getAllByTestId('uplot-tooltip-item-content')
|
||||
.map((row) => row.textContent ?? '');
|
||||
|
||||
it('names the bucket under the cursor and its total', () => {
|
||||
renderTooltip(plotAt(1.5, 2));
|
||||
|
||||
expect(screen.getByTestId('distribution-tooltip-range')).toHaveTextContent(
|
||||
'10 ms – 20 ms',
|
||||
);
|
||||
expect(screen.getByTestId('distribution-tooltip-total')).toHaveTextContent(
|
||||
'10',
|
||||
);
|
||||
});
|
||||
|
||||
it('puts the hovered group above the list, which runs largest first, with full labels', () => {
|
||||
renderTooltip(plotAt(1.5, 2));
|
||||
|
||||
expect(screen.getByTestId('distribution-tooltip-active')).toHaveTextContent(
|
||||
'{service.name="cart"}4',
|
||||
);
|
||||
expect(listRows()).toStrictEqual([
|
||||
'{service.name="checkout"}6',
|
||||
'{service.name="cart"}4',
|
||||
]);
|
||||
});
|
||||
|
||||
it('shows a single group only above the divider, as the time-series tooltip does', () => {
|
||||
renderTooltip(plotAt(1.5, 2), {
|
||||
labels: ['A'],
|
||||
colors: ['#f00'],
|
||||
counts: [counts[0]],
|
||||
});
|
||||
|
||||
expect(screen.getByTestId('distribution-tooltip-active')).toHaveTextContent(
|
||||
'A4',
|
||||
);
|
||||
expect(screen.queryByTestId('uplot-tooltip-list')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders nothing off the plot', () => {
|
||||
renderTooltip(plotAt(-1, -1));
|
||||
|
||||
expect(screen.queryByTestId('distribution-tooltip')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('lists the groups Other sums while Other is hovered', () => {
|
||||
renderTooltip(overOther(), withOther);
|
||||
|
||||
expect(screen.getByTestId('distribution-tooltip-active')).toHaveTextContent(
|
||||
'Other (2)6',
|
||||
);
|
||||
expect(listRows()).toStrictEqual([
|
||||
'{service.name="ad"}4',
|
||||
'{service.name="quote"}2',
|
||||
]);
|
||||
});
|
||||
|
||||
it('drills into a group of Other picked from the pinned tooltip', async () => {
|
||||
const dismiss = jest.fn() as jest.MockedFunction<
|
||||
DistributionTooltipProps['dismiss']
|
||||
>;
|
||||
const onOtherMemberClick = jest.fn() as jest.MockedFunction<
|
||||
NonNullable<DistributionTooltipProps['onOtherMemberClick']>
|
||||
>;
|
||||
renderTooltip(overOther(), {
|
||||
...withOther,
|
||||
isPinned: true,
|
||||
dismiss,
|
||||
onOtherMemberClick,
|
||||
});
|
||||
|
||||
expect(screen.getByTestId('grouped-tooltip-footer')).toHaveTextContent(
|
||||
'Click a series to drilldown',
|
||||
);
|
||||
await userEvent
|
||||
.setup()
|
||||
.click(screen.getAllByTestId('uplot-tooltip-item-button')[1]);
|
||||
|
||||
expect(dismiss).toHaveBeenCalledTimes(1);
|
||||
expect(onOtherMemberClick).toHaveBeenCalledWith(5, { x: 0, y: 0 });
|
||||
});
|
||||
|
||||
it('asks for a click on Other to pin it before a group can be picked', () => {
|
||||
renderTooltip(overOther(), {
|
||||
...withOther,
|
||||
onOtherMemberClick: jest.fn(),
|
||||
});
|
||||
|
||||
expect(screen.getByTestId('grouped-tooltip-footer')).toHaveTextContent(
|
||||
'Click to pin, then pick a series',
|
||||
);
|
||||
expect(
|
||||
screen.queryByTestId('uplot-tooltip-item-button'),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,78 @@
|
||||
import {
|
||||
buildDistributionTooltipItems,
|
||||
buildOtherMemberItems,
|
||||
} from '../distributionTooltipContent';
|
||||
|
||||
describe('buildDistributionTooltipItems', () => {
|
||||
it('sorts the groups largest first and returns the hovered one as active', () => {
|
||||
const { active, items } = buildDistributionTooltipItems({
|
||||
labels: ['cart', 'checkout'],
|
||||
colors: ['#f00', '#0f0'],
|
||||
counts: [
|
||||
[2, 6, 2],
|
||||
[1, 8, 1],
|
||||
],
|
||||
bucket: 1,
|
||||
hoveredSeries: 0,
|
||||
formatLabel: (label) => label.toUpperCase(),
|
||||
});
|
||||
|
||||
expect(items).toStrictEqual([
|
||||
{
|
||||
label: 'CHECKOUT',
|
||||
value: 8,
|
||||
tooltipValue: '8',
|
||||
color: '#0f0',
|
||||
isActive: false,
|
||||
},
|
||||
{
|
||||
label: 'CART',
|
||||
value: 6,
|
||||
tooltipValue: '6',
|
||||
color: '#f00',
|
||||
isActive: true,
|
||||
},
|
||||
]);
|
||||
expect(active).toBe(items[1]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('buildOtherMemberItems', () => {
|
||||
it('lists every member of Other, largest in the bucket first', () => {
|
||||
const members = buildOtherMemberItems({
|
||||
members: [
|
||||
{
|
||||
sourceIndex: 4,
|
||||
label: 'a',
|
||||
color: '#a',
|
||||
counts: [1, 3],
|
||||
},
|
||||
{
|
||||
sourceIndex: 7,
|
||||
label: 'b',
|
||||
color: '#b',
|
||||
counts: [0, 5],
|
||||
},
|
||||
{
|
||||
sourceIndex: 9,
|
||||
label: 'c',
|
||||
color: '#c',
|
||||
counts: [2, 0],
|
||||
},
|
||||
],
|
||||
bucket: 1,
|
||||
});
|
||||
|
||||
expect(
|
||||
members.map(({ sourceIndex, item }) => [
|
||||
sourceIndex,
|
||||
item.label,
|
||||
item.value,
|
||||
]),
|
||||
).toStrictEqual([
|
||||
[7, 'b', 5],
|
||||
[4, 'a', 3],
|
||||
[9, 'c', 0],
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,71 @@
|
||||
import type { TooltipContentItem } from 'lib/uPlotV2/components/types';
|
||||
|
||||
import { DistributionOtherMember, DistributionOtherMemberItem } from './types';
|
||||
|
||||
function toItem(
|
||||
label: string,
|
||||
color: string,
|
||||
count: number,
|
||||
isActive: boolean,
|
||||
): TooltipContentItem {
|
||||
return {
|
||||
label,
|
||||
value: count,
|
||||
tooltipValue: count.toLocaleString(),
|
||||
color,
|
||||
isActive,
|
||||
};
|
||||
}
|
||||
|
||||
const byValueDesc = (a: { value: number }, b: { value: number }): number =>
|
||||
b.value - a.value;
|
||||
|
||||
/**
|
||||
* Every drawn group's item for `bucket`, largest first, as the time-series tooltip
|
||||
* sorts; the hovered one is also returned as `active`.
|
||||
*/
|
||||
export function buildDistributionTooltipItems({
|
||||
labels,
|
||||
colors,
|
||||
counts,
|
||||
bucket,
|
||||
hoveredSeries,
|
||||
formatLabel,
|
||||
}: {
|
||||
labels: string[];
|
||||
colors: string[];
|
||||
/** `counts[series][bucket]`. */
|
||||
counts: number[][];
|
||||
bucket: number;
|
||||
hoveredSeries: number | null;
|
||||
formatLabel: (label: string, series: number) => string;
|
||||
}): { active: TooltipContentItem | null; items: TooltipContentItem[] } {
|
||||
const items = labels.map((label, series) =>
|
||||
toItem(
|
||||
formatLabel(label, series),
|
||||
colors[series],
|
||||
counts[series]?.[bucket] ?? 0,
|
||||
series === hoveredSeries,
|
||||
),
|
||||
);
|
||||
return {
|
||||
active: items.find((item) => item.isActive) ?? null,
|
||||
items: [...items].sort(byValueDesc),
|
||||
};
|
||||
}
|
||||
|
||||
/** Every member of Other with its count in `bucket`, largest first. */
|
||||
export function buildOtherMemberItems({
|
||||
members,
|
||||
bucket,
|
||||
}: {
|
||||
members: DistributionOtherMember[];
|
||||
bucket: number;
|
||||
}): DistributionOtherMemberItem[] {
|
||||
return members
|
||||
.map((member) => ({
|
||||
sourceIndex: member.sourceIndex,
|
||||
item: toItem(member.label, member.color, member.counts[bucket] ?? 0, false),
|
||||
}))
|
||||
.sort((a, b) => byValueDesc(a.item, b.item));
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import type {
|
||||
IRenderTooltipFooterArgs,
|
||||
TooltipContentItem,
|
||||
TooltipRenderArgs,
|
||||
} from 'lib/uPlotV2/components/types';
|
||||
|
||||
import type { DistributionBarsLayout, DistributionXAxis } from '../../types';
|
||||
|
||||
/** A group summed into Other, listed under it. */
|
||||
export interface DistributionOtherMember {
|
||||
/** Index among the source series. */
|
||||
sourceIndex: number;
|
||||
label: string;
|
||||
color: string;
|
||||
/** Per bucket. */
|
||||
counts: number[];
|
||||
}
|
||||
|
||||
/** A member of Other as a tooltip row, with the group it drills into. */
|
||||
export interface DistributionOtherMemberItem {
|
||||
sourceIndex: number;
|
||||
item: TooltipContentItem;
|
||||
}
|
||||
|
||||
export interface DistributionTooltipProps extends Pick<
|
||||
TooltipRenderArgs,
|
||||
'uPlotInstance' | 'isPinned' | 'dismiss'
|
||||
> {
|
||||
/** Widget id, for the list's analytics. */
|
||||
id: string;
|
||||
xAxis: DistributionXAxis;
|
||||
layout: DistributionBarsLayout;
|
||||
labels: string[];
|
||||
colors: string[];
|
||||
/** `counts[series][bucket]`. */
|
||||
counts: number[][];
|
||||
/** The groups summed into Other, the last drawn group; empty when there is none. */
|
||||
otherMembers: DistributionOtherMember[];
|
||||
/** Drills into a member of Other, picked from the pinned tooltip. */
|
||||
onOtherMemberClick?: (
|
||||
sourceIndex: number,
|
||||
coordinates: { x: number; y: number },
|
||||
) => void;
|
||||
formatBound: (value: number) => string;
|
||||
renderTooltipFooter?: (args: IRenderTooltipFooterArgs) => React.ReactNode;
|
||||
}
|
||||
294
frontend/src/lib/visualization/charts/Distribution/config.ts
Normal file
294
frontend/src/lib/visualization/charts/Distribution/config.ts
Normal file
@@ -0,0 +1,294 @@
|
||||
import { PrecisionOption } from 'components/Graph/types';
|
||||
import {
|
||||
DistributionType,
|
||||
DrawStyle,
|
||||
StackMode,
|
||||
} from 'lib/uPlotV2/config/types';
|
||||
import { UPlotConfigBuilder } from 'lib/uPlotV2/config/UPlotConfigBuilder';
|
||||
import { createVariableWidthBarsPathBuilder } from 'lib/uPlotV2/paths/variableWidthBars';
|
||||
import {
|
||||
createBucketValueFormatter,
|
||||
resolveRowIndex,
|
||||
} from 'lib/uPlotV2/plugins/HeatmapPlugin/geometry';
|
||||
import { createHatchPattern } from 'lib/uPlotV2/plugins/HeatmapPlugin/paint';
|
||||
import uPlot from 'uplot';
|
||||
|
||||
import { withOpacity } from './colors';
|
||||
import {
|
||||
drawPercentileMarkers,
|
||||
MARKER_HIT_PX,
|
||||
resolveHoveredMarker,
|
||||
} from './drawPercentileMarkers';
|
||||
import { resolveNearestSeries, thinLabelledSplits } from './layout';
|
||||
import { groupPercentileMarkers } from './percentiles';
|
||||
import {
|
||||
DistributionBarsLayout,
|
||||
DistributionPercentile,
|
||||
DistributionXAxis,
|
||||
PercentileMarkerHitArea,
|
||||
} from './types';
|
||||
|
||||
/** Minimum space between two x tick labels, in CSS pixels. */
|
||||
const X_LABEL_GAP_PX = 12;
|
||||
const BAR_GAP_PX = 1;
|
||||
const BAR_OPACITY = 0.85;
|
||||
const OVERFLOW_BAR_OPACITY = 0.4;
|
||||
/** Every group but the hovered one fades to this. */
|
||||
const DIMMED_BAR_OPACITY = 0.25;
|
||||
const DIMMED_OVERFLOW_BAR_OPACITY = 0.12;
|
||||
const OVERFLOW_AXIS_LABEL = '∞';
|
||||
/** Headroom above the tallest bar: a fraction on linear, a factor on log. Marker
|
||||
* labels sit at the top of the plot, so they take more. */
|
||||
const LINEAR_HEADROOM = 1.1;
|
||||
const LINEAR_HEADROOM_WITH_MARKERS = 1.3;
|
||||
const LOG_HEADROOM = 2;
|
||||
const LOG_HEADROOM_WITH_MARKERS = 6;
|
||||
|
||||
function resolveYRange({
|
||||
yMin,
|
||||
yMax,
|
||||
isLogY,
|
||||
stack,
|
||||
hasMarkers,
|
||||
}: {
|
||||
yMin: number;
|
||||
yMax: number;
|
||||
isLogY: boolean;
|
||||
stack: StackMode;
|
||||
hasMarkers: boolean;
|
||||
}): [number, number] {
|
||||
if (stack === StackMode.Percent) {
|
||||
return [0, hasMarkers ? 100 * LINEAR_HEADROOM_WITH_MARKERS : 100];
|
||||
}
|
||||
if (isLogY) {
|
||||
const headroom = hasMarkers ? LOG_HEADROOM_WITH_MARKERS : LOG_HEADROOM;
|
||||
return [yMin, Math.max(yMax, yMin) * headroom];
|
||||
}
|
||||
const headroom = hasMarkers ? LINEAR_HEADROOM_WITH_MARKERS : LINEAR_HEADROOM;
|
||||
return [0, yMax > 0 ? yMax * headroom : 1];
|
||||
}
|
||||
|
||||
export interface BuildDistributionConfigArgs {
|
||||
id: string;
|
||||
xAxis: DistributionXAxis;
|
||||
layout: DistributionBarsLayout;
|
||||
labels: string[];
|
||||
colors: string[];
|
||||
stack: StackMode;
|
||||
isLogY: boolean;
|
||||
isDarkMode: boolean;
|
||||
/** Drawn across the plot, labelled at the top. */
|
||||
markers: DistributionPercentile[];
|
||||
/** Unit of the bucket bounds; counts take none. */
|
||||
xAxisUnit?: string;
|
||||
decimalPrecision?: PrecisionOption;
|
||||
}
|
||||
|
||||
export function buildDistributionConfig({
|
||||
id,
|
||||
xAxis,
|
||||
layout,
|
||||
labels,
|
||||
colors,
|
||||
stack,
|
||||
isLogY,
|
||||
isDarkMode,
|
||||
markers,
|
||||
xAxisUnit,
|
||||
decimalPrecision,
|
||||
}: BuildDistributionConfigArgs): UPlotConfigBuilder {
|
||||
const builder = new UPlotConfigBuilder({ id });
|
||||
// uPlot's focus picks the series nearest in value, meaningless for stacked bars; the
|
||||
// setCursor hook focuses the one under the cursor itself. Alpha 1 leaves the
|
||||
// dimming to the bar fills.
|
||||
builder.setFocus({ alpha: 1 });
|
||||
// The x range is pinned to the buckets, so a drag-zoom would only flash a box.
|
||||
builder.setCursor({
|
||||
focus: { prox: -1 },
|
||||
points: { show: false },
|
||||
drag: { x: false, y: false },
|
||||
});
|
||||
|
||||
const formatBound = createBucketValueFormatter(xAxisUnit, decimalPrecision);
|
||||
|
||||
builder.addScale({
|
||||
scaleKey: 'x',
|
||||
time: false,
|
||||
auto: false,
|
||||
range: (): [number, number] => [xAxis.min, xAxis.max],
|
||||
});
|
||||
const yRange = resolveYRange({
|
||||
yMin: layout.yMin,
|
||||
yMax: layout.yMax,
|
||||
isLogY,
|
||||
stack,
|
||||
hasMarkers: markers.length > 0,
|
||||
});
|
||||
builder.addScale({
|
||||
scaleKey: 'y',
|
||||
time: false,
|
||||
auto: false,
|
||||
distribution: isLogY ? DistributionType.Logarithmic : DistributionType.Linear,
|
||||
range: (): [number, number] => yRange,
|
||||
});
|
||||
|
||||
const axisSplits =
|
||||
xAxis.overflowSplit === null
|
||||
? xAxis.splits
|
||||
: [...xAxis.splits, xAxis.overflowSplit];
|
||||
const splitLabels = new Map<number, string>();
|
||||
xAxis.splits.forEach((split, index) => {
|
||||
splitLabels.set(split, formatBound(xAxis.rows[index].upper));
|
||||
});
|
||||
if (xAxis.overflowSplit !== null) {
|
||||
splitLabels.set(xAxis.overflowSplit, OVERFLOW_AXIS_LABEL);
|
||||
}
|
||||
|
||||
const labelOf = (split: number): string =>
|
||||
splitLabels.get(split) ?? formatBound(xAxis.toBucketValue(split));
|
||||
|
||||
builder.addAxis({
|
||||
scaleKey: 'x',
|
||||
side: 2,
|
||||
isDarkMode,
|
||||
// Thinned by each label's own width: bound labels run from `5 s` to
|
||||
// `16.67 mins`, so no fixed spacing keeps them apart.
|
||||
splits: (self, axisIdx): number[] => {
|
||||
const visible = axisSplits.filter(
|
||||
(split) => split >= xAxis.min && split <= xAxis.max,
|
||||
);
|
||||
const font = self.axes[axisIdx]?.font?.[0];
|
||||
if (font) {
|
||||
self.ctx.font = font;
|
||||
}
|
||||
const kept = thinLabelledSplits({
|
||||
positions: visible.map((split) => self.valToPos(split, 'x')),
|
||||
widths: visible.map(
|
||||
(split) => self.ctx.measureText(labelOf(split)).width / uPlot.pxRatio,
|
||||
),
|
||||
gap: X_LABEL_GAP_PX,
|
||||
});
|
||||
return kept.map((index) => visible[index]);
|
||||
},
|
||||
values: (_, splits): string[] => splits.map(labelOf),
|
||||
});
|
||||
builder.addAxis({
|
||||
scaleKey: 'y',
|
||||
side: 3,
|
||||
isDarkMode,
|
||||
yAxisUnit: stack === StackMode.Percent ? 'percent' : 'short',
|
||||
// The marker headroom runs a share axis past 100%, which labels nothing real.
|
||||
...(stack === StackMode.Percent && {
|
||||
filter: (_self: uPlot, splits: number[]): Array<number | null> =>
|
||||
splits.map((split) => (split <= 100 ? split : null)),
|
||||
}),
|
||||
});
|
||||
|
||||
let hatchPattern: CanvasPattern | null | undefined;
|
||||
const getHatchPattern = (
|
||||
ctx: CanvasRenderingContext2D,
|
||||
): CanvasPattern | null => {
|
||||
hatchPattern ??= createHatchPattern(ctx, isDarkMode);
|
||||
return hatchPattern;
|
||||
};
|
||||
|
||||
// Read by every series' fill on each draw; a change redraws the paths.
|
||||
const hover: {
|
||||
series: number | null;
|
||||
focused: number | null;
|
||||
marker: number | null;
|
||||
} = { series: null, focused: null, marker: null };
|
||||
const plotMarkers = groupPercentileMarkers(
|
||||
markers.filter(
|
||||
({ axisValue }) => axisValue >= xAxis.min && axisValue <= xAxis.max,
|
||||
),
|
||||
);
|
||||
let markerHitAreas: PercentileMarkerHitArea[] = [];
|
||||
const isDimmed = (seriesIndex: number): boolean =>
|
||||
hover.series !== null && hover.series !== seriesIndex;
|
||||
|
||||
labels.forEach((label, seriesIndex) => {
|
||||
const color = colors[seriesIndex];
|
||||
builder.addSeries({
|
||||
scaleKey: 'y',
|
||||
label,
|
||||
drawStyle: DrawStyle.Bar,
|
||||
pathBuilder: createVariableWidthBarsPathBuilder({
|
||||
getBars: () => layout.rects[seriesIndex] ?? [],
|
||||
fill: () =>
|
||||
withOpacity(
|
||||
color,
|
||||
isDimmed(seriesIndex) ? DIMMED_BAR_OPACITY : BAR_OPACITY,
|
||||
),
|
||||
hatchedFill: () =>
|
||||
withOpacity(
|
||||
color,
|
||||
isDimmed(seriesIndex)
|
||||
? DIMMED_OVERFLOW_BAR_OPACITY
|
||||
: OVERFLOW_BAR_OPACITY,
|
||||
),
|
||||
getHatchPattern,
|
||||
gapPx: BAR_GAP_PX,
|
||||
}),
|
||||
lineColor: color,
|
||||
lineWidth: 0,
|
||||
colorMapping: {},
|
||||
isDarkMode,
|
||||
showPoints: false,
|
||||
spanGaps: false,
|
||||
});
|
||||
});
|
||||
|
||||
builder.addHook('draw', (uPlotInstance: uPlot): void => {
|
||||
markerHitAreas = drawPercentileMarkers(
|
||||
uPlotInstance,
|
||||
plotMarkers,
|
||||
formatBound,
|
||||
isDarkMode,
|
||||
hover.marker,
|
||||
);
|
||||
});
|
||||
|
||||
// Registered as a hook, not a plugin, so it runs before TooltipPlugin's: the tooltip
|
||||
// only shows for a focused series, and must find it focused when it positions.
|
||||
builder.addHook('setCursor', (uPlotInstance: uPlot): void => {
|
||||
const { left = -1, top = -1 } = uPlotInstance.cursor;
|
||||
const isOnPlot = left >= 0 && top >= 0;
|
||||
const x = isOnPlot ? uPlotInstance.posToVal(left, 'x') : Number.NaN;
|
||||
const bucket = isOnPlot ? resolveRowIndex(xAxis.edges, x) : null;
|
||||
const marker = isOnPlot
|
||||
? resolveHoveredMarker(markerHitAreas, left, top, MARKER_HIT_PX)
|
||||
: null;
|
||||
// Over a marker, the bars neither dim nor show their tooltip.
|
||||
const hovered =
|
||||
bucket === null || marker !== null
|
||||
? null
|
||||
: resolveNearestSeries(layout, bucket, x, uPlotInstance.posToVal(top, 'y'));
|
||||
// An empty bucket still gets a tooltip, as a bar chart's zero column does; with no
|
||||
// nearest group to name, the first stands in.
|
||||
const isEmptyBucket = bucket !== null && marker === null && hovered === null;
|
||||
const focused = isEmptyBucket && labels.length > 0 ? 0 : hovered;
|
||||
|
||||
if (focused !== hover.focused) {
|
||||
hover.focused = focused;
|
||||
uPlotInstance.setSeries(focused === null ? null : focused + 1, {
|
||||
focus: true,
|
||||
});
|
||||
}
|
||||
if (marker !== hover.marker) {
|
||||
// The crosshair would cut through the marker's badges.
|
||||
uPlotInstance.root
|
||||
.querySelectorAll<HTMLElement>('.u-cursor-x, .u-cursor-y')
|
||||
.forEach((line) => {
|
||||
line.style.visibility = marker === null ? '' : 'hidden';
|
||||
});
|
||||
}
|
||||
if (hovered !== hover.series || marker !== hover.marker) {
|
||||
hover.series = hovered;
|
||||
hover.marker = marker;
|
||||
uPlotInstance.redraw(true, false);
|
||||
}
|
||||
});
|
||||
|
||||
return builder;
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
import { Color } from '@signozhq/design-tokens';
|
||||
import { themeColors } from 'constants/theme';
|
||||
import uPlot from 'uplot';
|
||||
|
||||
import { formatPercentileBadge, formatPercentileValue } from './percentiles';
|
||||
import { DistributionPercentile, PercentileMarkerHitArea } from './types';
|
||||
|
||||
const MARKER_DASH: [number, number] = [3, 3];
|
||||
/** Opacity of a marker line that is not hovered. */
|
||||
const MARKER_IDLE_ALPHA = 0.55;
|
||||
/** Cap height as a share of the font size. */
|
||||
const CAP_HEIGHT_RATIO = 0.7;
|
||||
const MARKER_FONT_SIZE_PX = 9;
|
||||
/** Space between a badge's name and its diamond's edges. */
|
||||
const MARKER_BADGE_PADDING_PX = 2;
|
||||
const MARKER_BADGE_GAP_PX = 2;
|
||||
const MARKER_VALUE_FONT_SIZE_PX = 11;
|
||||
/** How far from a marker line the cursor still hovers it, in CSS pixels. */
|
||||
export const MARKER_HIT_PX = 4;
|
||||
const MARKER_PILL_PADDING_X_PX = 6;
|
||||
const MARKER_PILL_PADDING_Y_PX = 3;
|
||||
const MARKER_PILL_RADIUS_PX = 4;
|
||||
/** Height of the pill's notch pointing up at the line; also its gap from the axis. */
|
||||
const MARKER_PILL_POINTER_PX = 4;
|
||||
|
||||
/**
|
||||
* The marker under `(x, y)`: one whose badge it is over, else the line nearest
|
||||
* `x` within `tolerance`. `null` when none is.
|
||||
*/
|
||||
export function resolveHoveredMarker(
|
||||
areas: PercentileMarkerHitArea[],
|
||||
x: number,
|
||||
y: number,
|
||||
tolerance: number,
|
||||
): number | null {
|
||||
const badgeIndex = areas.findIndex(({ badges }) =>
|
||||
badges.some(
|
||||
(badge) =>
|
||||
x >= badge.left && x <= badge.right && y >= badge.top && y <= badge.bottom,
|
||||
),
|
||||
);
|
||||
if (badgeIndex !== -1) {
|
||||
return badgeIndex;
|
||||
}
|
||||
let nearest: number | null = null;
|
||||
let nearestDistance = tolerance;
|
||||
areas.forEach((area, index) => {
|
||||
const distance = Math.abs(area.x - x);
|
||||
if (distance <= nearestDistance) {
|
||||
nearest = index;
|
||||
nearestDistance = distance;
|
||||
}
|
||||
});
|
||||
return nearest;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stacks marker badges into rows so none overlap: each goes in the first row whose
|
||||
* last badge ends before it starts. Input and output are in the same pixel space.
|
||||
*/
|
||||
export function layoutMarkerLabels(
|
||||
labels: Array<{ x: number; width: number }>,
|
||||
gap: number,
|
||||
): number[] {
|
||||
const rowEnds: number[] = [];
|
||||
const order = labels
|
||||
.map((label, index) => ({ ...label, index }))
|
||||
.sort((a, b) => a.x - b.x);
|
||||
const rows = new Array<number>(labels.length).fill(0);
|
||||
|
||||
order.forEach(({ x, width, index }) => {
|
||||
let row = rowEnds.findIndex((end) => x >= end + gap);
|
||||
if (row === -1) {
|
||||
row = rowEnds.length;
|
||||
rowEnds.push(0);
|
||||
}
|
||||
rowEnds[row] = x + width;
|
||||
rows[index] = row;
|
||||
});
|
||||
|
||||
return rows;
|
||||
}
|
||||
|
||||
/** A square diamond centred on `(x, y)` with half-diagonal `radius`, filled then outlined. */
|
||||
function drawDiamond(
|
||||
ctx: CanvasRenderingContext2D,
|
||||
x: number,
|
||||
y: number,
|
||||
radius: number,
|
||||
fill: string,
|
||||
stroke: string,
|
||||
): void {
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(x, y - radius);
|
||||
ctx.lineTo(x + radius, y);
|
||||
ctx.lineTo(x, y + radius);
|
||||
ctx.lineTo(x - radius, y);
|
||||
ctx.closePath();
|
||||
ctx.fillStyle = fill;
|
||||
ctx.fill();
|
||||
ctx.strokeStyle = stroke;
|
||||
ctx.stroke();
|
||||
}
|
||||
|
||||
/**
|
||||
* Dashed lines across the plot with a diamond badge at each end naming the
|
||||
* percentile, one per group on the same spot; badges stack into rows so none overlap. The hovered marker is
|
||||
* emphasised and shows its value on the x axis. Returns each marker's hover targets.
|
||||
*/
|
||||
export function drawPercentileMarkers(
|
||||
uPlotInstance: uPlot,
|
||||
markers: DistributionPercentile[][],
|
||||
formatBound: (value: number) => string,
|
||||
isDarkMode: boolean,
|
||||
hovered: number | null,
|
||||
): PercentileMarkerHitArea[] {
|
||||
if (markers.length === 0) {
|
||||
return [];
|
||||
}
|
||||
const { ctx, bbox } = uPlotInstance;
|
||||
const { pxRatio } = uPlot;
|
||||
const color = isDarkMode ? themeColors.white : themeColors.black;
|
||||
const background = isDarkMode ? Color.BG_INK_400 : Color.BG_VANILLA_100;
|
||||
const bottom = bbox.top + bbox.height;
|
||||
|
||||
ctx.save();
|
||||
ctx.font = `600 ${MARKER_FONT_SIZE_PX * pxRatio}px Inter, sans-serif`;
|
||||
ctx.textAlign = 'center';
|
||||
ctx.textBaseline = 'middle';
|
||||
|
||||
const badgeLabels = markers.map((group) => {
|
||||
const text = formatPercentileBadge(group);
|
||||
return { text, width: ctx.measureText(text).width };
|
||||
});
|
||||
// One square diamond for all, fitting the widest name's box: |dx| + |dy| ≤ radius at
|
||||
// its corners. Cap height stands in for the text's height.
|
||||
const radius =
|
||||
(Math.max(...badgeLabels.map(({ width }) => width)) +
|
||||
MARKER_FONT_SIZE_PX * pxRatio * CAP_HEIGHT_RATIO) /
|
||||
2 +
|
||||
MARKER_BADGE_PADDING_PX * pxRatio;
|
||||
const badges = markers.map((group, index) => ({
|
||||
text: badgeLabels[index].text,
|
||||
x: uPlotInstance.valToPos(group[0].axisValue, 'x', true),
|
||||
}));
|
||||
const rows = layoutMarkerLabels(
|
||||
badges.map(({ x }) => ({ x: x - radius, width: 2 * radius })),
|
||||
MARKER_BADGE_GAP_PX * pxRatio,
|
||||
);
|
||||
const rowStep = 2 * radius + MARKER_BADGE_GAP_PX * pxRatio;
|
||||
const badgeCentres = (index: number): [number, number] => {
|
||||
const offset = radius + rows[index] * rowStep;
|
||||
return [bbox.top + offset, bottom - offset];
|
||||
};
|
||||
|
||||
const drawMarker = (index: number): void => {
|
||||
const { text, x } = badges[index];
|
||||
const isHovered = index === hovered;
|
||||
|
||||
ctx.globalAlpha = isHovered ? 1 : MARKER_IDLE_ALPHA;
|
||||
ctx.strokeStyle = color;
|
||||
ctx.lineWidth = pxRatio;
|
||||
ctx.setLineDash(MARKER_DASH.map((dash) => dash * pxRatio));
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(x, bbox.top);
|
||||
ctx.lineTo(x, bottom);
|
||||
ctx.stroke();
|
||||
|
||||
ctx.globalAlpha = 1;
|
||||
ctx.setLineDash([]);
|
||||
badgeCentres(index).forEach((y) => {
|
||||
drawDiamond(ctx, x, y, radius, isHovered ? color : background, color);
|
||||
ctx.fillStyle = isHovered ? background : color;
|
||||
ctx.fillText(text, x, y);
|
||||
});
|
||||
|
||||
if (!isHovered) {
|
||||
return;
|
||||
}
|
||||
// The value sits on the x axis under the line, over the tick labels, in a pill
|
||||
// whose notch points up at the line.
|
||||
ctx.font = `500 ${MARKER_VALUE_FONT_SIZE_PX * pxRatio}px Inter, sans-serif`;
|
||||
const value = formatPercentileValue(markers[index], formatBound);
|
||||
const pillPaddingX = MARKER_PILL_PADDING_X_PX * pxRatio;
|
||||
const pillPaddingY = MARKER_PILL_PADDING_Y_PX * pxRatio;
|
||||
const pointer = MARKER_PILL_POINTER_PX * pxRatio;
|
||||
const width = ctx.measureText(value).width + 2 * pillPaddingX;
|
||||
const height = MARKER_VALUE_FONT_SIZE_PX * pxRatio + 2 * pillPaddingY;
|
||||
const left = Math.min(Math.max(x - width / 2, 0), ctx.canvas.width - width);
|
||||
const top = bottom + 2 * pointer;
|
||||
const notchX = Math.min(
|
||||
Math.max(x, left + pointer + MARKER_PILL_RADIUS_PX * pxRatio),
|
||||
left + width - pointer - MARKER_PILL_RADIUS_PX * pxRatio,
|
||||
);
|
||||
// A halo in the chart's background hides the tick labels it overlaps.
|
||||
ctx.fillStyle = background;
|
||||
ctx.fillRect(
|
||||
left - pillPaddingX,
|
||||
top,
|
||||
width + 2 * pillPaddingX,
|
||||
height + 2 * pillPaddingY,
|
||||
);
|
||||
ctx.fillStyle = isDarkMode ? Color.BG_SLATE_400 : Color.BG_INK_400;
|
||||
ctx.beginPath();
|
||||
ctx.roundRect(left, top, width, height, MARKER_PILL_RADIUS_PX * pxRatio);
|
||||
ctx.moveTo(notchX - pointer, top);
|
||||
ctx.lineTo(notchX, top - pointer);
|
||||
ctx.lineTo(notchX + pointer, top);
|
||||
ctx.closePath();
|
||||
ctx.fill();
|
||||
ctx.fillStyle = Color.BG_VANILLA_100;
|
||||
ctx.fillText(value, left + width / 2, top + height / 2);
|
||||
};
|
||||
|
||||
// The hovered one last, so it draws over its neighbours.
|
||||
badges.forEach((_, index) => index !== hovered && drawMarker(index));
|
||||
if (hovered !== null && hovered < badges.length) {
|
||||
drawMarker(hovered);
|
||||
}
|
||||
ctx.restore();
|
||||
|
||||
return badges.map(({ x }, index) => {
|
||||
const toPlot = (value: number, origin: number): number =>
|
||||
(value - origin) / pxRatio;
|
||||
return {
|
||||
x: toPlot(x, bbox.left),
|
||||
badges: badgeCentres(index).map((y) => ({
|
||||
left: toPlot(x - radius, bbox.left),
|
||||
right: toPlot(x + radius, bbox.left),
|
||||
top: toPlot(y - radius, bbox.top),
|
||||
bottom: toPlot(y + radius, bbox.top),
|
||||
})),
|
||||
};
|
||||
});
|
||||
}
|
||||
245
frontend/src/lib/visualization/charts/Distribution/layout.ts
Normal file
245
frontend/src/lib/visualization/charts/Distribution/layout.ts
Normal file
@@ -0,0 +1,245 @@
|
||||
import { StackMode } from 'lib/uPlotV2/config/types';
|
||||
import {
|
||||
cropHeatmapYAxis,
|
||||
resolveHeatmapYAxis,
|
||||
} from 'lib/uPlotV2/plugins/HeatmapPlugin/geometry';
|
||||
import { HeatmapAxisScale } from 'lib/uPlotV2/plugins/HeatmapPlugin/types';
|
||||
|
||||
import {
|
||||
DistributionBarRect,
|
||||
DistributionBarsLayout,
|
||||
DistributionXAxis,
|
||||
} from './types';
|
||||
|
||||
/**
|
||||
* Bottom of a log count axis: the decade below the smallest positive count, so every
|
||||
* bar, a single observation included, starts under its top. 1 when nothing is positive.
|
||||
*/
|
||||
export function resolveLogYBase(counts: number[][]): number {
|
||||
// A loop, not `Math.min(...)`: every group's every bucket can pass the argument limit.
|
||||
let smallest = Number.POSITIVE_INFINITY;
|
||||
counts.forEach((seriesCounts) =>
|
||||
seriesCounts.forEach((count) => {
|
||||
if (count > 0 && count < smallest) {
|
||||
smallest = count;
|
||||
}
|
||||
}),
|
||||
);
|
||||
return Number.isFinite(smallest)
|
||||
? 10 ** (Math.floor(Math.log10(smallest)) - 1)
|
||||
: 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* N bounds give N + 1 buckets: `≤ first`, the finite ones, and `> last`. Every bucket
|
||||
* is equally wide: bucket `i` spans `[i, i + 1]`, and ticks still name the bounds.
|
||||
*/
|
||||
export function resolveDistributionXAxis(buckets: number[]): DistributionXAxis {
|
||||
const { rows, overflowSplit } = resolveHeatmapYAxis(
|
||||
buckets,
|
||||
HeatmapAxisScale.Linear,
|
||||
);
|
||||
const edges = rows.map((_, index) => index).concat(rows.length);
|
||||
return {
|
||||
rows,
|
||||
edges,
|
||||
splits: rows.slice(0, -1).map((_, index) => index + 1),
|
||||
overflowSplit: overflowSplit === null ? null : rows.length,
|
||||
toBucketValue: (axisValue: number): number => {
|
||||
const index = Math.min(rows.length - 1, Math.max(0, Math.floor(axisValue)));
|
||||
const row = rows[index];
|
||||
return row.lower + (axisValue - index) * (row.upper - row.lower);
|
||||
},
|
||||
min: 0,
|
||||
max: rows.length,
|
||||
};
|
||||
}
|
||||
|
||||
/** Sum of each bucket across the visible series. */
|
||||
export function sumVisibleCounts(
|
||||
counts: number[][],
|
||||
visible: boolean[],
|
||||
bucketCount: number,
|
||||
): number[] {
|
||||
const totals = new Array<number>(bucketCount).fill(0);
|
||||
counts.forEach((seriesCounts, seriesIndex) => {
|
||||
if (!visible[seriesIndex]) {
|
||||
return;
|
||||
}
|
||||
for (let bucket = 0; bucket < bucketCount; bucket += 1) {
|
||||
totals[bucket] += seriesCounts[bucket] ?? 0;
|
||||
}
|
||||
});
|
||||
return totals;
|
||||
}
|
||||
|
||||
/** Drops empty buckets past the last occupied one, as the heatmap does. */
|
||||
export function cropDistributionXAxis(
|
||||
axis: DistributionXAxis,
|
||||
totals: number[],
|
||||
): DistributionXAxis {
|
||||
return cropHeatmapYAxis(
|
||||
axis,
|
||||
totals.map((total) => [total]),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Narrows the axis window to the buckets overlapping `[min, max]`, never below one.
|
||||
* A bucket straddling a bound stays whole: cutting it would misstate its count.
|
||||
*/
|
||||
export function clampDistributionXAxis(
|
||||
axis: DistributionXAxis,
|
||||
min?: number,
|
||||
max?: number,
|
||||
): DistributionXAxis {
|
||||
const { rows, edges } = axis;
|
||||
let first = edges.indexOf(axis.min);
|
||||
let last = edges.indexOf(axis.max) - 1;
|
||||
while (min !== undefined && first < last && rows[first].upper <= min) {
|
||||
first += 1;
|
||||
}
|
||||
while (max !== undefined && last > first && rows[last].lower >= max) {
|
||||
last -= 1;
|
||||
}
|
||||
return {
|
||||
...axis,
|
||||
overflowSplit: rows[last].isOverflow ? axis.overflowSplit : null,
|
||||
min: edges[first],
|
||||
max: edges[last + 1],
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Every bar, in scale space. `normal` stacks the series in each bucket, `percent`
|
||||
* stacks their shares of it, `none` splits the bucket width between them.
|
||||
*/
|
||||
export function resolveDistributionBars({
|
||||
xAxis,
|
||||
counts,
|
||||
stack,
|
||||
isLogY,
|
||||
}: {
|
||||
xAxis: DistributionXAxis;
|
||||
/** `counts[series][bucket]`. */
|
||||
counts: number[][];
|
||||
stack: StackMode;
|
||||
isLogY: boolean;
|
||||
}): DistributionBarsLayout {
|
||||
const { rows, edges } = xAxis;
|
||||
const rects: DistributionBarRect[][] = counts.map(() => []);
|
||||
const base = isLogY ? resolveLogYBase(counts) : 0;
|
||||
let yMax = 0;
|
||||
|
||||
rows.forEach((row, bucketIndex) => {
|
||||
const x0 = edges[bucketIndex];
|
||||
const x1 = edges[bucketIndex + 1];
|
||||
// Buckets outside the window are off the plot and mustn't set its height.
|
||||
const isInWindow = x0 >= xAxis.min && x1 <= xAxis.max;
|
||||
const total = counts.reduce(
|
||||
(sum, seriesCounts) => sum + (seriesCounts[bucketIndex] ?? 0),
|
||||
0,
|
||||
);
|
||||
let cumulative = 0;
|
||||
|
||||
counts.forEach((seriesCounts, seriesIndex) => {
|
||||
const count = seriesCounts[bucketIndex] ?? 0;
|
||||
if (count <= 0) {
|
||||
return;
|
||||
}
|
||||
const bar = { bucketIndex, hatched: row.isOverflow };
|
||||
|
||||
if (stack === StackMode.None) {
|
||||
// Below the log base a bar would draw downwards from the axis.
|
||||
if (count <= base) {
|
||||
return;
|
||||
}
|
||||
const width = (x1 - x0) / counts.length;
|
||||
rects[seriesIndex].push({
|
||||
...bar,
|
||||
x0: x0 + seriesIndex * width,
|
||||
x1: x0 + (seriesIndex + 1) * width,
|
||||
y0: base,
|
||||
y1: count,
|
||||
});
|
||||
if (isInWindow) {
|
||||
yMax = Math.max(yMax, count);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const scale = stack === StackMode.Percent ? 100 / total : 1;
|
||||
const y0 = cumulative * scale;
|
||||
cumulative += count;
|
||||
const y1 = cumulative * scale;
|
||||
if (y1 <= base) {
|
||||
return;
|
||||
}
|
||||
rects[seriesIndex].push({
|
||||
...bar,
|
||||
x0,
|
||||
x1,
|
||||
y0: Math.max(y0, base),
|
||||
y1,
|
||||
});
|
||||
if (isInWindow) {
|
||||
yMax = Math.max(yMax, y1);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
return { rects, yMin: base, yMax };
|
||||
}
|
||||
|
||||
/**
|
||||
* The group nearest `(x, y)` vertically in `bucket`, as uPlot focuses bar series;
|
||||
* side by side, only the sub-bar under `x` competes. `null` over an empty bucket.
|
||||
*/
|
||||
export function resolveNearestSeries(
|
||||
layout: DistributionBarsLayout,
|
||||
bucket: number,
|
||||
x: number,
|
||||
y: number,
|
||||
): number | null {
|
||||
const candidates = layout.rects.flatMap((rects, series) =>
|
||||
rects
|
||||
.filter((rect) => rect.bucketIndex === bucket)
|
||||
.map((rect) => ({ rect, series })),
|
||||
);
|
||||
const underX = candidates.filter(({ rect }) => x >= rect.x0 && x < rect.x1);
|
||||
let nearest: number | null = null;
|
||||
let nearestDistance = Number.POSITIVE_INFINITY;
|
||||
(underX.length > 0 ? underX : candidates).forEach(({ rect, series }) => {
|
||||
const distance = Math.max(rect.y0 - y, y - rect.y1, 0);
|
||||
if (distance < nearestDistance) {
|
||||
nearest = series;
|
||||
nearestDistance = distance;
|
||||
}
|
||||
});
|
||||
return nearest;
|
||||
}
|
||||
|
||||
/**
|
||||
* Indexes of the ticks whose centred labels fit without touching, walking from the
|
||||
* right so the `∞` edge survives. Positions and widths share one pixel space.
|
||||
*/
|
||||
export function thinLabelledSplits({
|
||||
positions,
|
||||
widths,
|
||||
gap,
|
||||
}: {
|
||||
positions: number[];
|
||||
widths: number[];
|
||||
gap: number;
|
||||
}): number[] {
|
||||
const kept: number[] = [];
|
||||
let leftEdge = Number.POSITIVE_INFINITY;
|
||||
for (let index = positions.length - 1; index >= 0; index -= 1) {
|
||||
const half = widths[index] / 2;
|
||||
if (positions[index] + half + gap <= leftEdge) {
|
||||
kept.push(index);
|
||||
leftEdge = positions[index] - half;
|
||||
}
|
||||
}
|
||||
return kept.reverse();
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
import { DistributionPercentile, DistributionXAxis } from './types';
|
||||
|
||||
/**
|
||||
* Percentiles of the summed counts, by `histogram_quantile`'s method: find the bucket
|
||||
* holding the target rank and interpolate linearly inside it, with the lowest bucket
|
||||
* starting at zero. So the values match a time-series panel's percentiles.
|
||||
*/
|
||||
export function computeDistributionPercentiles({
|
||||
xAxis,
|
||||
totals,
|
||||
percentiles,
|
||||
}: {
|
||||
xAxis: DistributionXAxis;
|
||||
/** Summed visible counts per bucket. */
|
||||
totals: number[];
|
||||
percentiles: readonly number[];
|
||||
}): DistributionPercentile[] {
|
||||
const { rows, edges } = xAxis;
|
||||
const total = totals.reduce((sum, count) => sum + count, 0);
|
||||
if (total <= 0 || rows.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return percentiles.flatMap<DistributionPercentile>((percentile) => {
|
||||
const rank = (percentile / 100) * total;
|
||||
let below = 0;
|
||||
for (let index = 0; index < rows.length; index += 1) {
|
||||
const count = totals[index] ?? 0;
|
||||
if (count > 0 && below + count >= rank) {
|
||||
const row = rows[index];
|
||||
if (row.isOverflow) {
|
||||
return [
|
||||
{
|
||||
percentile,
|
||||
value: row.lower,
|
||||
axisValue: edges[index],
|
||||
isOverflow: true,
|
||||
},
|
||||
];
|
||||
}
|
||||
const fraction = (rank - below) / count;
|
||||
const lower = row.isUnderflow ? Math.min(0, row.upper) : row.lower;
|
||||
return [
|
||||
{
|
||||
percentile,
|
||||
value: lower + fraction * (row.upper - lower),
|
||||
axisValue: edges[index] + fraction * (edges[index + 1] - edges[index]),
|
||||
isOverflow: false,
|
||||
},
|
||||
];
|
||||
}
|
||||
below += count;
|
||||
}
|
||||
return [];
|
||||
});
|
||||
}
|
||||
|
||||
export function formatPercentileName(percentile: number): string {
|
||||
return `p${Number(percentile.toFixed(3))}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Markers that fall on the same spot, sharing one badge: the percentiles landing
|
||||
* in overflow all sit on its edge. Each group is in ascending percentile order.
|
||||
*/
|
||||
export function groupPercentileMarkers(
|
||||
markers: DistributionPercentile[],
|
||||
): DistributionPercentile[][] {
|
||||
const groups = new Map<number, DistributionPercentile[]>();
|
||||
markers.forEach((marker) => {
|
||||
groups.set(marker.axisValue, [
|
||||
...(groups.get(marker.axisValue) ?? []),
|
||||
marker,
|
||||
]);
|
||||
});
|
||||
return [...groups.values()].map((group) =>
|
||||
[...group].sort((a, b) => a.percentile - b.percentile),
|
||||
);
|
||||
}
|
||||
|
||||
/** `p90` for one marker; `p90+` for a group, starting at its lowest percentile. */
|
||||
export function formatPercentileBadge(group: DistributionPercentile[]): string {
|
||||
const name = formatPercentileName(group[0].percentile);
|
||||
return group.length > 1 ? `${name}+` : name;
|
||||
}
|
||||
|
||||
/**
|
||||
* `p99 ≈ 412 ms` for an estimate; `p90, p99 > 5 s` where only the overflow bound is
|
||||
* known. A group shares one spot, but an estimate ending at the overflow edge keeps
|
||||
* its own sign: `p90 ≈ 5 s, p99 > 5 s`.
|
||||
*/
|
||||
export function formatPercentileValue(
|
||||
group: DistributionPercentile[],
|
||||
formatBound: (value: number) => string,
|
||||
): string {
|
||||
return [false, true]
|
||||
.map((isOverflow) =>
|
||||
group.filter((marker) => marker.isOverflow === isOverflow),
|
||||
)
|
||||
.filter((members) => members.length > 0)
|
||||
.map((members) => {
|
||||
const names = members
|
||||
.map(({ percentile }) => formatPercentileName(percentile))
|
||||
.join(', ');
|
||||
const [{ value, isOverflow }] = members;
|
||||
return `${names} ${isOverflow ? '>' : '≈'} ${formatBound(value)}`;
|
||||
})
|
||||
.join(', ');
|
||||
}
|
||||
119
frontend/src/lib/visualization/charts/Distribution/topGroups.ts
Normal file
119
frontend/src/lib/visualization/charts/Distribution/topGroups.ts
Normal file
@@ -0,0 +1,119 @@
|
||||
import { sum } from 'lodash-es';
|
||||
import { StackMode } from 'lib/uPlotV2/config/types';
|
||||
import { OTHER_GROUP_LABEL } from 'lib/visualization/charts/utils/otherGroup';
|
||||
|
||||
import { DistributionSeries, DistributionXAxis, DrawnGroups } from './types';
|
||||
|
||||
/** Colours stop being told apart past this many groups side by side. */
|
||||
export const MAX_SIDE_BY_SIDE_GROUPS = 10;
|
||||
/** Narrowest a side-by-side bar may get, in CSS pixels. */
|
||||
const MIN_SIDE_BY_SIDE_BAR_PX = 3;
|
||||
|
||||
/**
|
||||
* How many series fit: every one when stacked, since a stack never narrows its bars;
|
||||
* side by side, as many as keep every bar in the narrowest bucket at least
|
||||
* `MIN_SIDE_BY_SIDE_BAR_PX` wide, up to `MAX_SIDE_BY_SIDE_GROUPS`.
|
||||
*/
|
||||
export function resolveMaxDrawnGroups({
|
||||
stack,
|
||||
xAxis,
|
||||
plotWidth,
|
||||
}: {
|
||||
stack: StackMode;
|
||||
xAxis: DistributionXAxis;
|
||||
/** Approximate width of the plotting area, in CSS pixels. */
|
||||
plotWidth: number;
|
||||
}): number {
|
||||
if (stack !== StackMode.None) {
|
||||
return Number.POSITIVE_INFINITY;
|
||||
}
|
||||
const span = xAxis.max - xAxis.min;
|
||||
let narrowest = Number.POSITIVE_INFINITY;
|
||||
for (let index = 0; index + 1 < xAxis.edges.length; index += 1) {
|
||||
if (xAxis.edges[index] < xAxis.max) {
|
||||
narrowest = Math.min(narrowest, xAxis.edges[index + 1] - xAxis.edges[index]);
|
||||
}
|
||||
}
|
||||
if (!(span > 0) || !Number.isFinite(narrowest)) {
|
||||
return MAX_SIDE_BY_SIDE_GROUPS;
|
||||
}
|
||||
const narrowestPx = (plotWidth * narrowest) / span;
|
||||
return Math.min(
|
||||
MAX_SIDE_BY_SIDE_GROUPS,
|
||||
Math.max(1, Math.floor(narrowestPx / MIN_SIDE_BY_SIDE_BAR_PX)),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The visible groups to draw: all of them when they fit, else the largest by total
|
||||
* and one Other series summing the rest. Exact, because bucket counts add. Drawn
|
||||
* groups keep legend order.
|
||||
*/
|
||||
export function groupIntoOther({
|
||||
labels,
|
||||
counts,
|
||||
colors,
|
||||
visible,
|
||||
maxGroups,
|
||||
otherColor,
|
||||
}: {
|
||||
labels: string[];
|
||||
counts: number[][];
|
||||
colors: string[];
|
||||
visible: boolean[];
|
||||
maxGroups: number;
|
||||
otherColor: string;
|
||||
}): DrawnGroups {
|
||||
const visibleIndexes = labels
|
||||
.map((_, index) => index)
|
||||
.filter((index) => visible[index]);
|
||||
|
||||
if (visibleIndexes.length <= maxGroups) {
|
||||
return {
|
||||
labels: visibleIndexes.map((index) => labels[index]),
|
||||
counts: visibleIndexes.map((index) => counts[index]),
|
||||
colors: visibleIndexes.map((index) => colors[index]),
|
||||
sourceIndexes: visibleIndexes,
|
||||
otherSourceIndexes: [],
|
||||
visibleGroupCount: visibleIndexes.length,
|
||||
};
|
||||
}
|
||||
|
||||
const ranked = [...visibleIndexes].sort(
|
||||
(a, b) => sum(counts[b]) - sum(counts[a]) || a - b,
|
||||
);
|
||||
const keptCount = Math.max(0, maxGroups - 1);
|
||||
const keep = new Set(ranked.slice(0, keptCount));
|
||||
const kept = visibleIndexes.filter((index) => keep.has(index));
|
||||
const folded = ranked.slice(keptCount);
|
||||
const bucketCount = Math.max(...folded.map((index) => counts[index].length));
|
||||
const other = Array.from({ length: bucketCount }, (_, bucket) =>
|
||||
folded.reduce((total, index) => total + (counts[index][bucket] ?? 0), 0),
|
||||
);
|
||||
|
||||
return {
|
||||
labels: [...kept.map((index) => labels[index]), OTHER_GROUP_LABEL],
|
||||
counts: [...kept.map((index) => counts[index]), other],
|
||||
colors: [...kept.map((index) => colors[index]), otherColor],
|
||||
sourceIndexes: [...kept, null],
|
||||
otherSourceIndexes: folded,
|
||||
visibleGroupCount: visibleIndexes.length,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The drawn group at `drawnIndex` as a source series and its colour; `null` for Other,
|
||||
* which sums several groups no single filter can name.
|
||||
*/
|
||||
export function resolveClickedGroup(
|
||||
drawn: DrawnGroups,
|
||||
drawnIndex: number | null,
|
||||
series: DistributionSeries[],
|
||||
): { series: DistributionSeries; color: string } | null {
|
||||
const source =
|
||||
drawnIndex === null ? null : (drawn.sourceIndexes[drawnIndex] ?? null);
|
||||
if (drawnIndex === null || source === null) {
|
||||
return null;
|
||||
}
|
||||
return { series: series[source], color: drawn.colors[drawnIndex] };
|
||||
}
|
||||
97
frontend/src/lib/visualization/charts/Distribution/types.ts
Normal file
97
frontend/src/lib/visualization/charts/Distribution/types.ts
Normal file
@@ -0,0 +1,97 @@
|
||||
import type { VariableWidthBar } from 'lib/uPlotV2/paths/variableWidthBars';
|
||||
import type { HeatmapYAxis } from 'lib/uPlotV2/plugins/HeatmapPlugin/types';
|
||||
import type { ChartClickData } from 'lib/uPlotV2/plugins/TooltipPlugin/types';
|
||||
|
||||
export interface DistributionSeries {
|
||||
label: string;
|
||||
/** Group-by key → value, for drilling into this group. Empty when ungrouped. */
|
||||
groupLabels?: Record<string, string>;
|
||||
/** One count per bucket bound plus the trailing overflow, summed over the range. */
|
||||
counts: number[];
|
||||
}
|
||||
|
||||
/** A click on a group's bar; never on Other, which no filter can name. */
|
||||
export interface DistributionBarClick {
|
||||
series: DistributionSeries;
|
||||
color: string;
|
||||
/** Viewport coordinates of the click. */
|
||||
coordinates: { x: number; y: number };
|
||||
}
|
||||
|
||||
export enum DistributionYScale {
|
||||
Linear = 'linear',
|
||||
Log = 'log',
|
||||
}
|
||||
|
||||
/** The bucket axis in x-scale space. The heatmap's row axis, laid sideways. */
|
||||
export type DistributionXAxis = HeatmapYAxis;
|
||||
|
||||
/** `x` in bucket-axis units, `y` in counts (or percent); the overflow bucket is hatched. */
|
||||
export interface DistributionBarRect extends VariableWidthBar {
|
||||
bucketIndex: number;
|
||||
}
|
||||
|
||||
export interface DrawnGroups {
|
||||
labels: string[];
|
||||
counts: number[][];
|
||||
colors: string[];
|
||||
/** Each drawn group's index among the source series; `null` for Other. */
|
||||
sourceIndexes: (number | null)[];
|
||||
/** Source indexes of the visible groups summed into Other, largest first; empty when none were. */
|
||||
otherSourceIndexes: number[];
|
||||
/** Visible groups in all, drawn or folded. */
|
||||
visibleGroupCount: number;
|
||||
}
|
||||
|
||||
export interface DistributionBarsLayout {
|
||||
/** One list per series, in series order. */
|
||||
rects: DistributionBarRect[][];
|
||||
/** Where every bar starts: 0, or the log axis base. */
|
||||
yMin: number;
|
||||
/** Top of the tallest bar inside the axis window, for the count axis range. */
|
||||
yMax: number;
|
||||
}
|
||||
|
||||
export interface DistributionPercentile {
|
||||
/** 0–100, as configured. */
|
||||
percentile: number;
|
||||
/** The estimate; in overflow, the last finite bound it is known to exceed. */
|
||||
value: number;
|
||||
/** Where the marker is drawn, in x-scale space. */
|
||||
axisValue: number;
|
||||
isOverflow: boolean;
|
||||
}
|
||||
|
||||
export interface HitRect {
|
||||
left: number;
|
||||
right: number;
|
||||
top: number;
|
||||
bottom: number;
|
||||
}
|
||||
|
||||
/** A drawn marker's hover targets, in CSS pixels relative to the plot. */
|
||||
export interface PercentileMarkerHitArea {
|
||||
x: number;
|
||||
badges: HitRect[];
|
||||
}
|
||||
|
||||
export interface UseDistributionBarClickArgs {
|
||||
xAxis: DistributionXAxis;
|
||||
layout: DistributionBarsLayout;
|
||||
drawn: DrawnGroups;
|
||||
series: DistributionSeries[];
|
||||
/** Each source series' colour, for a group picked out of Other. */
|
||||
colors: string[];
|
||||
onBarClick?: (click: DistributionBarClick) => void;
|
||||
}
|
||||
|
||||
export interface UseDistributionBarClickReturn {
|
||||
onClick?: (data: ChartClickData) => void;
|
||||
/** True over the Other bar, whose click pins the tooltip so a group in it can be picked. */
|
||||
shouldPinOnClick?: (data: ChartClickData) => boolean;
|
||||
/** Drills into a group summed into Other, picked from the pinned tooltip. */
|
||||
onOtherMemberClick?: (
|
||||
sourceIndex: number,
|
||||
coordinates: { x: number; y: number },
|
||||
) => void;
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import { useCallback, useRef } from 'react';
|
||||
import { resolveRowIndex } from 'lib/uPlotV2/plugins/HeatmapPlugin/geometry';
|
||||
import type { ChartClickData } from 'lib/uPlotV2/plugins/TooltipPlugin/types';
|
||||
|
||||
import { resolveNearestSeries } from './layout';
|
||||
import { resolveClickedGroup } from './topGroups';
|
||||
import type {
|
||||
UseDistributionBarClickArgs,
|
||||
UseDistributionBarClickReturn,
|
||||
} from './types';
|
||||
|
||||
/**
|
||||
* Resolves a plot click to the group under it. A click on Other pins the tooltip instead,
|
||||
* as Pie's Other does, so one of its groups can be picked; an empty bucket reports none.
|
||||
*/
|
||||
export function useDistributionBarClick({
|
||||
xAxis,
|
||||
layout,
|
||||
drawn,
|
||||
series,
|
||||
colors,
|
||||
onBarClick,
|
||||
}: UseDistributionBarClickArgs): UseDistributionBarClickReturn {
|
||||
const onBarClickRef = useRef(onBarClick);
|
||||
onBarClickRef.current = onBarClick;
|
||||
|
||||
const resolveDrawnIndex = useCallback(
|
||||
({ xValue, yValue }: ChartClickData): number | null => {
|
||||
const bucket = resolveRowIndex(xAxis.edges, xValue);
|
||||
return bucket === null
|
||||
? null
|
||||
: resolveNearestSeries(layout, bucket, xValue, yValue);
|
||||
},
|
||||
[xAxis, layout],
|
||||
);
|
||||
|
||||
const handleClick = useCallback(
|
||||
(data: ChartClickData): void => {
|
||||
const clicked = resolveClickedGroup(drawn, resolveDrawnIndex(data), series);
|
||||
if (clicked) {
|
||||
onBarClickRef.current?.({
|
||||
...clicked,
|
||||
coordinates: { x: data.absoluteMouseX, y: data.absoluteMouseY },
|
||||
});
|
||||
}
|
||||
},
|
||||
[resolveDrawnIndex, drawn, series],
|
||||
);
|
||||
|
||||
const shouldPinOnClick = useCallback(
|
||||
(data: ChartClickData): boolean => {
|
||||
const drawnIndex = resolveDrawnIndex(data);
|
||||
return drawnIndex !== null && drawn.sourceIndexes[drawnIndex] === null;
|
||||
},
|
||||
[resolveDrawnIndex, drawn],
|
||||
);
|
||||
|
||||
const handleOtherMemberClick = useCallback(
|
||||
(sourceIndex: number, coordinates: { x: number; y: number }): void => {
|
||||
onBarClickRef.current?.({
|
||||
series: series[sourceIndex],
|
||||
color: colors[sourceIndex],
|
||||
coordinates,
|
||||
});
|
||||
},
|
||||
[series, colors],
|
||||
);
|
||||
|
||||
return {
|
||||
onClick: onBarClick ? handleClick : undefined,
|
||||
onOtherMemberClick: onBarClick ? handleOtherMemberClick : undefined,
|
||||
shouldPinOnClick:
|
||||
drawn.otherSourceIndexes.length > 0 ? shouldPinOnClick : undefined,
|
||||
};
|
||||
}
|
||||
22
frontend/src/lib/visualization/charts/Distribution/utils.ts
Normal file
22
frontend/src/lib/visualization/charts/Distribution/utils.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
import uPlot from 'uplot';
|
||||
|
||||
import { DistributionXAxis } from './types';
|
||||
|
||||
/**
|
||||
* `[bucket centres, ...counts per series]`. The series draw from the layout, so the
|
||||
* data only feeds uPlot's cursor and tooltip.
|
||||
*/
|
||||
export function prepareDistributionChartData(
|
||||
xAxis: DistributionXAxis,
|
||||
counts: number[][],
|
||||
): uPlot.AlignedData {
|
||||
const centres = xAxis.rows.map(
|
||||
(_, index) => (xAxis.edges[index] + xAxis.edges[index + 1]) / 2,
|
||||
);
|
||||
return [
|
||||
centres,
|
||||
...counts.map((seriesCounts) =>
|
||||
centres.map((_, index) => seriesCounts[index] ?? 0),
|
||||
),
|
||||
];
|
||||
}
|
||||
@@ -1,10 +1,10 @@
|
||||
import { Timezone } from 'components/CustomTimePicker/timezoneUtils';
|
||||
import { PrecisionOption, PrecisionOptionsEnum } from 'components/Graph/types';
|
||||
import { getToolTipValue } from 'components/Graph/yAxisConfig';
|
||||
import { uPlotXAxisValuesFormat } from 'lib/uPlotLib/utils/constants';
|
||||
import { DrawStyle } from 'lib/uPlotV2/config/types';
|
||||
import { UPlotConfigBuilder } from 'lib/uPlotV2/config/UPlotConfigBuilder';
|
||||
import {
|
||||
createBucketValueFormatter,
|
||||
decimateAxisSplits,
|
||||
formatRowLabel,
|
||||
resolveColumnAlignedSplits,
|
||||
@@ -65,7 +65,7 @@ export function resolveBoundaryPrecision({
|
||||
|
||||
const separates = (candidate: PrecisionOption): boolean => {
|
||||
const labels = boundaries.map((boundary) =>
|
||||
getToolTipValue(String(boundary), yAxisUnit, candidate),
|
||||
createBucketValueFormatter(yAxisUnit, candidate)(boundary),
|
||||
);
|
||||
return labels.every(
|
||||
(label, index) => index === 0 || label !== labels[index - 1],
|
||||
@@ -166,8 +166,10 @@ export function buildHeatmapConfig({
|
||||
builder.setFocus({ alpha: 1 });
|
||||
builder.setCursor({ focus: { prox: -1 }, points: { show: false } });
|
||||
|
||||
const formatBucketValue = (value: number): string =>
|
||||
getToolTipValue(String(value), yAxisUnit, decimalPrecision);
|
||||
const formatBucketValue = createBucketValueFormatter(
|
||||
yAxisUnit,
|
||||
decimalPrecision,
|
||||
);
|
||||
|
||||
const lastTimestamp = grid.timestamps[grid.timestamps.length - 1] ?? 0;
|
||||
const xRange: [number, number] = [
|
||||
|
||||
@@ -163,7 +163,7 @@ describe('Pie', () => {
|
||||
|
||||
renderPie();
|
||||
await user.hover(arcGroups()[0]);
|
||||
expect(screen.queryByTestId('pie-tooltip-footer')).toBeNull();
|
||||
expect(screen.queryByTestId('grouped-tooltip-footer')).toBeNull();
|
||||
});
|
||||
|
||||
it('does not re-render the legend while the tooltip follows the cursor', async () => {
|
||||
@@ -324,7 +324,7 @@ describe('Pie', () => {
|
||||
expect(screen.queryByTestId('uplot-tooltip-list')).toBeNull();
|
||||
|
||||
await user.click(await hoverOther());
|
||||
await user.click(screen.getByTestId('pie-tooltip-unpin'));
|
||||
await user.click(screen.getByTestId('grouped-tooltip-unpin'));
|
||||
expect(screen.queryByTestId('uplot-tooltip-list')).toBeNull();
|
||||
});
|
||||
|
||||
@@ -361,7 +361,7 @@ describe('Pie', () => {
|
||||
await user.click(await hoverOther());
|
||||
|
||||
expect(screen.queryByTestId('uplot-tooltip-item-button')).toBeNull();
|
||||
expect(screen.getByTestId('pie-tooltip-unpin')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('grouped-tooltip-unpin')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -5,7 +5,7 @@ import TooltipList from 'lib/uPlotV2/components/Tooltip/components/TooltipList/T
|
||||
import TooltipPinnedBadge from 'lib/uPlotV2/components/Tooltip/components/TooltipPinnedBadge/TooltipPinnedBadge';
|
||||
|
||||
import { PieTooltipData } from 'lib/visualization/charts/Pie/types';
|
||||
import PieTooltipFooter from 'lib/visualization/charts/Pie/components/PieTooltip/PieTooltipFooter';
|
||||
import GroupedTooltipFooter from 'lib/visualization/panels/components/GroupedTooltipFooter';
|
||||
|
||||
import styles from 'lib/visualization/charts/Pie/components/PieTooltip/PieTooltip.module.scss';
|
||||
|
||||
@@ -59,7 +59,7 @@ export default function PieTooltipContent({
|
||||
</>
|
||||
)}
|
||||
{showFooter && (
|
||||
<PieTooltipFooter
|
||||
<GroupedTooltipFooter
|
||||
isGroup={!!groupedMembers}
|
||||
isPinned={isPinned}
|
||||
canDrilldown={canDrilldown}
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
import type { PieSlice } from 'lib/visualization/charts/types';
|
||||
|
||||
import {
|
||||
groupPieSlices,
|
||||
OTHER_SLICE_LABEL,
|
||||
} from 'lib/visualization/charts/Pie/utils/groupPieSlices';
|
||||
import { groupPieSlices } from 'lib/visualization/charts/Pie/utils/groupPieSlices';
|
||||
import { OTHER_GROUP_LABEL } from 'lib/visualization/charts/utils/otherGroup';
|
||||
|
||||
const slice = (label: string, value: number): PieSlice => ({
|
||||
label,
|
||||
@@ -29,7 +27,7 @@ describe('groupPieSlices', () => {
|
||||
expect(result.map((s) => [s.label, s.value])).toStrictEqual([
|
||||
['b', 400],
|
||||
['a', 500],
|
||||
[OTHER_SLICE_LABEL, 7],
|
||||
[OTHER_GROUP_LABEL, 7],
|
||||
]);
|
||||
expect(result[2].groupedMembers?.map((s) => s.label)).toStrictEqual([
|
||||
'tail2',
|
||||
@@ -48,7 +46,7 @@ describe('groupPieSlices', () => {
|
||||
expect(result.slice(0, 14).map((s) => s.label)).toStrictEqual(
|
||||
slices.slice(0, 14).map((s) => s.label),
|
||||
);
|
||||
expect(result[14].label).toBe(OTHER_SLICE_LABEL);
|
||||
expect(result[14].label).toBe(OTHER_GROUP_LABEL);
|
||||
expect(result[14].groupedMembers).toHaveLength(16);
|
||||
});
|
||||
|
||||
@@ -72,7 +70,7 @@ describe('groupPieSlices', () => {
|
||||
|
||||
const result = group(slices);
|
||||
|
||||
expect(result.map((s) => s.label)).toStrictEqual(['a', OTHER_SLICE_LABEL]);
|
||||
expect(result.map((s) => s.label)).toStrictEqual(['a', OTHER_GROUP_LABEL]);
|
||||
expect(result[1].value).toBe(400);
|
||||
expect(result[1].groupedMembers).toHaveLength(400);
|
||||
});
|
||||
@@ -91,7 +89,7 @@ describe('groupPieSlices', () => {
|
||||
'a',
|
||||
'b',
|
||||
'c',
|
||||
OTHER_SLICE_LABEL,
|
||||
OTHER_GROUP_LABEL,
|
||||
]);
|
||||
expect(result[3].groupedMembers).toHaveLength(13);
|
||||
});
|
||||
@@ -105,7 +103,7 @@ describe('groupPieSlices', () => {
|
||||
expect(result.slice(0, 14).map((s) => s.label)).toStrictEqual(
|
||||
slices.slice(0, 14).map((s) => s.label),
|
||||
);
|
||||
expect(result[14].label).toBe(OTHER_SLICE_LABEL);
|
||||
expect(result[14].label).toBe(OTHER_GROUP_LABEL);
|
||||
expect(result[14].groupedMembers).toHaveLength(186);
|
||||
expect(result[14].value).toBe(930);
|
||||
});
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { Color } from '@signozhq/design-tokens';
|
||||
import type { PieSlice } from 'lib/visualization/charts/types';
|
||||
|
||||
export const OTHER_SLICE_LABEL = 'Other';
|
||||
import {
|
||||
OTHER_GROUP_LABEL,
|
||||
resolveOtherColor,
|
||||
} from 'lib/visualization/charts/utils/otherGroup';
|
||||
|
||||
const MIN_SHARE = 0.01;
|
||||
const MAX_SLICES = 15;
|
||||
@@ -31,9 +32,9 @@ export function groupPieSlices(
|
||||
|
||||
const kept = new Set(sorted.slice(0, keptCount));
|
||||
const other: PieSlice = {
|
||||
label: OTHER_SLICE_LABEL,
|
||||
label: OTHER_GROUP_LABEL,
|
||||
value: groupedMembers.reduce((sum, slice) => sum + slice.value, 0),
|
||||
color: isDarkMode ? Color.BG_SLATE_50 : Color.BG_VANILLA_400,
|
||||
color: resolveOtherColor(isDarkMode),
|
||||
groupedMembers,
|
||||
};
|
||||
return [...slices.filter((slice) => kept.has(slice)), other];
|
||||
|
||||
@@ -26,6 +26,11 @@ import {
|
||||
} from 'lib/uPlotV2/plugins/TooltipPlugin/types';
|
||||
import { BaseAutocompleteData } from 'types/api/queryBuilder/queryAutocompleteResponse';
|
||||
import type { StackMode } from 'lib/uPlotV2/config/types';
|
||||
import type {
|
||||
DistributionBarClick,
|
||||
DistributionSeries,
|
||||
DistributionYScale,
|
||||
} from 'lib/visualization/charts/Distribution/types';
|
||||
|
||||
interface BaseChartProps {
|
||||
width: number;
|
||||
@@ -37,6 +42,8 @@ interface BaseChartProps {
|
||||
pinKey?: string;
|
||||
/** Called when the user clicks the uPlot overlay. Receives resolved click data. */
|
||||
onClick?: (clickData: ChartClickData) => void;
|
||||
/** With `canPinTooltip`, a click it returns true for pins the tooltip instead of calling `onClick`. */
|
||||
shouldPinOnClick?: (clickData: ChartClickData) => boolean;
|
||||
yAxisUnit?: string;
|
||||
decimalPrecision?: PrecisionOption;
|
||||
pinnedTooltipElement?: (clickData: ChartClickData) => React.ReactNode;
|
||||
@@ -169,6 +176,48 @@ export interface HeatmapChartProps {
|
||||
'data-testid'?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whole-range bucket counts, one series per group, drawn as bars whose widths follow
|
||||
* the bucket bounds. Builds its own config, since `buckets` fully determines the x
|
||||
* axis. `buckets` and `series` must be referentially stable: a new identity rebuilds
|
||||
* the plot.
|
||||
*/
|
||||
export interface DistributionChartProps {
|
||||
/** Widget id; the group selection persists under it. */
|
||||
id: string;
|
||||
/** Ascending. N boundaries describe N+1 buckets, the last one overflow. */
|
||||
buckets: number[];
|
||||
series: DistributionSeries[];
|
||||
width: number;
|
||||
height: number;
|
||||
isDarkMode: boolean;
|
||||
/** Buckets wholly below it are hidden. */
|
||||
xMin?: number;
|
||||
/** Buckets wholly above it are hidden; unset crops trailing empty buckets. */
|
||||
xMax?: number;
|
||||
/** Default linear. Ignored under `percent`, whose axis is a share. */
|
||||
yScale?: DistributionYScale;
|
||||
/** Default normal. `none` draws the groups side by side. */
|
||||
stack?: StackMode;
|
||||
/** Unit of the bucket bounds; counts are always plain numbers. */
|
||||
xAxisUnit?: string;
|
||||
decimalPrecision?: PrecisionOption;
|
||||
/** Hex colours keyed by group label, overriding the automatic palette. */
|
||||
customColors?: Record<string, string>;
|
||||
/** 0–100. Marked across the plot, over the visible groups combined. */
|
||||
percentiles?: readonly number[];
|
||||
/** Fires for a click on a group's bar; not on Other or empty space. */
|
||||
onBarClick?: (click: DistributionBarClick) => void;
|
||||
showLegend?: boolean;
|
||||
legendPosition?: LegendPosition;
|
||||
showTooltip?: boolean;
|
||||
canPinTooltip?: boolean;
|
||||
renderTooltipFooter?: (args: IRenderTooltipFooterArgs) => React.ReactNode;
|
||||
tooltipPortalRoot?: HTMLElement | null;
|
||||
layoutChildren?: React.ReactNode;
|
||||
'data-testid'?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* One resolved pie/donut slice: a display label, its (already parsed) positive
|
||||
* numeric value, and the colour used for the arc + legend swatch.
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
import { Color } from '@signozhq/design-tokens';
|
||||
|
||||
/** The slice or series summing the groups a chart folds away. */
|
||||
export const OTHER_GROUP_LABEL = 'Other';
|
||||
|
||||
/** Neutral, so the summed remainder never reads as one more group. */
|
||||
export function resolveOtherColor(isDarkMode: boolean): string {
|
||||
return isDarkMode ? Color.BG_SLATE_50 : Color.BG_VANILLA_400;
|
||||
}
|
||||
@@ -2,22 +2,25 @@ import { MousePointerClick, X } from '@signozhq/icons';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { Kbd } from '@signozhq/ui/kbd';
|
||||
|
||||
import footerStyles from 'lib/visualization/panels/components/TooltipFooter.module.scss';
|
||||
import footerStyles from './TooltipFooter.module.scss';
|
||||
|
||||
interface PieTooltipFooterProps {
|
||||
interface GroupedTooltipFooterProps {
|
||||
isGroup: boolean;
|
||||
isPinned: boolean;
|
||||
canDrilldown: boolean;
|
||||
onUnpin: () => void;
|
||||
}
|
||||
|
||||
/** The timeseries tooltip footer's look, with the pie's click-to-pin hints. */
|
||||
export default function PieTooltipFooter({
|
||||
/**
|
||||
* The time-series tooltip footer's look, with the click-to-pin hints of a grouped item
|
||||
* (Pie's Other slice, Distribution's Other bar) whose series are picked once pinned.
|
||||
*/
|
||||
export default function GroupedTooltipFooter({
|
||||
isGroup,
|
||||
isPinned,
|
||||
canDrilldown,
|
||||
onUnpin,
|
||||
}: PieTooltipFooterProps): JSX.Element {
|
||||
}: GroupedTooltipFooterProps): JSX.Element {
|
||||
let clickHint = canDrilldown ? 'Click to drilldown' : null;
|
||||
if (isGroup) {
|
||||
clickHint = canDrilldown
|
||||
@@ -29,7 +32,7 @@ export default function PieTooltipFooter({
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={footerStyles.footer} data-testid="pie-tooltip-footer">
|
||||
<div className={footerStyles.footer} data-testid="grouped-tooltip-footer">
|
||||
<div className={footerStyles.hintList}>
|
||||
{clickHint && (
|
||||
<div className={footerStyles.hint} data-active="false">
|
||||
@@ -42,7 +45,7 @@ export default function PieTooltipFooter({
|
||||
{isPinned && (
|
||||
<div className={footerStyles.hint} data-active="false">
|
||||
<span>Press</span>
|
||||
<Kbd value="Escape" testId="pie-tooltip-escape-key" />
|
||||
<Kbd value="Escape" testId="grouped-tooltip-escape-key" />
|
||||
<span>to unpin</span>
|
||||
</div>
|
||||
)}
|
||||
@@ -55,7 +58,7 @@ export default function PieTooltipFooter({
|
||||
size="sm"
|
||||
onClick={onUnpin}
|
||||
aria-label="Unpin tooltip"
|
||||
testId="pie-tooltip-unpin"
|
||||
testId="grouped-tooltip-unpin"
|
||||
prefix={<X size={10} />}
|
||||
>
|
||||
<span>Unpin</span>
|
||||
@@ -6,10 +6,12 @@
|
||||
import { TIMELINE_TABLE_PAGE_SIZE } from 'container/AlertHistory/constants';
|
||||
import { rest } from 'msw';
|
||||
|
||||
import { countControl } from '@/storybook/controls/controls';
|
||||
import { choiceControl, countControl } from '@/storybook/controls/controls';
|
||||
import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';
|
||||
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
|
||||
|
||||
import {
|
||||
RELATED_EXPLORERS,
|
||||
ruleHistoryFilterKeysResponse,
|
||||
ruleHistoryFilterValuesResponse,
|
||||
ruleHistoryOverallStatusResponse,
|
||||
@@ -19,6 +21,7 @@ import {
|
||||
TIMELINE_MAX,
|
||||
TOP_CONTRIBUTOR_MAX,
|
||||
type HistoryWindow,
|
||||
type RelatedExplorer,
|
||||
} from './__story_mockdata__/alertHistory';
|
||||
|
||||
import {
|
||||
@@ -75,6 +78,13 @@ export const alertHistoryMocks = defineStoryMocks({
|
||||
value: 30,
|
||||
max: 60,
|
||||
}),
|
||||
relatedExplorer: choiceControl<RelatedExplorer>('Related explorer', {
|
||||
group: TIMELINE,
|
||||
description:
|
||||
"Where a row's actions lead, for top contributors and timeline rows alike. The backend picks it from the rule's alert type; `none` is a metrics rule, whose actions are disabled.",
|
||||
options: RELATED_EXPLORERS,
|
||||
value: 'traces',
|
||||
}),
|
||||
},
|
||||
handlers: (values, response) => [
|
||||
rest.get(
|
||||
@@ -91,7 +101,11 @@ export const alertHistoryMocks = defineStoryMocks({
|
||||
rest.get(
|
||||
'http://localhost/api/v2/rules/:id/history/top_contributors',
|
||||
response.json(() =>
|
||||
ruleHistoryTopContributorsResponse(values.topContributors, values.triggers),
|
||||
ruleHistoryTopContributorsResponse(
|
||||
values.topContributors,
|
||||
values.triggers,
|
||||
values.relatedExplorer,
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
@@ -111,6 +125,7 @@ export const alertHistoryMocks = defineStoryMocks({
|
||||
end: windowOf(req).end,
|
||||
ruleId: String(req.params.id),
|
||||
ruleName: FIRST_RULE_NAME,
|
||||
relatedExplorer: values.relatedExplorer,
|
||||
}),
|
||||
),
|
||||
),
|
||||
@@ -146,3 +161,21 @@ export const alertHistoryMocks = defineStoryMocks({
|
||||
route: `/alerts/history?ruleId=${STORY_RULE_ID}&relativeTime=${STORY_RELATIVE_TIME}`,
|
||||
}),
|
||||
});
|
||||
|
||||
export type AlertHistoryArgs = PageStoryArgs<typeof alertHistoryMocks>;
|
||||
|
||||
export const untilLoaded = { timeout: 15_000 };
|
||||
|
||||
export const listsTimelineRows = (args: AlertHistoryArgs): boolean =>
|
||||
args.dataState === 'loaded' && args.timelineEntries > 0;
|
||||
|
||||
const POPOVER_LINK_TEST_IDS: Record<RelatedExplorer, string | null> = {
|
||||
logs: 'alert-popover-view-logs',
|
||||
traces: 'alert-popover-view-traces',
|
||||
'ai-traces': 'alert-popover-view-ai-traces',
|
||||
none: null,
|
||||
};
|
||||
|
||||
/** The popover link a row's actions open, or null when the rule has none and the actions are disabled. */
|
||||
export const rowActionLinkTestId = (args: AlertHistoryArgs): string | null =>
|
||||
POPOVER_LINK_TEST_IDS[args.relatedExplorer];
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
import type { Meta, StoryObj } from '@storybook/react-vite';
|
||||
|
||||
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
|
||||
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
|
||||
|
||||
import { alertHistoryMocks } from './AlertHistory.stories.mocks';
|
||||
import {
|
||||
alertHistoryMocks,
|
||||
type AlertHistoryArgs,
|
||||
} from './AlertHistory.stories.mocks';
|
||||
import { openRowActions } from './__story_mockdata__/alertHistory.play';
|
||||
|
||||
import AlertList from '../../index';
|
||||
|
||||
type AlertHistoryArgs = PageStoryArgs<typeof alertHistoryMocks>;
|
||||
|
||||
const pageStory = storyMocks(alertHistoryMocks, { layout: 'app' });
|
||||
|
||||
/**
|
||||
@@ -19,6 +20,7 @@ const pageStory = storyMocks(alertHistoryMocks, { layout: 'app' });
|
||||
*/
|
||||
const meta = {
|
||||
title: 'Pages/Alerts/History',
|
||||
tags: ['play'],
|
||||
component: AlertList,
|
||||
...pageStory,
|
||||
parameters: { ...pageStory.parameters },
|
||||
@@ -49,3 +51,12 @@ export const NeverTriggered: Story = {
|
||||
export const Noisy: Story = {
|
||||
args: { triggers: 184, timelineEntries: 40, topContributors: 8 },
|
||||
};
|
||||
|
||||
/**
|
||||
* A timeline row's actions on an AI traces rule: the popover's one link opens
|
||||
* the AI traces explorer.
|
||||
*/
|
||||
export const AITracesRowActions: Story = {
|
||||
args: { relatedExplorer: 'ai-traces' },
|
||||
play: openRowActions,
|
||||
};
|
||||
|
||||
42
frontend/src/pages/AlertList/AlertHistory/stories/__story_mockdata__/alertHistory.play.ts
generated
Normal file
42
frontend/src/pages/AlertList/AlertHistory/stories/__story_mockdata__/alertHistory.play.ts
generated
Normal file
@@ -0,0 +1,42 @@
|
||||
/**
|
||||
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
|
||||
* Do not hand-edit: regenerate instead.
|
||||
*/
|
||||
|
||||
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
|
||||
|
||||
import {
|
||||
type AlertHistoryArgs,
|
||||
listsTimelineRows,
|
||||
rowActionLinkTestId,
|
||||
untilLoaded,
|
||||
} from '../AlertHistory.stories.mocks';
|
||||
|
||||
interface PlayContext {
|
||||
canvasElement: HTMLElement;
|
||||
args: AlertHistoryArgs;
|
||||
}
|
||||
|
||||
export const openRowActions = async ({
|
||||
canvasElement,
|
||||
args,
|
||||
}: PlayContext): Promise<void> => {
|
||||
if (!listsTimelineRows(args)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const [actions] = await within(canvasElement).findAllByTestId(
|
||||
'timeline-row-actions',
|
||||
undefined,
|
||||
untilLoaded,
|
||||
);
|
||||
const linkTestId = rowActionLinkTestId(args);
|
||||
if (!linkTestId) {
|
||||
await expect(actions).toHaveAttribute('disabled');
|
||||
return;
|
||||
}
|
||||
|
||||
await userEvent.click(actions);
|
||||
const link = await screen.findByTestId(linkTestId);
|
||||
await waitFor(() => expect(link).toBeVisible());
|
||||
};
|
||||
@@ -88,19 +88,46 @@ export const ruleHistoryStatsResponse = (
|
||||
};
|
||||
};
|
||||
|
||||
export const RELATED_EXPLORERS = [
|
||||
'logs',
|
||||
'traces',
|
||||
'ai-traces',
|
||||
'none',
|
||||
] as const;
|
||||
|
||||
export type RelatedExplorer = (typeof RELATED_EXPLORERS)[number];
|
||||
|
||||
type RelatedLinks = Pick<
|
||||
RulestatehistorytypesGettableRuleStateHistoryDTO,
|
||||
'relatedLogsLink' | 'relatedTracesLink' | 'relatedAITracesLink'
|
||||
>;
|
||||
|
||||
// The backend sends one link, picked by the rule's alert type, as explorer query params.
|
||||
const RELATED_LINK_PARAMS = 'relativeTime=6h';
|
||||
|
||||
const RELATED_LINKS: Record<RelatedExplorer, RelatedLinks> = {
|
||||
logs: { relatedLogsLink: RELATED_LINK_PARAMS },
|
||||
traces: { relatedTracesLink: RELATED_LINK_PARAMS },
|
||||
'ai-traces': { relatedAITracesLink: RELATED_LINK_PARAMS },
|
||||
none: {},
|
||||
};
|
||||
|
||||
const relatedLinksFor = (explorer: RelatedExplorer): RelatedLinks =>
|
||||
RELATED_LINKS[explorer];
|
||||
|
||||
export const TOP_CONTRIBUTOR_MAX = 8;
|
||||
|
||||
export const ruleHistoryTopContributorsResponse = (
|
||||
count: number,
|
||||
totalTriggers: number,
|
||||
relatedExplorer: RelatedExplorer,
|
||||
): GetRuleHistoryTopContributors200 => ({
|
||||
status: 'success',
|
||||
data: Array.from({ length: count }, (_unused, index) => ({
|
||||
fingerprint: 100_000 + index,
|
||||
count: Math.max(1, Math.round(totalTriggers / (index + 2))),
|
||||
labels: labelsFor(index),
|
||||
relatedLogsLink: 'http://localhost/logs/logs-explorer',
|
||||
relatedTracesLink: 'http://localhost/traces-explorer',
|
||||
...relatedLinksFor(relatedExplorer),
|
||||
})),
|
||||
});
|
||||
|
||||
@@ -136,6 +163,7 @@ export interface TimelineShape {
|
||||
state?: RuletypesAlertStateDTO;
|
||||
ruleId: string;
|
||||
ruleName: string;
|
||||
relatedExplorer: RelatedExplorer;
|
||||
}
|
||||
|
||||
const timelineItem = (
|
||||
@@ -159,8 +187,7 @@ const timelineItem = (
|
||||
stateChanged: index % 2 === 0,
|
||||
unixMilli: shape.end - index * 7 * MINUTE,
|
||||
value: Number((60 + (index % 9) * 4.5).toFixed(2)),
|
||||
relatedLogsLink: 'http://localhost/logs/logs-explorer',
|
||||
relatedTracesLink: 'http://localhost/traces-explorer',
|
||||
...relatedLinksFor(shape.relatedExplorer),
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
@@ -35,6 +35,7 @@ const ALERT_MODES = [
|
||||
'metrics',
|
||||
'logs',
|
||||
'traces',
|
||||
'ai-traces',
|
||||
'exceptions',
|
||||
'anomaly',
|
||||
] as const;
|
||||
@@ -45,6 +46,7 @@ const ALERT_TYPE_BY_MODE: Partial<Record<AlertMode, AlertTypes>> = {
|
||||
metrics: AlertTypes.METRICS_BASED_ALERT,
|
||||
logs: AlertTypes.LOGS_BASED_ALERT,
|
||||
traces: AlertTypes.TRACES_BASED_ALERT,
|
||||
'ai-traces': AlertTypes.AI_TRACES_BASED_ALERT,
|
||||
exceptions: AlertTypes.EXCEPTIONS_BASED_ALERT,
|
||||
anomaly: AlertTypes.METRICS_BASED_ALERT,
|
||||
};
|
||||
@@ -191,9 +193,9 @@ export const clickFooterButton = async (
|
||||
): Promise<void> => {
|
||||
const button = await within(canvasElement).findByTestId(testId);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(button).toBeEnabled();
|
||||
expect(button).not.toHaveAttribute('aria-disabled', 'true');
|
||||
await waitFor(async () => {
|
||||
await expect(button).toBeEnabled();
|
||||
await expect(button).not.toHaveAttribute('aria-disabled', 'true');
|
||||
});
|
||||
await userEvent.click(button);
|
||||
};
|
||||
|
||||
@@ -51,6 +51,14 @@ export const LogsAlert: Story = {
|
||||
args: { alertMode: 'logs' },
|
||||
};
|
||||
|
||||
/**
|
||||
* An AI traces alert, whose query section has only the AI Query Builder tab,
|
||||
* querying traces.
|
||||
*/
|
||||
export const AITracesAlert: Story = {
|
||||
args: { alertMode: 'ai-traces' },
|
||||
};
|
||||
|
||||
/**
|
||||
* Anomaly detection: the condition is a number of deviations from the seasonal
|
||||
* forecast instead of a fixed threshold, and only builder metric queries apply.
|
||||
|
||||
@@ -2,4 +2,5 @@
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
background: var(--l1-background);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
import { Flame } from '@signozhq/icons';
|
||||
import type { DashboardtypesPanelDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import { isAIQueryType } from 'lib/query/builderSlot';
|
||||
import { getPanelDefinition } from 'pages/DashboardPage/DashboardContainer/Panels/registry';
|
||||
import { useCreateAlertFromPanel } from 'pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Panel/hooks/useCreateAlertFromPanel';
|
||||
|
||||
@@ -24,13 +22,11 @@ function ConfigActions({
|
||||
panelId,
|
||||
}: ConfigActionsProps): JSX.Element | null {
|
||||
const createAlert = useCreateAlertFromPanel();
|
||||
const { currentQuery } = useQueryBuilder();
|
||||
const { actions } = getPanelDefinition(panel.spec.plugin.kind);
|
||||
|
||||
// Only kinds whose query can seed an alert offer this today; mirror the panel
|
||||
// menu's create-alert capability.
|
||||
//TODO: AI query check should be removed after we support alerts on ai query @tewarig
|
||||
if (!actions.createAlert || isAIQueryType(currentQuery.queryType)) {
|
||||
if (!actions.createAlert) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user