mirror of
https://github.com/SigNoz/signoz.git
synced 2026-10-30 13:00:42 +00:00
Compare commits
2 Commits
refactor/s
...
refactor/m
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5d7f068085 | ||
|
|
44bbf847dd |
@@ -1,6 +1,6 @@
|
||||
import { useMemo } from 'react';
|
||||
import MEditor, { EditorProps } from '@monaco-editor/react';
|
||||
import { useIsDarkMode } from 'hooks/useDarkMode';
|
||||
import { EditorProps } from '@monaco-editor/react';
|
||||
import MonacoEditor from 'lib/monaco/MonacoEditor';
|
||||
|
||||
function Editor({
|
||||
value,
|
||||
@@ -10,8 +10,6 @@ function Editor({
|
||||
height,
|
||||
options,
|
||||
}: MEditorProps): JSX.Element {
|
||||
const isDarkMode = useIsDarkMode();
|
||||
|
||||
const onChangeHandler = (newValue?: string): void => {
|
||||
if (readOnly) {
|
||||
return;
|
||||
@@ -28,8 +26,7 @@ function Editor({
|
||||
);
|
||||
|
||||
return (
|
||||
<MEditor
|
||||
theme={isDarkMode ? 'vs-dark' : 'vs-light'}
|
||||
<MonacoEditor
|
||||
language={language}
|
||||
value={value}
|
||||
options={editorOptions}
|
||||
|
||||
@@ -4,7 +4,6 @@ import { Button } from '@signozhq/ui/button';
|
||||
import { Drawer, Tooltip } from 'antd';
|
||||
import { ToggleGroup } from '@signozhq/ui/toggle-group';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import LogStateIndicator from 'components/Logs/LogStateIndicator/LogStateIndicator';
|
||||
import OverlayScrollbar from 'components/OverlayScrollbar/OverlayScrollbar';
|
||||
import QuerySearch from 'components/QueryBuilderV2/QueryV2/QuerySearch/QuerySearch';
|
||||
@@ -148,7 +147,7 @@ function LogDetailInner({
|
||||
|
||||
const { options } = useOptionsMenu({
|
||||
storageKey: LOCALSTORAGE.LOGS_LIST_OPTIONS,
|
||||
sourcePage: SavedviewtypesSourceDTO.logs,
|
||||
dataSource: DataSource.LOGS,
|
||||
aggregateOperator: listQuery?.aggregateOperator || StringOperators.NOOP,
|
||||
});
|
||||
|
||||
|
||||
@@ -1,17 +1,11 @@
|
||||
import MEditor from '@monaco-editor/react';
|
||||
import { Play, RotateCcw } from '@signozhq/icons';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { Callout } from '@signozhq/ui/callout';
|
||||
import { useIsDarkMode } from 'hooks/useDarkMode';
|
||||
import MonacoEditor from 'lib/monaco/MonacoEditor';
|
||||
|
||||
import styles from './TestTab.module.scss';
|
||||
import JsonEditorSkeleton from './JsonEditorSkeleton';
|
||||
import TestResult from './TestResult';
|
||||
import {
|
||||
defineSignozJsonTheme,
|
||||
SIGNOZ_JSON_THEME_DARK,
|
||||
SIGNOZ_JSON_THEME_LIGHT,
|
||||
} from './jsonEditorTheme';
|
||||
import { UseTestSpanMapper } from './useTestSpanMapper';
|
||||
|
||||
interface TestTabProps {
|
||||
@@ -32,7 +26,6 @@ function TestTab({ spanTest }: TestTabProps): JSX.Element {
|
||||
error,
|
||||
validationError,
|
||||
} = spanTest;
|
||||
const isDarkMode = useIsDarkMode();
|
||||
|
||||
function renderResults(): JSX.Element {
|
||||
if (error) {
|
||||
@@ -122,14 +115,12 @@ function TestTab({ spanTest }: TestTabProps): JSX.Element {
|
||||
data-testid="test-span-input"
|
||||
aria-label="Sample span JSON"
|
||||
>
|
||||
<MEditor
|
||||
<MonacoEditor
|
||||
language="json"
|
||||
value={input}
|
||||
onChange={(value): void => setInput(value ?? '')}
|
||||
height="100%"
|
||||
loading={<JsonEditorSkeleton />}
|
||||
theme={isDarkMode ? SIGNOZ_JSON_THEME_DARK : SIGNOZ_JSON_THEME_LIGHT}
|
||||
beforeMount={defineSignozJsonTheme}
|
||||
options={{
|
||||
minimap: { enabled: false },
|
||||
fontSize: 12,
|
||||
|
||||
@@ -1,38 +0,0 @@
|
||||
//TODO: This is a local theme for now, but ideally for the editor as well. Just like prettyViewer, we have a theme. We should have a theme for the editor as well.
|
||||
import { Monaco } from '@monaco-editor/react';
|
||||
import { Color } from '@signozhq/design-tokens';
|
||||
|
||||
export const SIGNOZ_JSON_THEME_DARK = 'signoz-attr-mapping-json-dark';
|
||||
export const SIGNOZ_JSON_THEME_LIGHT = 'signoz-attr-mapping-json-light';
|
||||
|
||||
const SHARED_THEME = {
|
||||
inherit: true,
|
||||
colors: {
|
||||
'editor.background': '#00000000', // transparent — inherit the panel bg
|
||||
},
|
||||
fontFamily: 'SF Mono, Geist Mono, Fira Code, monospace',
|
||||
fontSize: 12,
|
||||
fontWeight: 'normal',
|
||||
lineHeight: 18,
|
||||
letterSpacing: -0.06,
|
||||
};
|
||||
|
||||
export function defineSignozJsonTheme(monaco: Monaco): void {
|
||||
monaco.editor.defineTheme(SIGNOZ_JSON_THEME_DARK, {
|
||||
...SHARED_THEME,
|
||||
base: 'vs-dark',
|
||||
rules: [
|
||||
{ token: 'string.key.json', foreground: Color.BG_ROBIN_400 },
|
||||
{ token: 'string.value.json', foreground: Color.BG_VANILLA_400 },
|
||||
],
|
||||
});
|
||||
|
||||
monaco.editor.defineTheme(SIGNOZ_JSON_THEME_LIGHT, {
|
||||
...SHARED_THEME,
|
||||
base: 'vs',
|
||||
rules: [
|
||||
{ token: 'string.key.json', foreground: Color.BG_ROBIN_500 },
|
||||
{ token: 'string.value.json', foreground: Color.BG_INK_400 },
|
||||
],
|
||||
});
|
||||
}
|
||||
@@ -2,7 +2,6 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useLocation } from 'react-router-dom';
|
||||
import { Switch } from '@signozhq/ui/switch';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import FieldsSelector from 'components/FieldsSelector';
|
||||
import LogsFormatOptionsMenu from 'components/LogsFormatOptionsMenu/LogsFormatOptionsMenu';
|
||||
import { MAX_LOGS_LIST_SIZE } from 'constants/liveTail';
|
||||
@@ -55,7 +54,7 @@ function LiveLogsContainer({
|
||||
|
||||
const { options, config } = useOptionsMenu({
|
||||
storageKey: LOCALSTORAGE.LOGS_LIST_OPTIONS,
|
||||
sourcePage: SavedviewtypesSourceDTO.logs,
|
||||
dataSource: DataSource.LOGS,
|
||||
aggregateOperator: listQuery?.aggregateOperator || StringOperators.NOOP,
|
||||
});
|
||||
|
||||
|
||||
@@ -5,7 +5,6 @@ import { Virtuoso, VirtuosoHandle } from 'react-virtuoso';
|
||||
import { toast } from '@signozhq/ui/sonner';
|
||||
import { Card } from 'antd';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import LogDetail from 'components/LogDetail';
|
||||
import { VIEW_TYPES } from 'components/LogDetail/constants';
|
||||
import ListLogView from 'components/Logs/ListLogView';
|
||||
@@ -31,7 +30,7 @@ import { useIsDarkMode } from 'hooks/useDarkMode';
|
||||
import { useEventSource } from 'providers/EventSource';
|
||||
// interfaces
|
||||
import { ILog } from 'types/api/logs/log';
|
||||
import { StringOperators } from 'types/common/queryBuilder';
|
||||
import { DataSource, StringOperators } from 'types/common/queryBuilder';
|
||||
|
||||
import loadingPlaneUrl from '@/assets/Icons/loading-plane.gif';
|
||||
import { getAbsoluteUrl } from 'utils/basePath';
|
||||
@@ -69,7 +68,7 @@ function LiveLogsList({
|
||||
|
||||
const { options, config } = useOptionsMenu({
|
||||
storageKey: LOCALSTORAGE.LOGS_LIST_OPTIONS,
|
||||
sourcePage: SavedviewtypesSourceDTO.logs,
|
||||
dataSource: DataSource.LOGS,
|
||||
aggregateOperator: StringOperators.NOOP,
|
||||
});
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { Virtuoso } from 'react-virtuoso';
|
||||
import { Button, Skeleton } from 'antd';
|
||||
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import RawLogView from 'components/Logs/RawLogView';
|
||||
import OverlayScrollbar from 'components/OverlayScrollbar/OverlayScrollbar';
|
||||
import { LOCALSTORAGE } from 'constants/localStorage';
|
||||
@@ -17,7 +16,7 @@ import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import useUrlQuery from 'hooks/useUrlQuery';
|
||||
import { ILog } from 'types/api/logs/log';
|
||||
import { Query, TagFilter } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { StringOperators } from 'types/common/queryBuilder';
|
||||
import { DataSource, StringOperators } from 'types/common/queryBuilder';
|
||||
import { withBasePath } from 'utils/basePath';
|
||||
|
||||
import { useContextLogData } from './useContextLogData';
|
||||
@@ -46,7 +45,7 @@ function ContextLogRenderer({
|
||||
|
||||
const { options } = useOptionsMenu({
|
||||
storageKey: LOCALSTORAGE.LOGS_LIST_OPTIONS,
|
||||
sourcePage: SavedviewtypesSourceDTO.logs,
|
||||
dataSource: DataSource.LOGS,
|
||||
aggregateOperator: listQuery?.aggregateOperator || StringOperators.NOOP,
|
||||
});
|
||||
|
||||
|
||||
@@ -5,7 +5,6 @@ import { Virtuoso, VirtuosoHandle } from 'react-virtuoso';
|
||||
import { toast } from '@signozhq/ui/sonner';
|
||||
import { Card } from 'antd';
|
||||
import logEvent from 'api/common/logEvent';
|
||||
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import ErrorInPlace from 'components/ErrorInPlace/ErrorInPlace';
|
||||
import LogDetail from 'components/LogDetail';
|
||||
import { VIEW_TYPES } from 'components/LogDetail/constants';
|
||||
@@ -78,7 +77,7 @@ function LogsExplorerList({
|
||||
|
||||
const { options, config } = useOptionsMenu({
|
||||
storageKey: LOCALSTORAGE.LOGS_LIST_OPTIONS,
|
||||
sourcePage: SavedviewtypesSourceDTO.logs,
|
||||
dataSource: DataSource.LOGS,
|
||||
aggregateOperator:
|
||||
currentStagedQueryData?.aggregateOperator || StringOperators.NOOP,
|
||||
});
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { ReactNode, useState } from 'react';
|
||||
import { Switch } from '@signozhq/ui/switch';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import DownloadOptionsMenu from 'components/DownloadOptionsMenu/DownloadOptionsMenu';
|
||||
import FieldsSelector from 'components/FieldsSelector';
|
||||
import LogsFormatOptionsMenu from 'components/LogsFormatOptionsMenu/LogsFormatOptionsMenu';
|
||||
@@ -29,7 +28,7 @@ function LogsActionsContainer({
|
||||
}): JSX.Element {
|
||||
const { options, config } = useOptionsMenu({
|
||||
storageKey: LOCALSTORAGE.LOGS_LIST_OPTIONS,
|
||||
sourcePage: SavedviewtypesSourceDTO.logs,
|
||||
dataSource: DataSource.LOGS,
|
||||
aggregateOperator: listQuery?.aggregateOperator || StringOperators.NOOP,
|
||||
});
|
||||
|
||||
|
||||
@@ -1,20 +1,11 @@
|
||||
import { createElement, ReactNode } from 'react';
|
||||
import { QueryClient, QueryClientProvider } from 'react-query';
|
||||
import type { NotificationInstance } from 'antd/es/notification/interface';
|
||||
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { useQueries } from 'react-query';
|
||||
import { renderHook } from '@testing-library/react';
|
||||
import { useGetQueryKeySuggestions } from 'hooks/querySuggestions/useGetQueryKeySuggestions';
|
||||
import { useNotifications } from 'hooks/useNotifications';
|
||||
import useUrlQueryData from 'hooks/useUrlQueryData';
|
||||
import { usePreferenceContext } from 'providers/preferences/context/PreferenceContextProvider';
|
||||
import {
|
||||
FormattingOptions,
|
||||
PreferenceContextValue,
|
||||
PreferenceSlice,
|
||||
} from 'providers/preferences/types';
|
||||
import { renderHook } from 'tests/test-utils';
|
||||
import { TelemetryFieldKey } from 'types/api/v5/queryRange';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import { FontSize } from '../types';
|
||||
import useOptionsMenu from '../useOptionsMenu';
|
||||
|
||||
// Mock all dependencies
|
||||
@@ -22,118 +13,104 @@ jest.mock('hooks/useNotifications');
|
||||
jest.mock('providers/preferences/context/PreferenceContextProvider');
|
||||
jest.mock('hooks/useUrlQueryData');
|
||||
jest.mock('hooks/querySuggestions/useGetQueryKeySuggestions');
|
||||
|
||||
const mockUseNotifications = jest.mocked(useNotifications);
|
||||
const mockUsePreferenceContext = jest.mocked(usePreferenceContext);
|
||||
const mockUseUrlQueryData = jest.mocked(useUrlQueryData);
|
||||
const mockUseGetQueryKeySuggestions = jest.mocked(useGetQueryKeySuggestions);
|
||||
|
||||
type KeySuggestionsResult = ReturnType<typeof useGetQueryKeySuggestions>;
|
||||
|
||||
// The hook reads only `data.data.data.keys` and `isFetching`.
|
||||
const keySuggestions = (
|
||||
attributeKeys: Record<string, string>[],
|
||||
): KeySuggestionsResult =>
|
||||
({
|
||||
data: { data: { data: { complete: true, keys: { attributeKeys } } } },
|
||||
isFetching: false,
|
||||
}) as unknown as KeySuggestionsResult;
|
||||
|
||||
const wrapper = ({ children }: { children: ReactNode }): JSX.Element =>
|
||||
createElement(QueryClientProvider, { client: new QueryClient() }, children);
|
||||
|
||||
const toIds = (columns: TelemetryFieldKey[]): string[] =>
|
||||
columns.map((column) => `${column.fieldContext}:${column.name}`);
|
||||
jest.mock('react-query', () => ({
|
||||
...jest.requireActual('react-query'),
|
||||
useQueries: jest.fn(),
|
||||
}));
|
||||
|
||||
describe('useOptionsMenu', () => {
|
||||
const mockNotifications = {
|
||||
error: jest.fn() as jest.MockedFunction<NotificationInstance['error']>,
|
||||
success: jest.fn() as jest.MockedFunction<NotificationInstance['success']>,
|
||||
} as Partial<NotificationInstance> as NotificationInstance;
|
||||
const mockUpdateColumns = jest.fn() as jest.MockedFunction<
|
||||
PreferenceSlice['updateColumns']
|
||||
>;
|
||||
const mockUpdateFormatting = jest.fn() as jest.MockedFunction<
|
||||
PreferenceSlice['updateFormatting']
|
||||
>;
|
||||
const mockRedirectWithQuery = jest.fn() as jest.MockedFunction<
|
||||
(newQueryData: unknown) => void
|
||||
>;
|
||||
|
||||
const slice = (
|
||||
columns: TelemetryFieldKey[],
|
||||
formatting: FormattingOptions,
|
||||
): PreferenceSlice => ({
|
||||
preferences: { columns, formatting },
|
||||
loading: false,
|
||||
error: null,
|
||||
updateColumns: mockUpdateColumns,
|
||||
updateFormatting: mockUpdateFormatting,
|
||||
});
|
||||
|
||||
const rawFormatting: FormattingOptions = {
|
||||
format: 'raw',
|
||||
maxLines: 1,
|
||||
fontSize: FontSize.SMALL,
|
||||
};
|
||||
const mockNotifications = { error: jest.fn(), success: jest.fn() };
|
||||
const mockUpdateColumns = jest.fn();
|
||||
const mockUpdateFormatting = jest.fn();
|
||||
const mockRedirectWithQuery = jest.fn();
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
|
||||
mockUseNotifications.mockReturnValue({
|
||||
(useNotifications as jest.Mock).mockReturnValue({
|
||||
notifications: mockNotifications,
|
||||
});
|
||||
|
||||
mockUsePreferenceContext.mockReturnValue({
|
||||
[SavedviewtypesSourceDTO.traces]: slice([], rawFormatting),
|
||||
[SavedviewtypesSourceDTO.logs]: slice([], rawFormatting),
|
||||
} satisfies PreferenceContextValue);
|
||||
(usePreferenceContext as jest.Mock).mockReturnValue({
|
||||
traces: {
|
||||
preferences: {
|
||||
columns: [],
|
||||
formatting: {
|
||||
format: 'raw',
|
||||
maxLines: 1,
|
||||
fontSize: 'small',
|
||||
},
|
||||
},
|
||||
updateColumns: mockUpdateColumns,
|
||||
updateFormatting: mockUpdateFormatting,
|
||||
},
|
||||
logs: {
|
||||
preferences: {
|
||||
columns: [],
|
||||
formatting: {
|
||||
format: 'raw',
|
||||
maxLines: 1,
|
||||
fontSize: 'small',
|
||||
},
|
||||
},
|
||||
updateColumns: mockUpdateColumns,
|
||||
updateFormatting: mockUpdateFormatting,
|
||||
},
|
||||
});
|
||||
|
||||
mockUseUrlQueryData.mockReturnValue({
|
||||
(useUrlQueryData as jest.Mock).mockReturnValue({
|
||||
query: null,
|
||||
queryData: undefined,
|
||||
redirectWithQuery: mockRedirectWithQuery,
|
||||
});
|
||||
|
||||
(useQueries as jest.Mock).mockReturnValue([]);
|
||||
});
|
||||
|
||||
it('does not show isRoot or isEntryPoint in column options when sourcePage is traces', () => {
|
||||
it('does not show isRoot or isEntryPoint in column options when dataSource is TRACES', () => {
|
||||
// Mock the query key suggestions to return data including isRoot and isEntryPoint
|
||||
mockUseGetQueryKeySuggestions.mockReturnValue(
|
||||
keySuggestions([
|
||||
{
|
||||
name: 'isRoot',
|
||||
signal: 'traces',
|
||||
fieldDataType: 'bool',
|
||||
fieldContext: '',
|
||||
(useGetQueryKeySuggestions as jest.Mock).mockReturnValue({
|
||||
data: {
|
||||
data: {
|
||||
data: {
|
||||
keys: {
|
||||
attributeKeys: [
|
||||
{
|
||||
name: 'isRoot',
|
||||
signal: 'traces',
|
||||
fieldDataType: 'bool',
|
||||
fieldContext: '',
|
||||
},
|
||||
{
|
||||
name: 'isEntryPoint',
|
||||
signal: 'traces',
|
||||
fieldDataType: 'bool',
|
||||
fieldContext: '',
|
||||
},
|
||||
{
|
||||
name: 'duration',
|
||||
signal: 'traces',
|
||||
fieldDataType: 'float64',
|
||||
fieldContext: '',
|
||||
},
|
||||
{
|
||||
name: 'serviceName',
|
||||
signal: 'traces',
|
||||
fieldDataType: 'string',
|
||||
fieldContext: '',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'isEntryPoint',
|
||||
signal: 'traces',
|
||||
fieldDataType: 'bool',
|
||||
fieldContext: '',
|
||||
},
|
||||
{
|
||||
name: 'duration',
|
||||
signal: 'traces',
|
||||
fieldDataType: 'float64',
|
||||
fieldContext: '',
|
||||
},
|
||||
{
|
||||
name: 'serviceName',
|
||||
signal: 'traces',
|
||||
fieldDataType: 'string',
|
||||
fieldContext: '',
|
||||
},
|
||||
]),
|
||||
);
|
||||
},
|
||||
isFetching: false,
|
||||
});
|
||||
|
||||
const { result } = renderHook(
|
||||
() =>
|
||||
useOptionsMenu({
|
||||
sourcePage: SavedviewtypesSourceDTO.traces,
|
||||
aggregateOperator: 'count',
|
||||
}),
|
||||
{ wrapper },
|
||||
const { result } = renderHook(() =>
|
||||
useOptionsMenu({
|
||||
dataSource: DataSource.TRACES,
|
||||
aggregateOperator: 'count',
|
||||
}),
|
||||
);
|
||||
|
||||
// Get the column options from the config
|
||||
@@ -150,38 +127,98 @@ describe('useOptionsMenu', () => {
|
||||
expect(optionNames).toContain('serviceName');
|
||||
});
|
||||
|
||||
it('shows body in column options when sourcePage is logs', () => {
|
||||
it('does not show body in column options when dataSource is METRICS', () => {
|
||||
// Mock the query key suggestions to return data including body
|
||||
mockUseGetQueryKeySuggestions.mockReturnValue(
|
||||
keySuggestions([
|
||||
{
|
||||
name: 'body',
|
||||
signal: 'logs',
|
||||
fieldDataType: 'string',
|
||||
fieldContext: '',
|
||||
(useGetQueryKeySuggestions as jest.Mock).mockReturnValue({
|
||||
data: {
|
||||
data: {
|
||||
data: {
|
||||
keys: {
|
||||
attributeKeys: [
|
||||
{
|
||||
name: 'body',
|
||||
signal: 'logs',
|
||||
fieldDataType: 'string',
|
||||
fieldContext: '',
|
||||
},
|
||||
{
|
||||
name: 'status',
|
||||
signal: 'metrics',
|
||||
fieldDataType: 'int64',
|
||||
fieldContext: '',
|
||||
},
|
||||
{
|
||||
name: 'value',
|
||||
signal: 'metrics',
|
||||
fieldDataType: 'float64',
|
||||
fieldContext: '',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'level',
|
||||
signal: 'logs',
|
||||
fieldDataType: 'string',
|
||||
fieldContext: '',
|
||||
},
|
||||
{
|
||||
name: 'timestamp',
|
||||
signal: 'logs',
|
||||
fieldDataType: 'int64',
|
||||
fieldContext: '',
|
||||
},
|
||||
]),
|
||||
},
|
||||
isFetching: false,
|
||||
});
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
useOptionsMenu({
|
||||
dataSource: DataSource.METRICS,
|
||||
aggregateOperator: 'count',
|
||||
}),
|
||||
);
|
||||
|
||||
const { result } = renderHook(
|
||||
() =>
|
||||
useOptionsMenu({
|
||||
sourcePage: SavedviewtypesSourceDTO.logs,
|
||||
aggregateOperator: 'count',
|
||||
}),
|
||||
{ wrapper },
|
||||
// Get the column options from the config
|
||||
const columnOptions = result.current.config.addColumn?.options ?? [];
|
||||
const optionNames = columnOptions.map((option) => option.label);
|
||||
|
||||
// body should NOT be in the options
|
||||
expect(optionNames).not.toContain('body');
|
||||
|
||||
// Other attributes should be present
|
||||
expect(optionNames).toContain('status');
|
||||
expect(optionNames).toContain('value');
|
||||
});
|
||||
|
||||
it('does not show body in column options when dataSource is LOGS', () => {
|
||||
// Mock the query key suggestions to return data including body
|
||||
(useGetQueryKeySuggestions as jest.Mock).mockReturnValue({
|
||||
data: {
|
||||
data: {
|
||||
data: {
|
||||
keys: {
|
||||
attributeKeys: [
|
||||
{
|
||||
name: 'body',
|
||||
signal: 'logs',
|
||||
fieldDataType: 'string',
|
||||
fieldContext: '',
|
||||
},
|
||||
{
|
||||
name: 'level',
|
||||
signal: 'logs',
|
||||
fieldDataType: 'string',
|
||||
fieldContext: '',
|
||||
},
|
||||
{
|
||||
name: 'timestamp',
|
||||
signal: 'logs',
|
||||
fieldDataType: 'int64',
|
||||
fieldContext: '',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
isFetching: false,
|
||||
});
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
useOptionsMenu({
|
||||
dataSource: DataSource.LOGS,
|
||||
aggregateOperator: 'count',
|
||||
}),
|
||||
);
|
||||
|
||||
// Get the column options from the config
|
||||
@@ -197,15 +234,15 @@ describe('useOptionsMenu', () => {
|
||||
});
|
||||
|
||||
describe('reorderSelectColumns / handleRemoveSelectedColumn — composite ID lookup', () => {
|
||||
const baseFormatting: FormattingOptions = {
|
||||
const baseFormatting = {
|
||||
format: 'table',
|
||||
maxLines: 1,
|
||||
fontSize: FontSize.SMALL,
|
||||
fontSize: 'small',
|
||||
};
|
||||
|
||||
// Two entries share the same `name` but differ in `fieldContext` — the
|
||||
// exact case composite IDs are meant to disambiguate.
|
||||
const seedColumns: TelemetryFieldKey[] = [
|
||||
const seedColumns = [
|
||||
{
|
||||
name: 'body',
|
||||
fieldContext: 'log',
|
||||
@@ -227,26 +264,36 @@ describe('useOptionsMenu', () => {
|
||||
{
|
||||
name: 'timestamp',
|
||||
fieldContext: 'log',
|
||||
fieldDataType: '',
|
||||
signal: 'logs',
|
||||
},
|
||||
];
|
||||
|
||||
beforeEach(() => {
|
||||
mockUseGetQueryKeySuggestions.mockReturnValue(keySuggestions([]));
|
||||
mockUsePreferenceContext.mockReturnValue({
|
||||
[SavedviewtypesSourceDTO.traces]: slice([], baseFormatting),
|
||||
[SavedviewtypesSourceDTO.logs]: slice(seedColumns, baseFormatting),
|
||||
} satisfies PreferenceContextValue);
|
||||
(useGetQueryKeySuggestions as jest.Mock).mockReturnValue({
|
||||
data: { data: { data: { keys: {} } } },
|
||||
isFetching: false,
|
||||
});
|
||||
(usePreferenceContext as jest.Mock).mockReturnValue({
|
||||
traces: {
|
||||
preferences: { columns: [], formatting: baseFormatting },
|
||||
updateColumns: mockUpdateColumns,
|
||||
updateFormatting: mockUpdateFormatting,
|
||||
},
|
||||
logs: {
|
||||
preferences: { columns: seedColumns, formatting: baseFormatting },
|
||||
updateColumns: mockUpdateColumns,
|
||||
updateFormatting: mockUpdateFormatting,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('reorders by composite IDs — preserves both same-name variants distinctly', () => {
|
||||
const { result } = renderHook(
|
||||
() =>
|
||||
useOptionsMenu({
|
||||
sourcePage: SavedviewtypesSourceDTO.logs,
|
||||
aggregateOperator: 'count',
|
||||
}),
|
||||
{ wrapper },
|
||||
const { result } = renderHook(() =>
|
||||
useOptionsMenu({
|
||||
dataSource: DataSource.LOGS,
|
||||
aggregateOperator: 'count',
|
||||
}),
|
||||
);
|
||||
|
||||
// New order: [attribute:service.name, log:body, resource:service.name, log:timestamp]
|
||||
@@ -259,7 +306,12 @@ describe('useOptionsMenu', () => {
|
||||
|
||||
expect(mockUpdateColumns).toHaveBeenCalledTimes(1);
|
||||
const reordered = mockUpdateColumns.mock.calls[0][0];
|
||||
expect(toIds(reordered)).toStrictEqual([
|
||||
expect(
|
||||
reordered.map(
|
||||
(c: { name: string; fieldContext: string }) =>
|
||||
`${c.fieldContext}:${c.name}`,
|
||||
),
|
||||
).toStrictEqual([
|
||||
'attribute:service.name',
|
||||
'log:body',
|
||||
'resource:service.name',
|
||||
@@ -268,13 +320,11 @@ describe('useOptionsMenu', () => {
|
||||
});
|
||||
|
||||
it('reorder ignores ids that are not columns (e.g. state-indicator) and skips unknown ids', () => {
|
||||
const { result } = renderHook(
|
||||
() =>
|
||||
useOptionsMenu({
|
||||
sourcePage: SavedviewtypesSourceDTO.logs,
|
||||
aggregateOperator: 'count',
|
||||
}),
|
||||
{ wrapper },
|
||||
const { result } = renderHook(() =>
|
||||
useOptionsMenu({
|
||||
dataSource: DataSource.LOGS,
|
||||
aggregateOperator: 'count',
|
||||
}),
|
||||
);
|
||||
|
||||
result.current.config.addColumn?.onReorder([
|
||||
@@ -288,7 +338,12 @@ describe('useOptionsMenu', () => {
|
||||
|
||||
const reordered = mockUpdateColumns.mock.calls[0][0];
|
||||
// state-indicator + unknown.composite filtered; rest preserved in given order.
|
||||
expect(toIds(reordered)).toStrictEqual([
|
||||
expect(
|
||||
reordered.map(
|
||||
(c: { name: string; fieldContext: string }) =>
|
||||
`${c.fieldContext}:${c.name}`,
|
||||
),
|
||||
).toStrictEqual([
|
||||
'log:timestamp',
|
||||
'log:body',
|
||||
'resource:service.name',
|
||||
@@ -297,13 +352,11 @@ describe('useOptionsMenu', () => {
|
||||
});
|
||||
|
||||
it('removes only the variant whose composite ID matches', () => {
|
||||
const { result } = renderHook(
|
||||
() =>
|
||||
useOptionsMenu({
|
||||
sourcePage: SavedviewtypesSourceDTO.logs,
|
||||
aggregateOperator: 'count',
|
||||
}),
|
||||
{ wrapper },
|
||||
const { result } = renderHook(() =>
|
||||
useOptionsMenu({
|
||||
dataSource: DataSource.LOGS,
|
||||
aggregateOperator: 'count',
|
||||
}),
|
||||
);
|
||||
|
||||
// Removing 'resource:service.name' should drop ONLY the resource variant.
|
||||
@@ -311,21 +364,20 @@ describe('useOptionsMenu', () => {
|
||||
|
||||
expect(mockUpdateColumns).toHaveBeenCalledTimes(1);
|
||||
const remaining = mockUpdateColumns.mock.calls[0][0];
|
||||
expect(toIds(remaining)).toStrictEqual([
|
||||
'log:body',
|
||||
'attribute:service.name',
|
||||
'log:timestamp',
|
||||
]);
|
||||
expect(
|
||||
remaining.map(
|
||||
(c: { name: string; fieldContext: string }) =>
|
||||
`${c.fieldContext}:${c.name}`,
|
||||
),
|
||||
).toStrictEqual(['log:body', 'attribute:service.name', 'log:timestamp']);
|
||||
});
|
||||
|
||||
it('removing by a non-matching composite ID is a no-op (filter returns the full list)', () => {
|
||||
const { result } = renderHook(
|
||||
() =>
|
||||
useOptionsMenu({
|
||||
sourcePage: SavedviewtypesSourceDTO.logs,
|
||||
aggregateOperator: 'count',
|
||||
}),
|
||||
{ wrapper },
|
||||
const { result } = renderHook(() =>
|
||||
useOptionsMenu({
|
||||
dataSource: DataSource.LOGS,
|
||||
aggregateOperator: 'count',
|
||||
}),
|
||||
);
|
||||
|
||||
result.current.config.addColumn?.onRemove('unknown.composite');
|
||||
@@ -338,34 +390,35 @@ describe('useOptionsMenu', () => {
|
||||
|
||||
describe('fieldsSelector.value drops legacy columns without a name', () => {
|
||||
it('excludes entries missing name while keeping valid columns', () => {
|
||||
mockUseGetQueryKeySuggestions.mockReturnValue(keySuggestions([]));
|
||||
mockUsePreferenceContext.mockReturnValue({
|
||||
[SavedviewtypesSourceDTO.traces]: slice(
|
||||
[
|
||||
{ name: 'body', fieldContext: 'log' },
|
||||
// A legacy stored column: `key` only, no `name`.
|
||||
{
|
||||
key: 'legacy-key-no-name',
|
||||
fieldContext: 'log',
|
||||
} as unknown as TelemetryFieldKey,
|
||||
{ name: 'timestamp', fieldContext: 'log' },
|
||||
],
|
||||
{
|
||||
format: 'table',
|
||||
maxLines: 1,
|
||||
fontSize: FontSize.SMALL,
|
||||
(useGetQueryKeySuggestions as jest.Mock).mockReturnValue({
|
||||
data: { data: { data: { keys: {} } } },
|
||||
isFetching: false,
|
||||
});
|
||||
(usePreferenceContext as jest.Mock).mockReturnValue({
|
||||
traces: {
|
||||
preferences: {
|
||||
columns: [
|
||||
{ name: 'body', fieldContext: 'log' },
|
||||
{ key: 'legacy-key-no-name', fieldContext: 'log' },
|
||||
{ name: 'timestamp', fieldContext: 'log' },
|
||||
],
|
||||
formatting: { format: 'table', maxLines: 1, fontSize: 'small' },
|
||||
},
|
||||
),
|
||||
[SavedviewtypesSourceDTO.logs]: slice([], {}),
|
||||
} satisfies PreferenceContextValue);
|
||||
updateColumns: mockUpdateColumns,
|
||||
updateFormatting: mockUpdateFormatting,
|
||||
},
|
||||
logs: {
|
||||
preferences: { columns: [], formatting: {} },
|
||||
updateColumns: mockUpdateColumns,
|
||||
updateFormatting: mockUpdateFormatting,
|
||||
},
|
||||
});
|
||||
|
||||
const { result } = renderHook(
|
||||
() =>
|
||||
useOptionsMenu({
|
||||
sourcePage: SavedviewtypesSourceDTO.traces,
|
||||
aggregateOperator: 'count',
|
||||
}),
|
||||
{ wrapper },
|
||||
const { result } = renderHook(() =>
|
||||
useOptionsMenu({
|
||||
dataSource: DataSource.TRACES,
|
||||
aggregateOperator: 'count',
|
||||
}),
|
||||
);
|
||||
|
||||
const fields = result.current.config.fieldsSelector?.value ?? [];
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { TelemetryFieldKey } from 'api/v5/v5';
|
||||
import { PREFERENCE_SOURCE_PAGES } from 'providers/preferences/constants';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import { FontSize, OptionsQuery } from './types';
|
||||
@@ -15,14 +13,6 @@ export const defaultOptionsQuery: OptionsQuery = {
|
||||
fontSize: FontSize.SMALL,
|
||||
};
|
||||
|
||||
export const SOURCE_PAGE_SIGNAL: Record<
|
||||
(typeof PREFERENCE_SOURCE_PAGES)[number],
|
||||
DataSource
|
||||
> = {
|
||||
[SavedviewtypesSourceDTO.logs]: DataSource.LOGS,
|
||||
[SavedviewtypesSourceDTO.traces]: DataSource.TRACES,
|
||||
};
|
||||
|
||||
export const EXCLUDED_COLUMNS: Record<DataSource, string[]> = {
|
||||
[DataSource.TRACES]: ['body', 'isRoot', 'isEntryPoint'],
|
||||
[DataSource.METRICS]: ['body'],
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
/* eslint-disable sonarjs/cognitive-complexity */
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { useQueries } from 'react-query';
|
||||
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { getKeySuggestions } from 'api/querySuggestions/getKeySuggestions';
|
||||
import { TelemetryFieldKey } from 'api/v5/v5';
|
||||
import { AxiosResponse } from 'axios';
|
||||
@@ -12,7 +11,6 @@ import useUrlQueryData from 'hooks/useUrlQueryData';
|
||||
import { has } from 'lodash-es';
|
||||
import { AllTraceFilterKeyValue } from 'constants/traceFilterKeys';
|
||||
import { usePreferenceContext } from 'providers/preferences/context/PreferenceContextProvider';
|
||||
import { PreferenceSourcePage } from 'providers/preferences/types';
|
||||
import {
|
||||
QueryKeyRequestProps,
|
||||
QueryKeySuggestionsResponseProps,
|
||||
@@ -22,13 +20,13 @@ import {
|
||||
FieldDataType,
|
||||
SignalType,
|
||||
} from 'types/api/v5/queryRange';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import {
|
||||
defaultLogsSelectedColumns,
|
||||
defaultOptionsQuery,
|
||||
defaultTraceSelectedColumns,
|
||||
EXCLUDED_COLUMNS,
|
||||
SOURCE_PAGE_SIGNAL,
|
||||
URL_OPTIONS,
|
||||
} from './constants';
|
||||
import {
|
||||
@@ -42,7 +40,7 @@ import { buildCompositeKey, getOptionsFromKeys } from './utils';
|
||||
|
||||
interface UseOptionsMenuProps {
|
||||
storageKey?: string;
|
||||
sourcePage: PreferenceSourcePage;
|
||||
dataSource: DataSource;
|
||||
aggregateOperator?: string;
|
||||
initialOptions?: InitialOptions;
|
||||
}
|
||||
@@ -54,14 +52,15 @@ interface UseOptionsMenu {
|
||||
}
|
||||
|
||||
const useOptionsMenu = ({
|
||||
sourcePage,
|
||||
dataSource,
|
||||
// aggregateOperator,
|
||||
initialOptions = {},
|
||||
}: UseOptionsMenuProps): UseOptionsMenu => {
|
||||
const signal = SOURCE_PAGE_SIGNAL[sourcePage];
|
||||
const { notifications } = useNotifications();
|
||||
const prefCtx = usePreferenceContext();
|
||||
// TODO: send null to updateColumns and updateFormatting if dataSource is not logs or traces
|
||||
const { preferences, updateColumns, updateFormatting } =
|
||||
usePreferenceContext()[sourcePage];
|
||||
const slice = dataSource === DataSource.TRACES ? prefCtx.traces : prefCtx.logs;
|
||||
const { preferences, updateColumns, updateFormatting } = slice;
|
||||
|
||||
const [searchText, setSearchText] = useState<string>('');
|
||||
const [isFocused, setIsFocused] = useState<boolean>(false);
|
||||
@@ -69,10 +68,10 @@ const useOptionsMenu = ({
|
||||
|
||||
const initialQueryParamsV5: QueryKeyRequestProps = useMemo(
|
||||
() => ({
|
||||
signal,
|
||||
signal: dataSource,
|
||||
searchText: '',
|
||||
}),
|
||||
[signal],
|
||||
[dataSource],
|
||||
);
|
||||
|
||||
const { query: optionsQuery, redirectWithQuery: redirectWithOptionsData } =
|
||||
@@ -128,7 +127,7 @@ const useOptionsMenu = ({
|
||||
?.map((column) => attributesData.find(({ name }) => name === column))
|
||||
.filter((e) => !!e) || []) as TelemetryFieldKey[];
|
||||
|
||||
if (sourcePage === SavedviewtypesSourceDTO.traces) {
|
||||
if (dataSource === DataSource.TRACES) {
|
||||
initialSelected = initialSelected
|
||||
?.map((col) => {
|
||||
if (col && Object.keys(AllTraceFilterKeyValue).includes(col?.name)) {
|
||||
@@ -158,7 +157,7 @@ const useOptionsMenu = ({
|
||||
isFetchedInitialAttributes,
|
||||
initialOptions?.selectColumns,
|
||||
initialAttributesResult,
|
||||
sourcePage,
|
||||
dataSource,
|
||||
]);
|
||||
|
||||
const {
|
||||
@@ -196,7 +195,7 @@ const useOptionsMenu = ({
|
||||
fieldDataType: e.fieldDataType,
|
||||
}));
|
||||
}
|
||||
if (sourcePage === SavedviewtypesSourceDTO.traces) {
|
||||
if (dataSource === DataSource.TRACES) {
|
||||
return defaultTraceSelectedColumns.map((e) => ({
|
||||
...e,
|
||||
name: e.name,
|
||||
@@ -204,16 +203,16 @@ const useOptionsMenu = ({
|
||||
}
|
||||
|
||||
return [];
|
||||
}, [sourcePage, searchedAttributesDataV5?.data.data.keys]);
|
||||
}, [dataSource, searchedAttributesDataV5?.data.data.keys]);
|
||||
|
||||
const initialOptionsQuery: OptionsQuery = useMemo(() => {
|
||||
let defaultColumns: TelemetryFieldKey[] = defaultOptionsQuery.selectColumns;
|
||||
if (sourcePage === SavedviewtypesSourceDTO.traces) {
|
||||
if (dataSource === DataSource.TRACES) {
|
||||
defaultColumns = defaultTraceSelectedColumns.map((e) => ({
|
||||
...e,
|
||||
name: e.name,
|
||||
}));
|
||||
} else if (sourcePage === SavedviewtypesSourceDTO.logs) {
|
||||
} else if (dataSource === DataSource.LOGS) {
|
||||
// eslint-disable-next-line sonarjs/no-identical-functions
|
||||
defaultColumns = defaultLogsSelectedColumns.map((e) => ({
|
||||
...e,
|
||||
@@ -233,7 +232,7 @@ const useOptionsMenu = ({
|
||||
...initialOptions,
|
||||
selectColumns: finalSelectColumns,
|
||||
};
|
||||
}, [sourcePage, initialOptions, initialSelectedColumns]);
|
||||
}, [dataSource, initialOptions, initialSelectedColumns]);
|
||||
|
||||
const selectedColumnKeys = useMemo(
|
||||
() => preferences?.columns?.map(({ name }) => name) || [],
|
||||
@@ -242,7 +241,7 @@ const useOptionsMenu = ({
|
||||
|
||||
const optionsFromAttributeKeys = useMemo(() => {
|
||||
const filteredAttributeKeys = searchedAttributeKeys.filter((item) => {
|
||||
const exclusions = EXCLUDED_COLUMNS[signal];
|
||||
const exclusions = EXCLUDED_COLUMNS[dataSource];
|
||||
if (exclusions) {
|
||||
return !exclusions.includes(item.name);
|
||||
}
|
||||
@@ -250,7 +249,7 @@ const useOptionsMenu = ({
|
||||
});
|
||||
|
||||
return getOptionsFromKeys(filteredAttributeKeys, selectedColumnKeys);
|
||||
}, [signal, searchedAttributeKeys, selectedColumnKeys]);
|
||||
}, [dataSource, searchedAttributeKeys, selectedColumnKeys]);
|
||||
|
||||
const handleRedirectWithOptionsData = useCallback(
|
||||
(newQueryData: OptionsQuery) => {
|
||||
@@ -286,10 +285,7 @@ const useOptionsMenu = ({
|
||||
buildCompositeKey(f.name, f.fieldContext, f.fieldDataType) !== columnKey,
|
||||
);
|
||||
|
||||
if (
|
||||
!newSelectedColumns?.length &&
|
||||
sourcePage !== SavedviewtypesSourceDTO.logs
|
||||
) {
|
||||
if (!newSelectedColumns?.length && dataSource !== DataSource.LOGS) {
|
||||
notifications.error({
|
||||
message: 'There must be at least one selected column',
|
||||
});
|
||||
@@ -298,7 +294,7 @@ const useOptionsMenu = ({
|
||||
|
||||
updateColumns(newSelectedColumns || []);
|
||||
},
|
||||
[sourcePage, notifications, preferences, updateColumns],
|
||||
[dataSource, notifications, preferences, updateColumns],
|
||||
);
|
||||
|
||||
const handleFormatChange = useCallback(
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
import { ChangeEvent, useCallback } from 'react';
|
||||
import MEditor, { Monaco } from '@monaco-editor/react';
|
||||
import { Color } from '@signozhq/design-tokens';
|
||||
import { Input } from 'antd';
|
||||
import { LEGEND } from 'constants/global';
|
||||
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import { useIsDarkMode } from 'hooks/useDarkMode';
|
||||
import MonacoEditor from 'lib/monaco/MonacoEditor';
|
||||
import { IClickHouseQuery } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { EQueryType } from 'types/common/dashboard';
|
||||
import { getFormatedLegend } from 'utils/getFormatedLegend';
|
||||
@@ -71,22 +69,6 @@ function ClickHouseQueryBuilder({
|
||||
[handleUpdateQuery],
|
||||
);
|
||||
|
||||
const isDarkMode = useIsDarkMode();
|
||||
|
||||
function setEditorTheme(monaco: Monaco): void {
|
||||
monaco.editor.defineTheme('my-theme', {
|
||||
base: 'vs-dark',
|
||||
inherit: true,
|
||||
rules: [
|
||||
{ token: 'string.key.json', foreground: Color.BG_VANILLA_400 },
|
||||
{ token: 'string.value.json', foreground: Color.BG_ROBIN_400 },
|
||||
],
|
||||
colors: {
|
||||
'editor.background': Color.BG_INK_300,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<QueryHeader
|
||||
name={queryData?.name}
|
||||
@@ -95,15 +77,13 @@ function ClickHouseQueryBuilder({
|
||||
onDelete={handleRemoveQuery}
|
||||
deletable={deletable}
|
||||
>
|
||||
<MEditor
|
||||
<MonacoEditor
|
||||
language="sql"
|
||||
height="200px"
|
||||
onChange={handleUpdateEditor}
|
||||
value={queryData?.query}
|
||||
onMount={(_, monaco): void => {
|
||||
document.fonts.ready.then(() => {
|
||||
monaco.editor.remeasureFonts();
|
||||
});
|
||||
void document.fonts.ready.then(() => monaco.editor.remeasureFonts());
|
||||
}}
|
||||
options={{
|
||||
scrollbar: {
|
||||
@@ -115,8 +95,6 @@ function ClickHouseQueryBuilder({
|
||||
fontSize: 14,
|
||||
fontFamily: 'Space Mono',
|
||||
}}
|
||||
theme={isDarkMode ? 'my-theme' : 'light'}
|
||||
beforeMount={setEditorTheme}
|
||||
/>
|
||||
<Input
|
||||
onChange={handleUpdateInput}
|
||||
|
||||
@@ -7,7 +7,7 @@ import {
|
||||
useRef,
|
||||
} from 'react';
|
||||
import { useCopyToClipboard } from 'react-use';
|
||||
import MEditor, { Monaco, OnMount } from '@monaco-editor/react';
|
||||
import { Monaco, OnMount } from '@monaco-editor/react';
|
||||
import { Color } from '@signozhq/design-tokens';
|
||||
import { Check, Copy } from '@signozhq/icons';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
@@ -15,12 +15,9 @@ import { Tooltip } from '@signozhq/ui/tooltip';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import type { AuthtypesTransactionGroupDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { useIsDarkMode } from 'hooks/useDarkMode';
|
||||
import { EDITABLE_EDITOR_OPTIONS } from 'lib/monaco/editorOptions';
|
||||
import MonacoEditor from 'lib/monaco/MonacoEditor';
|
||||
|
||||
import {
|
||||
defineJsonTheme,
|
||||
EDITABLE_EDITOR_OPTIONS,
|
||||
JSON_THEME_DARK,
|
||||
} from '../../monaco.config';
|
||||
import {
|
||||
transformResourcePermissionsToTransactionGroups,
|
||||
transformTransactionGroupsToResourcePermissions,
|
||||
@@ -34,7 +31,7 @@ import {
|
||||
import styles from './JsonEditor.module.scss';
|
||||
import { JsonEditorProps, JsonEditorRef } from './JsonEditor.types';
|
||||
|
||||
type MonacoEditor = Parameters<OnMount>[0];
|
||||
type MonacoEditorInstance = Parameters<OnMount>[0];
|
||||
|
||||
const JsonEditor = forwardRef<JsonEditorRef, JsonEditorProps>(
|
||||
function JsonEditor({ resources, mode, onChange, onValidityChange }, ref) {
|
||||
@@ -50,7 +47,7 @@ const JsonEditor = forwardRef<JsonEditorRef, JsonEditorProps>(
|
||||
});
|
||||
const prevModeRef = useRef(mode);
|
||||
const completionDisposableRef = useRef<{ dispose(): void } | null>(null);
|
||||
const editorRef = useRef<MonacoEditor | null>(null);
|
||||
const editorRef = useRef<MonacoEditorInstance | null>(null);
|
||||
const markersListenerRef = useRef<{ dispose(): void } | null>(null);
|
||||
|
||||
const hasError = parseError !== null || schemaErrors.length > 0;
|
||||
@@ -100,7 +97,6 @@ const JsonEditor = forwardRef<JsonEditorRef, JsonEditorProps>(
|
||||
);
|
||||
|
||||
const configureMonaco = useCallback((monaco: Monaco): void => {
|
||||
defineJsonTheme(monaco);
|
||||
registerJsonSchema(monaco);
|
||||
completionDisposableRef.current = registerCompletionProvider(monaco);
|
||||
}, []);
|
||||
@@ -184,7 +180,7 @@ const JsonEditor = forwardRef<JsonEditorRef, JsonEditorProps>(
|
||||
</Button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
<MEditor
|
||||
<MonacoEditor
|
||||
value={jsonBuffer}
|
||||
language="json"
|
||||
path={ROLE_PERMISSIONS_MODEL_PATH}
|
||||
@@ -192,7 +188,6 @@ const JsonEditor = forwardRef<JsonEditorRef, JsonEditorProps>(
|
||||
onChange={handleEditorChange}
|
||||
onMount={handleEditorMount}
|
||||
height="100%"
|
||||
theme={isDarkMode ? JSON_THEME_DARK : 'light'}
|
||||
beforeMount={configureMonaco}
|
||||
/>
|
||||
</div>
|
||||
@@ -225,7 +220,11 @@ const JsonEditor = forwardRef<JsonEditorRef, JsonEditorProps>(
|
||||
className={styles.jsonEditorErrorMessage}
|
||||
>
|
||||
{schemaErrors[0]}
|
||||
{schemaErrors.length > 1 && ` (+${schemaErrors.length - 1} more)`}
|
||||
{schemaErrors.length > 1 && (
|
||||
<span className="translate-safe">
|
||||
{` (+${schemaErrors.length - 1} more)`}
|
||||
</span>
|
||||
)}
|
||||
</Typography>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -1,17 +1,13 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { useCopyToClipboard } from 'react-use';
|
||||
import MEditor from '@monaco-editor/react';
|
||||
import { Color } from '@signozhq/design-tokens';
|
||||
import { Check, Copy } from '@signozhq/icons';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { Tooltip } from '@signozhq/ui/tooltip';
|
||||
import { useIsDarkMode } from 'hooks/useDarkMode';
|
||||
import { READONLY_EDITOR_OPTIONS } from 'lib/monaco/editorOptions';
|
||||
import MonacoEditor from 'lib/monaco/MonacoEditor';
|
||||
|
||||
import {
|
||||
defineJsonTheme,
|
||||
JSON_THEME_DARK,
|
||||
READONLY_EDITOR_OPTIONS,
|
||||
} from '../monaco.config';
|
||||
import { RolePermissionsData } from '../types';
|
||||
import { transformResourcePermissionsToTransactionGroups } from '../hooks/useRolePermissions';
|
||||
|
||||
@@ -79,13 +75,11 @@ function ReadOnlyJsonViewer({
|
||||
</Button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
<MEditor
|
||||
<MonacoEditor
|
||||
value={jsonContent}
|
||||
language="json"
|
||||
options={READONLY_EDITOR_OPTIONS}
|
||||
height="100%"
|
||||
theme={isDarkMode ? JSON_THEME_DARK : 'light'}
|
||||
beforeMount={defineJsonTheme}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { useState } from 'react';
|
||||
import { act, screen, waitFor } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import ROUTES from 'constants/routes';
|
||||
import { usePreferenceContext } from 'providers/preferences/context/PreferenceContextProvider';
|
||||
import { act, screen, userEvent, waitFor } from 'tests/test-utils';
|
||||
|
||||
import SavedViewsHeader from '../SavedViewsHeader';
|
||||
import { mockSavedViewsApi } from './savedViewsApiMock';
|
||||
@@ -27,7 +28,7 @@ const errors = {
|
||||
};
|
||||
|
||||
function Harness(): JSX.Element {
|
||||
const traces = usePreferenceContext()[SavedviewtypesSourceDTO.traces];
|
||||
const { traces } = usePreferenceContext();
|
||||
const [headerKey, setHeaderKey] = useState(0);
|
||||
const columns = traces.preferences?.columns ?? [];
|
||||
|
||||
@@ -36,7 +37,7 @@ function Harness(): JSX.Element {
|
||||
<SavedViewsHeader
|
||||
key={headerKey}
|
||||
source={SavedviewtypesSourceDTO.traces}
|
||||
onOpenViews={jest.fn() as jest.MockedFunction<() => void>}
|
||||
onOpenViews={jest.fn()}
|
||||
/>
|
||||
<span data-testid="columns">
|
||||
{columns.map((column) => column.name).join(',')}
|
||||
@@ -83,14 +84,13 @@ describe('SavedViewsHeader columns', () => {
|
||||
});
|
||||
|
||||
it('keeps edited columns when the view is fetched again', async () => {
|
||||
const user = userEvent.setup();
|
||||
mockSavedViewsApi([errors]);
|
||||
await openView();
|
||||
|
||||
await user.click(screen.getByTestId('add-column'));
|
||||
await userEvent.click(screen.getByTestId('add-column'));
|
||||
await waitFor(() => expect(isDirty()).toBe(true));
|
||||
|
||||
await user.click(screen.getByTestId('remount-header'));
|
||||
await userEvent.click(screen.getByTestId('remount-header'));
|
||||
await act(() => new Promise((resolve) => setTimeout(resolve, 200)));
|
||||
|
||||
expect(columnsText()).toBe('service.name,name,extra-2');
|
||||
@@ -98,37 +98,35 @@ describe('SavedViewsHeader columns', () => {
|
||||
});
|
||||
|
||||
it('discard puts the saved columns back', async () => {
|
||||
const user = userEvent.setup();
|
||||
mockSavedViewsApi([errors]);
|
||||
await openView();
|
||||
|
||||
await user.click(screen.getByTestId('add-column'));
|
||||
await userEvent.click(screen.getByTestId('add-column'));
|
||||
await waitFor(() => expect(isDirty()).toBe(true));
|
||||
|
||||
await user.click(screen.getByTestId('saved-views-discard'));
|
||||
await userEvent.click(screen.getByTestId('saved-views-discard'));
|
||||
|
||||
await waitFor(() => expect(columnsText()).toBe('service.name,name'));
|
||||
expect(isDirty()).toBe(false);
|
||||
});
|
||||
|
||||
it('discard after an update goes back to the updated columns', async () => {
|
||||
const user = userEvent.setup();
|
||||
mockSavedViewsApi([errors]);
|
||||
await openView();
|
||||
|
||||
await user.click(screen.getByTestId('add-column'));
|
||||
await userEvent.click(screen.getByTestId('add-column'));
|
||||
await waitFor(() => expect(isDirty()).toBe(true));
|
||||
await user.click(screen.getByTestId('saved-views-save-changes'));
|
||||
await userEvent.click(screen.getByTestId('saved-views-save-changes'));
|
||||
const update = await screen.findByTestId(
|
||||
'saved-views-save-changes-item-update',
|
||||
);
|
||||
await waitFor(() => expectRowUsable(update), MENU_CHECK_TIMEOUT);
|
||||
await user.click(update);
|
||||
await userEvent.click(update);
|
||||
await waitFor(() => expect(isDirty()).toBe(false));
|
||||
|
||||
await user.click(screen.getByTestId('add-column'));
|
||||
await userEvent.click(screen.getByTestId('add-column'));
|
||||
await waitFor(() => expect(isDirty()).toBe(true));
|
||||
await user.click(screen.getByTestId('saved-views-discard'));
|
||||
await userEvent.click(screen.getByTestId('saved-views-discard'));
|
||||
|
||||
await waitFor(() => expect(columnsText()).toBe('service.name,name,extra-2'));
|
||||
expect(isDirty()).toBe(false);
|
||||
|
||||
@@ -1,16 +1,28 @@
|
||||
import { Copy, Link, PenLine, Trash2 } from '@signozhq/icons';
|
||||
import { SavedviewtypesSchemaVersionDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import {
|
||||
SavedviewtypesSchemaVersionDTO,
|
||||
SavedviewtypesSourceDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { QueryParams } from 'constants/query';
|
||||
import ROUTES from 'constants/routes';
|
||||
import {
|
||||
buildSavedViewDeletePermission,
|
||||
buildSavedViewUpdatePermission,
|
||||
} from 'lib/authz/hooks/useAuthZ/permissions/saved-view.permissions';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import { SavedViewRowActionConfig, SaveViewModalMode } from './types';
|
||||
|
||||
export const SAVED_VIEW_SCHEMA_VERSION = SavedviewtypesSchemaVersionDTO.v2;
|
||||
|
||||
// Only the logs and traces explorers have columns and formatting to save.
|
||||
export const SAVED_VIEW_OPTIONS_DATA_SOURCE: Partial<
|
||||
Record<SavedviewtypesSourceDTO, DataSource>
|
||||
> = {
|
||||
[SavedviewtypesSourceDTO.logs]: DataSource.LOGS,
|
||||
[SavedviewtypesSourceDTO.traces]: DataSource.TRACES,
|
||||
};
|
||||
|
||||
// What selecting a view writes to the url, so clearing it removes exactly these.
|
||||
export const SAVED_VIEW_URL_PARAMS = [
|
||||
QueryParams.viewKey,
|
||||
|
||||
@@ -8,9 +8,10 @@ import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import { useGetSavedViewParams } from 'hooks/saveViews/useGetSavedViewParams';
|
||||
import { buildSavedViewReadPermission } from 'lib/authz/hooks/useAuthZ/permissions/saved-view.permissions';
|
||||
import { useAuthZ } from 'lib/authz/hooks/useAuthZ/useAuthZ';
|
||||
import { isPreferenceSourcePage } from 'providers/preferences/utils';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
import { toAPIError } from 'utils/errorUtils';
|
||||
|
||||
import { SAVED_VIEW_OPTIONS_DATA_SOURCE } from '../constants';
|
||||
import { UseActiveSavedViewResult } from '../types';
|
||||
import { hasUnsavedViewChanges } from '../utils/hasUnsavedViewChanges';
|
||||
|
||||
@@ -20,9 +21,9 @@ export function useActiveSavedView(
|
||||
const { viewKey } = useGetSavedViewParams();
|
||||
const { stagedQuery, panelType } = useQueryBuilder();
|
||||
|
||||
const hasOptions = isPreferenceSourcePage(source);
|
||||
const optionsDataSource = SAVED_VIEW_OPTIONS_DATA_SOURCE[source];
|
||||
const { options } = useOptionsMenu({
|
||||
sourcePage: hasOptions ? source : SavedviewtypesSourceDTO.logs,
|
||||
dataSource: optionsDataSource ?? DataSource.LOGS,
|
||||
});
|
||||
|
||||
const { isLoading: isCheckingRead, deniedPermissions } = useAuthZ(
|
||||
@@ -62,7 +63,7 @@ export function useActiveSavedView(
|
||||
view,
|
||||
stagedQuery,
|
||||
panelType: panelType ?? PANEL_TYPES.LIST,
|
||||
options: hasOptions ? options : undefined,
|
||||
options: optionsDataSource ? options : undefined,
|
||||
});
|
||||
}, [
|
||||
view,
|
||||
@@ -70,7 +71,7 @@ export function useActiveSavedView(
|
||||
isStagedQueryCurrent,
|
||||
stagedQuery,
|
||||
panelType,
|
||||
hasOptions,
|
||||
optionsDataSource,
|
||||
options,
|
||||
]);
|
||||
|
||||
|
||||
@@ -20,12 +20,13 @@ import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import { useGetSavedViewParams } from 'hooks/saveViews/useGetSavedViewParams';
|
||||
import { useHandleExplorerTabChange } from 'hooks/useHandleExplorerTabChange';
|
||||
import { useSafeNavigate } from 'hooks/useSafeNavigate';
|
||||
import { usePreferenceSlice } from 'providers/preferences/context/usePreferenceSlice';
|
||||
import { isPreferenceSourcePage } from 'providers/preferences/utils';
|
||||
import { usePreferenceContext } from 'providers/preferences/context/PreferenceContextProvider';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
import { toAPIError } from 'utils/errorUtils';
|
||||
import { getUnstableCurrentSearchParams } from 'utils/getUnstableCurrentSearchParams';
|
||||
|
||||
import {
|
||||
SAVED_VIEW_OPTIONS_DATA_SOURCE,
|
||||
SAVED_VIEW_SCHEMA_VERSION,
|
||||
SAVED_VIEW_TOAST_POSITION,
|
||||
SAVED_VIEW_URL_PARAMS,
|
||||
@@ -59,11 +60,15 @@ export function useSavedViewActions(
|
||||
const { viewKey } = useGetSavedViewParams();
|
||||
const logSavedViewEvent = useSavedViewLogEvent(source);
|
||||
|
||||
const hasOptions = isPreferenceSourcePage(source);
|
||||
const optionsDataSource = SAVED_VIEW_OPTIONS_DATA_SOURCE[source];
|
||||
const { options } = useOptionsMenu({
|
||||
sourcePage: hasOptions ? source : SavedviewtypesSourceDTO.logs,
|
||||
dataSource: optionsDataSource ?? DataSource.LOGS,
|
||||
});
|
||||
const preferenceSlice = usePreferenceSlice(source);
|
||||
const preferences = usePreferenceContext();
|
||||
const preferencesSlice =
|
||||
optionsDataSource === DataSource.TRACES
|
||||
? preferences.traces
|
||||
: preferences.logs;
|
||||
|
||||
const { mutateAsync: createSavedView, isLoading: isCreating } =
|
||||
useCreateSavedView();
|
||||
@@ -81,10 +86,10 @@ export function useSavedViewActions(
|
||||
query: stagedQuery ?? currentQuery,
|
||||
panelType: panelType ?? PANEL_TYPES.LIST,
|
||||
displayName,
|
||||
options: hasOptions ? options : undefined,
|
||||
options: optionsDataSource ? options : undefined,
|
||||
color,
|
||||
}),
|
||||
[stagedQuery, currentQuery, panelType, hasOptions, options],
|
||||
[stagedQuery, currentQuery, panelType, optionsDataSource, options],
|
||||
);
|
||||
|
||||
const selectView = useCallback(
|
||||
@@ -100,14 +105,14 @@ export function useSavedViewActions(
|
||||
|
||||
const revertView = useCallback(
|
||||
(view: SavedviewtypesSavedViewDTO): void => {
|
||||
if (preferenceSlice) {
|
||||
if (optionsDataSource) {
|
||||
const { columns, formatting } = getViewColumnsAndFormatting(
|
||||
view.spec,
|
||||
source,
|
||||
optionsDataSource,
|
||||
);
|
||||
preferenceSlice.updateColumns(columns);
|
||||
preferencesSlice.updateColumns(columns);
|
||||
if (formatting) {
|
||||
preferenceSlice.updateFormatting(formatting);
|
||||
preferencesSlice.updateFormatting(formatting);
|
||||
}
|
||||
}
|
||||
selectView(view);
|
||||
@@ -115,7 +120,7 @@ export function useSavedViewActions(
|
||||
[SavedViewEventKeys.ViewId]: view.id,
|
||||
});
|
||||
},
|
||||
[source, preferenceSlice, selectView, logSavedViewEvent],
|
||||
[optionsDataSource, preferencesSlice, selectView, logSavedViewEvent],
|
||||
);
|
||||
|
||||
// The query builder redirects only ever add params, so the url is rebuilt
|
||||
|
||||
@@ -1,7 +1,4 @@
|
||||
import {
|
||||
SavedviewtypesSavedViewSpecDTO,
|
||||
SavedviewtypesSourceDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { SavedviewtypesSavedViewSpecDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { TelemetryFieldKey } from 'api/v5/v5';
|
||||
import {
|
||||
defaultLogsSelectedColumns,
|
||||
@@ -10,6 +7,7 @@ import {
|
||||
} from 'container/OptionsMenu/constants';
|
||||
import { FontSize, LogViewMode } from 'container/OptionsMenu/types';
|
||||
import { Preferences } from 'providers/preferences/types';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
function withColumnNames(
|
||||
columns: TelemetryFieldKey[] | undefined,
|
||||
@@ -27,11 +25,11 @@ function withColumnNames(
|
||||
// defaults filled in where the view has none.
|
||||
export function getViewColumnsAndFormatting(
|
||||
spec: SavedviewtypesSavedViewSpecDTO | undefined,
|
||||
sourcePage: SavedviewtypesSourceDTO,
|
||||
dataSource: DataSource,
|
||||
): Preferences {
|
||||
const selectedFields = spec?.selectedFields as TelemetryFieldKey[] | undefined;
|
||||
|
||||
if (sourcePage === SavedviewtypesSourceDTO.logs) {
|
||||
if (dataSource === DataSource.LOGS) {
|
||||
return {
|
||||
columns: ensureLogsRequiredColumns(
|
||||
withColumnNames(selectedFields) || defaultLogsSelectedColumns,
|
||||
@@ -44,7 +42,7 @@ export function getViewColumnsAndFormatting(
|
||||
},
|
||||
};
|
||||
}
|
||||
if (sourcePage === SavedviewtypesSourceDTO.traces) {
|
||||
if (dataSource === DataSource.TRACES) {
|
||||
return { columns: selectedFields || defaultTraceSelectedColumns };
|
||||
}
|
||||
return { columns: [] };
|
||||
|
||||
@@ -7,7 +7,6 @@ import { HasUnsavedViewChangesArgs } from '../types';
|
||||
import { getSavedViewQuery } from './getSavedViewQuery';
|
||||
import { toSavedViewPanelType } from './toSavedViewSpec';
|
||||
import { getViewColumnsAndFormatting } from './getViewColumnsAndFormatting';
|
||||
import { toSavedViewSource } from './toSavedViewSource';
|
||||
|
||||
// Legacy context names the server stores under their v5 name.
|
||||
const FIELD_CONTEXT_ALIASES: Record<string, TelemetrytypesFieldContextDTO> = {
|
||||
@@ -80,7 +79,7 @@ export function hasUnsavedViewChanges({
|
||||
const dataSource = stagedQuery.builder.queryData[0]?.dataSource;
|
||||
const { columns, formatting } = getViewColumnsAndFormatting(
|
||||
view.spec,
|
||||
toSavedViewSource(dataSource),
|
||||
dataSource,
|
||||
);
|
||||
const toNames = (fields: { name?: string; key?: string }[]): unknown[] =>
|
||||
fields.map((field) => field.name ?? field.key);
|
||||
|
||||
@@ -3,8 +3,11 @@ import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import { SavedViewSourcePage } from '../types';
|
||||
|
||||
// Queries and the AI assistant name a source by DataSource (the signal), the
|
||||
// api keys views by source page.
|
||||
// Explorers and the preferences module are keyed by DataSource (the signal),
|
||||
// the api keys views by source page. Same values today, so this is the one
|
||||
// place they meet. AI observability views will come with their own source and
|
||||
// DataSource cannot tell them apart from traces, so preferences should move to
|
||||
// source page at that point and this map goes with it.
|
||||
const SAVED_VIEW_SOURCE: Record<SavedViewSourcePage, SavedviewtypesSourceDTO> =
|
||||
{
|
||||
[DataSource.LOGS]: SavedviewtypesSourceDTO.logs,
|
||||
|
||||
@@ -11,7 +11,6 @@ import {
|
||||
// eslint-disable-next-line no-restricted-imports
|
||||
import { useSelector } from 'react-redux';
|
||||
import logEvent from 'api/common/logEvent';
|
||||
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import DownloadOptionsMenu from 'components/DownloadOptionsMenu/DownloadOptionsMenu';
|
||||
import ListViewOrderBy from 'components/OrderBy/ListViewOrderBy';
|
||||
import type { TableColumnDef } from 'components/TanStackTableView/types';
|
||||
@@ -87,7 +86,7 @@ function ListView({
|
||||
|
||||
const { options, config } = useOptionsMenu({
|
||||
storageKey: LOCALSTORAGE.TRACES_LIST_OPTIONS,
|
||||
sourcePage: SavedviewtypesSourceDTO.traces,
|
||||
dataSource: DataSource.TRACES,
|
||||
aggregateOperator: 'count',
|
||||
initialOptions: {
|
||||
selectColumns: defaultSelectedColumns,
|
||||
|
||||
25
frontend/src/lib/monaco/MonacoEditor.tsx
Normal file
25
frontend/src/lib/monaco/MonacoEditor.tsx
Normal file
@@ -0,0 +1,25 @@
|
||||
import { useCallback } from 'react';
|
||||
import MEditor, { EditorProps, Monaco } from '@monaco-editor/react';
|
||||
|
||||
import { EDITOR_THEME, registerEditorTheme } from './editorTheme';
|
||||
|
||||
export type MonacoEditorProps = Omit<EditorProps, 'theme'>;
|
||||
|
||||
function MonacoEditor({
|
||||
beforeMount,
|
||||
...props
|
||||
}: MonacoEditorProps): JSX.Element {
|
||||
const handleBeforeMount = useCallback(
|
||||
(monaco: Monaco): void => {
|
||||
registerEditorTheme(monaco);
|
||||
beforeMount?.(monaco);
|
||||
},
|
||||
[beforeMount],
|
||||
);
|
||||
|
||||
return (
|
||||
<MEditor {...props} theme={EDITOR_THEME} beforeMount={handleBeforeMount} />
|
||||
);
|
||||
}
|
||||
|
||||
export default MonacoEditor;
|
||||
58
frontend/src/lib/monaco/__tests__/MonacoEditor.test.tsx
Normal file
58
frontend/src/lib/monaco/__tests__/MonacoEditor.test.tsx
Normal file
@@ -0,0 +1,58 @@
|
||||
import type { EditorProps, Monaco } from '@monaco-editor/react';
|
||||
import { render } from '@testing-library/react';
|
||||
|
||||
import { EDITOR_THEME, registerEditorTheme } from '../editorTheme';
|
||||
import MonacoEditor from '../MonacoEditor';
|
||||
|
||||
const editorProps = jest.fn();
|
||||
|
||||
jest.mock('@monaco-editor/react', () => ({
|
||||
__esModule: true,
|
||||
default: (props: EditorProps): JSX.Element => {
|
||||
editorProps(props);
|
||||
return <div data-testid="monaco" />;
|
||||
},
|
||||
}));
|
||||
|
||||
jest.mock('../editorTheme', () => ({
|
||||
EDITOR_THEME: 'signoz',
|
||||
registerEditorTheme: jest.fn(),
|
||||
}));
|
||||
|
||||
function lastProps(): EditorProps {
|
||||
return editorProps.mock.calls[editorProps.mock.calls.length - 1][0];
|
||||
}
|
||||
|
||||
describe('MonacoEditor', () => {
|
||||
beforeEach(() => {
|
||||
editorProps.mockClear();
|
||||
jest.mocked(registerEditorTheme).mockClear();
|
||||
});
|
||||
|
||||
it('renders with the shared theme and forwards the other props', () => {
|
||||
render(<MonacoEditor language="json" value="{}" height="100%" />);
|
||||
|
||||
expect(lastProps()).toMatchObject({
|
||||
theme: EDITOR_THEME,
|
||||
language: 'json',
|
||||
value: '{}',
|
||||
height: '100%',
|
||||
});
|
||||
});
|
||||
|
||||
it('registers the theme before the caller sets up monaco', () => {
|
||||
const calls: string[] = [];
|
||||
jest
|
||||
.mocked(registerEditorTheme)
|
||||
.mockImplementation(() => calls.push('theme'));
|
||||
const beforeMount = jest.fn(() => calls.push('caller'));
|
||||
const monaco = {} as Monaco;
|
||||
|
||||
render(<MonacoEditor beforeMount={beforeMount} />);
|
||||
lastProps().beforeMount?.(monaco);
|
||||
|
||||
expect(registerEditorTheme).toHaveBeenCalledWith(monaco);
|
||||
expect(beforeMount).toHaveBeenCalledWith(monaco);
|
||||
expect(calls).toStrictEqual(['theme', 'caller']);
|
||||
});
|
||||
});
|
||||
138
frontend/src/lib/monaco/__tests__/editorTheme.test.ts
Normal file
138
frontend/src/lib/monaco/__tests__/editorTheme.test.ts
Normal file
@@ -0,0 +1,138 @@
|
||||
import type { Monaco } from '@monaco-editor/react';
|
||||
|
||||
type EditorThemeModule = typeof import('../editorTheme');
|
||||
|
||||
const DARK_TOKENS = {
|
||||
'--l1-background': '#0b0c0e',
|
||||
'--l1-foreground': '#eceef2',
|
||||
'--bg-vanilla-400': '#c0c1c3',
|
||||
'--bg-robin-400': '#7190f9',
|
||||
};
|
||||
|
||||
const LIGHT_TOKENS = {
|
||||
'--l1-background': '#ffffff',
|
||||
'--l1-foreground': '#121317',
|
||||
'--bg-vanilla-400': '#c0c1c3',
|
||||
'--bg-robin-400': '#7190f9',
|
||||
};
|
||||
|
||||
function setTokens(tokens: Record<string, string>): void {
|
||||
Object.entries(tokens).forEach(([name, value]) => {
|
||||
document.body.style.setProperty(name, value);
|
||||
});
|
||||
}
|
||||
|
||||
function createMonaco(): { monaco: Monaco; defineTheme: jest.Mock } {
|
||||
const defineTheme = jest.fn();
|
||||
return {
|
||||
monaco: { editor: { defineTheme } } as unknown as Monaco,
|
||||
defineTheme,
|
||||
};
|
||||
}
|
||||
|
||||
function loadModule(): EditorThemeModule {
|
||||
let mod: EditorThemeModule | undefined;
|
||||
jest.isolateModules(() => {
|
||||
mod = jest.requireActual<EditorThemeModule>('../editorTheme');
|
||||
});
|
||||
return mod as EditorThemeModule;
|
||||
}
|
||||
|
||||
async function flushMutations(): Promise<void> {
|
||||
await Promise.resolve();
|
||||
}
|
||||
|
||||
describe('registerEditorTheme', () => {
|
||||
afterEach(() => {
|
||||
document.body.removeAttribute('style');
|
||||
document.body.className = '';
|
||||
});
|
||||
|
||||
it('defines a dark theme with the JSON token colours on a dark surface', () => {
|
||||
setTokens(DARK_TOKENS);
|
||||
const { registerEditorTheme, EDITOR_THEME } = loadModule();
|
||||
const { monaco, defineTheme } = createMonaco();
|
||||
|
||||
registerEditorTheme(monaco);
|
||||
|
||||
expect(defineTheme).toHaveBeenCalledTimes(1);
|
||||
expect(defineTheme).toHaveBeenCalledWith(EDITOR_THEME, {
|
||||
base: 'vs-dark',
|
||||
inherit: true,
|
||||
rules: [
|
||||
{ token: 'string.key.json', foreground: 'c0c1c3' },
|
||||
{ token: 'string.value.json', foreground: '7190f9' },
|
||||
],
|
||||
colors: {
|
||||
'editor.background': '#0b0c0e',
|
||||
'editor.foreground': '#eceef2',
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps the vs palette on a light surface', () => {
|
||||
setTokens(LIGHT_TOKENS);
|
||||
const { registerEditorTheme } = loadModule();
|
||||
const { monaco, defineTheme } = createMonaco();
|
||||
|
||||
registerEditorTheme(monaco);
|
||||
|
||||
expect(defineTheme).toHaveBeenCalledWith(
|
||||
expect.any(String),
|
||||
expect.objectContaining({
|
||||
base: 'vs',
|
||||
rules: [],
|
||||
colors: {
|
||||
'editor.background': '#ffffff',
|
||||
'editor.foreground': '#121317',
|
||||
},
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('redefines the theme when the body class switches the tokens', async () => {
|
||||
setTokens(DARK_TOKENS);
|
||||
const { registerEditorTheme } = loadModule();
|
||||
const { monaco, defineTheme } = createMonaco();
|
||||
registerEditorTheme(monaco);
|
||||
|
||||
setTokens(LIGHT_TOKENS);
|
||||
document.body.classList.add('lightMode');
|
||||
await flushMutations();
|
||||
|
||||
expect(defineTheme).toHaveBeenCalledTimes(2);
|
||||
expect(defineTheme).toHaveBeenLastCalledWith(
|
||||
expect.any(String),
|
||||
expect.objectContaining({ base: 'vs' }),
|
||||
);
|
||||
});
|
||||
|
||||
it('ignores body class changes that leave the tokens alone', async () => {
|
||||
setTokens(DARK_TOKENS);
|
||||
const { registerEditorTheme } = loadModule();
|
||||
const { monaco, defineTheme } = createMonaco();
|
||||
registerEditorTheme(monaco);
|
||||
|
||||
document.body.classList.add('ant-scrolling-effect');
|
||||
await flushMutations();
|
||||
|
||||
expect(defineTheme).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('watches the body once however many editors mount', async () => {
|
||||
const observe = jest.spyOn(MutationObserver.prototype, 'observe');
|
||||
setTokens(DARK_TOKENS);
|
||||
const { registerEditorTheme } = loadModule();
|
||||
const { monaco, defineTheme } = createMonaco();
|
||||
registerEditorTheme(monaco);
|
||||
registerEditorTheme(monaco);
|
||||
|
||||
setTokens(LIGHT_TOKENS);
|
||||
document.body.classList.add('lightMode');
|
||||
await flushMutations();
|
||||
|
||||
expect(observe).toHaveBeenCalledTimes(1);
|
||||
expect(defineTheme).toHaveBeenCalledTimes(2);
|
||||
observe.mockRestore();
|
||||
});
|
||||
});
|
||||
@@ -1,24 +1,7 @@
|
||||
import { Monaco } from '@monaco-editor/react';
|
||||
import { Color } from '@signozhq/design-tokens';
|
||||
|
||||
type EditorOptions = Parameters<Monaco['editor']['create']>[1];
|
||||
|
||||
export const JSON_THEME_DARK = 'json-theme-dark';
|
||||
|
||||
export function defineJsonTheme(monaco: Monaco): void {
|
||||
monaco.editor.defineTheme(JSON_THEME_DARK, {
|
||||
base: 'vs-dark',
|
||||
inherit: true,
|
||||
rules: [
|
||||
{ token: 'string.key.json', foreground: Color.BG_VANILLA_400 },
|
||||
{ token: 'string.value.json', foreground: Color.BG_ROBIN_400 },
|
||||
],
|
||||
colors: {
|
||||
'editor.background': Color.BG_INK_400,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const BASE_EDITOR_OPTIONS: EditorOptions = {
|
||||
automaticLayout: true,
|
||||
wordWrap: 'on',
|
||||
78
frontend/src/lib/monaco/editorTheme.ts
Normal file
78
frontend/src/lib/monaco/editorTheme.ts
Normal file
@@ -0,0 +1,78 @@
|
||||
import type { Monaco } from '@monaco-editor/react';
|
||||
|
||||
export const EDITOR_THEME = 'signoz';
|
||||
|
||||
let definedBackground: string | undefined;
|
||||
let bodyClassObserver: MutationObserver | undefined;
|
||||
|
||||
function token(name: string): string {
|
||||
return getComputedStyle(document.body)
|
||||
.getPropertyValue(name)
|
||||
.trim()
|
||||
.replace('#', '');
|
||||
}
|
||||
|
||||
function isDark(hex: string): boolean {
|
||||
if (hex.length < 6) {
|
||||
return true;
|
||||
}
|
||||
const r = parseInt(hex.slice(0, 2), 16);
|
||||
const g = parseInt(hex.slice(2, 4), 16);
|
||||
const b = parseInt(hex.slice(4, 6), 16);
|
||||
return 0.299 * r + 0.587 * g + 0.114 * b < 128;
|
||||
}
|
||||
|
||||
function defineEditorTheme(monaco: Monaco): void {
|
||||
const background = token('--l1-background');
|
||||
if (background === definedBackground) {
|
||||
return;
|
||||
}
|
||||
definedBackground = background;
|
||||
|
||||
const foreground = token('--l1-foreground');
|
||||
const keyColor = token('--bg-vanilla-400');
|
||||
const valueColor = token('--bg-robin-400');
|
||||
|
||||
// Both token colours are picked to read on a dark surface, so on a light one
|
||||
// they wash out, the keys worst of all. Monaco's own `vs` palette is built
|
||||
// for that surface, so let it keep its colours there, as the role viewer does.
|
||||
const rules: { token: string; foreground: string }[] = [];
|
||||
if (isDark(background)) {
|
||||
if (keyColor) {
|
||||
rules.push({ token: 'string.key.json', foreground: keyColor });
|
||||
}
|
||||
if (valueColor) {
|
||||
rules.push({ token: 'string.value.json', foreground: valueColor });
|
||||
}
|
||||
}
|
||||
|
||||
const colors: Record<string, string> = {};
|
||||
if (background) {
|
||||
colors['editor.background'] = `#${background}`;
|
||||
}
|
||||
if (foreground) {
|
||||
colors['editor.foreground'] = `#${foreground}`;
|
||||
}
|
||||
|
||||
monaco.editor.defineTheme(EDITOR_THEME, {
|
||||
base: isDark(background) ? 'vs-dark' : 'vs',
|
||||
inherit: true,
|
||||
rules,
|
||||
colors,
|
||||
});
|
||||
}
|
||||
|
||||
// Monaco has a single theme for every editor on the page, and the design tokens
|
||||
// switch with the body's `dark` class, so the theme follows that class instead
|
||||
// of being defined per editor.
|
||||
export function registerEditorTheme(monaco: Monaco): void {
|
||||
defineEditorTheme(monaco);
|
||||
if (bodyClassObserver) {
|
||||
return;
|
||||
}
|
||||
bodyClassObserver = new MutationObserver(() => defineEditorTheme(monaco));
|
||||
bodyClassObserver.observe(document.body, {
|
||||
attributes: true,
|
||||
attributeFilter: ['class'],
|
||||
});
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
import type { Monaco } from '@monaco-editor/react';
|
||||
|
||||
export const JSON_EDITOR_THEME = 'signoz-json';
|
||||
|
||||
function token(el: HTMLElement, name: string): string {
|
||||
return getComputedStyle(el).getPropertyValue(name).trim().replace('#', '');
|
||||
}
|
||||
|
||||
function isDark(hex: string): boolean {
|
||||
if (hex.length < 6) {
|
||||
return true;
|
||||
}
|
||||
const r = parseInt(hex.slice(0, 2), 16);
|
||||
const g = parseInt(hex.slice(2, 4), 16);
|
||||
const b = parseInt(hex.slice(4, 6), 16);
|
||||
return 0.299 * r + 0.587 * g + 0.114 * b < 128;
|
||||
}
|
||||
|
||||
export function defineJsonEditorTheme(monaco: Monaco, el: HTMLElement): void {
|
||||
const background = token(el, '--l1-background');
|
||||
const foreground = token(el, '--l1-foreground');
|
||||
const keyColor = token(el, '--bg-vanilla-400');
|
||||
const valueColor = token(el, '--bg-robin-400');
|
||||
|
||||
// Both token colours are picked to read on a dark surface, so on a light one
|
||||
// they wash out, the keys worst of all. Monaco's own `vs` palette is built
|
||||
// for that surface, so let it keep its colours there, as the role viewer does.
|
||||
const rules: { token: string; foreground: string }[] = [];
|
||||
if (isDark(background)) {
|
||||
if (keyColor) {
|
||||
rules.push({ token: 'string.key.json', foreground: keyColor });
|
||||
}
|
||||
if (valueColor) {
|
||||
rules.push({ token: 'string.value.json', foreground: valueColor });
|
||||
}
|
||||
}
|
||||
|
||||
const colors: Record<string, string> = {};
|
||||
if (background) {
|
||||
colors['editor.background'] = `#${background}`;
|
||||
}
|
||||
if (foreground) {
|
||||
colors['editor.foreground'] = `#${foreground}`;
|
||||
}
|
||||
|
||||
monaco.editor.defineTheme(JSON_EDITOR_THEME, {
|
||||
base: isDark(background) ? 'vs-dark' : 'vs',
|
||||
inherit: true,
|
||||
rules,
|
||||
colors,
|
||||
});
|
||||
}
|
||||
@@ -1,15 +1,11 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { useCopyToClipboard } from 'react-use';
|
||||
import MEditor from '@monaco-editor/react';
|
||||
import { DrawerWrapper } from '@signozhq/ui/drawer';
|
||||
import { useGetNotificationChannel } from 'api/generated/services/channels';
|
||||
import ErrorEmptyState from 'components/Alerts/ErrorEmptyState';
|
||||
import Spinner from 'components/Spinner';
|
||||
import { READONLY_EDITOR_OPTIONS } from 'container/RolesSettings/monaco.config';
|
||||
import {
|
||||
defineJsonEditorTheme,
|
||||
JSON_EDITOR_THEME,
|
||||
} from 'lib/monaco/jsonEditorTheme';
|
||||
import { READONLY_EDITOR_OPTIONS } from 'lib/monaco/editorOptions';
|
||||
import MonacoEditor from 'lib/monaco/MonacoEditor';
|
||||
|
||||
import { channelToJson, hasSecrets } from '../../utils/channelJson';
|
||||
import styles from './ChannelJsonDialog.module.scss';
|
||||
@@ -92,18 +88,11 @@ function ChannelJsonDialog({
|
||||
/>
|
||||
|
||||
<div className={styles.editor}>
|
||||
<MEditor
|
||||
<MonacoEditor
|
||||
value={json}
|
||||
language="json"
|
||||
options={READONLY_EDITOR_OPTIONS}
|
||||
height="100%"
|
||||
theme="vs-dark"
|
||||
// the same theme the dashboard JSON drawer uses: it reads the
|
||||
// page's own tokens, so it follows light and dark
|
||||
onMount={(editor, monaco): void => {
|
||||
defineJsonEditorTheme(monaco, editor.getContainerDomNode());
|
||||
monaco.editor.setTheme(JSON_EDITOR_THEME);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { KeyboardEvent, useCallback } from 'react';
|
||||
import MEditor from '@monaco-editor/react';
|
||||
import { TriangleAlert } from '@signozhq/icons';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { Tooltip } from '@signozhq/ui/tooltip';
|
||||
@@ -12,10 +11,7 @@ import { DashboardDetailEvents } from 'pages/DashboardPage/constants/events';
|
||||
import { useCopyToClipboard } from 'react-use';
|
||||
import { toast } from '@signozhq/ui/sonner';
|
||||
|
||||
import {
|
||||
defineJsonEditorTheme,
|
||||
JSON_EDITOR_THEME,
|
||||
} from 'lib/monaco/jsonEditorTheme';
|
||||
import MonacoEditor from 'lib/monaco/MonacoEditor';
|
||||
import styles from './JsonEditorDrawer.module.scss';
|
||||
import JsonEditorToolbar from './JsonEditorToolbar';
|
||||
import { useJsonEditor } from './useJsonEditor';
|
||||
@@ -213,7 +209,7 @@ function JsonEditorDrawer({
|
||||
onReset={reset}
|
||||
/>
|
||||
<div className={styles.editor}>
|
||||
<MEditor
|
||||
<MonacoEditor
|
||||
language="json"
|
||||
height="100%"
|
||||
value={draft}
|
||||
@@ -225,10 +221,7 @@ function JsonEditorDrawer({
|
||||
fontSize: 13,
|
||||
fontFamily: 'Space Mono',
|
||||
}}
|
||||
theme="vs-dark"
|
||||
onMount={(editor, monaco): void => {
|
||||
defineJsonEditorTheme(monaco, editor.getContainerDomNode());
|
||||
monaco.editor.setTheme(JSON_EDITOR_THEME);
|
||||
onMount={(_editor, monaco): void => {
|
||||
void document.fonts.ready.then(() => monaco.editor.remeasureFonts());
|
||||
}}
|
||||
/>
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
import type { ComponentType } from 'react';
|
||||
import type { Meta, StoryObj } from '@storybook/react-vite';
|
||||
import { Route } from 'react-router-dom';
|
||||
import * as monaco from 'monaco-editor';
|
||||
import ROUTES from 'constants/routes';
|
||||
import { screen, userEvent, within } from 'storybook/test';
|
||||
import { screen, userEvent, waitFor, within } from 'storybook/test';
|
||||
|
||||
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
|
||||
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
|
||||
import { waitForMonacoText } from '@/storybook/visual/waitForMonacoText';
|
||||
|
||||
import { panelEditorMocks, savePanel } from './PanelEditorPage.stories.mocks';
|
||||
|
||||
@@ -249,3 +251,43 @@ export const TextPanelSavedToast: Story = {
|
||||
args: { panel: 'new', newPanelKind: 'text' },
|
||||
play: PanelSavedToast.play,
|
||||
};
|
||||
|
||||
const CLICKHOUSE_QUERY =
|
||||
'SELECT toStartOfInterval(timestamp, INTERVAL 1 MINUTE) AS ts, serviceName, count() AS calls FROM signoz_traces.distributed_signoz_index_v3 WHERE timestamp > now() - INTERVAL 1 HOUR GROUP BY ts, serviceName ORDER BY ts';
|
||||
|
||||
/**
|
||||
* The ClickHouse Query tab with a query written in its SQL editor, over the
|
||||
* panel the editor opened on.
|
||||
*/
|
||||
export const ClickHouseQuery: Story = {
|
||||
play: async ({ canvasElement }): Promise<void> => {
|
||||
const tab = await within(canvasElement).findByRole(
|
||||
'tab',
|
||||
{ name: /ClickHouse Query/ },
|
||||
{ timeout: 10000 },
|
||||
);
|
||||
|
||||
await userEvent.click(tab);
|
||||
|
||||
// Typing into Monaco's hidden textarea never reaches its model in this runner.
|
||||
const model = await waitFor(
|
||||
() => {
|
||||
const found = monaco.editor
|
||||
.getModels()
|
||||
.find((candidate) => candidate.getLanguageId() === 'sql');
|
||||
|
||||
if (!found) {
|
||||
throw new Error('The SQL editor has not mounted');
|
||||
}
|
||||
|
||||
return found;
|
||||
},
|
||||
{ timeout: 15000 },
|
||||
);
|
||||
|
||||
model.setValue(CLICKHOUSE_QUERY);
|
||||
await waitForMonacoText(canvasElement);
|
||||
await userEvent.unhover(tab);
|
||||
(document.activeElement as HTMLElement | null)?.blur();
|
||||
},
|
||||
};
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
import { useState } from 'react';
|
||||
import MEditor, { Monaco } from '@monaco-editor/react';
|
||||
import { Color } from '@signozhq/design-tokens';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { DialogWrapper } from '@signozhq/ui/dialog';
|
||||
import { Maximize2 } from '@signozhq/icons';
|
||||
import { useIsDarkMode } from 'hooks/useDarkMode';
|
||||
import MonacoEditor from 'lib/monaco/MonacoEditor';
|
||||
|
||||
import styles from './NewDashboardModal.module.scss';
|
||||
|
||||
@@ -15,18 +13,6 @@ interface Props {
|
||||
height?: string;
|
||||
}
|
||||
|
||||
const defineTheme = (monaco: Monaco): void => {
|
||||
monaco.editor.defineTheme('my-theme', {
|
||||
base: 'vs-dark',
|
||||
inherit: true,
|
||||
rules: [
|
||||
{ token: 'string.key.json', foreground: Color.BG_VANILLA_400 },
|
||||
{ token: 'string.value.json', foreground: Color.BG_ROBIN_400 },
|
||||
],
|
||||
colors: { 'editor.background': Color.BG_INK_300 },
|
||||
});
|
||||
};
|
||||
|
||||
// JSON editor with a one-click "expand" into an extra-wide modal for easier
|
||||
// editing/review. The expanded editor shares the same value, so edits persist.
|
||||
function JsonEditor({
|
||||
@@ -35,11 +21,10 @@ function JsonEditor({
|
||||
readOnly = false,
|
||||
height = '38vh',
|
||||
}: Props): JSX.Element {
|
||||
const isDarkMode = useIsDarkMode();
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
|
||||
const renderEditor = (editorHeight: string): JSX.Element => (
|
||||
<MEditor
|
||||
<MonacoEditor
|
||||
language="json"
|
||||
height={editorHeight}
|
||||
value={value}
|
||||
@@ -51,8 +36,6 @@ function JsonEditor({
|
||||
fontSize: 14,
|
||||
fontFamily: 'Space Mono',
|
||||
}}
|
||||
theme={isDarkMode ? 'my-theme' : 'light'}
|
||||
beforeMount={defineTheme}
|
||||
/>
|
||||
);
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
|
||||
|
||||
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
|
||||
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
|
||||
import { waitForMonacoText } from '@/storybook/visual/waitForMonacoText';
|
||||
|
||||
import LLMObservabilityPage from '../../index';
|
||||
import {
|
||||
@@ -101,3 +102,21 @@ export const ChangesSavedToast: Story = {
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* The Test tab: the JSON editor pre-filled with the sample span, before any run.
|
||||
*/
|
||||
export const TestTab: Story = {
|
||||
play: async ({ canvasElement }): Promise<void> => {
|
||||
const tab = await within(canvasElement).findByRole(
|
||||
'tab',
|
||||
{ name: 'Test' },
|
||||
{ timeout: 10000 },
|
||||
);
|
||||
|
||||
await userEvent.click(tab);
|
||||
await waitForMonacoText(canvasElement);
|
||||
await userEvent.unhover(tab);
|
||||
(document.activeElement as HTMLElement | null)?.blur();
|
||||
},
|
||||
};
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
|
||||
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
|
||||
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
|
||||
import { waitForMonacoText } from '@/storybook/visual/waitForMonacoText';
|
||||
|
||||
import {
|
||||
focusSpanIndex,
|
||||
@@ -325,3 +326,19 @@ export const TraceExportCancelledToast: Story = {
|
||||
await userEvent.click(await screen.findByTestId('trace-download-cancel'));
|
||||
},
|
||||
};
|
||||
|
||||
/** The span panel switched from the pretty view to the span's raw JSON. */
|
||||
export const SpanJsonView: Story = {
|
||||
play: async ({ canvasElement }): Promise<void> => {
|
||||
const option = await within(canvasElement).findByTestId(
|
||||
'data-viewer-view-mode-button-json',
|
||||
undefined,
|
||||
untilLoaded,
|
||||
);
|
||||
|
||||
await userEvent.click(option);
|
||||
await waitForMonacoText(canvasElement);
|
||||
await userEvent.unhover(option);
|
||||
(document.activeElement as HTMLElement | null)?.blur();
|
||||
},
|
||||
};
|
||||
|
||||
@@ -73,7 +73,7 @@ function TracesExplorer(): JSX.Element {
|
||||
|
||||
const { options } = useOptionsMenu({
|
||||
storageKey: LOCALSTORAGE.TRACES_LIST_OPTIONS,
|
||||
sourcePage: SavedviewtypesSourceDTO.traces,
|
||||
dataSource: DataSource.TRACES,
|
||||
aggregateOperator: 'noop',
|
||||
initialOptions: {
|
||||
selectColumns: defaultSelectedColumns,
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
import { useState } from 'react';
|
||||
import MEditor, { EditorProps, Monaco } from '@monaco-editor/react';
|
||||
import { Color } from '@signozhq/design-tokens';
|
||||
import { EditorProps } from '@monaco-editor/react';
|
||||
import { Switch } from '@signozhq/ui/switch';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import { useIsDarkMode } from 'hooks/useDarkMode';
|
||||
import MonacoEditor from 'lib/monaco/MonacoEditor';
|
||||
|
||||
import './JsonView.styles.scss';
|
||||
|
||||
@@ -38,36 +37,16 @@ const editorOptions: EditorProps['options'] = {
|
||||
folding: false,
|
||||
};
|
||||
|
||||
function setEditorTheme(monaco: Monaco): void {
|
||||
monaco.editor.defineTheme('signoz-dark', {
|
||||
base: 'vs-dark',
|
||||
inherit: true,
|
||||
rules: [
|
||||
{ token: 'string.key.json', foreground: Color.BG_VANILLA_400 },
|
||||
{ token: 'string.value.json', foreground: Color.BG_ROBIN_400 },
|
||||
],
|
||||
colors: {
|
||||
'editor.background': '#00000000', // transparent
|
||||
},
|
||||
fontFamily: 'SF Mono, Geist Mono, Fira Code, monospace',
|
||||
fontSize: 12,
|
||||
fontWeight: 'normal',
|
||||
lineHeight: 18,
|
||||
letterSpacing: -0.06,
|
||||
});
|
||||
}
|
||||
|
||||
function JsonView({
|
||||
data,
|
||||
height = '575px',
|
||||
fontSize = 12,
|
||||
}: JsonViewProps): JSX.Element {
|
||||
const [isWrapWord, setIsWrapWord] = useState(true);
|
||||
const isDarkMode = useIsDarkMode();
|
||||
|
||||
return (
|
||||
<div className="json-view">
|
||||
<MEditor
|
||||
<MonacoEditor
|
||||
value={data}
|
||||
language="json"
|
||||
options={{
|
||||
@@ -77,8 +56,6 @@ function JsonView({
|
||||
}}
|
||||
onChange={(): void => {}}
|
||||
height={height}
|
||||
theme={isDarkMode ? 'signoz-dark' : 'light'}
|
||||
beforeMount={setEditorTheme}
|
||||
/>
|
||||
<div className="json-view__footer">
|
||||
<div className="json-view__wrap-toggle">
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { TelemetryFieldKey } from 'api/v5/v5';
|
||||
import { LOCALSTORAGE } from 'constants/localStorage';
|
||||
import { LogViewMode, FontSize } from 'container/OptionsMenu/types';
|
||||
import { LogViewMode } from 'container/OptionsMenu/types';
|
||||
import {
|
||||
defaultLogsSelectedColumns,
|
||||
defaultTraceSelectedColumns,
|
||||
} from 'container/OptionsMenu/constants';
|
||||
import { FontSize } from 'container/OptionsMenu/types';
|
||||
import { render, screen, userEvent } from 'tests/test-utils';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import { usePreferenceContext } from '../context/PreferenceContextProvider';
|
||||
import { PreferenceSourcePage } from '../types';
|
||||
|
||||
const ROUTE_LOGS = '/logs';
|
||||
const ROUTE_TRACES = '/traces';
|
||||
@@ -38,13 +38,14 @@ function getLocalStorageJSON<T>(key: string): T | null {
|
||||
}
|
||||
|
||||
function Consumer({
|
||||
sourcePage,
|
||||
dataSource,
|
||||
testIdPrefix,
|
||||
}: {
|
||||
sourcePage: PreferenceSourcePage;
|
||||
dataSource: DataSource;
|
||||
testIdPrefix: string;
|
||||
}): JSX.Element {
|
||||
const slice = usePreferenceContext()[sourcePage];
|
||||
const ctx = usePreferenceContext();
|
||||
const slice = dataSource === DataSource.TRACES ? ctx.traces : ctx.logs;
|
||||
|
||||
return (
|
||||
<div>
|
||||
@@ -57,7 +58,7 @@ function Consumer({
|
||||
type="button"
|
||||
onClick={(): void => {
|
||||
const newCols: TelemetryFieldKey[] =
|
||||
sourcePage === SavedviewtypesSourceDTO.traces
|
||||
dataSource === DataSource.TRACES
|
||||
? (defaultTraceSelectedColumns.slice(0, 1) as TelemetryFieldKey[])
|
||||
: (defaultLogsSelectedColumns.slice(0, 1) as TelemetryFieldKey[]);
|
||||
slice.updateColumns(newCols);
|
||||
@@ -77,10 +78,7 @@ describe('PreferencesProvider integration', () => {
|
||||
describe('Logs', () => {
|
||||
it('loads defaults when no localStorage or url provided', () => {
|
||||
render(
|
||||
<Consumer
|
||||
sourcePage={SavedviewtypesSourceDTO.logs}
|
||||
testIdPrefix={TESTID_LOGS}
|
||||
/>,
|
||||
<Consumer dataSource={DataSource.LOGS} testIdPrefix={TESTID_LOGS} />,
|
||||
undefined,
|
||||
{
|
||||
initialRoute: ROUTE_LOGS,
|
||||
@@ -103,10 +101,7 @@ describe('PreferencesProvider integration', () => {
|
||||
});
|
||||
|
||||
render(
|
||||
<Consumer
|
||||
sourcePage={SavedviewtypesSourceDTO.logs}
|
||||
testIdPrefix={TESTID_LOGS}
|
||||
/>,
|
||||
<Consumer dataSource={DataSource.LOGS} testIdPrefix={TESTID_LOGS} />,
|
||||
undefined,
|
||||
{
|
||||
initialRoute: ROUTE_LOGS,
|
||||
@@ -121,10 +116,7 @@ describe('PreferencesProvider integration', () => {
|
||||
it('direct mode updateColumns persists to localStorage', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
render(
|
||||
<Consumer
|
||||
sourcePage={SavedviewtypesSourceDTO.logs}
|
||||
testIdPrefix={TESTID_LOGS}
|
||||
/>,
|
||||
<Consumer dataSource={DataSource.LOGS} testIdPrefix={TESTID_LOGS} />,
|
||||
undefined,
|
||||
{
|
||||
initialRoute: ROUTE_LOGS,
|
||||
@@ -150,7 +142,7 @@ describe('PreferencesProvider integration', () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
|
||||
render(
|
||||
<Consumer sourcePage={SavedviewtypesSourceDTO.logs} testIdPrefix="logs" />,
|
||||
<Consumer dataSource={DataSource.LOGS} testIdPrefix="logs" />,
|
||||
undefined,
|
||||
{
|
||||
initialRoute: initialEntry,
|
||||
@@ -183,10 +175,7 @@ describe('PreferencesProvider integration', () => {
|
||||
});
|
||||
|
||||
render(
|
||||
<Consumer
|
||||
sourcePage={SavedviewtypesSourceDTO.logs}
|
||||
testIdPrefix={TESTID_LOGS}
|
||||
/>,
|
||||
<Consumer dataSource={DataSource.LOGS} testIdPrefix={TESTID_LOGS} />,
|
||||
undefined,
|
||||
{
|
||||
initialRoute: ROUTE_LOGS,
|
||||
@@ -208,7 +197,7 @@ describe('PreferencesProvider integration', () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
|
||||
function FormattingConsumer(): JSX.Element {
|
||||
const logs = usePreferenceContext()[SavedviewtypesSourceDTO.logs];
|
||||
const { logs } = usePreferenceContext();
|
||||
return (
|
||||
<button
|
||||
data-testid="logs-update-formatting"
|
||||
@@ -246,10 +235,7 @@ describe('PreferencesProvider integration', () => {
|
||||
const initialEntry = `/logs?viewKey=${encodeURIComponent(viewKey)}`;
|
||||
|
||||
render(
|
||||
<Consumer
|
||||
sourcePage={SavedviewtypesSourceDTO.logs}
|
||||
testIdPrefix={TESTID_LOGS}
|
||||
/>,
|
||||
<Consumer dataSource={DataSource.LOGS} testIdPrefix={TESTID_LOGS} />,
|
||||
undefined,
|
||||
{ initialRoute: initialEntry },
|
||||
);
|
||||
@@ -268,10 +254,7 @@ describe('PreferencesProvider integration', () => {
|
||||
describe('Traces', () => {
|
||||
it('loads defaults when no localStorage or url provided', () => {
|
||||
render(
|
||||
<Consumer
|
||||
sourcePage={SavedviewtypesSourceDTO.traces}
|
||||
testIdPrefix={TESTID_TRACES}
|
||||
/>,
|
||||
<Consumer dataSource={DataSource.TRACES} testIdPrefix={TESTID_TRACES} />,
|
||||
undefined,
|
||||
{
|
||||
initialRoute: ROUTE_TRACES,
|
||||
@@ -290,10 +273,7 @@ describe('PreferencesProvider integration', () => {
|
||||
});
|
||||
|
||||
render(
|
||||
<Consumer
|
||||
sourcePage={SavedviewtypesSourceDTO.traces}
|
||||
testIdPrefix={TESTID_TRACES}
|
||||
/>,
|
||||
<Consumer dataSource={DataSource.TRACES} testIdPrefix={TESTID_TRACES} />,
|
||||
undefined,
|
||||
{
|
||||
initialRoute: ROUTE_TRACES,
|
||||
@@ -306,10 +286,7 @@ describe('PreferencesProvider integration', () => {
|
||||
it('direct mode updateColumns persists to localStorage', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
render(
|
||||
<Consumer
|
||||
sourcePage={SavedviewtypesSourceDTO.traces}
|
||||
testIdPrefix={TESTID_TRACES}
|
||||
/>,
|
||||
<Consumer dataSource={DataSource.TRACES} testIdPrefix={TESTID_TRACES} />,
|
||||
undefined,
|
||||
{
|
||||
initialRoute: ROUTE_TRACES,
|
||||
@@ -332,10 +309,7 @@ describe('PreferencesProvider integration', () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
|
||||
render(
|
||||
<Consumer
|
||||
sourcePage={SavedviewtypesSourceDTO.traces}
|
||||
testIdPrefix="traces"
|
||||
/>,
|
||||
<Consumer dataSource={DataSource.TRACES} testIdPrefix="traces" />,
|
||||
undefined,
|
||||
{
|
||||
initialRoute: initialEntry,
|
||||
@@ -364,10 +338,7 @@ describe('PreferencesProvider integration', () => {
|
||||
});
|
||||
|
||||
render(
|
||||
<Consumer
|
||||
sourcePage={SavedviewtypesSourceDTO.traces}
|
||||
testIdPrefix={TESTID_TRACES}
|
||||
/>,
|
||||
<Consumer dataSource={DataSource.TRACES} testIdPrefix={TESTID_TRACES} />,
|
||||
undefined,
|
||||
{ initialRoute: ROUTE_TRACES },
|
||||
);
|
||||
@@ -384,7 +355,7 @@ describe('PreferencesProvider integration', () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
|
||||
function TracesFormattingConsumer(): JSX.Element {
|
||||
const traces = usePreferenceContext()[SavedviewtypesSourceDTO.traces];
|
||||
const { traces } = usePreferenceContext();
|
||||
return (
|
||||
<button
|
||||
data-testid="traces-update-formatting"
|
||||
@@ -419,10 +390,7 @@ describe('PreferencesProvider integration', () => {
|
||||
const initialEntry = `/traces?viewKey=${encodeURIComponent(viewKey)}`;
|
||||
|
||||
render(
|
||||
<Consumer
|
||||
sourcePage={SavedviewtypesSourceDTO.traces}
|
||||
testIdPrefix={TESTID_TRACES}
|
||||
/>,
|
||||
<Consumer dataSource={DataSource.TRACES} testIdPrefix={TESTID_TRACES} />,
|
||||
undefined,
|
||||
{ initialRoute: initialEntry },
|
||||
);
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
import { Dispatch, SetStateAction } from 'react';
|
||||
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { renderHook, waitFor } from '@testing-library/react';
|
||||
import { defaultLogsSelectedColumns } from 'container/OptionsMenu/constants';
|
||||
import { FontSize } from 'container/OptionsMenu/types';
|
||||
import { renderHook, waitFor } from 'tests/test-utils';
|
||||
import { BaseAutocompleteData } from 'types/api/queryBuilder/queryAutocompleteResponse';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import logsLoaderConfig from '../configs/logsLoaderConfig';
|
||||
import { usePreferenceLoader } from '../loader/usePreferenceLoader';
|
||||
@@ -45,18 +42,15 @@ jest.mock('../configs/tracesLoaderConfig', () => ({
|
||||
}));
|
||||
|
||||
describe('usePreferenceLoader', () => {
|
||||
const setReSync = jest.fn() as jest.MockedFunction<
|
||||
Dispatch<SetStateAction<boolean>>
|
||||
>;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
it('should load logs preferences based on priority order', async () => {
|
||||
const setReSync = jest.fn();
|
||||
const { result } = renderHook(() =>
|
||||
usePreferenceLoader({
|
||||
sourcePage: SavedviewtypesSourceDTO.logs,
|
||||
dataSource: DataSource.LOGS,
|
||||
reSync: false,
|
||||
setReSync,
|
||||
}),
|
||||
@@ -77,9 +71,10 @@ describe('usePreferenceLoader', () => {
|
||||
});
|
||||
|
||||
it('should load traces preferences', async () => {
|
||||
const setReSync = jest.fn();
|
||||
const { result } = renderHook(() =>
|
||||
usePreferenceLoader({
|
||||
sourcePage: SavedviewtypesSourceDTO.traces,
|
||||
dataSource: DataSource.TRACES,
|
||||
reSync: false,
|
||||
setReSync,
|
||||
}),
|
||||
@@ -98,11 +93,13 @@ describe('usePreferenceLoader', () => {
|
||||
});
|
||||
|
||||
it('should call setReSync when reSync is true', async () => {
|
||||
const setReSync = jest.fn();
|
||||
|
||||
// Test that the hook calls setReSync(false) when reSync is true
|
||||
// We'll unmount quickly to avoid the infinite loop
|
||||
const { unmount } = renderHook(() =>
|
||||
usePreferenceLoader({
|
||||
sourcePage: SavedviewtypesSourceDTO.logs,
|
||||
dataSource: DataSource.LOGS,
|
||||
reSync: true,
|
||||
setReSync,
|
||||
}),
|
||||
@@ -121,25 +118,19 @@ describe('usePreferenceLoader', () => {
|
||||
|
||||
it('should handle errors during loading', async () => {
|
||||
// Make first call succeed (initial state), second call throw in reSync effect
|
||||
const localSpy = jest.spyOn(logsLoaderConfig, 'local');
|
||||
// The loader reads stored columns by name, though `local()` types them as
|
||||
// the older key-based shape.
|
||||
const localSpy: jest.SpyInstance = jest.spyOn(logsLoaderConfig, 'local');
|
||||
localSpy.mockImplementationOnce(() => ({
|
||||
columns: [{ name: 'local-column' }] as unknown as BaseAutocompleteData[],
|
||||
formatting: {
|
||||
maxLines: 5,
|
||||
format: 'table',
|
||||
fontSize: FontSize.MEDIUM,
|
||||
version: 1,
|
||||
},
|
||||
columns: [{ name: 'local-column' }],
|
||||
formatting: { maxLines: 5, format: 'table', fontSize: 'medium', version: 1 },
|
||||
}));
|
||||
localSpy.mockImplementationOnce(() => {
|
||||
throw new Error('Loading failed');
|
||||
});
|
||||
|
||||
const setReSync = jest.fn();
|
||||
const { result } = renderHook(() =>
|
||||
usePreferenceLoader({
|
||||
sourcePage: SavedviewtypesSourceDTO.logs,
|
||||
dataSource: DataSource.LOGS,
|
||||
reSync: true,
|
||||
setReSync,
|
||||
}),
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { renderHook } from '@testing-library/react';
|
||||
import { useGetSavedView } from 'api/generated/services/saved-view';
|
||||
import {
|
||||
SavedviewtypesSavedViewDTO,
|
||||
@@ -8,21 +9,32 @@ import {
|
||||
defaultTraceSelectedColumns,
|
||||
ensureLogsRequiredColumns,
|
||||
} from 'container/OptionsMenu/constants';
|
||||
import { renderHook } from 'tests/test-utils';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import { usePreferenceLoader } from '../loader/usePreferenceLoader';
|
||||
import { usePreferenceSync } from '../sync/usePreferenceSync';
|
||||
import { PreferenceMode, Preferences } from '../types';
|
||||
import { usePreferenceUpdater } from '../updater/usePreferenceUpdater';
|
||||
import { PreferenceMode } from '../types';
|
||||
|
||||
jest.mock('api/generated/services/saved-view');
|
||||
|
||||
jest.mock('../loader/usePreferenceLoader');
|
||||
jest.mock('../updater/usePreferenceUpdater');
|
||||
const loaderPreferences = { columns: [{ name: 'from-loader' }] };
|
||||
jest.mock('../loader/usePreferenceLoader', () => ({
|
||||
usePreferenceLoader: jest.fn(() => ({
|
||||
preferences: loaderPreferences,
|
||||
loading: false,
|
||||
error: null,
|
||||
})),
|
||||
}));
|
||||
|
||||
const loaderPreferences: Preferences = { columns: [{ name: 'from-loader' }] };
|
||||
jest.mock('../updater/usePreferenceUpdater', () => ({
|
||||
usePreferenceUpdater: jest.fn(() => ({
|
||||
updateColumns: jest.fn(),
|
||||
updateFormatting: jest.fn(),
|
||||
})),
|
||||
}));
|
||||
|
||||
const mockedUseGetSavedView = jest.mocked(useGetSavedView);
|
||||
const mockedUseGetSavedView = useGetSavedView as jest.MockedFunction<
|
||||
typeof useGetSavedView
|
||||
>;
|
||||
|
||||
function makeView(
|
||||
id: string,
|
||||
@@ -64,19 +76,6 @@ function mockViews(views: SavedviewtypesSavedViewDTO[]): void {
|
||||
describe('usePreferenceSync in saved view mode', () => {
|
||||
beforeEach(() => {
|
||||
mockedUseGetSavedView.mockReset();
|
||||
jest.mocked(usePreferenceLoader).mockReturnValue({
|
||||
preferences: loaderPreferences,
|
||||
loading: false,
|
||||
error: null,
|
||||
});
|
||||
jest.mocked(usePreferenceUpdater).mockReturnValue({
|
||||
updateColumns: jest.fn() as jest.MockedFunction<
|
||||
ReturnType<typeof usePreferenceUpdater>['updateColumns']
|
||||
>,
|
||||
updateFormatting: jest.fn() as jest.MockedFunction<
|
||||
ReturnType<typeof usePreferenceUpdater>['updateFormatting']
|
||||
>,
|
||||
});
|
||||
});
|
||||
|
||||
it('fetches the view only in saved view mode with a view id', () => {
|
||||
@@ -85,7 +84,7 @@ describe('usePreferenceSync in saved view mode', () => {
|
||||
renderHook(() =>
|
||||
usePreferenceSync({
|
||||
mode: PreferenceMode.DIRECT,
|
||||
sourcePage: SavedviewtypesSourceDTO.logs,
|
||||
dataSource: DataSource.LOGS,
|
||||
savedViewId: undefined,
|
||||
}),
|
||||
);
|
||||
@@ -102,7 +101,7 @@ describe('usePreferenceSync in saved view mode', () => {
|
||||
const { result } = renderHook(() =>
|
||||
usePreferenceSync({
|
||||
mode: PreferenceMode.DIRECT,
|
||||
sourcePage: SavedviewtypesSourceDTO.logs,
|
||||
dataSource: DataSource.LOGS,
|
||||
savedViewId: undefined,
|
||||
}),
|
||||
);
|
||||
@@ -121,7 +120,7 @@ describe('usePreferenceSync in saved view mode', () => {
|
||||
const { result } = renderHook(() =>
|
||||
usePreferenceSync({
|
||||
mode: PreferenceMode.SAVED_VIEW,
|
||||
sourcePage: SavedviewtypesSourceDTO.logs,
|
||||
dataSource: DataSource.LOGS,
|
||||
savedViewId: 'view-1',
|
||||
}),
|
||||
);
|
||||
@@ -148,7 +147,7 @@ describe('usePreferenceSync in saved view mode', () => {
|
||||
const { result } = renderHook(() =>
|
||||
usePreferenceSync({
|
||||
mode: PreferenceMode.SAVED_VIEW,
|
||||
sourcePage: SavedviewtypesSourceDTO.logs,
|
||||
dataSource: DataSource.LOGS,
|
||||
savedViewId: 'view-1',
|
||||
}),
|
||||
);
|
||||
@@ -175,14 +174,14 @@ describe('usePreferenceSync in saved view mode', () => {
|
||||
const withFields = renderHook(() =>
|
||||
usePreferenceSync({
|
||||
mode: PreferenceMode.SAVED_VIEW,
|
||||
sourcePage: SavedviewtypesSourceDTO.traces,
|
||||
dataSource: DataSource.TRACES,
|
||||
savedViewId: 'with-fields',
|
||||
}),
|
||||
);
|
||||
const withoutFields = renderHook(() =>
|
||||
usePreferenceSync({
|
||||
mode: PreferenceMode.SAVED_VIEW,
|
||||
sourcePage: SavedviewtypesSourceDTO.traces,
|
||||
dataSource: DataSource.TRACES,
|
||||
savedViewId: 'without-fields',
|
||||
}),
|
||||
);
|
||||
@@ -203,7 +202,7 @@ describe('usePreferenceSync in saved view mode', () => {
|
||||
const { result } = renderHook(() =>
|
||||
usePreferenceSync({
|
||||
mode: PreferenceMode.SAVED_VIEW,
|
||||
sourcePage: SavedviewtypesSourceDTO.logs,
|
||||
dataSource: DataSource.LOGS,
|
||||
savedViewId: 'missing',
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -1,39 +1,45 @@
|
||||
import { Dispatch, SetStateAction } from 'react';
|
||||
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { act } from 'react-dom/test-utils';
|
||||
import { renderHook } from '@testing-library/react';
|
||||
import { TelemetryFieldKey } from 'api/v5/v5';
|
||||
import { LogViewMode, FontSize } from 'container/OptionsMenu/types';
|
||||
import useUrlQueryData from 'hooks/useUrlQueryData';
|
||||
import { LogViewMode } from 'container/OptionsMenu/types';
|
||||
import { FontSize } from 'container/OptionsMenu/types';
|
||||
import {
|
||||
FormattingOptions,
|
||||
PreferenceMode,
|
||||
Preferences,
|
||||
} from 'providers/preferences/types';
|
||||
import { act, renderHook } from 'tests/test-utils';
|
||||
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import getLogsUpdaterConfig from '../configs/logsUpdaterConfig';
|
||||
import getTracesUpdaterConfig from '../configs/tracesUpdaterConfig';
|
||||
import { usePreferenceUpdater } from '../updater/usePreferenceUpdater';
|
||||
|
||||
jest.mock('../configs/logsUpdaterConfig');
|
||||
jest.mock('../configs/tracesUpdaterConfig');
|
||||
jest.mock('hooks/useUrlQueryData');
|
||||
// Mock the config updaters
|
||||
const mockUpdateColumns = jest.fn();
|
||||
const mockUpdateFormatting = jest.fn();
|
||||
|
||||
type LogsUpdater = ReturnType<typeof getLogsUpdaterConfig>;
|
||||
type TracesUpdater = ReturnType<typeof getTracesUpdaterConfig>;
|
||||
jest.mock('../configs/logsUpdaterConfig', () => ({
|
||||
__esModule: true,
|
||||
default: jest.fn().mockImplementation(() => ({
|
||||
updateColumns: mockUpdateColumns,
|
||||
updateFormatting: mockUpdateFormatting,
|
||||
})),
|
||||
}));
|
||||
|
||||
const mockLogsUpdateColumns = jest.fn() as jest.MockedFunction<
|
||||
LogsUpdater['updateColumns']
|
||||
>;
|
||||
const mockLogsUpdateFormatting = jest.fn() as jest.MockedFunction<
|
||||
LogsUpdater['updateFormatting']
|
||||
>;
|
||||
const mockTracesUpdateColumns = jest.fn() as jest.MockedFunction<
|
||||
TracesUpdater['updateColumns']
|
||||
>;
|
||||
const mockTracesUpdateFormatting = jest.fn() as jest.MockedFunction<
|
||||
TracesUpdater['updateFormatting']
|
||||
>;
|
||||
jest.mock('../configs/tracesUpdaterConfig', () => ({
|
||||
__esModule: true,
|
||||
default: jest.fn().mockImplementation(() => ({
|
||||
updateColumns: mockUpdateColumns,
|
||||
updateFormatting: mockUpdateFormatting,
|
||||
})),
|
||||
}));
|
||||
|
||||
// Mock the URL query hook
|
||||
jest.mock('hooks/useUrlQueryData', () => ({
|
||||
__esModule: true,
|
||||
default: jest.fn().mockReturnValue({
|
||||
redirectWithQuery: jest.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
describe('usePreferenceUpdater', () => {
|
||||
const mockPreferences: Preferences = {
|
||||
@@ -45,36 +51,18 @@ describe('usePreferenceUpdater', () => {
|
||||
version: 1,
|
||||
},
|
||||
};
|
||||
const setReSync = jest.fn() as jest.MockedFunction<
|
||||
Dispatch<SetStateAction<boolean>>
|
||||
>;
|
||||
const setSavedViewPreferences = jest.fn() as jest.MockedFunction<
|
||||
Dispatch<SetStateAction<Preferences | null>>
|
||||
>;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
jest.mocked(getLogsUpdaterConfig).mockReturnValue({
|
||||
updateColumns: mockLogsUpdateColumns,
|
||||
updateFormatting: mockLogsUpdateFormatting,
|
||||
});
|
||||
jest.mocked(getTracesUpdaterConfig).mockReturnValue({
|
||||
updateColumns: mockTracesUpdateColumns,
|
||||
updateFormatting: mockTracesUpdateFormatting,
|
||||
});
|
||||
jest.mocked(useUrlQueryData).mockReturnValue({
|
||||
query: null,
|
||||
queryData: undefined,
|
||||
redirectWithQuery: jest.fn() as jest.MockedFunction<
|
||||
(newQueryData: unknown) => void
|
||||
>,
|
||||
});
|
||||
});
|
||||
|
||||
it('should return updateColumns and updateFormatting functions', () => {
|
||||
const setReSync = jest.fn();
|
||||
const setSavedViewPreferences = jest.fn();
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
usePreferenceUpdater({
|
||||
sourcePage: SavedviewtypesSourceDTO.logs,
|
||||
dataSource: DataSource.LOGS,
|
||||
mode: PreferenceMode.DIRECT,
|
||||
preferences: mockPreferences,
|
||||
setReSync,
|
||||
@@ -87,7 +75,9 @@ describe('usePreferenceUpdater', () => {
|
||||
expect(typeof result.current.updateFormatting).toBe('function');
|
||||
});
|
||||
|
||||
it('should call the logs updater for updateColumns with the logs list key', () => {
|
||||
it('should call the logs updater for updateColumns with logs dataSource', () => {
|
||||
const setReSync = jest.fn();
|
||||
const setSavedViewPreferences = jest.fn();
|
||||
const newColumns: TelemetryFieldKey[] = [
|
||||
{
|
||||
name: 'new-column',
|
||||
@@ -98,7 +88,7 @@ describe('usePreferenceUpdater', () => {
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
usePreferenceUpdater({
|
||||
sourcePage: SavedviewtypesSourceDTO.logs,
|
||||
dataSource: DataSource.LOGS,
|
||||
mode: PreferenceMode.DIRECT,
|
||||
preferences: mockPreferences,
|
||||
setReSync,
|
||||
@@ -111,15 +101,16 @@ describe('usePreferenceUpdater', () => {
|
||||
});
|
||||
|
||||
// Should call the logs updater
|
||||
expect(mockLogsUpdateColumns).toHaveBeenCalledWith(
|
||||
expect(mockUpdateColumns).toHaveBeenCalledWith(
|
||||
newColumns,
|
||||
PreferenceMode.DIRECT,
|
||||
);
|
||||
expect(mockTracesUpdateColumns).not.toHaveBeenCalled();
|
||||
expect(setReSync).toHaveBeenCalledWith(true);
|
||||
});
|
||||
|
||||
it('should call the logs updater for updateFormatting with the logs list key', () => {
|
||||
it('should call the logs updater for updateFormatting with logs dataSource', () => {
|
||||
const setReSync = jest.fn();
|
||||
const setSavedViewPreferences = jest.fn();
|
||||
const newFormatting: FormattingOptions = {
|
||||
maxLines: 10,
|
||||
format: 'table' as LogViewMode,
|
||||
@@ -129,7 +120,7 @@ describe('usePreferenceUpdater', () => {
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
usePreferenceUpdater({
|
||||
sourcePage: SavedviewtypesSourceDTO.logs,
|
||||
dataSource: DataSource.LOGS,
|
||||
mode: PreferenceMode.DIRECT,
|
||||
preferences: mockPreferences,
|
||||
setReSync,
|
||||
@@ -142,15 +133,16 @@ describe('usePreferenceUpdater', () => {
|
||||
});
|
||||
|
||||
// Should call the logs updater
|
||||
expect(mockLogsUpdateFormatting).toHaveBeenCalledWith(
|
||||
expect(mockUpdateFormatting).toHaveBeenCalledWith(
|
||||
newFormatting,
|
||||
PreferenceMode.DIRECT,
|
||||
);
|
||||
expect(mockTracesUpdateFormatting).not.toHaveBeenCalled();
|
||||
expect(setReSync).toHaveBeenCalledWith(true);
|
||||
});
|
||||
|
||||
it('should call the traces updater for updateColumns with the traces list key', () => {
|
||||
it('should call the traces updater for updateColumns with traces dataSource', () => {
|
||||
const setReSync = jest.fn();
|
||||
const setSavedViewPreferences = jest.fn();
|
||||
const newColumns: TelemetryFieldKey[] = [
|
||||
{
|
||||
name: 'new-trace-column',
|
||||
@@ -161,7 +153,7 @@ describe('usePreferenceUpdater', () => {
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
usePreferenceUpdater({
|
||||
sourcePage: SavedviewtypesSourceDTO.traces,
|
||||
dataSource: DataSource.TRACES,
|
||||
mode: PreferenceMode.DIRECT,
|
||||
preferences: mockPreferences,
|
||||
setReSync,
|
||||
@@ -174,15 +166,16 @@ describe('usePreferenceUpdater', () => {
|
||||
});
|
||||
|
||||
// Should call the traces updater
|
||||
expect(mockTracesUpdateColumns).toHaveBeenCalledWith(
|
||||
expect(mockUpdateColumns).toHaveBeenCalledWith(
|
||||
newColumns,
|
||||
PreferenceMode.DIRECT,
|
||||
);
|
||||
expect(mockLogsUpdateColumns).not.toHaveBeenCalled();
|
||||
expect(setReSync).toHaveBeenCalledWith(true);
|
||||
});
|
||||
|
||||
it('should call the traces updater for updateFormatting with the traces list key', () => {
|
||||
it('should call the traces updater for updateFormatting with traces dataSource', () => {
|
||||
const setReSync = jest.fn();
|
||||
const setSavedViewPreferences = jest.fn();
|
||||
const newFormatting: FormattingOptions = {
|
||||
maxLines: 10,
|
||||
format: 'table' as LogViewMode,
|
||||
@@ -192,7 +185,7 @@ describe('usePreferenceUpdater', () => {
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
usePreferenceUpdater({
|
||||
sourcePage: SavedviewtypesSourceDTO.traces,
|
||||
dataSource: DataSource.TRACES,
|
||||
mode: PreferenceMode.DIRECT,
|
||||
preferences: mockPreferences,
|
||||
setReSync,
|
||||
@@ -205,18 +198,20 @@ describe('usePreferenceUpdater', () => {
|
||||
});
|
||||
|
||||
// Should call the traces updater
|
||||
expect(mockTracesUpdateFormatting).toHaveBeenCalledWith(
|
||||
expect(mockUpdateFormatting).toHaveBeenCalledWith(
|
||||
newFormatting,
|
||||
PreferenceMode.DIRECT,
|
||||
);
|
||||
expect(mockLogsUpdateFormatting).not.toHaveBeenCalled();
|
||||
expect(setReSync).toHaveBeenCalledWith(true);
|
||||
});
|
||||
|
||||
it('should increment reSync counter when updates are called', () => {
|
||||
const setReSync = jest.fn();
|
||||
const setSavedViewPreferences = jest.fn();
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
usePreferenceUpdater({
|
||||
sourcePage: SavedviewtypesSourceDTO.logs,
|
||||
dataSource: DataSource.LOGS,
|
||||
mode: PreferenceMode.DIRECT,
|
||||
preferences: mockPreferences,
|
||||
setReSync,
|
||||
|
||||
@@ -1,20 +0,0 @@
|
||||
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
|
||||
import { isPreferenceSourcePage } from '../utils';
|
||||
|
||||
describe('isPreferenceSourcePage', () => {
|
||||
it.each([SavedviewtypesSourceDTO.logs, SavedviewtypesSourceDTO.traces])(
|
||||
'is true for %s',
|
||||
(source) => {
|
||||
expect(isPreferenceSourcePage(source)).toBe(true);
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
SavedviewtypesSourceDTO.metrics,
|
||||
SavedviewtypesSourceDTO.meter,
|
||||
SavedviewtypesSourceDTO.ai_observability,
|
||||
])('is false for %s', (source) => {
|
||||
expect(isPreferenceSourcePage(source)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,7 +0,0 @@
|
||||
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
|
||||
// Only the logs and traces explorers keep column and formatting preferences.
|
||||
export const PREFERENCE_SOURCE_PAGES = [
|
||||
SavedviewtypesSourceDTO.logs,
|
||||
SavedviewtypesSourceDTO.traces,
|
||||
] as const;
|
||||
@@ -5,12 +5,12 @@ import React, {
|
||||
useContext,
|
||||
useMemo,
|
||||
} from 'react';
|
||||
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import useUrlQuery from 'hooks/useUrlQuery';
|
||||
import {
|
||||
PreferenceContextValue,
|
||||
PreferenceMode,
|
||||
} from 'providers/preferences/types';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import { usePreferenceSync } from '../sync/usePreferenceSync';
|
||||
|
||||
@@ -38,19 +38,19 @@ export function PreferenceContextProvider({
|
||||
const logsSlice = usePreferenceSync({
|
||||
mode: savedViewId ? PreferenceMode.SAVED_VIEW : PreferenceMode.DIRECT,
|
||||
savedViewId: savedViewId || undefined,
|
||||
sourcePage: SavedviewtypesSourceDTO.logs,
|
||||
dataSource: DataSource.LOGS,
|
||||
});
|
||||
|
||||
const tracesSlice = usePreferenceSync({
|
||||
mode: savedViewId ? PreferenceMode.SAVED_VIEW : PreferenceMode.DIRECT,
|
||||
savedViewId: savedViewId || undefined,
|
||||
sourcePage: SavedviewtypesSourceDTO.traces,
|
||||
dataSource: DataSource.TRACES,
|
||||
});
|
||||
|
||||
const value = useMemo<PreferenceContextValue>(
|
||||
() => ({
|
||||
[SavedviewtypesSourceDTO.logs]: logsSlice,
|
||||
[SavedviewtypesSourceDTO.traces]: tracesSlice,
|
||||
logs: logsSlice,
|
||||
traces: tracesSlice,
|
||||
}),
|
||||
[logsSlice, tracesSlice],
|
||||
);
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
|
||||
import { PreferenceSlice } from '../types';
|
||||
import { isPreferenceSourcePage } from '../utils';
|
||||
import { usePreferenceContext } from './PreferenceContextProvider';
|
||||
|
||||
export function usePreferenceSlice(
|
||||
sourcePage: SavedviewtypesSourceDTO,
|
||||
): PreferenceSlice | undefined {
|
||||
const context = usePreferenceContext();
|
||||
return isPreferenceSourcePage(sourcePage) ? context[sourcePage] : undefined;
|
||||
}
|
||||
@@ -1,12 +1,12 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { TelemetryFieldKey } from 'api/v5/v5';
|
||||
import { ensureLogsRequiredColumns } from 'container/OptionsMenu/constants';
|
||||
import { has } from 'lodash-es';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import logsLoaderConfig from '../configs/logsLoaderConfig';
|
||||
import tracesLoaderConfig from '../configs/tracesLoaderConfig';
|
||||
import { FormattingOptions, Preferences, PreferenceSourcePage } from '../types';
|
||||
import { FormattingOptions, Preferences } from '../types';
|
||||
|
||||
const migrateColumns = (columns: any): any =>
|
||||
columns.map((column: any) => {
|
||||
@@ -62,21 +62,15 @@ function logsPreferencesLoader(): {
|
||||
function tracesPreferencesLoader(): {
|
||||
columns: TelemetryFieldKey[];
|
||||
} {
|
||||
const { columns } = preferencesLoader<Preferences>(tracesLoaderConfig);
|
||||
return { columns };
|
||||
return preferencesLoader(tracesLoaderConfig);
|
||||
}
|
||||
|
||||
const PREFERENCE_LOADERS: Record<PreferenceSourcePage, () => Preferences> = {
|
||||
[SavedviewtypesSourceDTO.logs]: logsPreferencesLoader,
|
||||
[SavedviewtypesSourceDTO.traces]: tracesPreferencesLoader,
|
||||
};
|
||||
|
||||
export function usePreferenceLoader({
|
||||
sourcePage,
|
||||
dataSource,
|
||||
reSync,
|
||||
setReSync,
|
||||
}: {
|
||||
sourcePage: PreferenceSourcePage;
|
||||
dataSource: DataSource;
|
||||
reSync: boolean;
|
||||
setReSync: (value: boolean) => void;
|
||||
}): {
|
||||
@@ -84,10 +78,17 @@ export function usePreferenceLoader({
|
||||
loading: boolean;
|
||||
error: Error | null;
|
||||
} {
|
||||
const loadSlicePreferences = PREFERENCE_LOADERS[sourcePage];
|
||||
const [preferences, setPreferences] = useState<Preferences | null>(
|
||||
loadSlicePreferences,
|
||||
);
|
||||
const [preferences, setPreferences] = useState<Preferences | null>(() => {
|
||||
if (dataSource === DataSource.LOGS) {
|
||||
const { columns, formatting } = logsPreferencesLoader();
|
||||
return { columns, formatting };
|
||||
}
|
||||
if (dataSource === DataSource.TRACES) {
|
||||
const { columns } = tracesPreferencesLoader();
|
||||
return { columns };
|
||||
}
|
||||
return null;
|
||||
});
|
||||
const [error, setError] = useState<Error | null>(null);
|
||||
|
||||
useEffect((): void => {
|
||||
@@ -95,7 +96,15 @@ export function usePreferenceLoader({
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
setPreferences(loadSlicePreferences());
|
||||
if (dataSource === DataSource.LOGS) {
|
||||
const { columns, formatting } = logsPreferencesLoader();
|
||||
setPreferences({ columns, formatting });
|
||||
}
|
||||
|
||||
if (dataSource === DataSource.TRACES) {
|
||||
const { columns } = tracesPreferencesLoader();
|
||||
setPreferences({ columns });
|
||||
}
|
||||
} catch (e) {
|
||||
setError(e as Error);
|
||||
} finally {
|
||||
@@ -110,7 +119,7 @@ export function usePreferenceLoader({
|
||||
if (reSync) {
|
||||
loadPreferences();
|
||||
}
|
||||
}, [loadSlicePreferences, reSync, setReSync]);
|
||||
}, [dataSource, reSync, setReSync]);
|
||||
|
||||
return { preferences, loading: false, error };
|
||||
}
|
||||
|
||||
@@ -3,23 +3,19 @@ import { useEffect, useRef, useState } from 'react';
|
||||
import { useGetSavedView } from 'api/generated/services/saved-view';
|
||||
import { TelemetryFieldKey } from 'api/v5/v5';
|
||||
import { getViewColumnsAndFormatting } from 'container/SavedViews/utils/getViewColumnsAndFormatting';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import { usePreferenceLoader } from '../loader/usePreferenceLoader';
|
||||
import {
|
||||
FormattingOptions,
|
||||
PreferenceMode,
|
||||
Preferences,
|
||||
PreferenceSourcePage,
|
||||
} from '../types';
|
||||
import { FormattingOptions, PreferenceMode, Preferences } from '../types';
|
||||
import { usePreferenceUpdater } from '../updater/usePreferenceUpdater';
|
||||
|
||||
export function usePreferenceSync({
|
||||
mode,
|
||||
sourcePage,
|
||||
dataSource,
|
||||
savedViewId,
|
||||
}: {
|
||||
mode: PreferenceMode;
|
||||
sourcePage: PreferenceSourcePage;
|
||||
dataSource: DataSource;
|
||||
savedViewId: string | undefined;
|
||||
}): {
|
||||
preferences: Preferences | null;
|
||||
@@ -45,25 +41,25 @@ export function usePreferenceSync({
|
||||
if (view && view.id === savedViewId) {
|
||||
if (seededViewId.current !== savedViewId) {
|
||||
seededViewId.current = savedViewId;
|
||||
setSavedViewPreferences(getViewColumnsAndFormatting(view.spec, sourcePage));
|
||||
setSavedViewPreferences(getViewColumnsAndFormatting(view.spec, dataSource));
|
||||
}
|
||||
return;
|
||||
}
|
||||
seededViewId.current = undefined;
|
||||
setSavedViewPreferences(getViewColumnsAndFormatting(undefined, sourcePage));
|
||||
}, [viewData, sourcePage, savedViewId]);
|
||||
setSavedViewPreferences(getViewColumnsAndFormatting(undefined, dataSource));
|
||||
}, [viewData, dataSource, savedViewId]);
|
||||
|
||||
// We are using a reSync state because we have URL updates as well as local storage updates
|
||||
// and we want to make sure we are always using the latest preferences
|
||||
const [reSync, setReSync] = useState(false);
|
||||
const { preferences, loading, error } = usePreferenceLoader({
|
||||
sourcePage,
|
||||
dataSource,
|
||||
reSync,
|
||||
setReSync,
|
||||
});
|
||||
|
||||
const { updateColumns, updateFormatting } = usePreferenceUpdater({
|
||||
sourcePage,
|
||||
dataSource,
|
||||
mode,
|
||||
preferences,
|
||||
setReSync,
|
||||
|
||||
@@ -1,15 +1,12 @@
|
||||
import { TelemetryFieldKey } from 'api/v5/v5';
|
||||
import { LogViewMode, FontSize } from 'container/OptionsMenu/types';
|
||||
|
||||
import { PREFERENCE_SOURCE_PAGES } from '../constants';
|
||||
import { LogViewMode } from 'container/OptionsMenu/types';
|
||||
import { FontSize } from 'container/OptionsMenu/types';
|
||||
|
||||
export enum PreferenceMode {
|
||||
SAVED_VIEW = 'savedView',
|
||||
DIRECT = 'direct',
|
||||
}
|
||||
|
||||
export type PreferenceSourcePage = (typeof PREFERENCE_SOURCE_PAGES)[number];
|
||||
|
||||
export interface PreferenceSlice {
|
||||
preferences: Preferences | null;
|
||||
loading: boolean;
|
||||
@@ -18,10 +15,10 @@ export interface PreferenceSlice {
|
||||
updateFormatting: (newFormatting: FormattingOptions) => void;
|
||||
}
|
||||
|
||||
export type PreferenceContextValue = Record<
|
||||
PreferenceSourcePage,
|
||||
PreferenceSlice
|
||||
>;
|
||||
export interface PreferenceContextValue {
|
||||
logs: PreferenceSlice;
|
||||
traces: PreferenceSlice;
|
||||
}
|
||||
|
||||
export interface FormattingOptions {
|
||||
maxLines?: number;
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { Dispatch, SetStateAction } from 'react';
|
||||
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { TelemetryFieldKey } from 'api/v5/v5';
|
||||
import {
|
||||
defaultOptionsQuery,
|
||||
@@ -7,41 +6,48 @@ import {
|
||||
} from 'container/OptionsMenu/constants';
|
||||
import { OptionsQuery } from 'container/OptionsMenu/types';
|
||||
import useUrlQueryData from 'hooks/useUrlQueryData';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import getLogsUpdaterConfig from '../configs/logsUpdaterConfig';
|
||||
import getTracesUpdaterConfig from '../configs/tracesUpdaterConfig';
|
||||
import { FormattingOptions, Preferences, PreferenceSourcePage } from '../types';
|
||||
import { FormattingOptions, Preferences } from '../types';
|
||||
|
||||
const metricsUpdater = {
|
||||
updateColumns: (): void => {}, // no-op for metrics
|
||||
updateFormatting: (): void => {}, // no-op for metrics
|
||||
};
|
||||
|
||||
const getUpdaterConfig = (
|
||||
preferences: Preferences | null,
|
||||
redirectWithOptionsData: (options: OptionsQuery) => void,
|
||||
setSavedViewPreferences: Dispatch<SetStateAction<Preferences | null>>,
|
||||
): Record<
|
||||
PreferenceSourcePage,
|
||||
DataSource,
|
||||
{
|
||||
updateColumns: (newColumns: TelemetryFieldKey[], mode: string) => void;
|
||||
updateFormatting: (newFormatting: FormattingOptions, mode: string) => void;
|
||||
}
|
||||
> => ({
|
||||
[SavedviewtypesSourceDTO.logs]: getLogsUpdaterConfig(
|
||||
[DataSource.LOGS]: getLogsUpdaterConfig(
|
||||
preferences,
|
||||
redirectWithOptionsData,
|
||||
setSavedViewPreferences,
|
||||
),
|
||||
[SavedviewtypesSourceDTO.traces]: getTracesUpdaterConfig(
|
||||
[DataSource.TRACES]: getTracesUpdaterConfig(
|
||||
redirectWithOptionsData,
|
||||
setSavedViewPreferences,
|
||||
),
|
||||
[DataSource.METRICS]: metricsUpdater,
|
||||
});
|
||||
|
||||
export function usePreferenceUpdater({
|
||||
sourcePage,
|
||||
dataSource,
|
||||
mode,
|
||||
preferences,
|
||||
setReSync,
|
||||
setSavedViewPreferences,
|
||||
}: {
|
||||
sourcePage: PreferenceSourcePage;
|
||||
dataSource: DataSource;
|
||||
mode: string;
|
||||
preferences: Preferences | null;
|
||||
setReSync: Dispatch<SetStateAction<boolean>>;
|
||||
@@ -56,7 +62,7 @@ export function usePreferenceUpdater({
|
||||
preferences,
|
||||
redirectWithOptionsData,
|
||||
setSavedViewPreferences,
|
||||
)[sourcePage];
|
||||
)[dataSource];
|
||||
|
||||
return {
|
||||
updateColumns: (newColumns: TelemetryFieldKey[]): void => {
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
|
||||
import { PREFERENCE_SOURCE_PAGES } from './constants';
|
||||
import { PreferenceSourcePage } from './types';
|
||||
|
||||
export function isPreferenceSourcePage(
|
||||
sourcePage: SavedviewtypesSourceDTO,
|
||||
): sourcePage is PreferenceSourcePage {
|
||||
return (
|
||||
PREFERENCE_SOURCE_PAGES as readonly SavedviewtypesSourceDTO[]
|
||||
).includes(sourcePage);
|
||||
}
|
||||
26
frontend/src/storybook/visual/waitForMonacoText.ts
Normal file
26
frontend/src/storybook/visual/waitForMonacoText.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
import { waitFor } from 'storybook/test';
|
||||
|
||||
/**
|
||||
* Monaco mounts its container before its language loads, so the editor is on
|
||||
* screen while still blank or uncoloured. Waits for text with at least two
|
||||
* token colours, which only exists once the tokenizer has run.
|
||||
*/
|
||||
export const waitForMonacoText = async (
|
||||
canvasElement: HTMLElement,
|
||||
): Promise<void> => {
|
||||
await waitFor(
|
||||
() => {
|
||||
const lines = canvasElement.querySelector('.monaco-editor .view-lines');
|
||||
const tokens = new Set(
|
||||
Array.from(lines?.querySelectorAll('span[class^="mtk"]') ?? []).map(
|
||||
(token) => token.className,
|
||||
),
|
||||
);
|
||||
|
||||
if (!lines?.textContent?.trim() || tokens.size < 2) {
|
||||
throw new Error('Monaco has not rendered its text');
|
||||
}
|
||||
},
|
||||
{ timeout: 15_000 },
|
||||
);
|
||||
};
|
||||
Reference in New Issue
Block a user