Skip to content

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

8.8 KB
Raw Blame
import type { Preview } from '@storybook/react-vite';
import type { SetupWorker } from 'msw';
import { setupWorker } from 'msw';
import { configure } from 'storybook/test';

import { settleForCapture } from '../src/storybook/visual/settleForCapture';
import PageDocs from '../src/storybook/docs/PageDocs';
import ThemedDocsContainer from '../src/storybook/docs/ThemedDocsContainer';
import { withProviders } from '../src/storybook/decorators/withProviders';
import { globalMocks } from '../src/storybook/globals';
import { resetStoryHistory } from '../src/storybook/navigation/containment';
import { clearBlockedNavigations } from '../src/storybook/navigation/blockedNavigationStore';
import {
	resolveStory,
	type StoryRuntimeContext,
} from '../src/storybook/runtime/resolveStory';
import { allModes } from './modes';

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/styles.scss';

import '../src/storybook/storybook-root.scss';

interface StorybookWorkerHolder {
	__signozStorybookWorker?: StorybookWorker;
}

const holder = window as unknown as StorybookWorkerHolder;

/**
 * One worker per page, even if this module is re-executed by HMR. Two live
 * workers both answer the service worker and the story gets whichever replies
 * first.
 */
interface StorybookWorker {
	worker: SetupWorker;
	ready: Promise<unknown>;
}

const { worker, ready } = (holder.__signozStorybookWorker ??=
	((): StorybookWorker => {
		const instance = setupWorker();

		return {
			worker: instance,
			ready: instance.start({
				serviceWorker: { url: './mockServiceWorker.js' },
				// Storybook's own traffic (index.json, HMR, telemetry) goes unhandled by
				// design; only flag the app's API calls so a missing handler is obvious.
				onUnhandledRequest: (request, print): void => {
					const url = new URL(request.url.href);
					const isStaticAsset =
						/\.(?:woff2?|ttf|otf|css|js|map|png|jpe?g|svg|webp|ico)$/.test(
							url.pathname,
						);
					const isAppRequest =
						!isStaticAsset &&
						(url.pathname.startsWith('/api/') || url.host !== window.location.host);

					if (isAppRequest) {
						print.warning();
					}
				},
			}),
		};
	})());

/**
 * `t()` answers with the key until the namespace's JSON has landed, and a `play`
 * that clicks as soon as the story renders is quick enough to catch it: the
 * channel form's "Channel name is mandatory" arrives as `channel_name_required`.
 * Every namespace under `public/locales/en` is loaded once, ahead of the first
 * story.
 */
const translationsReady = i18n.loadNamespaces(
	Object.keys(import.meta.glob('../public/locales/en/*.json')).map((path) =>
		path.slice(path.lastIndexOf('/') + 1, -'.json'.length),
	),
);

// testing-library's 1s default for `findBy*` and `waitFor` is shorter than a
// popup or a query takes to land on a loaded CI runner.
configure({ asyncUtilTimeout: 10_000 });

const preview: Preview = {
	parameters: {
		layout: 'fullscreen',
		controls: { expanded: true },
		// The sidebar order, mirroring the app's own side nav
		// (`container/SideNav/menuItems.tsx`), so a page sits where someone would
		// click it in the product. Storybook's default is the order the story files
		// happen to be globbed in, which puts `src/modules` first. Anything missing
		// from a level lands after the entries listed for it, in file order, so a new
		// story shows up at the end of its area rather than disappearing. Stories
		// inside a file are never listed, so they keep the order they are declared
		// in, `Default` first. Storybook parses this out of the file, so it has to
		// stay an inline literal.
		options: {
			storySort: {
				order: [
					'Docs',
					'Pages',
					[
						'Home',
						'Alerts',
						[
							'Rules',
							'Triggered',
							'Overview',
							'History',
							'Create',
							'Edit',
							'Planned Downtime',
							'Routing Policies',
							'Channels',
							['List', 'List Authz', 'New', 'New Authz', 'Edit', 'Edit Authz'],
						],
						'Dashboards',
						[
							'List',
							'Detail',
							[
								'Overview',
								'Panels',
								'Settings',
								'Variables',
								'New Variable',
								'Edit Variable',
								'Authz',
							],
							'Panel Editor',
							['Overview', 'Chart Options', 'Thresholds and Links'],
							'Public',
						],
						'Services',
						['List', 'Detail', 'Top Level Operations', 'Service Map'],
						'Logs',
						['Explorer', 'Live Tail', 'Pipelines', 'Settings'],
						'Traces',
						['Explorer', 'Trace Details', 'Funnel Details'],
						'Metrics',
						['Explorer'],
						'Infrastructure',
						[
							'Overview',
							'Kubernetes',
							[
								'Clusters',
								'Nodes',
								'Namespaces',
								'Pods',
								'Deployments',
								'DaemonSets',
								'StatefulSets',
								'Jobs',
								'Volumes',
							],
						],
						'Integrations',
						['List', 'Details', 'Cloud Account'],
						'Exceptions',
						['List', 'Detail'],
						'External APIs',
						'AI Observability',
						['Overview', 'Explorer', 'Model Pricing', 'Attribute Mapping'],
						'Noz',
						'Metering',
						['Cost Meter', 'Usage Explorer'],
						'Messaging Queues',
						['Overview', 'Kafka', 'Kafka Detail', 'Celery'],
						'Onboarding',
						['Questionnaire', 'Add Data Source'],
						'Settings',
						[
							'Workspace',
							'Account',
							'Billing',
							['Overview', 'Authz'],
							'MCP Server',
							'Roles',
							'Role Details',
							'Role Editor',
							'Members',
							'Service Accounts',
							'Ingestion',
							'Single Sign-on',
							'Keyboard Shortcuts',
						],
						'Auth',
						['Login', 'Sign Up', 'Forgot Password', 'Reset Password'],
						'System',
						[
							'Status',
							'Support',
							'License',
							'Not Found',
							'Unauthorized',
							'Error Fallback',
							'Workspace Locked',
							'Workspace Suspended',
							'Workspace Access Restricted',
						],
					],
				],
			},
		},
		docs: { page: PageDocs, container: ThemedDocsContainer },
		// One cloud snapshot per theme, for every story. A mode carries Storybook
		// globals, so `theme` here is the same toolbar global the app reads out of
		// localStorage. Widths are Chromatic's only real dimension, as they are
		// locally: the app shell sizes itself to the viewport, so the height is the
		// one it is given.
		chromatic: { modes: allModes },
	},
	// Every page story gets a docs page: the descriptions on the meta and on each
	// story are the page's documentation, and without this they render nowhere.
	tags: ['autodocs'],
	globalTypes: {
		theme: {
			description: 'SigNoz color scheme',
			toolbar: {
				title: 'Theme',
				icon: 'paintbrush',
				items: [
					{ value: 'dark', title: 'Dark' },
					{ value: 'light', title: 'Light' },
				],
				dynamicTitle: true,
			},
		},
		motion: {
			description:
				'Park every animation on its last frame once the story has settled. Still is what both capture stacks shoot; Live is for watching a transition.',
			toolbar: {
				title: 'Motion',
				icon: 'play',
				items: [
					{ value: 'still', title: 'Still' },
					{ value: 'live', title: 'Live' },
				],
				dynamicTitle: true,
			},
		},
	},
	initialGlobals: { theme: 'dark', motion: 'still' },
	// Controls every story carries: permissions, banners, and whether the page's
	// own endpoints answer, hang or fail.
	args: globalMocks.args,
	argTypes: globalMocks.argTypes,
	decorators: [withProviders],
	loaders: [
		// Runs on every render, args changes included, and ahead of the decorators:
		// the whole story world is put in place here, so the provider tree only has
		// to read it. Re-registering the handlers per render also means an edit to a
		// handler module takes effect on the next render instead of leaving the
		// worker on the set it was created with.
		async (context): Promise<void> => {
			const world = resolveStory(context as unknown as StoryRuntimeContext);

			world.apply();
			world.install(worker);

			await Promise.all([ready, translationsReady]);
		},
	],
	beforeEach: () => {
		clearBlockedNavigations();
		resetStoryHistory();

		// The runner clears its console/network buffer before it navigates, so
		// anything the outgoing story still has in flight would be reported
		// against this one. Stamping the moment this story starts gives the runner
		// a line to discard those by. `Date.now()` is faked for the stories, so
		// this reads the one clock the runner's own timestamps share.
		document.body.dataset.signozStoryStartedAt = String(
			performance.timeOrigin + performance.now(),
		);
	},
	// After `play`, which is the moment both capture stacks shoot at.
	afterEach: settleForCapture,
};

export default preview;