Skip to content

πŸͺ’ Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

chore(web): Re-organize storybook (#15274)

Ben Bachem147335c4db04
diff --git a/.agents/skills/storybook/SKILL.md b/.agents/skills/storybook/SKILL.md
index 1e5d00e5be..bd17ae665f 100644
--- a/.agents/skills/storybook/SKILL.md
+++ b/.agents/skills/storybook/SKILL.md
@@ -5,71 +5,6 @@ description: Use when writing or reviewing Storybook stories (`.stories.tsx`) fo
# Storybook Component Stories
-## Which Components Can Have Stories?
-
-Only create stories for components that **do not** do any of the following:
-
-- Depend on context.
-- Fetch data via any private API, including Langfuse’s own tRPC API.
-
-Stories should follow the `ComponentName.stories.tsx` filename pattern. Components covered by stories should have exactly one exported or public component.
-
-If this is not the case, suggest splitting up the file that includes the component to be covered first.
-
-Be mindful of the breadth a story covers. A story should show a component in isolation. Page-level compositions should be rare and intentional.
-
-## What to Do If a Component Violates the Criteria
-
-Suggest abstracting a presentational component that does not violate the criteria and receives relevant data via props.
-
-Make sure the props are well-defined using TypeScript.
-
-Keep the existing component, but update it to use the newly created component for rendering. These presentational components are easier to test and easier to reuse.
-
-## How Stories Should Be Written
-
-- Use "CSF Next" format by default.
-- Cover only the relevant component by default.
-- Do not use `args` on the meta story if most stories override these. Instead, define the args on each story.
-- Avoid custom render functions by default.
-- Do not define helper components inside story files unless the helper component is reused by multiple stories. For one-off setup, inline the stateful render logic directly in the story `render` function.
-- Never use `decorators` to add styling or layout to a story. Stories should render the components as they are.
-- Use `satisfies` and typed Storybook metadata so invalid args, decorators, and play functions are type-checked.
-- Use play functions to test user-relevant interactions after render, not to compensate for complex setup or hidden dependencies.
-- Prefix stories whose primary purpose is interaction test coverage with `(Test)` in the Storybook display name, for example `name: "(Test) Opens Menu"`.
-- Keep `(Test)` stories sorted at the bottom of the file so showcase and product-facing stories stay grouped first.
-- Name stories after the state they represent, not the implementation. Also do not include the component name in the story name.
- - Prefer: `Default`, `Empty`, `WithLongName`, `Error`, `Disabled`, `Loading`
- - Avoid: `Test1`, `CustomRenderExample`, `ButtonWithLongNameAndIcon`
-- Set callbacks up as Storybook Actions by default:
-
- ```ts
- import { fn } from "storybook/test";
- ```
-
-- Avoid large fixtures.
-- Use the smallest meaningful data shape needed to render the state.
-- If fixtures are required and may be shared, check whether a reusable helper function exists. Otherwise, create one for defining the fixture.
-
-## Variant and Design Showcase Stories
-
-If a component has many variants, and the point of the story is to showcase the design of a component rather than its functionality, stories may render the component multiple times.
-
-For example, a `Button` with a `size: "sm" | "md" | "lg"` prop may have a story that shows three buttons side by side.
-
-If the button also has a `variant: "primary" | "secondary"` prop, consider using a matrix-like UI that showcases all possible combinations.
-
-These compositional stories **should not** contain Storybook play functions. They should also not allow the Storybook user to customize the predefined args, such as `size` and `variant`, via Storybook args. Having an arg for non-bound props, such as `text`, may be acceptable.
-
-## Authoring MDX Docs
-
-- Use `.mdx` for prose docs and guides that sit alongside stories.
-- Keep `.mdx` files simple by default: standard markdown plus Storybook docs blocks such as `Meta` and `Canvas` are usually enough.
-- Do not build bespoke page layouts in `.mdx` with exported inline-styled React components unless there is a strong reason.
-- If docs need reusable typography, spacing, or docs-page chrome, add that once in Storybook preview/docs container setup rather than re-implementing it in a single `.mdx` file.
-- Keep illustrative examples in `.stories.tsx`; keep narrative and explanation in `.mdx`.
-- If an example needs a small wrapper in a story, keep it minimal and focused on presenting the example rather than recreating page design inside Storybook.
-
-## Additional Information
-
-- We do not use MSW and are not planning to add it.
+Before writing or reviewing Storybook stories, read and follow the canonical
+[Writing Good Stories](../../../web/storybook/docs/WritingGoodStories.mdx)
+guide.
diff --git a/web/.storybook/docs.css b/web/.storybook/docs.css
new file mode 100644
index 0000000000..3d5ec9caa6
--- /dev/null
+++ b/web/.storybook/docs.css
@@ -0,0 +1,337 @@
+.sbdocs.sbdocs-wrapper {
+ background: hsl(var(--background));
+ color: hsl(var(--foreground));
+ padding: 0;
+}
+
+.sbdocs.sbdocs-content {
+ /* Major-third type scale (1.25) for prose hierarchy. */
+ --docs-type-0: 1rem;
+ --docs-type-1: calc(var(--docs-type-0) * 1.25);
+ --docs-type-2: calc(var(--docs-type-1) * 1.25);
+ --docs-type-3: calc(var(--docs-type-2) * 1.25);
+ --docs-type-4: calc(var(--docs-type-3) * 1.25);
+ --docs-type-small: 0.875rem;
+
+ /* Four-pixel baseline grid for vertical rhythm and component spacing. */
+ --docs-space-unit: 0.25rem;
+ --docs-space-1: var(--docs-space-unit);
+ --docs-space-2: calc(var(--docs-space-unit) * 2);
+ --docs-space-3: calc(var(--docs-space-unit) * 3);
+ --docs-space-4: calc(var(--docs-space-unit) * 4);
+ --docs-space-5: calc(var(--docs-space-unit) * 5);
+ --docs-space-6: calc(var(--docs-space-unit) * 6);
+ --docs-space-8: calc(var(--docs-space-unit) * 8);
+ --docs-space-12: calc(var(--docs-space-unit) * 12);
+ --docs-space-16: calc(var(--docs-space-unit) * 16);
+ --docs-space-24: calc(var(--docs-space-unit) * 24);
+
+ box-sizing: border-box;
+ width: 100%;
+ max-width: 52rem;
+ padding: var(--docs-space-16) var(--docs-space-12) var(--docs-space-24);
+ color: hsl(var(--foreground));
+ font-size: var(--docs-type-0);
+ line-height: 1.6;
+ overflow-wrap: break-word;
+}
+
+.sbdocs.sbdocs-content .docblock-source {
+ max-width: 52rem;
+ margin-top: 0;
+ margin-bottom: var(--docs-space-3);
+}
+
+.sbdocs.sbdocs-content a {
+ color: hsl(var(--link));
+ font-weight: 500;
+ text-decoration-line: underline;
+ text-decoration-color: hsl(var(--link) / 0.35);
+ text-decoration-thickness: 0.0625rem;
+ text-underline-offset: 0.18em;
+}
+
+.sbdocs.sbdocs-content a:hover {
+ color: hsl(var(--link-hover));
+ text-decoration-color: currentColor;
+}
+
+.sbdocs.sbdocs-content h1,
+.sbdocs.sbdocs-content h2,
+.sbdocs.sbdocs-content h3,
+.sbdocs.sbdocs-content h4,
+.sbdocs.sbdocs-content h5,
+.sbdocs.sbdocs-content h6 {
+ position: relative;
+ margin-top: var(--docs-space-8);
+ margin-bottom: var(--docs-space-4);
+ color: hsl(var(--foreground));
+ font-weight: 600;
+ line-height: 1.2;
+ letter-spacing: -0.015em;
+ border: 0;
+}
+
+.sbdocs.sbdocs-content h1 > a[aria-hidden="true"],
+.sbdocs.sbdocs-content h2 > a[aria-hidden="true"],
+.sbdocs.sbdocs-content h3 > a[aria-hidden="true"],
+.sbdocs.sbdocs-content h4 > a[aria-hidden="true"],
+.sbdocs.sbdocs-content h5 > a[aria-hidden="true"],
+.sbdocs.sbdocs-content h6 > a[aria-hidden="true"] {
+ position: absolute;
+ top: 50%;
+ right: 100%;
+ display: inline-flex;
+ padding-right: var(--docs-space-2);
+ color: hsl(var(--foreground-tertiary));
+ opacity: 0;
+ transform: translateY(-50%);
+}
+
+.sbdocs.sbdocs-content h1:hover > a[aria-hidden="true"],
+.sbdocs.sbdocs-content h2:hover > a[aria-hidden="true"],
+.sbdocs.sbdocs-content h3:hover > a[aria-hidden="true"],
+.sbdocs.sbdocs-content h4:hover > a[aria-hidden="true"],
+.sbdocs.sbdocs-content h5:hover > a[aria-hidden="true"],
+.sbdocs.sbdocs-content h6:hover > a[aria-hidden="true"] {
+ opacity: 1;
+}
+
+.sbdocs.sbdocs-content h1 {
+ margin-top: 0;
+ margin-bottom: var(--docs-space-4);
+ font-size: clamp(2rem, 1.75rem + 1vw, var(--docs-type-4));
+ font-weight: 650;
+ letter-spacing: -0.035em;
+}
+
+.sbdocs.sbdocs-content h2 {
+ margin-top: var(--docs-space-12);
+ padding-bottom: var(--docs-space-2);
+ border-bottom: 1px solid hsl(var(--border));
+ font-size: clamp(1.375rem, 1.25rem + 0.5vw, var(--docs-type-2));
+}
+
+.sbdocs.sbdocs-content h1 + h2 {
+ margin-top: var(--docs-space-8);
+}
+
+.sbdocs.sbdocs-content h3,
+.sbdocs.sbdocs-content h3:first-of-type {
+ margin-top: var(--docs-space-8);
+ font-size: var(--docs-type-1);
+}
+
+.sbdocs.sbdocs-content h4 {
+ font-size: var(--docs-type-0);
+}
+
+.sbdocs.sbdocs-content h5 {
+ font-size: var(--docs-type-small);
+}
+
+.sbdocs.sbdocs-content h6 {
+ color: hsl(var(--foreground-tertiary));
+ font-size: calc(var(--docs-type-0) * 0.8);
+ letter-spacing: 0.04em;
+ text-transform: uppercase;
+}
+
+.sbdocs.sbdocs-content p,
+.sbdocs.sbdocs-content blockquote,
+.sbdocs.sbdocs-content ul,
+.sbdocs.sbdocs-content ol,
+.sbdocs.sbdocs-content dl,
+.sbdocs.sbdocs-content table,
+.sbdocs.sbdocs-content pre,
+.sbdocs.sbdocs-content details {
+ margin-top: 0;
+ margin-bottom: var(--docs-space-3);
+}
+
+.sbdocs.sbdocs-content ul,
+.sbdocs.sbdocs-content ol {
+ padding-left: var(--docs-space-6);
+}
+
+.sbdocs.sbdocs-content p + ul,
+.sbdocs.sbdocs-content p + ol {
+ margin-top: calc(var(--docs-space-2) * -1);
+}
+
+.sbdocs.sbdocs-content li {
+ padding-left: var(--docs-space-1);
+}
+
+.sbdocs.sbdocs-content li::marker {
+ color: hsl(var(--foreground-tertiary));
+}
+
+.sbdocs.sbdocs-content li + li {
+ margin-top: var(--docs-space-1);
+}
+
+.sbdocs.sbdocs-content li > p {
+ margin-top: var(--docs-space-4);
+}
+
+.sbdocs.sbdocs-content ul ul,
+.sbdocs.sbdocs-content ul ol,
+.sbdocs.sbdocs-content ol ol,
+.sbdocs.sbdocs-content ol ul {
+ margin-top: 0;
+ margin-bottom: 0;
+}
+
+.sbdocs.sbdocs-content code {
+ background: hsl(var(--surface-code));
+ border: 1px solid hsl(var(--border));
+ border-radius: 0.3rem;
+ padding: 0.15em 0.35em;
+ font-size: 0.875em;
+}
+
+.sbdocs.sbdocs-content pre {
+ background: hsl(var(--surface-code));
+ border: 1px solid hsl(var(--border));
+ border-radius: 0.5rem;
+ color: hsl(var(--foreground));
+ overflow: auto;
+ padding: var(--docs-space-4) var(--docs-space-5);
+ font-size: var(--docs-type-small);
+ line-height: 1.6;
+}
+
+.sbdocs.sbdocs-content pre code {
+ background: transparent;
+ border: 0;
+ font-size: 100%;
+ padding: 0;
+}
+
+.sbdocs.sbdocs-content .docblock-source pre {
+ margin: 0;
+ padding: var(--docs-space-4) var(--docs-space-5);
+ background: transparent;
+ border: 0;
+ border-radius: 0;
+}
+
+.sbdocs.sbdocs-content blockquote {
+ border-left: 0.1875rem solid hsl(var(--primary));
+ color: hsl(var(--muted-foreground));
+ padding: var(--docs-space-1) 0 var(--docs-space-1) var(--docs-space-5);
+}
+
+.sbdocs.sbdocs-content blockquote > :first-child {
+ margin-top: 0;
+}
+
+.sbdocs.sbdocs-content blockquote > :last-child {
+ margin-bottom: 0;
+}
+
+.sbdocs.sbdocs-content hr {
+ height: 0;
+ margin: var(--docs-space-12) 0;
+ padding: 0;
+ background: transparent;
+ border: 0;
+ border-top: 1px solid hsl(var(--border));
+}
+
+.sbdocs.sbdocs-content table {
+ display: block;
+ width: max-content;
+ max-width: 100%;
+ overflow: auto;
+ border-collapse: collapse;
+ border-spacing: 0;
+ font-size: var(--docs-type-small);
+ line-height: 1.5;
+}
+
+.sbdocs.sbdocs-content table tr {
+ background: hsl(var(--background));
+ border-top: 1px solid hsl(var(--border));
+}
+
+.sbdocs.sbdocs-content table tr:nth-child(2n) {
+ background: hsl(var(--muted) / 0.45);
+}
+
+.sbdocs.sbdocs-content table th,
+.sbdocs.sbdocs-content table td {
+ padding: var(--docs-space-2) var(--docs-space-3);
+ border: 1px solid hsl(var(--border));
+ text-align: left;
+ vertical-align: top;
+}
+
+.sbdocs.sbdocs-content table th {
+ background: hsl(var(--muted) / 0.65);
+ font-weight: 600;
+}
+
+.sbdocs.sbdocs-content img {
+ box-sizing: content-box;
+ max-width: 100%;
+}
+
+.sbdocs.sbdocs-content summary {
+ cursor: pointer;
+ font-weight: 600;
+}
+
+.sbdocs.sbdocs-content details {
+ padding: var(--docs-space-3) var(--docs-space-4);
+ background: hsl(var(--muted) / 0.35);
+ border: 1px solid hsl(var(--border));
+ border-radius: 0.5rem;
+}
+
+.sbdocs.sbdocs-content details[open] > summary {
+ margin-bottom: var(--docs-space-3);
+}
+
+.sbdocs.sbdocs-content > :first-child {
+ margin-top: 0;
+}
+
+.sbdocs.sbdocs-content > :last-child {
+ margin-bottom: 0;
+}
+
+.sbdocs.sbdocs-content .sbdocs.sbdocs-preview {
+ margin: var(--docs-space-6) 0 var(--docs-space-8);
+ background: hsl(var(--card));
+ border: 1px solid hsl(var(--border));
+ border-radius: 0.625rem;
+ box-shadow: none;
+}
+
+.sbdocs.sbdocs-content .storybook-token-grid {
+ display: grid;
+ grid-template-columns: repeat(4, minmax(0, 1fr));
+ gap: var(--docs-space-3);
+ margin: var(--docs-space-4) 0;
+}
+
+.sbdocs.sbdocs-content .storybook-token-grid > * {
+ min-width: 0;
+}
+
+@media (max-width: 47.9375rem) {
+ .sbdocs.sbdocs-content {
+ padding: var(--docs-space-8) var(--docs-space-5) var(--docs-space-16);
+ font-size: 0.9375rem;
+ }
+
+ .sbdocs.sbdocs-content h2 {
+ margin-top: var(--docs-space-8);
+ }
+
+ .sbdocs.sbdocs-content .storybook-token-grid {
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ }
+}
diff --git a/web/.storybook/main.ts b/web/.storybook/main.ts
index a6d9709c42..64ffc6e9cb 100644
--- a/web/.storybook/main.ts
+++ b/web/.storybook/main.ts
@@ -1,8 +1,19 @@
import type { StorybookConfig } from "@storybook/nextjs-vite";
-import { dirname, resolve } from "path";
+import { basename, dirname, resolve } from "path";
import { fileURLToPath } from "url";
+import {
+ flatStoryTitlesPlugin,
+ flattenStoryIndexTitles,
+} from "./storybook-flat-story-titles";
+
+const STORY_EXTENSIONS = "@(js|jsx|mjs|ts|tsx)";
+const DESIGN_COMPONENT_STORIES = [
+ "LangfuseIcon/LangfuseIcon",
+ "Spinner/Spinner",
+ "Switch/Switch",
+] as const;
/**
* This function is used to resolve the absolute path of a package.
@@ -13,7 +24,35 @@ function getAbsolutePath(value: string) {
}
const config: StorybookConfig = {
- stories: ["../src/**/*.mdx", "../src/**/*.stories.@(js|jsx|mjs|ts|tsx)"],
+ stories: [
+ // Curated design-system documentation shown under Design.
+ {
+ directory: "../storybook/docs",
+ files: "**/*.mdx",
+ titlePrefix: "Design",
+ },
+ // Technical MDX documents colocated with implementation code.
+ {
+ directory: "../src",
+ files: "**/*.mdx",
+ titlePrefix: "Playground/Docs",
+ },
+ // Reviewed components that are part of the design-system reference.
+ ...DESIGN_COMPONENT_STORIES.map((storyPath) => ({
+ directory: "../src/components/design-system",
+ files: `${storyPath}.stories.${STORY_EXTENSIONS}`,
+ titlePrefix: "Design/Components",
+ })),
+ // All other component stories belong to the flat Playground by default.
+ {
+ directory: "../src",
+ files: `**/!(${DESIGN_COMPONENT_STORIES.map((storyPath) =>
+ basename(storyPath),
+ ).join("|")}).stories.${STORY_EXTENSIONS}`,
+ titlePrefix: "Playground",
+ },
+ ],
+ experimental_indexers: flattenStoryIndexTitles,
addons: [
getAbsolutePath("@storybook/addon-a11y"),
getAbsolutePath("@storybook/addon-docs"),
@@ -33,6 +72,8 @@ const config: StorybookConfig = {
// pulled in transitively by the table stories). Pointing at the source makes
// Storybook resolve named exports exactly like the app does.
viteFinal: async (viteConfig) => {
+ viteConfig.plugins = [flatStoryTitlesPlugin, ...(viteConfig.plugins ?? [])];
+
const sharedSrc = resolve(
dirname(fileURLToPath(import.meta.url)),
"../../packages/shared/src",
diff --git a/web/.storybook/preview.tsx b/web/.storybook/preview.tsx
index 0c3cf3bf7f..22c269f09c 100644
--- a/web/.storybook/preview.tsx
+++ b/web/.storybook/preview.tsx
@@ -2,6 +2,8 @@ import { definePreview } from "@storybook/nextjs-vite";
import addonA11y from "@storybook/addon-a11y";
import addonDocs from "@storybook/addon-docs";
import { DocsContainer } from "@storybook/addon-docs/blocks";
+import { GLOBALS_UPDATED, SET_GLOBALS } from "storybook/internal/core-events";
+import { addons } from "storybook/preview-api";
import { themes } from "storybook/theming";
import {
useEffect,
@@ -13,6 +15,7 @@ import { TooltipProvider } from "../src/components/ui/tooltip";
import { MarkdownContextProvider } from "../src/features/theming/useMarkdownContext";
import { LAYER_ORDER } from "../src/components/ui/layer";
import "../src/styles/globals.css";
+import "./docs.css";
// Mirror the global CSS that _app.tsx imports so vendored components
// (react18-json-view, streamdown markdown) render identically to the app.
import "react18-json-view/src/style.css";
@@ -20,11 +23,9 @@ import "streamdown/styles.css";
function StorybookThemeProvider({
children,
- theme,
fullHeight,
}: {
children?: ReactNode;
- theme: "light" | "dark";
/**
* Give `#__next` a real viewport height so the app's `height: 100%` chains
* resolve (canvas/story view). In docs view this must be OFF, or every inline
@@ -33,14 +34,6 @@ function StorybookThemeProvider({
*/
fullHeight: boolean;
}) {
- useEffect(() => {
- document.documentElement.classList.toggle("dark", theme === "dark");
-
- return () => {
- document.documentElement.classList.remove("dark");
- };
- }, [theme]);
-
// Overlay layer containers, declared exactly like _document.tsx: a
// <div data-overlay-root> holding one <div data-layer={name}/> per
// LAYER_ORDER. This is what the layer system (components/ui/layer.tsx)
@@ -83,14 +76,21 @@ function StorybookThemeProvider({
);
}
+const syncTheme = ({ globals }: { globals?: { theme?: unknown } }) => {
+ document.documentElement.classList.toggle("dark", globals?.theme === "dark");
+};
+
+const channel = addons.getChannel();
+channel.on(SET_GLOBALS, syncTheme);
+channel.on(GLOBALS_UPDATED, syncTheme);
+
/**
* Docs/guide pages render outside the story decorator, so they don't get our
* theme β€” Storybook's own docs theme is light and makes prose unreadable in
* dark mode (and the page stays white). This container switches Storybook's
- * docs theme to match the app's `.dark` class (which the story decorators
- * toggle on <html>), so every guide's prose, chrome, and example cards follow
- * the theme. It also bumps the base type β€” the default docs body is too small.
- * (LFE-10549)
+ * docs theme to match the app's `.dark` class (which the global theme listener
+ * toggles on <html>), so every guide's prose, chrome, and example cards follow
+ * the theme. (LFE-10549)
*/
function ThemedDocsContainer({
context,
@@ -111,58 +111,6 @@ function ThemedDocsContainer({
return (
<DocsContainer context={context} theme={dark ? themes.dark : themes.light}>
- <style>{`
- .sbdocs-wrapper {
- background: hsl(var(--background));
- color: hsl(var(--foreground));
- padding: 0;
- }
-
- .sbdocs-content {
- max-width: 56rem;
- padding: 3.5rem 2rem;
- color: hsl(var(--foreground));
- }
-
- .sbdocs-content a {
- color: hsl(var(--primary));
- }
-
- .sbdocs-content code {
- background: hsl(var(--muted));
- border-radius: 0.25rem;
- padding: 0.125rem 0.375rem;
- }
-
- .sbdocs-content pre {
- background: hsl(var(--muted));
- border: 1px solid hsl(var(--border));
- border-radius: 0.5rem;
- color: hsl(var(--foreground));
- }
-
- .sbdocs-content pre code {
- background: transparent;
- padding: 0;
- }
-
- .sbdocs-content blockquote {
- border-left: 3px solid hsl(var(--border));
- color: hsl(var(--muted-foreground));
- margin-left: 0;
- padding-left: 1rem;
- }
-
- .sbdocs-content hr {
- border-color: hsl(var(--border));
- }
-
- .sbdocs-content .sbdocs.sbdocs-preview {
- background: transparent;
- border: 1px solid hsl(var(--border));
- box-shadow: none;
- }
- `}</style>
{children}
</DocsContainer>
);
@@ -191,26 +139,19 @@ export default definePreview({
theme: "light",
},
decorators: [
- (Story, context) => {
- const theme = context.globals.theme === "dark" ? "dark" : "light";
-
- return (
- <StorybookThemeProvider
- theme={theme}
- fullHeight={context.viewMode !== "docs"}
- >
- {/* MarkdownContextProvider mirrors the app: pages render inside it so
+ (Story, context) => (
+ <StorybookThemeProvider fullHeight={context.viewMode !== "docs"}>
+ {/* MarkdownContextProvider mirrors the app: pages render inside it so
the JSON/IO viewers (CodeJsonViewer's JSONView calls
useMarkdownContext) work identically to production. Without it,
multi-line IOTableCell renders (rowHeight m/l) throw. */}
- <MarkdownContextProvider>
- <TooltipProvider>
- <Story />
- </TooltipProvider>
- </MarkdownContextProvider>
- </StorybookThemeProvider>
- );
- },
+ <MarkdownContextProvider>
+ <TooltipProvider>
+ <Story />
+ </TooltipProvider>
+ </MarkdownContextProvider>
+ </StorybookThemeProvider>
+ ),
],
parameters: {
a11y: {
@@ -219,5 +160,10 @@ export default definePreview({
docs: {
container: ThemedDocsContainer,
},
+ options: {
+ storySort: {
+ order: ["Design", "Playground"],
+ },
+ },
},
});
diff --git a/web/.storybook/storybook-flat-story-titles.ts b/web/.storybook/storybook-flat-story-titles.ts
new file mode 100644
index 0000000000..0467d81576
--- /dev/null
+++ b/web/.storybook/storybook-flat-story-titles.ts
@@ -0,0 +1,117 @@
+import type { StorybookConfig } from "@storybook/nextjs-vite";
+import { storyNameFromExport, toId } from "storybook/internal/csf";
+import type { Plugin } from "vite";
+import { readFile } from "node:fs/promises";
+import { basename } from "path";
+import * as ts from "typescript";
+
+const STORY_FILE_PATTERN = /\.stories\.[cm]?[jt]sx?$/;
+
+function findMetaObject(code: string, fileName: string) {
+ const sourceFile = ts.createSourceFile(
+ fileName,
+ code,
+ ts.ScriptTarget.Latest,
+ true,
+ fileName.endsWith(".tsx") || fileName.endsWith(".jsx")
+ ? ts.ScriptKind.TSX
+ : ts.ScriptKind.TS,
+ );
+
+ let metaObject: ts.ObjectLiteralExpression | undefined;
+
+ const visit = (node: ts.Node) => {
+ if (metaObject) return;
+
+ if (
+ ts.isCallExpression(node) &&
+ ts.isPropertyAccessExpression(node.expression) &&
+ node.expression.name.text === "meta" &&
+ ts.isObjectLiteralExpression(node.arguments[0])
+ ) {
+ metaObject = node.arguments[0];
+ return;
+ }
+
+ ts.forEachChild(node, visit);
+ };
+
+ visit(sourceFile);
+ return metaObject;
+}
+
+function hasTitleProperty(metaObject: ts.ObjectLiteralExpression) {
+ return metaObject.properties.some(
+ (property) =>
+ (ts.isPropertyAssignment(property) ||
+ ts.isShorthandPropertyAssignment(property)) &&
+ (ts.isIdentifier(property.name) || ts.isStringLiteral(property.name)) &&
+ property.name.text === "title",
+ );
+}
+
+export function assertNoExplicitStoryTitle(code: string, fileName: string) {
+ const metaObject = findMetaObject(code, fileName);
+ if (metaObject && hasTitleProperty(metaObject)) {
+ throw new Error(
+ `Explicit Storybook titles are not allowed in ${fileName}. Rename the story file to set its title.`,
+ );
+ }
+
+ return metaObject;
+}
+
+function addFlatStoryTitle(code: string, fileName: string) {
+ const metaObject = assertNoExplicitStoryTitle(code, fileName);
+ if (!metaObject) return null;
+
+ const componentTitle = basename(fileName).replace(STORY_FILE_PATTERN, "");
+ const insertionPoint = metaObject.getStart() + 1;
+
+ return `${code.slice(0, insertionPoint)}\n title: ${JSON.stringify(componentTitle)},${code.slice(insertionPoint)}`;
+}
+
+// Storybook computes index and runtime titles separately. Keep both paths in
+// this module so inferred titles and their derived story IDs cannot diverge.
+export const flattenStoryIndexTitles: NonNullable<
+ StorybookConfig["experimental_indexers"]
+> = async (indexers) =>
+ indexers?.map((indexer) => ({
+ ...indexer,
+ createIndex: async (fileName, options) => {
+ if (!STORY_FILE_PATTERN.test(fileName)) {
+ return indexer.createIndex(fileName, options);
+ }
+
+ assertNoExplicitStoryTitle(await readFile(fileName, "utf8"), fileName);
+ const entries = await indexer.createIndex(fileName, options);
+
+ return entries.map((entry) => {
+ const componentTitle = entry.title?.split("/").at(-1);
+ if (!componentTitle) return entry;
+
+ const title = options.makeTitle(componentTitle);
+ const storyName = storyNameFromExport(entry.exportName);
+ const derivedId = entry.title
+ ? toId(entry.title, storyName)
+ : undefined;
+
+ return {
+ ...entry,
+ title,
+ __id: entry.__id === derivedId ? toId(title, storyName) : entry.__id,
+ };
+ });
+ },
+ }));
+
+export const flatStoryTitlesPlugin = {
+ name: "storybook-flat-story-titles",
+ enforce: "pre",
+ transform(code, id) {
+ const [fileName] = id.split("?");
+ if (!fileName || !STORY_FILE_PATTERN.test(fileName)) return null;
+
+ return addFlatStoryTitle(code, fileName);
+ },
+} satisfies Plugin;
diff --git a/web/src/__tests__/server/unit/storybook-flat-story-titles.servertest.ts b/web/src/__tests__/server/unit/storybook-flat-story-titles.servertest.ts
new file mode 100644
index 0000000000..c3e7cd8ae7
--- /dev/null
+++ b/web/src/__tests__/server/unit/storybook-flat-story-titles.servertest.ts
@@ -0,0 +1,23 @@
+import { assertNoExplicitStoryTitle } from "../../../../.storybook/storybook-flat-story-titles";
+
+describe("assertNoExplicitStoryTitle", () => {
+ it("rejects explicit story titles", () => {
+ expect(() =>
+ assertNoExplicitStoryTitle(
+ 'const meta = preview.meta({ title: "CustomTitle", component });',
+ "/components/Example.stories.tsx",
+ ),
+ ).toThrowError(
+ "Explicit Storybook titles are not allowed in /components/Example.stories.tsx",
+ );
+ });
+
+ it("allows inferred story titles", () => {
+ expect(() =>
+ assertNoExplicitStoryTitle(
+ "const meta = preview.meta({ component });",
+ "/components/Example.stories.tsx",
+ ),
+ ).not.toThrow();
+ });
+});
diff --git a/web/src/components/ScoreLevels.mdx b/web/src/components/ScoreTag.mdx
similarity index 95%
rename from web/src/components/ScoreLevels.mdx
rename to web/src/components/ScoreTag.mdx
index 2916280b28..67a2d520eb 100644
--- a/web/src/components/ScoreLevels.mdx
+++ b/web/src/components/ScoreTag.mdx
@@ -1,7 +1,7 @@
import { Meta, Canvas } from "@storybook/addon-docs/blocks";
-import * as ScoreTagStories from "./score-tag.stories";
+import * as ScoreTagStories from "./ScoreTag.stories";
-<Meta title="components/ScoreTag/Guidance" />
+<Meta of={ScoreTagStories} name="Guidance" />
# Score levels & the `ScoreTag` color coding
diff --git a/web/src/components/score-tag.stories.tsx b/web/src/components/ScoreTag.stories.tsx
similarity index 98%
rename from web/src/components/score-tag.stories.tsx
rename to web/src/components/ScoreTag.stories.tsx
index a239b7fd9d..c86916bf5b 100644
--- a/web/src/components/score-tag.stories.tsx
+++ b/web/src/components/ScoreTag.stories.tsx
@@ -4,7 +4,6 @@ import preview from "../../.storybook/preview";
import { ScoreTag, SCORE_LEVEL_LABELS, type ScoreLevel } from "./score-tag";
const meta = preview.meta({
- title: "components/ScoreTag",
component: ScoreTag,
});
diff --git a/web/src/components/design-system/ComponentGallery.stories.tsx b/web/src/components/design-system/ComponentGallery.stories.tsx
deleted file mode 100644
index bb090df9be..0000000000
--- a/web/src/components/design-system/ComponentGallery.stories.tsx
+++ /dev/null
@@ -1,374 +0,0 @@
-import React from "react";
-import { AlertCircle, Info, Plus } from "lucide-react";
-import preview from "../../../.storybook/preview";
-
-import { Button, type ButtonProps } from "@/src/components/ui/button";
-import { Badge, type BadgeProps } from "@/src/components/ui/badge";
-import { Alert, AlertDescription, AlertTitle } from "@/src/components/ui/alert";
-import { Callout } from "@/src/components/ui/callout";
-import { Input } from "@/src/components/ui/input";
-import { Textarea } from "@/src/components/ui/textarea";
-import {
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from "@/src/components/ui/select";
-import { Checkbox } from "@/src/components/ui/checkbox";
-import { Switch } from "@/src/components/design-system/Switch/Switch";
-import {
- Card,
- CardContent,
- CardDescription,
- CardFooter,
- CardHeader,
- CardTitle,
-} from "@/src/components/ui/card";
-import {
- Tabs,
- TabsContent,
- TabsList,
- TabsTrigger,
-} from "@/src/components/ui/tabs";
-import {
- Tooltip,
- TooltipContent,
- TooltipTrigger,
-} from "@/src/components/ui/tooltip";
-import { ItemBadge, type LangfuseItemType } from "@/src/components/ItemBadge";
-import { EXPERIMENT_COLOR_STYLES } from "@/src/features/experiments/components/table/types";
-
-/**
- * Design-system gallery: the key primitives rendered in all their variants on
- * one scannable page, so light/dark rendering can be audited with the global
- * Theme toolbar toggle. Everything is the real component, imported from the
- * app β€” no copies.
- *
- * Deliberately skipped (need heavy context or fight the gallery layout):
- * - DataTable and any component needing tRPC/router/session context.
- * - Recharts charts β€” heavy; the chart palette is covered as swatches in
- * "Design System/Theme Tokens" (a dedicated chart story can come later).
- * - Dialog / DropdownMenu / Popover / Sheet β€” transient overlays; stacking is
- * documented in "Design System/Overlay Layers". Tooltip is included
- * statically open since it stays anchored to its trigger.
- *
- * Known/expected: ItemBadge observation-type icon colors (text-purple-600
- * etc.) have no dark: variants β€” flagged by the dark-theme audit, rendered
- * here as-is on purpose. Same for the experiments "text-dark-gray" baseline
- * class, which has no backing token.
- */
-
-const BUTTON_VARIANTS: ButtonProps["variant"][] = [
- "default",
- "destructive",
- "destructive-secondary",
- "outline",
- "secondary",
- "tertiary",
- "ghost",
- "link",
- "errorNotification",
-];
-
-const BUTTON_TEXT_SIZES: ButtonProps["size"][] = ["xs", "sm", "default", "lg"];
-const BUTTON_ICON_SIZES: ButtonProps["size"][] = ["icon-xs", "icon-sm", "icon"];
-
-const BADGE_VARIANTS: BadgeProps["variant"][] = [
- "default",
- "secondary",
- "destructive",
- "outline",
- "outline-solid",
- "tertiary",
- "success",
- "error",
- "warning",
-];
-
-const ITEM_BADGE_TYPES: LangfuseItemType[] = [
- "TRACE",
- "GENERATION",
- "EVENT",
- "SPAN",
- "AGENT",
- "TOOL",
- "CHAIN",
- "RETRIEVER",
- "EMBEDDING",
- "GUARDRAIL",
- "SESSION",
- "USER",
- "QUEUE_ITEM",
- "DATASET",
- "DATASET_RUN",
- "DATASET_ITEM",
- "ANNOTATION_QUEUE",
- "PROMPT",
- "EVALUATOR",
- "RUNNING_EVALUATOR",
- "EXPERIMENT",
-];
-
-const EXPERIMENT_STYLE_LABELS = [
- "Baseline",
- "Comparison 1",
- "Comparison 2",
- "Comparison 3",
- "Comparison 4",
-];
-
-function Section({
- title,
- note,
- children,
-}: {
- title: string;
- note?: string;
- children: React.ReactNode;
-}) {
- return (
- <section className="mt-8">
- <h2 className="text-foreground text-lg font-bold">{title}</h2>
- {note && <p className="text-muted-foreground mt-1 text-xs">{note}</p>}
- <div className="mt-3">{children}</div>
- </section>
- );
-}
-
-function Row({
- label,
- children,
-}: {
- label?: string;
- children: React.ReactNode;
-}) {
- return (
- <div className="mb-3 flex flex-wrap items-center gap-3">
- {label && (
- <span className="text-muted-foreground w-24 shrink-0 font-mono text-[11px]">
- {label}
- </span>
- )}
- {children}
- </div>
- );
-}
-
-function ComponentGalleryDoc() {
- return (
- <div className="text-foreground mx-auto max-w-5xl p-8 text-sm leading-relaxed">
- <h1 className="text-2xl font-bold">Component gallery</h1>
- <p className="text-muted-foreground mt-1">
- Key primitives in all their variants β€” flip the Theme toolbar toggle to
- audit light and dark rendering.
- </p>
-
- <Section title="Button" note="All variants at default size, then sizes.">
- <Row label="variants">
- {BUTTON_VARIANTS.map((variant) => (
- <Button key={variant} variant={variant}>
- {variant}
- </Button>
- ))}
- </Row>
- <Row label="sizes">
- {BUTTON_TEXT_SIZES.map((size) => (
- <Button key={size} size={size}>
- {size}
- </Button>
- ))}
- {BUTTON_ICON_SIZES.map((size) => (
- <Button key={size} size={size} aria-label={`icon button ${size}`}>
- <Plus className="h-4 w-4" />
- </Button>
- ))}
- </Row>
- <Row label="states">
- <Button disabled>disabled</Button>
- <Button loading>loading</Button>
- </Row>
- </Section>
-
- <Section title="Badge">
- <Row label="default">
- {BADGE_VARIANTS.map((variant) => (
- <Badge key={variant} variant={variant}>
- {variant}
- </Badge>
- ))}
- </Row>
- <Row label="sm">
- {BADGE_VARIANTS.map((variant) => (
- <Badge key={variant} variant={variant} size="sm">
- {variant}
- </Badge>
- ))}
- </Row>
- </Section>
-
- <Section
- title="ItemBadge"
- note="One badge per entity type. The observation-type icon colors (AGENT…GUARDRAIL) intentionally have no dark: variants yet β€” audit finding, rendered as-is."
- >
- <div className="flex flex-wrap gap-2">
- {ITEM_BADGE_TYPES.map((type) => (
- <ItemBadge key={type} type={type} showLabel />
- ))}
- </div>
- </Section>
-
- <Section title="Alert & Callout">
- <div className="flex max-w-2xl flex-col gap-3">
- <Alert>
- <Info className="h-4 w-4" />
- <AlertTitle>Default alert</AlertTitle>
- <AlertDescription>
- Neutral information on the page surface.
- </AlertDescription>
- </Alert>
- <Alert variant="destructive">
- <AlertCircle className="h-4 w-4" />
- <AlertTitle>Destructive alert</AlertTitle>
- <AlertDescription>Something went wrong.</AlertDescription>
- </Alert>
- <Alert variant="info">
- <Info className="h-4 w-4" />
- <AlertTitle>Info alert</AlertTitle>
- <AlertDescription>Blue informational surface.</AlertDescription>
- </Alert>
- {/* Callout persists dismissal in localStorage (30d TTL) β€” if one is
- missing here, clear the "storybook-gallery-*" keys. */}
- <Callout id="storybook-gallery-info" variant="info">
- Info callout β€” dismissible, light-blue surface.
- </Callout>
- <Callout id="storybook-gallery-warning" variant="warning">
- Warning callout β€” dismissible, light-yellow surface.
- </Callout>
- </div>
- </Section>
-
- <Section title="Form controls">
- <div className="grid max-w-2xl grid-cols-2 gap-4">
- <Input placeholder="Input placeholder" aria-label="Example input" />
- <Input
- defaultValue="Disabled input"
- disabled
- aria-label="Disabled input"
- />
- <Textarea
- placeholder="Textarea placeholder"
- aria-label="Example textarea"
- />
- <Select>
- <SelectTrigger aria-label="Example select">
- <SelectValue placeholder="Select an option" />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="one">Option one</SelectItem>
- <SelectItem value="two">Option two</SelectItem>
- <SelectItem value="three">Option three</SelectItem>
- </SelectContent>
- </Select>
- </div>
- <Row label="checkbox">
- <Checkbox aria-label="Unchecked" />
- <Checkbox defaultChecked aria-label="Checked" />
- <Checkbox disabled aria-label="Disabled" />
- <Checkbox defaultChecked disabled aria-label="Checked disabled" />
- </Row>
- <Row label="switch">
- <Switch aria-label="Off" />
- <Switch defaultChecked aria-label="On" />
- <Switch disabled aria-label="Disabled" />
- <Switch defaultChecked disabled aria-label="On disabled" />
- </Row>
- </Section>
-
- <Section title="Card">
- <Card className="max-w-md">
- <CardHeader>
- <CardTitle>Card title</CardTitle>
- <CardDescription>Card description in muted text.</CardDescription>
- </CardHeader>
- <CardContent>
- Card content on the card surface β€” check the border and background
- separation against the page in both themes.
- </CardContent>
- <CardFooter className="gap-2">
- <Button size="sm">Confirm</Button>
- <Button size="sm" variant="ghost">
- Cancel
- </Button>
- </CardFooter>
- </Card>
- </Section>
-
- <Section title="Tabs">
- <Tabs defaultValue="first" className="max-w-md">
- <TabsList>
- <TabsTrigger value="first">First</TabsTrigger>
- <TabsTrigger value="second">Second</TabsTrigger>
- <TabsTrigger value="third" disabled>
- Disabled
- </TabsTrigger>
- </TabsList>
- <TabsContent value="first">
- Content of the first tab β€” active trigger vs. inactive contrast.
- </TabsContent>
- <TabsContent value="second">Content of the second tab.</TabsContent>
- </Tabs>
- </Section>
-
- <Section
- title="Tooltip"
- note="Statically open so the popover surface is scannable without hovering."
- >
- <div className="flex h-20 items-end">
- <Tooltip open>
- <TooltipTrigger asChild>
- <Button variant="outline">Tooltip anchor</Button>
- </TooltipTrigger>
- <TooltipContent>Tooltip surface (bg-popover)</TooltipContent>
- </Tooltip>
- </div>
- </Section>
-
- <Section
- title="Experiment colors"
- note="EXPERIMENT_COLOR_STYLES from the experiments table β€” badge, marker, and text class per slot."
- >
- <div className="flex flex-col gap-2">
- {EXPERIMENT_COLOR_STYLES.map((style, i) => (
- <div key={i} className="flex items-center gap-3">
- <span
- className={`inline-block h-3 w-3 rounded-full ${style.markerClass}`}
- />
- <span
- className={`rounded-md border px-2 py-0.5 text-xs font-bold ${style.badgeClass}`}
- >
- {EXPERIMENT_STYLE_LABELS[i]}
- </span>
- <span className={`text-xs ${style.textClass}`}>
- {style.textClass}
- </span>
- </div>
- ))}
- </div>
- </Section>
-
- <p className="text-muted-foreground mt-10 border-t pt-4 text-xs">
- Part of the design system. Companion pages: &ldquo;Theme Tokens&rdquo;
- (raw palette) and &ldquo;Overlay Layers&rdquo; (stacking).
- </p>
- </div>
- );
-}
-
-const meta = preview.meta({
- title: "Design System/Component Gallery",
- component: ComponentGalleryDoc,
- parameters: { layout: "fullscreen" },
-});
-
-export const Overview = meta.story({});
diff --git a/web/src/components/design-system/OverlayLayers.mdx b/web/src/components/design-system/OverlayLayers.mdx
index 3d1cb794ac..abf8523e95 100644
--- a/web/src/components/design-system/OverlayLayers.mdx
+++ b/web/src/components/design-system/OverlayLayers.mdx
@@ -1,9 +1,6 @@
import { Meta } from "@storybook/addon-docs/blocks";
-<Meta
- title="Design System/Overlay Layers"
- parameters={{ layout: "fullscreen" }}
-/>
+<Meta title="Overlay Layers" parameters={{ layout: "fullscreen" }} />
# Overlay Layers
diff --git a/web/src/components/design-system/Spinner/Spinner.stories.tsx b/web/src/components/design-system/Spinner/Spinner.stories.tsx
index a70fe685d4..f4e43059b9 100644
--- a/web/src/components/design-system/Spinner/Spinner.stories.tsx
+++ b/web/src/components/design-system/Spinner/Spinner.stories.tsx
@@ -26,7 +26,7 @@ const allSizes = Object.keys({
full: true,
} satisfies Record<Size, true>) as Size[];
-export const AllVariants = meta.story({
+export const VariantMatrix = meta.story({
render: () => (
<div
className="grid gap-x-8 gap-y-4"
diff --git a/web/src/components/design-system/ThemeTokens.stories.tsx b/web/src/components/design-system/ThemeTokens.stories.tsx
deleted file mode 100644
index 18307d4c5b..0000000000
--- a/web/src/components/design-system/ThemeTokens.stories.tsx
+++ /dev/null
@@ -1,247 +0,0 @@
-import React from "react";
-import preview from "../../../.storybook/preview";
-
-/**
- * Design-system documentation: every color token declared in
- * `src/styles/globals.css` (`:root` + `.dark`), rendered live so the palette
- * can be scanned in both themes with the global Theme toolbar toggle.
- *
- * Swatches read the CSS variables at render time β€” `hsl(var(--token))` for the
- * HSL triplet tokens, `var(--color-N)` for the oklch heatmap scale β€” so they
- * resolve exactly like the app (the Storybook preview imports the same
- * globals.css and flips the `dark` class on <html>).
- */
-
-/** A single color token rendered as a bordered block + its variable name. */
-function Swatch({ token, css }: { token: string; css?: string }) {
- return (
- <div className="flex w-36 flex-col gap-1">
- <div
- className="border-border h-12 w-full rounded-md border"
- style={{ backgroundColor: css ?? `hsl(var(--${token}))` }}
- />
- <code className="text-muted-foreground font-mono text-[11px] leading-tight">
- --{token}
- </code>
- </div>
- );
-}
-
-/**
- * A background/foreground token pair rendered as a filled chip with text, so
- * the contrast of the pair is visible at a glance.
- */
-function PairChip({
- bg,
- fg,
- label,
-}: {
- bg: string;
- fg: string;
- label?: string;
-}) {
- return (
- <div className="flex w-52 flex-col gap-1">
- <div
- className="border-border flex h-12 items-center justify-center rounded-md border px-2 text-sm font-bold"
- style={{
- backgroundColor: `hsl(var(--${bg}))`,
- color: `hsl(var(--${fg}))`,
- }}
- >
- {label ?? "Aa β€” sample text"}
- </div>
- <code className="text-muted-foreground font-mono text-[11px] leading-tight">
- --{bg} / --{fg}
- </code>
- </div>
- );
-}
-
-function Section({
- title,
- note,
- children,
-}: {
- title: string;
- note?: string;
- children: React.ReactNode;
-}) {
- return (
- <section className="mt-8">
- <h2 className="text-foreground text-lg font-bold">{title}</h2>
- {note && <p className="text-muted-foreground mt-1 text-xs">{note}</p>}
- <div className="mt-3 flex flex-wrap gap-3">{children}</div>
- </section>
- );
-}
-
-const SEMANTIC_PAIRS = [
- "primary",
- "secondary",
- "tertiary",
- "accent",
- "destructive",
-] as const;
-
-const STATUS_PAIRS: { bg: string; fg: string }[] = [
- { bg: "light-red", fg: "dark-red" },
- { bg: "light-yellow", fg: "dark-yellow" },
- { bg: "light-green", fg: "dark-green" },
- { bg: "light-blue", fg: "dark-blue" },
- { bg: "accent-light-green", fg: "accent-dark-green" },
- { bg: "accent-light-blue", fg: "accent-dark-blue" },
-];
-
-const QLANG_TOKENS = [
- "qlang-field",
- "qlang-value",
- "qlang-number",
- "qlang-keyword",
-] as const;
-
-function ThemeTokensDoc() {
- return (
- <div className="text-foreground mx-auto max-w-5xl p-8 text-sm leading-relaxed">
- <h1 className="text-2xl font-bold">Theme tokens</h1>
- <p className="text-muted-foreground mt-1">
- All color tokens from <code>globals.css</code>, resolved live. Flip the
- Theme toolbar toggle to compare light and dark.
- </p>
-
- <Section
- title="Surfaces"
- note="App surfaces and their foregrounds, plus the structural border/input/ring tokens."
- >
- <PairChip bg="background" fg="foreground" />
- <PairChip bg="card" fg="card-foreground" />
- <PairChip bg="popover" fg="popover-foreground" />
- <PairChip bg="header" fg="header-foreground" />
- <PairChip bg="muted" fg="muted-foreground" />
- <PairChip bg="background" fg="foreground-tertiary" label="faint text" />
- <Swatch token="border" />
- <Swatch token="border-contrast" />
- <Swatch token="input" />
- <Swatch token="ring" />
- <Swatch token="surface-code" />
- </Section>
-
- <Section
- title="Semantic"
- note="shadcn action colors β€” each pair rendered as a filled chip so contrast is scannable."
- >
- {SEMANTIC_PAIRS.map((name) => (
- <PairChip
- key={name}
- bg={name}
- fg={`${name}-foreground`}
- label={name}
- />
- ))}
- </Section>
-
- <Section
- title="Langfuse accents"
- note="Brand accent + the muted categorical set used across entity icons and charts."
- >
- <Swatch token="primary-accent" />
- <Swatch token="link" />
- <Swatch token="link-hover" />
- <Swatch token="control-fill" />
- <Swatch token="control-track" />
- <Swatch token="muted-blue" />
- <Swatch token="muted-green" />
- <Swatch token="muted-magenta" />
- <Swatch token="muted-gray" />
- </Section>
-
- <Section
- title="Status / accent pairs"
- note="light-* backgrounds with their dark-* foregrounds β€” the Badge success/error/warning recipe."
- >
- {STATUS_PAIRS.map(({ bg, fg }) => (
- <PairChip key={bg} bg={bg} fg={fg} label={bg.replace("light-", "")} />
- ))}
- </Section>
-
- <Section
- title="Search grammar (qlang)"
- note="Editor-style syntax theme for the search-bar filter grammar β€” deliberately its own palette."
- >
- {QLANG_TOKENS.map((token) => (
- <Swatch key={token} token={token} />
- ))}
- <div className="border-border bg-background flex h-12 items-center rounded-md border px-3 font-mono text-sm">
- <span style={{ color: "hsl(var(--qlang-field))" }}>level</span>
- <span className="text-muted-foreground">=</span>
- <span style={{ color: "hsl(var(--qlang-value))" }}>
- &quot;ERROR&quot;
- </span>
- <span style={{ color: "hsl(var(--qlang-keyword))" }}>
- &nbsp;and&nbsp;
- </span>
- <span style={{ color: "hsl(var(--qlang-field))" }}>latency</span>
- <span className="text-muted-foreground">&gt;</span>
- <span style={{ color: "hsl(var(--qlang-number))" }}>2</span>
- </div>
- </Section>
-
- <Section title="Sidebar">
- <PairChip bg="sidebar-background" fg="sidebar-foreground" />
- <PairChip bg="sidebar-primary" fg="sidebar-primary-foreground" />
- <PairChip bg="sidebar-accent" fg="sidebar-accent-foreground" />
- <Swatch token="sidebar-border" />
- <Swatch token="sidebar-ring" />
- </Section>
-
- <Section
- title="Find match"
- note="In-page text search highlights (all matches vs. the selected match)."
- >
- <PairChip bg="find-match-background" fg="foreground" label="match" />
- <PairChip
- bg="find-match-selected-background"
- fg="find-match-selected-foreground"
- label="selected match"
- />
- </Section>
-
- <Section
- title="Charts"
- note="Categorical chart series 1–8 plus the grid line color."
- >
- {Array.from({ length: 8 }, (_, i) => (
- <Swatch key={i} token={`chart-${i + 1}`} />
- ))}
- <Swatch token="chart-grid" />
- </Section>
-
- <Section
- title="Heatmap (oklch)"
- note="color-1..5 are full oklch values, read via var(--color-N) directly."
- >
- {Array.from({ length: 5 }, (_, i) => (
- <Swatch
- key={i}
- token={`color-${i + 1}`}
- css={`var(--color-${i + 1})`}
- />
- ))}
- </Section>
-
- <p className="text-muted-foreground mt-10 border-t pt-4 text-xs">
- Part of the design system. Tokens live in{" "}
- <code>src/styles/globals.css</code>; this page reads them live, so it
- can never drift from the app.
- </p>
- </div>
- );
-}
-
-const meta = preview.meta({
- title: "Design System/Theme Tokens",
- component: ThemeTokensDoc,
- parameters: { layout: "fullscreen" },
-});
-
-export const Overview = meta.story({});
diff --git a/web/src/components/table/data-table.stories.tsx b/web/src/components/table/DataTable.stories.tsx
similarity index 99%
rename from web/src/components/table/data-table.stories.tsx
rename to web/src/components/table/DataTable.stories.tsx
index df6d2076d1..ddeeee669f 100644
--- a/web/src/components/table/data-table.stories.tsx
+++ b/web/src/components/table/DataTable.stories.tsx
@@ -723,7 +723,6 @@ function DataTableDemo(props: DataTableDemoProps) {
}
const meta = preview.meta({
- title: "Components/Table/DataTable",
component: DataTableDemo,
parameters: {
layout: "fullscreen",
diff --git a/web/src/components/ui/media/MediaTag.stories.tsx b/web/src/components/ui/media/MediaTag.stories.tsx
index 1302b7cdd9..bd0c1665a1 100644
--- a/web/src/components/ui/media/MediaTag.stories.tsx
+++ b/web/src/components/ui/media/MediaTag.stories.tsx
@@ -20,7 +20,6 @@ const sampleImage =
);
const meta = preview.meta({
- title: "components/media/MediaTag",
component: MediaTag,
args: {
contentType: "image/png",
diff --git a/web/src/features/widgets/chart-library/ChartInteractivity.stories.tsx b/web/src/features/widgets/chart-library/ChartInteractivity.stories.tsx
deleted file mode 100644
index 699d7e0d5a..0000000000
--- a/web/src/features/widgets/chart-library/ChartInteractivity.stories.tsx
+++ /dev/null
@@ -1,135 +0,0 @@
-import preview from "../../../../.storybook/preview";
-import { LineChartTimeSeries } from "./LineChartTimeSeries";
-import { formatMetric } from "./utils";
-import { type DataPoint, type MetricFormatterFunction } from "./chart-props";
-
-// Shared time buckets so the synced crosshair lines up across panels (recharts
-// syncId matches by index). Deterministic β€” no Math.random.
-const HOURS = 48;
-const labelAt = (i: number) => {
- const h = (13 + Math.floor(i / 2)) % 24;
- return `${String(h).padStart(2, "0")}:${i % 2 === 0 ? "00" : "30"}`;
-};
-
-const buildPanel = (
- series: { name: string; base: number; amp: number; spike?: number }[],
-): DataPoint[] => {
- const points: DataPoint[] = [];
- for (let i = 0; i < HOURS; i++) {
- const time = labelAt(i);
- series.forEach(({ name, base, amp, spike }, seed) => {
- const wave = 0.5 + 0.5 * Math.sin((i + seed * 2.1) / 3.3);
- const jitter = ((seed * 31 + i * 17) % 13) / 13;
- const spikeAdd = spike && i === 30 ? spike : 0;
- points.push({
- time_dimension: time,
- dimension: name,
- metric: Math.round(base + amp * wave + amp * 0.3 * jitter + spikeAdd),
- });
- });
- }
- return points;
-};
-
-const requestsData = buildPanel([
- { name: "web", base: 14_000, amp: 6_000 },
- { name: "worker", base: 9_000, amp: 4_000 },
-]);
-const latencyData = buildPanel([
- { name: "post /api/chat-completion", base: 800, amp: 700, spike: 9_000 },
- { name: "get /api/traces", base: 300, amp: 200 },
- { name: "post /api/ingestion", base: 500, amp: 400 },
-]);
-const errorsData = buildPanel([{ name: "5xx", base: 1, amp: 3, spike: 8 }]);
-
-// The common "spaghetti" case β€” many series at once. Magnitudes are spread so
-// the lines occupy different vertical bands (good for the proximity highlight).
-const spaghettiData = buildPanel(
- Array.from({ length: 14 }, (_, i) => ({
- name: `model-${String.fromCharCode(97 + i)}`,
- base: 150 + i * 120,
- amp: 80 + (i % 4) * 70,
- })),
-);
-
-const msFormatter: MetricFormatterFunction = (value, options) =>
- formatMetric(value, { ...options, unit: "millisecond" });
-
-const PANELS: {
- title: string;
- data: DataPoint[];
- formatter?: MetricFormatterFunction;
-}[] = [
- { title: "Requests", data: requestsData },
- { title: "p95 Latency", data: latencyData, formatter: msFormatter },
- { title: "Errors", data: errorsData },
-];
-
-/**
- * A mini-dashboard of charts that share a `syncId`. Hovering any panel drives a
- * synced vertical crosshair + tooltip across ALL panels at the same timestamp;
- * tooltips can escape a panel's bounds (allowEscapeViewBox). This is the
- * interactivity prototype for LFE-10549 β€” best viewed live, not as a screenshot.
- */
-const SyncedDashboardDemo = ({
- syncId = "lfe10549-demo",
-}: {
- syncId?: string;
-}) => (
- <div className="flex flex-col gap-4">
- <p className="text-muted-foreground text-xs">
- Hover any chart β€” the time crosshair + tooltip track across all three.
- </p>
- {PANELS.map((panel) => (
- <div key={panel.title} className="bg-background rounded-md border p-3">
- <div className="mb-1 text-sm font-bold">{panel.title}</div>
- <div className="h-[180px] w-full">
- <LineChartTimeSeries
- data={panel.data}
- syncId={syncId}
- legendPosition="below"
- legendSummary="none"
- showDataPointDots={false}
- metricFormatter={panel.formatter}
- />
- </div>
- </div>
- ))}
- </div>
-);
-
-const meta = preview.meta({
- component: SyncedDashboardDemo,
- args: { syncId: "lfe10549-demo" },
- decorators: [
- (Story) => (
- <div className="w-[560px]">
- <Story />
- </div>
- ),
- ],
-});
-
-export const SyncedTimeline = meta.story({});
-
-/**
- * The common overloaded case. Move the cursor vertically near a line: the
- * nearest line(s) emphasize and the rest dim; two lines within the pixel
- * threshold both light up; away from any line it renders normally.
- */
-export const Spaghetti = meta.story({
- render: () => (
- <div className="bg-background h-[380px] w-full rounded-md border p-3">
- <div className="mb-1 text-sm font-bold">p95 Latency β€” 14 models</div>
- <div className="h-[330px] w-full">
- <LineChartTimeSeries
- data={spaghettiData}
- legendPosition="below"
- legendSummary="none"
- showDataPointDots={false}
- metricFormatter={msFormatter}
- />
- </div>
- </div>
- ),
-});
diff --git a/web/src/features/widgets/chart-library/ChartPolish.stories.tsx b/web/src/features/widgets/chart-library/ChartPolish.stories.tsx
deleted file mode 100644
index 0c99e7bbea..0000000000
--- a/web/src/features/widgets/chart-library/ChartPolish.stories.tsx
+++ /dev/null
@@ -1,316 +0,0 @@
-import preview from "../../../../.storybook/preview";
-import { Bar, BarChart, CartesianGrid, XAxis, YAxis } from "recharts";
-import { ChartContainer } from "@/src/components/ui/chart";
-import { LineChartTimeSeries } from "./LineChartTimeSeries";
-import { VerticalBarChartTimeSeries } from "./VerticalBarChartTimeSeries";
-import { seriesColor } from "./TimeSeriesLegend";
-import {
- formatMetric,
- groupDataByTimeDimension,
- toFullMetricString,
-} from "./utils";
-import {
- type DataPoint,
- type LegendPosition,
- type ChartProps,
-} from "./chart-props";
-
-/**
- * Decision surface for the LFE-10576 chart polish. Each story isolates one
- * taste call (vertical grid density, bar-chart grid, default legend
- * visibility) or one interactive fix (tooltip placement/sizing) on realistic
- * data, so the choice is made by looking at renders, not diffs. Deterministic
- * data only β€” no Math.random β€” so the renders are stable.
- */
-
-// ── deterministic data ───────────────────────────────────────────────────────
-
-/** ISO timestamps so prepareTimeAxis picks the temporal (not category) axis. */
-const isoDay = (day: number, hour = 0) =>
- new Date(Date.UTC(2026, 5, 22 + day, hour)).toISOString();
-
-const buildSeries = (
- series: { name: string; base: number; amp: number }[],
- buckets: number,
- timeAt: (i: number) => string,
-): DataPoint[] => {
- const points: DataPoint[] = [];
- for (let i = 0; i < buckets; i++) {
- const time = timeAt(i);
- series.forEach(({ name, base, amp }, seed) => {
- const wave = 0.5 + 0.5 * Math.sin((i + seed * 1.7) / 2.3);
- const jitter = ((seed * 37 + i * 13) % 17) / 17;
- points.push({
- time_dimension: time,
- dimension: name,
- metric: Math.round(base + amp * wave + amp * 0.25 * jitter),
- });
- });
- }
- return points;
-};
-
-const MODELS = [
- { name: "gpt-4o", base: 40_000, amp: 30_000 },
- { name: "claude-3-5-sonnet", base: 25_000, amp: 18_000 },
- { name: "gpt-4o-mini", base: 90_000, amp: 60_000 },
- { name: "llama-3-70b", base: 12_000, amp: 9_000 },
-];
-
-/** 14 daily buckets β†’ date-mode axis ("Jun 22" … "Jul 5"). */
-const dailyData = buildSeries(MODELS, 14, (i) => isoDay(i));
-/** 24 hourly buckets in one day β†’ time-mode axis ("2 AM" … "11 PM"). */
-const hourlyData = buildSeries(MODELS, 24, (i) => isoDay(0, i));
-/** Single-series variant of the daily data. */
-const dailySingle = dailyData.filter((p) => p.dimension === "gpt-4o-mini");
-
-/** Long observation-type names β€” the tooltip-truncation stress case. */
-const longNameData = buildSeries(
- [
- { name: "sa-investigation:sa-evidence-verifier", base: 4_000, amp: 2_500 },
- { name: "tool-bash-loghouse-querylog-reader", base: 28_000, amp: 9_000 },
- { name: "step-loghouse-cplogs-aggregation-pass", base: 2_600, amp: 1_400 },
- { name: "tool-bash-dwh-resolve-org-membership", base: 700, amp: 420 },
- { name: "answer", base: 11_000, amp: 4_000 },
- { name: "step-write-io", base: 6_300, amp: 2_100 },
- ],
- 14,
- (i) => isoDay(i),
-);
-
-// ── shared framing ───────────────────────────────────────────────────────────
-
-const OptionCard = ({
- label,
- caption,
- children,
-}: {
- label: string;
- caption: string;
- children: React.ReactNode;
-}) => (
- <div className="flex min-w-[340px] flex-1 flex-col gap-1">
- <div className="text-xs font-bold tracking-wide uppercase">{label}</div>
- <div className="bg-background h-[240px] w-full rounded-md border p-2">
- {children}
- </div>
- <div className="text-muted-foreground w-full text-xs">{caption}</div>
- </div>
-);
-
-/** A dashboard-widget-shaped card (title + description + plot). */
-const WidgetCard = ({
- title,
- description,
- legendPosition,
- data,
-}: {
- title: string;
- description: string;
- legendPosition: LegendPosition;
- data: DataPoint[];
-}) => (
- <div className="bg-background flex h-[300px] w-[480px] flex-col rounded-lg border p-4">
- <span className="truncate font-bold">{title}</span>
- <div className="text-muted-foreground mb-2 truncate text-sm">
- {description}
- </div>
- <div className="min-h-0 flex-1">
- <LineChartTimeSeries data={data} legendPosition={legendPosition} />
- </div>
- </div>
-);
-
-/**
- * Raw-recharts stacked bar twin of `VerticalBarChartTimeSeries`, with the grid
- * exposed β€” the real component has NO grid today, so the variants have to be
- * drawn side-by-side here for the decision.
- */
-const BarGridVariant = ({
- data,
- grid,
-}: {
- data: DataPoint[];
- grid: "none" | "horizontal" | "both";
-}) => {
- const grouped = groupDataByTimeDimension(data);
- const dimensions = [...new Set(data.map((p) => p.dimension ?? ""))];
- return (
- // ChartContainer so tick text/grid pick up the same CSS the real chart
- // gets β€” the variants must differ ONLY in the grid.
- <ChartContainer config={{}}>
- <BarChart data={grouped}>
- {grid !== "none" && (
- <CartesianGrid
- stroke="hsl(var(--chart-grid))"
- vertical={grid === "both"}
- syncWithTicks
- />
- )}
- <XAxis
- dataKey="time_dimension"
- stroke="hsl(var(--chart-grid))"
- fontSize={12}
- tickLine={false}
- axisLine={false}
- interval={2}
- tickFormatter={(v: string) =>
- new Date(v).toLocaleDateString("en-US", {
- month: "short",
- day: "numeric",
- })
- }
- />
- <YAxis
- type="number"
- stroke="hsl(var(--chart-grid))"
- fontSize={12}
- tickLine={false}
- axisLine={false}
- niceTicks="auto"
- tickFormatter={(value: number) =>
- toFullMetricString(formatMetric(value, { style: "compact" }))
- }
- />
- {dimensions.map((dimension, index) => (
- <Bar
- key={dimension}
- dataKey={dimension}
- stackId="stack"
- fill={seriesColor(index)}
- isAnimationActive={false}
- />
- ))}
- </BarChart>
- </ChartContainer>
- );
-};
-
-const ChartPolishDemo = (props: ChartProps) => (
- <LineChartTimeSeries {...props} />
-);
-
-const meta = preview.meta({
- title: "Design System/Charts/Polish (LFE-10576)",
- component: ChartPolishDemo,
-});
-
-// ── β‘€ Vertical grid lines ────────────────────────────────────────────────────
-
-/**
- * DECIDED (Nikita, 2026-07-07): vertical lines on ALL temporal scales. They
- * land on the shown x ticks (`syncWithTicks`), so density follows the tick
- * budget; categorical axes stay clean.
- */
-export const GridVerticalLines = meta.story({
- render: () => (
- <div className="flex flex-wrap gap-5 p-1">
- <OptionCard
- label="Date scale (days)"
- caption="One line per shown day tick β€” the ticket's ask."
- >
- <LineChartTimeSeries data={dailyData} legendPosition="none" />
- </OptionCard>
- <OptionCard
- label="Time scale (hours)"
- caption="Same rule zoomed into a day: a line per shown hour tick."
- >
- <LineChartTimeSeries data={hourlyData} legendPosition="none" />
- </OptionCard>
- </div>
- ),
-});
-
-// ── β‘€b Bar chart grid ────────────────────────────────────────────────────────
-
-/** DECIDED (Nikita, 2026-07-07): horizontal only β€” first card is the real component. */
-export const BarChartGrid = meta.story({
- render: () => (
- <div className="flex flex-wrap gap-5 p-1">
- <OptionCard
- label="Adopted: horizontal only"
- caption="y-gridlines make bar heights gaugeable; the bars themselves mark the x-rhythm."
- >
- <VerticalBarChartTimeSeries data={dailyData} legendPosition="none" />
- </OptionCard>
- <OptionCard
- label="Rejected: no grid"
- caption="The old bar time series β€” values were hard to gauge."
- >
- <BarGridVariant data={dailyData} grid="none" />
- </OptionCard>
- <OptionCard
- label="Rejected: horizontal + vertical"
- caption="Vertical lines fall between bars and only add noise."
- >
- <BarGridVariant data={dailyData} grid="both" />
- </OptionCard>
- </div>
- ),
-});
-
-// ── β‘£ Default legend visibility ──────────────────────────────────────────────
-
-/**
- * DECIDED (Nikita, 2026-07-07): default is "auto" β€” a legend only when the
- * chart draws >1 series (a single-series legend just echoes the card title) β€”
- * and a rendered legend sits BELOW the plot. Dashboard widgets used to never
- * show a legend (old default "none") while the built-in home charts forced
- * one; "auto" heals that inconsistency without call-site changes.
- */
-export const LegendDefaultVisibility = meta.story({
- render: () => (
- <div className="flex flex-col gap-4 p-1">
- <div className="flex flex-wrap gap-4">
- <WidgetCard
- title="Total tokens"
- description="auto, single series β†’ no legend"
- legendPosition="auto"
- data={dailySingle}
- />
- <WidgetCard
- title="Total tokens"
- description='single series, legend forced on ("below")'
- legendPosition="below"
- data={dailySingle}
- />
- </div>
- <div className="flex flex-wrap gap-4">
- <WidgetCard
- title="Total tokens by model"
- description='4 series, legend opted out ("none")'
- legendPosition="none"
- data={dailyData}
- />
- <WidgetCard
- title="Total tokens by model"
- description="auto, 4 series β†’ legend below the plot"
- legendPosition="auto"
- data={dailyData}
- />
- </div>
- </div>
- ),
-});
-
-// ── β‘ β‘‘β‘’ Tooltip placement / sizing (interactive) ─────────────────────────────
-
-/**
- * Live check for the tooltip fixes: sweep the cursor left↔right across the
- * full chart width. The tooltip must keep a stable, readable width on both
- * sides of the flip (no all-ellipsis collapse near the right edge), the
- * proximity-highlighted row must not shift or re-truncate, and descenders
- * (g/y/p) must not lose their bottom pixel.
- */
-export const TooltipEdgePlacement = meta.story({
- render: () => (
- <div className="bg-background w-[95vw] rounded-md border p-3">
- <div className="mb-1 text-sm font-bold">
- Hover near the right edge β€” long names, viewport-wide chart
- </div>
- <div className="h-[300px] w-full">
- <LineChartTimeSeries data={longNameData} legendPosition="below" />
- </div>
- </div>
- ),
-});
diff --git a/web/src/features/widgets/chart-library/ChartingPrinciples.mdx b/web/src/features/widgets/chart-library/ChartingPrinciples.mdx
index 1a79057339..0b64fe252c 100644
--- a/web/src/features/widgets/chart-library/ChartingPrinciples.mdx
+++ b/web/src/features/widgets/chart-library/ChartingPrinciples.mdx
@@ -1,7 +1,7 @@
import { Meta, Canvas } from "@storybook/addon-docs/blocks";
import * as Principles from "./ChartingPrinciples.stories";
-<Meta title="Design System/Charts/Principles" />
+<Meta title="Charting Principles" />
# Charting Principles
diff --git a/web/src/features/widgets/chart-library/ChartingPrinciples.stories.tsx b/web/src/features/widgets/chart-library/ChartingPrinciples.stories.tsx
index ffa8702e77..8020ca2f25 100644
--- a/web/src/features/widgets/chart-library/ChartingPrinciples.stories.tsx
+++ b/web/src/features/widgets/chart-library/ChartingPrinciples.stories.tsx
@@ -85,8 +85,8 @@ const axes = (
);
const meta = preview.meta({
- title: "Design System/Charts/Illustrations",
component: LineChartTimeSeries,
+ tags: ["!dev"],
});
// ── V1 Β· Draw what was measured ──────────────────────────────────────────────
diff --git a/web/src/features/widgets/chart-library/LineChartTimeSeries.stories.tsx b/web/src/features/widgets/chart-library/LineChartTimeSeries.stories.tsx
index 761f011143..3058c0e9c9 100644
--- a/web/src/features/widgets/chart-library/LineChartTimeSeries.stories.tsx
+++ b/web/src/features/widgets/chart-library/LineChartTimeSeries.stories.tsx
@@ -21,14 +21,15 @@ const LineChartTimeSeriesDemo = (props: ChartProps) => (
*/
const buildSeries = (
series: { name: string; base: number; amp: number }[],
- days = 14,
+ buckets: number,
+ labelAt: (bucket: number) => string,
): DataPoint[] => {
const points: DataPoint[] = [];
- for (let day = 0; day < days; day++) {
- const label = `6/${day + 1}`;
+ for (let bucket = 0; bucket < buckets; bucket++) {
+ const label = labelAt(bucket);
series.forEach(({ name, base, amp }, seed) => {
- const wave = 0.5 + 0.5 * Math.sin((day + seed * 1.7) / 2.3);
- const jitter = ((seed * 37 + day * 13) % 17) / 17;
+ const wave = 0.5 + 0.5 * Math.sin((bucket + seed * 1.7) / 2.3);
+ const jitter = ((seed * 37 + bucket * 13) % 17) / 17;
points.push({
time_dimension: label,
dimension: name,
@@ -39,20 +40,32 @@ const buildSeries = (
return points;
};
+const categoryLabelAt = (bucket: number) => `6/${bucket + 1}`;
+const isoDay = (day: number, hour: number) =>
+ new Date(Date.UTC(2026, 5, 22 + day, hour)).toISOString();
+
// Non-additive latencies (ms) β€” summing these is nonsense; avg/median/last read well.
-const latencyData = buildSeries([
- { name: "gpt-4o", base: 800, amp: 600 },
- { name: "claude-3-5-sonnet", base: 1200, amp: 900 },
- { name: "gpt-4o-mini", base: 300, amp: 250 },
- { name: "<synthetic>", base: 1500, amp: 1100 },
-]);
+const latencyData = buildSeries(
+ [
+ { name: "gpt-4o", base: 800, amp: 600 },
+ { name: "claude-3-5-sonnet", base: 1200, amp: 900 },
+ { name: "gpt-4o-mini", base: 300, amp: 250 },
+ { name: "<synthetic>", base: 1500, amp: 1100 },
+ ],
+ 14,
+ categoryLabelAt,
+);
// Additive token counts β€” "sum" reconciles with a headline total.
-const tokenData = buildSeries([
- { name: "gpt-4o", base: 40_000, amp: 30_000 },
- { name: "claude-3-5-sonnet", base: 25_000, amp: 18_000 },
- { name: "gpt-4o-mini", base: 90_000, amp: 60_000 },
-]);
+const tokenData = buildSeries(
+ [
+ { name: "gpt-4o", base: 40_000, amp: 30_000 },
+ { name: "claude-3-5-sonnet", base: 25_000, amp: 18_000 },
+ { name: "gpt-4o-mini", base: 90_000, amp: 60_000 },
+ ],
+ 14,
+ categoryLabelAt,
+);
// Overloaded: many models at once (the Model-latencies failure case).
const manySeriesData = buildSeries(
@@ -61,6 +74,58 @@ const manySeriesData = buildSeries(
base: 200 + i * 90,
amp: 150 + i * 60,
})),
+ 14,
+ categoryLabelAt,
+);
+
+const temporalModels = [
+ { name: "gpt-4o", base: 40_000, amp: 30_000 },
+ { name: "claude-3-5-sonnet", base: 25_000, amp: 18_000 },
+ { name: "gpt-4o-mini", base: 90_000, amp: 60_000 },
+];
+const dailyData = buildSeries(temporalModels, 14, (bucket) =>
+ isoDay(bucket, 0),
+);
+const hourlyData = buildSeries(temporalModels, 24, (bucket) =>
+ isoDay(0, bucket),
+);
+const singleSeriesData = dailyData.filter(
+ (point) => point.dimension === "gpt-4o-mini",
+);
+const longNameData = buildSeries(
+ [
+ { name: "sa-investigation:sa-evidence-verifier", base: 4_000, amp: 2_500 },
+ { name: "tool-bash-loghouse-querylog-reader", base: 28_000, amp: 9_000 },
+ {
+ name: "step-loghouse-cplogs-aggregation-pass",
+ base: 2_600,
+ amp: 1_400,
+ },
+ { name: "answer", base: 11_000, amp: 4_000 },
+ ],
+ 14,
+ (bucket) => isoDay(bucket, 0),
+);
+
+const syncedLabelAt = (bucket: number) => {
+ const hour = 13 + Math.floor(bucket / 2);
+ return `${hour}:${bucket % 2 === 0 ? "00" : "30"}`;
+};
+const syncedRequestsData = buildSeries(
+ [
+ { name: "web", base: 14_000, amp: 6_000 },
+ { name: "worker", base: 9_000, amp: 4_000 },
+ ],
+ 8,
+ syncedLabelAt,
+);
+const syncedLatencyData = buildSeries(
+ [
+ { name: "post /api/chat-completion", base: 800, amp: 700 },
+ { name: "get /api/traces", base: 300, amp: 200 },
+ ],
+ 8,
+ syncedLabelAt,
);
const msFormatter: MetricFormatterFunction = (value, options) =>
@@ -68,19 +133,7 @@ const msFormatter: MetricFormatterFunction = (value, options) =>
const meta = preview.meta({
component: LineChartTimeSeriesDemo,
- args: {
- data: latencyData,
- legendPosition: "below",
- metricFormatter: msFormatter,
- },
- // Host in a card-sized box so ResponsiveContainer has room (the widget shape).
- decorators: [
- (Story) => (
- <div className="bg-background h-[320px] w-[640px] rounded-md border p-3">
- <Story />
- </div>
- ),
- ],
+ parameters: { layout: "fullscreen" },
});
// ── Legend summary ───────────────────────────────────────────────────────────
@@ -89,11 +142,20 @@ const meta = preview.meta({
// an unlabeled non-sum number reads ambiguously. (LFE-10549)
export const LegendNoneOnLatency = meta.story({
- args: { data: latencyData, legendSummary: "none" },
+ args: {
+ data: latencyData,
+ legendPosition: "below",
+ legendSummary: "none",
+ metricFormatter: msFormatter,
+ },
});
export const LegendSumOnAdditive = meta.story({
- args: { data: tokenData, legendSummary: "sum", metricFormatter: undefined },
+ args: {
+ data: tokenData,
+ legendPosition: "below",
+ legendSummary: "sum",
+ },
});
// ── Overload handling (decide the de-clutter approach here) ───────────────────
@@ -102,24 +164,95 @@ export const LegendSumOnAdditive = meta.story({
export const OverloadAllSeriesHighlight = meta.story({
args: {
data: manySeriesData,
+ legendPosition: "below",
legendSummary: "none",
legendInteraction: "highlight",
+ metricFormatter: msFormatter,
},
});
export const OverloadToggleVisibility = meta.story({
args: {
data: manySeriesData,
+ legendPosition: "below",
legendSummary: "none",
legendInteraction: "toggle",
+ metricFormatter: msFormatter,
},
});
export const OverloadTopFive = meta.story({
args: {
data: manySeriesData,
+ legendPosition: "below",
legendSummary: "none",
legendInteraction: "toggle",
maxVisibleSeries: 5,
+ metricFormatter: msFormatter,
+ },
+});
+
+export const DailyTimeScale = meta.story({
+ args: {
+ data: dailyData,
+ legendPosition: "none",
+ },
+});
+
+export const HourlyTimeScale = meta.story({
+ args: {
+ data: hourlyData,
+ legendPosition: "none",
},
});
+
+export const SingleSeriesAutomaticLegend = meta.story({
+ args: {
+ data: singleSeriesData,
+ legendPosition: "auto",
+ },
+});
+
+export const MultipleSeriesAutomaticLegend = meta.story({
+ args: {
+ data: dailyData,
+ legendPosition: "auto",
+ },
+});
+
+export const WithLongSeriesNames = meta.story({
+ args: {
+ data: longNameData,
+ legendPosition: "below",
+ },
+});
+
+export const SyncedTimeline = meta.story({
+ parameters: { controls: { disable: true } },
+ render: () => (
+ <div className="flex w-[640px] flex-col gap-4 p-4">
+ <p className="text-muted-foreground text-xs">
+ Hover either chart to move the shared timeline across both.
+ </p>
+ <div className="bg-background h-[220px] rounded-md border p-3">
+ <LineChartTimeSeries
+ data={syncedRequestsData}
+ syncId="synced-timeline"
+ legendPosition="below"
+ legendSummary="none"
+ showDataPointDots={false}
+ />
+ </div>
+ <div className="bg-background h-[220px] rounded-md border p-3">
+ <LineChartTimeSeries
+ data={syncedLatencyData}
+ syncId="synced-timeline"
+ legendPosition="below"
+ legendSummary="none"
+ showDataPointDots={false}
+ metricFormatter={msFormatter}
+ />
+ </div>
+ </div>
+ ),
+});
diff --git a/web/src/features/widgets/chart-library/VerticalBarChartTimeSeries.stories.tsx b/web/src/features/widgets/chart-library/VerticalBarChartTimeSeries.stories.tsx
new file mode 100644
index 0000000000..d62e92b55b
--- /dev/null
+++ b/web/src/features/widgets/chart-library/VerticalBarChartTimeSeries.stories.tsx
@@ -0,0 +1,52 @@
+import preview from "../../../../.storybook/preview";
+import { type ChartProps, type DataPoint } from "./chart-props";
+import { VerticalBarChartTimeSeries } from "./VerticalBarChartTimeSeries";
+
+const VerticalBarChartTimeSeriesDemo = (props: ChartProps) => (
+ <VerticalBarChartTimeSeries {...props} />
+);
+
+const data: DataPoint[] = [
+ {
+ time_dimension: "2026-06-22T00:00:00.000Z",
+ dimension: "gpt-4o",
+ metric: 42_000,
+ },
+ {
+ time_dimension: "2026-06-22T00:00:00.000Z",
+ dimension: "gpt-4o-mini",
+ metric: 68_000,
+ },
+ {
+ time_dimension: "2026-06-23T00:00:00.000Z",
+ dimension: "gpt-4o",
+ metric: 51_000,
+ },
+ {
+ time_dimension: "2026-06-23T00:00:00.000Z",
+ dimension: "gpt-4o-mini",
+ metric: 73_000,
+ },
+ {
+ time_dimension: "2026-06-24T00:00:00.000Z",
+ dimension: "gpt-4o",
+ metric: 47_000,
+ },
+ {
+ time_dimension: "2026-06-24T00:00:00.000Z",
+ dimension: "gpt-4o-mini",
+ metric: 81_000,
+ },
+];
+
+const meta = preview.meta({
+ component: VerticalBarChartTimeSeriesDemo,
+ parameters: { layout: "fullscreen" },
+});
+
+export const Default = meta.story({
+ args: {
+ data,
+ legendPosition: "auto",
+ },
+});
diff --git a/web/storybook/docs/Overview.mdx b/web/storybook/docs/Overview.mdx
new file mode 100644
index 0000000000..33b38dcff1
--- /dev/null
+++ b/web/storybook/docs/Overview.mdx
@@ -0,0 +1,27 @@
+import { Meta } from "@storybook/addon-docs/blocks";
+
+<Meta />
+
+# Overview
+
+Storybook is the shared workspace for documenting Langfuse's interface and
+developing UI components in isolation. It keeps design guidance and component
+examples easy to discover without requiring the full application.
+
+Before modifying content in this Storybook, please read the [Writing Good Stories](?path=/docs/design-writing-good-stories--docs) page.
+
+## Structure
+
+Our Storybook is split into two sections with different purposes:
+
+#### Design
+
+Design contains the curated documentation for Langfuse's visual language,
+patterns, and conventions. Use it for guidance that should remain stable and
+help contributors make consistent product decisions.
+
+#### Playground
+
+Playground contains isolated component stories and supporting technical
+documentation. Use it to develop, test, and explore components independently
+from the application. New component stories belong here by default.
diff --git a/web/storybook/docs/ThemeTokens.mdx b/web/storybook/docs/ThemeTokens.mdx
new file mode 100644
index 0000000000..302d4b86b6
--- /dev/null
+++ b/web/storybook/docs/ThemeTokens.mdx
@@ -0,0 +1,168 @@
+import { Meta } from "@storybook/addon-docs/blocks";
+
+<Meta title="Theme Tokens" />
+
+export const Swatch = ({ token, css }) => (
+ <div className="flex min-w-0 flex-col gap-1">
+ <div
+ className="border-border h-12 w-full rounded-md border"
+ style={{ backgroundColor: css ?? `hsl(var(--${token}))` }}
+ />
+ <div
+ className="text-muted-foreground font-mono text-xs leading-tight"
+ style={{ fontSize: "0.75rem" }}
+ >
+ --{token}
+ </div>
+ </div>
+);
+
+export const PairChip = ({ bg, fg, label = "Aa β€” sample text" }) => (
+ <div className="flex min-w-0 flex-col gap-1">
+ <div
+ className="border-border flex h-12 items-center justify-center rounded-md border px-2 text-xs font-bold"
+ style={{
+ backgroundColor: `hsl(var(--${bg}))`,
+ color: `hsl(var(--${fg}))`,
+ }}
+ >
+ {label}
+ </div>
+ <div
+ className="text-muted-foreground font-mono text-xs leading-tight"
+ style={{ fontSize: "0.75rem" }}
+ >
+ --{bg} / --{fg}
+ </div>
+ </div>
+);
+
+export const TokenGrid = ({ children }) => (
+ <div className="storybook-token-grid">{children}</div>
+);
+
+export const semanticPairs = [
+ "primary",
+ "secondary",
+ "tertiary",
+ "accent",
+ "destructive",
+];
+
+export const statusPairs = [
+ ["light-red", "dark-red"],
+ ["light-yellow", "dark-yellow"],
+ ["light-green", "dark-green"],
+ ["light-blue", "dark-blue"],
+ ["accent-light-green", "accent-dark-green"],
+ ["accent-light-blue", "accent-dark-blue"],
+];
+
+# Theme Tokens
+
+## Surfaces
+
+<TokenGrid>
+ <PairChip bg="background" fg="foreground" />
+ <PairChip bg="card" fg="card-foreground" />
+ <PairChip bg="popover" fg="popover-foreground" />
+ <PairChip bg="header" fg="header-foreground" />
+ <PairChip bg="muted" fg="muted-foreground" />
+ <PairChip bg="background" fg="foreground-tertiary" label="faint text" />
+ <Swatch token="border" />
+ <Swatch token="border-contrast" />
+ <Swatch token="input" />
+ <Swatch token="ring" />
+ <Swatch token="surface-code" />
+</TokenGrid>
+
+## Semantic
+
+<TokenGrid>
+ {semanticPairs.map((name) => (
+ <PairChip key={name} bg={name} fg={`${name}-foreground`} label={name} />
+ ))}
+</TokenGrid>
+
+## Langfuse Accents
+
+<TokenGrid>
+ {[
+ "primary-accent",
+ "link",
+ "link-hover",
+ "control-fill",
+ "control-track",
+ "muted-blue",
+ "muted-green",
+ "muted-magenta",
+ "muted-gray",
+ ].map((token) => (
+ <Swatch key={token} token={token} />
+ ))}
+</TokenGrid>
+
+## Status and Accent Pairs
+
+<TokenGrid>
+ {statusPairs.map(([bg, fg]) => (
+ <PairChip key={bg} bg={bg} fg={fg} label={bg.replace("light-", "")} />
+ ))}
+</TokenGrid>
+
+## Search Grammar
+
+<TokenGrid>
+ {["qlang-field", "qlang-value", "qlang-number", "qlang-keyword"].map(
+ (token) => (
+ <Swatch key={token} token={token} />
+ ),
+ )}
+</TokenGrid>
+
+## Sidebar
+
+<TokenGrid>
+ <PairChip bg="sidebar-background" fg="sidebar-foreground" />
+ <PairChip bg="sidebar-primary" fg="sidebar-primary-foreground" />
+ <PairChip bg="sidebar-accent" fg="sidebar-accent-foreground" />
+ <Swatch token="sidebar-border" />
+ <Swatch token="sidebar-ring" />
+</TokenGrid>
+
+## Find Match
+
+<TokenGrid>
+ <PairChip bg="find-match-background" fg="foreground" label="match" />
+ <PairChip
+ bg="find-match-selected-background"
+ fg="find-match-selected-foreground"
+ label="selected match"
+ />
+</TokenGrid>
+
+## Charts
+
+<TokenGrid>
+ {Array.from({ length: 8 }, (_, index) => (
+ <Swatch key={index} token={`chart-${index + 1}`} />
+ ))}
+ <Swatch token="chart-grid" />
+</TokenGrid>
+
+## Heatmap
+
+<TokenGrid>
+ {Array.from({ length: 5 }, (_, index) => (
+ <Swatch
+ key={index}
+ token={`color-${index + 1}`}
+ css={`var(--color-${index + 1})`}
+ />
+ ))}
+</TokenGrid>
+
+---
+
+Tokens live in `web/src/styles/globals.css`. This page reads them directly, so
+the reference stays aligned with the application theme.
diff --git a/web/storybook/docs/WritingGoodStories.mdx b/web/storybook/docs/WritingGoodStories.mdx
new file mode 100644
index 0000000000..a9bd60b45c
--- /dev/null
+++ b/web/storybook/docs/WritingGoodStories.mdx
@@ -0,0 +1,107 @@
+import { Meta } from "@storybook/addon-docs/blocks";
+
+<Meta title="Writing Good Stories" />
+
+# Writing Good Stories
+
+## Which Components Can Have Stories?
+
+Only create stories for components that **do not** do any of the following:
+
+- Depend on context.
+- Fetch data via any private API, including Langfuse’s own tRPC API.
+
+Stories should follow the `ComponentName.stories.tsx` filename pattern. Components covered by stories should have exactly one exported or public component.
+
+If this is not the case, suggest splitting up the file that includes the component to be covered first.
+
+Be mindful of the breadth a story covers. A story should show a component in isolation. Page-level compositions should be rare and intentional.
+
+## What to Do If a Component Violates the Criteria
+
+Suggest abstracting a presentational component that does not violate the criteria and receives relevant data via props.
+
+Make sure the props are well-defined using TypeScript.
+
+Keep the existing component, but update it to use the newly created component for rendering. These presentational components are easier to test and easier to reuse.
+
+## How Stories Should Be Written
+
+- Use "CSF Next" format by default.
+- Cover only the relevant component by default.
+- Do not use `args` on the meta story if most stories override these. Instead, define the args on each story.
+- Avoid custom render functions by default.
+- Do not define helper components inside story files unless the helper component is reused by multiple stories. For one-off setup, inline the stateful render logic directly in the story `render` function.
+- Never use `decorators` to add styling or layout to a story. Stories should render the components as they are.
+- Use `satisfies` and typed Storybook metadata so invalid args, decorators, and play functions are type-checked.
+- Use play functions to test user-relevant interactions after render, not to compensate for complex setup or hidden dependencies.
+- Prefix stories whose primary purpose is interaction test coverage with `(Test)` in the Storybook display name, for example `name: "(Test) Opens Menu"`.
+- Keep `(Test)` stories sorted at the bottom of the file so showcase and product-facing stories stay grouped first.
+- Name stories after the state they represent, not the implementation. Also do not include the component name in the story name.
+ - Prefer: `Default`, `Empty`, `WithLongName`, `Error`, `Disabled`, `Loading`
+ - Avoid: `Test1`, `CustomRenderExample`, `ButtonWithLongNameAndIcon`
+- Set callbacks up as Storybook Actions by default:
+
+ ```ts
+ import { fn } from "storybook/test";
+ ```
+
+- Avoid large fixtures.
+- Use the smallest meaningful data shape needed to render the state.
+- If fixtures are required and may be shared, check whether a reusable helper function exists. Otherwise, create one for defining the fixture.
+
+## Variant and Design Showcase Stories
+
+If a component has many variants, and the point of the story is to showcase the design of a component rather than its functionality, stories may render the component multiple times.
+
+For example, a `Button` with a `size: "sm" | "md" | "lg"` prop may have a story that shows three buttons side by side.
+
+If the button also has a `variant: "primary" | "secondary"` prop, consider using a matrix-like UI that showcases all possible combinations.
+
+Name a story that renders this kind of variant grid `VariantMatrix` so it appears as **Variant Matrix** in Storybook. Do not use generic names such as `AllVariants`.
+
+These compositional stories **should not** contain Storybook play functions. They should also not allow the Storybook user to customize the predefined args, such as `size` and `variant`, via Storybook args. Having an arg for non-bound props, such as `text`, may be acceptable.
+
+## Authoring MDX Docs
+
+- Use `.mdx` for prose docs and guides that sit alongside stories.
+- Keep `.mdx` files simple by default: standard markdown plus Storybook docs blocks such as `Meta` and `Canvas` are usually enough.
+- Do not build bespoke page layouts in `.mdx` with exported inline-styled React components unless there is a strong reason.
+- If docs need reusable typography, spacing, or docs-page chrome, add that once in Storybook preview/docs container setup rather than re-implementing it in a single `.mdx` file.
+- Keep illustrative examples in `.stories.tsx`; keep narrative and explanation in `.mdx`.
+- If an example needs a small wrapper in a story, keep it minimal and focused on presenting the example rather than recreating page design inside Storybook.
+
+### Placing MDX Docs
+
+Attach component-specific guidance to its stories:
+
+```mdx
+import * as ComponentStories from "./ComponentName.stories";
+
+<Meta of={ComponentStories} name="Guidance" />
+```
+
+Pass the full story module to `of` and colocate the MDX file with the component.
+Use a standalone page only when its guidance spans multiple components and has
+no single story file it naturally belongs to.
+
+### Docs-Only Backing Stories
+
+When a CSF file exists only to provide examples for `Canvas` blocks in a
+manually authored MDX page, remove the built-in `dev` tag at meta level:
+
+```tsx
+const meta = preview.meta({
+ component: ExampleComponent,
+ tags: ["!dev"],
+});
+```
+
+This keeps the stories indexed and renderable from MDX while hiding them from
+the Storybook sidebar. They remain eligible for Storybook tests by default.
+Do not create a separate sidebar section for these backing stories, and do not
+add `autodocs` when the MDX page is manually authored.
+
+## Additional Information
+
+- We do not use MSW and are not planning to add it.