Compare commits

...

4 Commits

Author SHA1 Message Date
Vinícius Lourenço
f6e9ebc2f3 test(storybook): wait for the schema error in the unknown relation role story 2026-11-20 23:59:25 -03:00
Vinícius Lourenço
bcc1aa4572 test(storybook): cover the role, dashboard and ClickHouse editors once Monaco renders 2026-11-20 22:16:42 -03:00
Vinícius Lourenço
dc975b6aaa fix(storybook): load Monaco through the lazy loader 2026-11-20 22:16:27 -03:00
Vinícius Lourenço
f20d2f66d0 perf(web): load Monaco on the first editor mount 2026-11-20 21:34:48 -03:00
14 changed files with 302 additions and 8 deletions

View File

@@ -21,7 +21,7 @@ import i18n from '../src/ReactI18';
// `src/index.tsx` does this at boot: without it `@monaco-editor/react` falls back
// to its loader default and pulls Monaco from cdn.jsdelivr.net, which msw does
// not report because the requests look like static assets.
import '../src/lib/monaco/setup';
import '../src/lib/monaco/loader';
import '../src/styles.scss';

View File

@@ -13,7 +13,7 @@ import store from 'store';
import APIError from 'types/api/error';
import { installTranslationResilience } from 'translation-resilience';
import 'lib/monaco/setup';
import 'lib/monaco/loader';
import './ReactI18';

View File

@@ -0,0 +1,21 @@
import { loader } from '@monaco-editor/react';
import '../loader';
const mockMonaco = { editor: {} };
jest.mock('../setup', () => ({ monaco: mockMonaco }));
describe('lazy monaco loader', () => {
it('rejects a canceled init with the cancelation error', async () => {
const init = loader.init();
init.cancel();
await expect(init).rejects.toMatchObject({ type: 'cancelation' });
});
it('resolves with the bundled instance without adding a CDN script', async () => {
await expect(loader.init()).resolves.toBe(mockMonaco);
expect(document.querySelector('script')).toBeNull();
});
});

View File

@@ -0,0 +1,33 @@
import { loader } from '@monaco-editor/react';
type LoaderInit = typeof loader.init;
type CancelableMonaco = ReturnType<LoaderInit>;
const CANCELATION = {
type: 'cancelation',
msg: 'operation is manually canceled',
};
const initLoader: LoaderInit = loader.init;
let monacoLoaded: Promise<void> | undefined;
// monaco-editor is about a third of the entry chunk, so it loads on the first editor
// mount instead of with the app. Every editor goes through @monaco-editor/react, whose
// components call `loader.init()` on mount; handing the loader the bundled instance
// before the original init runs keeps it from fetching Monaco from the CDN.
loader.init = (): CancelableMonaco => {
monacoLoaded ??= import('./setup').then(({ monaco }) =>
loader.config({ monaco }),
);
let canceled = false;
const promise = monacoLoaded.then(() => {
if (canceled) {
throw CANCELATION;
}
return initLoader();
}) as CancelableMonaco;
promise.cancel = (): void => {
canceled = true;
};
return promise;
};

View File

@@ -1,4 +1,3 @@
import { loader } from '@monaco-editor/react';
import * as monaco from 'monaco-editor';
import EditorWorker from 'monaco-editor/esm/vs/editor/editor.worker?worker';
import JsonWorker from 'monaco-editor/esm/vs/language/json/json.worker?worker';
@@ -18,4 +17,4 @@ self.MonacoEnvironment = {
},
};
loader.config({ monaco });
export { monaco };

View File

@@ -13,6 +13,7 @@ import {
openAddColumn,
openAIQueryBuilder,
openClickHouseQuery,
writeClickHouseQuery,
openPanelTypeSwitcher,
openPromQLQuery,
saveAndExpectToast,
@@ -58,6 +59,11 @@ export const ClickHouseQuery: Story = {
play: openClickHouseQuery,
};
/** A ClickHouse query written into the tab's editor, highlighted as SQL. */
export const ClickHouseQueryWritten: Story = {
play: writeClickHouseQuery,
};
/** The PromQL query tab, its query and legend fields empty. */
export const PromQLQuery: Story = {
play: openPromQLQuery,

View File

@@ -6,6 +6,12 @@
import { EQueryType } from 'types/common/dashboard';
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
import {
blurActiveElement,
findMonacoEditor,
setMonacoText,
} from '@/storybook/play/monacoEditor';
import {
hasClickHouseTab,
hasDisconnectValues,
@@ -130,6 +136,31 @@ export const openClickHouseQuery = async ({
await screen.findByText(/ClickHouse query agent skill/i, undefined, {
timeout: 15000,
});
// A new query starts empty, so the editor has no text to wait for.
await findMonacoEditor(document, '');
blurActiveElement();
};
const CLICKHOUSE_SQL = `SELECT
toStartOfInterval(timestamp, INTERVAL 1 MINUTE) AS ts,
serviceName,
count() AS value
FROM signoz_traces.distributed_signoz_index_v3
WHERE timestamp BETWEEN {{.start_datetime}} AND {{.end_datetime}}
GROUP BY ts, serviceName
ORDER BY ts`;
export const writeClickHouseQuery = async (
context: PlayContext,
): Promise<void> => {
if (!hasClickHouseTab(context.args)) {
return;
}
await openClickHouseQuery(context);
await setMonacoText('sql', CLICKHOUSE_SQL);
await findMonacoEditor(document, 'distributed_signoz_index_v3');
blurActiveElement();
};
export const openPromQLQuery = async ({

View File

@@ -25,6 +25,7 @@ import {
import {
expandPanelSearch,
hoverJsonValidation,
showJsonEditor,
openDeleteDashboardDialog,
openAIQueryBuilderViewPanel,
openClickHouseViewPanel,
@@ -570,6 +571,14 @@ export const JsonCopiedToast: Story = {
},
};
/**
* The JSON editor drawer over the dashboard: the stored document, the footer's
* validation and the copy and apply actions.
*/
export const JsonEditor: Story = {
play: showJsonEditor,
};
/**
* The JSON editor on a dashboard stored with `1s`: the footer rejects
* `spec.duration` on its line, and hovering it shows the full message.

View File

@@ -5,6 +5,11 @@
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
import {
blurActiveElement,
findMonacoEditor,
} from '@/storybook/play/monacoEditor';
import { dashboardDurationError } from '../../DashboardContainer/utils/dashboardDuration';
import {
canDeleteDashboard,
@@ -18,6 +23,7 @@ import {
openJsonEditor,
openSettings,
PAGE_LOAD,
showsDashboard,
} from '../DashboardPage.stories.mocks';
import type { PanelId } from './dashboard';
@@ -79,11 +85,25 @@ export const openDefaultTimeRange = async (
await screen.findByRole('listbox');
};
export const showJsonEditor = async ({
canvasElement,
args,
}: DashboardPlayContext): Promise<void> => {
if (!showsDashboard(args)) {
return;
}
await openJsonEditor(canvasElement);
await findMonacoEditor();
blurActiveElement();
};
export const hoverJsonValidation = async ({
canvasElement,
args,
}: DashboardPlayContext): Promise<void> => {
await openJsonEditor(canvasElement);
await findMonacoEditor();
const validation = await screen.findByTestId('json-editor-validation');
if (args.duration === 'unset' || !dashboardDurationError(args.duration)) {

View File

@@ -6,6 +6,7 @@
import { expect, screen, userEvent, within } from 'storybook/test';
import { isCloudShell } from '@/storybook/globals/appShellMocks';
import { findMonacoEditor } from '@/storybook/play/monacoEditor';
import { findToastText } from '@/storybook/play/toastText';
import {
@@ -106,6 +107,7 @@ export const importInvalidJson = async ({
await openNewDashboard(canvasElement);
await userEvent.click(await screen.findByText('Import JSON'));
await findMonacoEditor(document, '');
await userEvent.click(await screen.findByTestId('import-json-submit'));
await screen.findByText(/error loading json/i);
// The error modal and the toast under it carry the same message.

View File

@@ -10,6 +10,7 @@ import { RoleType } from 'types/roles';
import { choiceControl } from '@/storybook/controls/controls';
import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import {
MUTATION_OUTCOMES,
@@ -33,7 +34,7 @@ const EDITORS = ['interactive', 'json'] as const;
type Editor = (typeof EDITORS)[number];
const CUSTOM_ROLE_NAME = 'oncall-responder';
export const CUSTOM_ROLE_NAME = 'oncall-responder';
/**
* Create and edit are the same page on two routes: `roles/new` reads as create,
@@ -101,6 +102,8 @@ export const roleEditorMocks = defineStoryMocks({
config: (values) => ({ route: routeFor(values.mode, values.editor) }),
});
export type RoleEditorArgs = PageStoryArgs<typeof roleEditorMocks>;
/** Opens the Logs card and returns it. */
export const openLogsCard = async (
canvasElement: HTMLElement,

View File

@@ -2,19 +2,21 @@ import type { Meta, StoryObj } from '@storybook/react-vite';
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import {
enterUnknownRelation,
showJsonEditor,
} from './__story_mockdata__/roleEditor.play';
import {
openLogsCard,
openSelectorWizard,
roleEditorMocks,
type RoleEditorArgs,
save,
} from './RoleEditor.stories.mocks';
import SettingsPage from '../../../Settings';
type RoleEditorArgs = PageStoryArgs<typeof roleEditorMocks>;
const pageStory = storyMocks(roleEditorMocks, { layout: 'app' });
/**
@@ -49,6 +51,16 @@ export const EditExisting: Story = {
/** The JSON the API stores, which is the other way the same grant is written. */
export const JsonEditor: Story = {
args: { mode: 'edit', editor: 'json' },
play: showJsonEditor,
};
/**
* A grant whose relation the schema does not list, which schema validation
* underlines and reports under the editor, keeping the role from being saved.
*/
export const JsonUnknownRelation: Story = {
args: { mode: 'edit', editor: 'json' },
play: enterUnknownRelation,
};
/**
@@ -79,6 +91,7 @@ export const Tooltips: Story = {
/** The copy action over the JSON editor, which the resource cards replace. */
export const TooltipsInJsonEditor: Story = {
args: { tooltipsOpen: true, mode: 'edit', editor: 'json' },
play: showJsonEditor,
};
/** The Logs card's first verb granted over everything instead of nothing. */

View File

@@ -0,0 +1,102 @@
/**
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
* Do not hand-edit: regenerate instead.
*/
import { buildRoleReadPermission } from 'lib/authz/hooks/useAuthZ/permissions/role.permissions';
import { expect, waitFor, within } from 'storybook/test';
import { grantsAll } from '@/storybook/access/access';
import {
blurActiveElement,
findMonacoEditor,
setMonacoText,
} from '@/storybook/play/monacoEditor';
import {
CUSTOM_ROLE_NAME,
type RoleEditorArgs,
} from '../RoleEditor.stories.mocks';
interface PlayContext {
canvasElement: HTMLElement;
args: RoleEditorArgs;
}
const PAGE_LOAD = { timeout: 15_000 };
/**
* A relation the schema's enum does not list. The JSON parses, so only schema
* validation can flag it.
*/
const UNKNOWN_RELATION_JSON = JSON.stringify(
[
{
objectGroup: {
resource: { kind: 'dashboard', type: 'metaresource' },
selectors: ['*'],
},
relation: 'approve',
},
],
null,
2,
);
const UNKNOWN_RELATION_LINE =
UNKNOWN_RELATION_JSON.split('\n').findIndex((line) =>
line.includes('"relation"'),
) + 1;
/** Custom roles need a valid license, and editing one needs the role and `read` on it. */
const showsJsonEditor = (args: RoleEditorArgs): boolean =>
args.editor === 'json' &&
(args.license === 'cloud' || args.license === 'enterprise') &&
(args.mode === 'create' ||
(args.dataState === 'loaded' &&
(args.authzState === 'error' ||
grantsAll(args, buildRoleReadPermission(CUSTOM_ROLE_NAME)))));
const findJsonEditor = async ({
canvasElement,
}: PlayContext): Promise<HTMLElement> => {
const editor = await within(canvasElement).findByTestId(
'json-editor',
undefined,
PAGE_LOAD,
);
await findMonacoEditor(editor);
return editor;
};
export const showJsonEditor = async (context: PlayContext): Promise<void> => {
if (!showsJsonEditor(context.args)) {
return;
}
await findJsonEditor(context);
blurActiveElement();
};
export const enterUnknownRelation = async (
context: PlayContext,
): Promise<void> => {
if (!showsJsonEditor(context.args)) {
return;
}
const editor = await findJsonEditor(context);
await setMonacoText('json', UNKNOWN_RELATION_JSON);
await findMonacoEditor(editor, 'approve');
await waitFor(
() =>
expect(
within(editor).getByTestId('json-editor-schema-error'),
).toHaveTextContent(`Line ${UNKNOWN_RELATION_LINE}:`),
PAGE_LOAD,
);
blurActiveElement();
};

View File

@@ -0,0 +1,55 @@
import { loader } from '@monaco-editor/react';
import type { editor as monacoEditor } from 'monaco-editor';
import { waitFor } from 'storybook/test';
// The first editor on a page loads Monaco itself, which takes a while on a cold
// cache.
const MONACO_LOAD = { timeout: 20_000 };
/**
* The first Monaco editor under `root`, once it has painted its lines. Until then
* `@monaco-editor/react` shows its loading text in place of the editor.
*/
export const findMonacoEditor = (
root: ParentNode = document,
text: string | RegExp = /\S/,
): Promise<HTMLElement> =>
waitFor(() => {
const editor = root.querySelector<HTMLElement>('.monaco-editor');
const lines = editor?.querySelector('.view-lines')?.textContent ?? '';
const painted =
typeof text === 'string' ? lines.includes(text) : text.test(lines);
if (!editor || !painted) {
throw new Error('Monaco has not rendered its lines yet');
}
return editor;
}, MONACO_LOAD);
/**
* Replaces the text of the model whose language is `languageId`. Typing into
* Monaco's hidden textarea never reaches the model in the test runner; an edit
* on the model reaches the editor's `onChange` like a keystroke does.
*/
export const setMonacoText = async (
languageId: string,
text: string,
): Promise<void> => {
const monaco = await loader.init();
const models: monacoEditor.ITextModel[] = monaco.editor.getModels();
const model = models.find(
(candidate) => candidate.getLanguageId() === languageId,
);
if (!model) {
throw new Error(`No Monaco model in ${languageId}`);
}
model.applyEdits([{ range: model.getFullModelRange(), text }]);
};
/** Drops focus, so the capture has no blinking cursor or focus ring. */
export const blurActiveElement = (): void => {
(document.activeElement as HTMLElement | null)?.blur();
};