0
Fork 0
mirror of https://github.com/mastra-ai/mastra.git synced 2026-11-17 08:44:46 +00:00
mastra/packages/playground-ui
History 2026-11-12 21:12:29 +00:00
..
.cursor/rules chore: add Claude Code skills for React and Tailwind best practices (#12090) 2026-01-20 14:36:56 +01:00
.storybook fix(ui): use Mona Sans's default letters in Studio and share fonts from Playground UI (#29915) 2026-11-10 20:42:54 +04:00
fonts fix(ui): use Mona Sans's default letters in Studio and share fonts from Playground UI (#29915) 2026-11-10 20:42:54 +04:00
oxlint chore(ui): standardize metadata layout and enforce copy lint (#29312) 2026-11-04 16:15:13 +01:00
scripts feat(playground-ui): live updates for the Spans and Threads lists (#28591) 2026-10-27 14:25:10 +01:00
src feat(ui): one settings layout across Studio, Factory and Platform (#29400) 2026-11-12 18:05:50 +04:00
theme fix(ui): use Mona Sans's default letters in Studio and share fonts from Playground UI (#29915) 2026-11-10 20:42:54 +04:00
.gitignore test(playground-ui): raise mutation score on 20 files from ~55% to 89% (#22182) 2026-08-24 14:01:53 +02:00
.oxfmtrc.json chore(playground): configure oxfmt tailwind class sorting (#24682) 2026-09-22 20:08:29 +02:00
agent.md chore: remove playground-ui root barrel exports (#18791) 2026-07-02 17:42:05 +02:00
AGENTS.md perf(ui): cut Playground UI build from ~16.5 s to ~3.5 s by using TypeScript 7 (#27815) 2026-10-23 11:40:20 +04:00
CHANGELOG.md chore: version - exit prerelease mode 2026-11-12 21:12:29 +00:00
CLAUDE.md Add a full playground development command (#21747) 2026-08-18 15:08:30 +02:00
components.css fix(ui): fix hover highlight not covering the corner (#30047) 2026-11-12 14:07:56 +04:00
components.json feat(playground): migrate to Tailwind CSS v4 (#14772) 2026-03-30 10:49:00 +02:00
fonts.css fix(ui): use Mona Sans's default letters in Studio and share fonts from Playground UI (#29915) 2026-11-10 20:42:54 +04:00
index.html feat(studio): finish light mode support (#14796) 2026-03-30 15:40:20 +02:00
lint-staged.config.js refactor(lint): replace ESLint with type-aware oxlint (#27476) 2026-10-18 10:38:35 -07:00
oxlint.config.ts chore(ui): standardize metadata layout and enforce copy lint (#29312) 2026-11-04 16:15:13 +01:00
package.json chore: version - exit prerelease mode 2026-11-12 21:12:29 +00:00
README.md fix(ui): use Mona Sans's default letters in Studio and share fonts from Playground UI (#29915) 2026-11-10 20:42:54 +04:00
sources.css feat(playground-ui): ship sources.css so app Tailwind builds scan the components (#27178) 2026-10-16 09:22:48 +02:00
stryker.config.json test(playground): add targeted mutation testing (#21848) 2026-08-19 10:23:56 +02:00
theme.css fix(playground-ui): DatePicker fills its container; time Input shows a design-system clock (#29769) 2026-11-10 13:54:22 +04:00
tsconfig.app.json chore: upgrade TypeScript from 5.9.3 to 6.0.3 (#15884) 2026-04-29 10:18:03 -07:00
tsconfig.build.json perf(ui): cut Playground UI build from ~16.5 s to ~3.5 s by using TypeScript 7 (#27815) 2026-10-23 11:40:20 +04:00
tsconfig.json chore(playground-ui): enable noUncheckedIndexedAccess (#18860) 2026-07-06 10:06:13 +02:00
vite.config.ts fix(ui): stop hover highlights gliding between items (#28757) 2026-10-29 18:50:07 +04:00
vitest.config.ts feat(mcp-apps-components): add prebuilt MCP Apps with a dashboard renderer (#29321) 2026-11-04 10:41:58 -08:00

@mastra/playground-ui

Reusable React components, hooks, domains, and design tokens used by Mastra Studio. It provides the UI building blocks for logs, memory, metrics, traces, and agent management.

Installation

npm install @mastra/playground-ui

Usage

Import the package styles once in your React application.

import '@mastra/playground-ui/style.css';
import { Button } from '@mastra/playground-ui/components/Button';

export function SaveButton() {
  return <Button>Save</Button>;
}

With a Tailwind build of your own, compile one sheet instead of style.css: import the components' stylesheet uncompiled, and sources.css so Tailwind emits the classes the compiled components use.

@import 'tailwindcss';
@import '@mastra/playground-ui/components.css';
@import '@mastra/playground-ui/sources.css';

To use Mastra's product fonts, Mona Sans for text and Commit Mono for code, add fonts.css. The font files ship inside the package as woff2, split by script so a page only downloads the characters it renders, and the stylesheet points the font tokens at them. Without it, text uses the system font stacks.

@import '@mastra/playground-ui/fonts.css';

Metadata

Use separate elements for metadata fields. Metadata keeps a compact gap between fields, and Metadata.Item groups an icon with its label. Fields wrap as space narrows.

Rows that must keep one line, such as cards, menu options, and truncated titles, pass singleLine: fields stay on one line and each shrinks with an ellipsis. Give a short field className="shrink-0" to keep it whole while a longer one truncates.

import { Metadata } from '@mastra/playground-ui/components/Metadata';
import { Txt } from '@mastra/playground-ui/components/Txt';

<Metadata>
  <Metadata.Item>
    <Txt as="span" variant="label">
      v8
    </Txt>
  </Metadata.Item>
  <Metadata.Item>
    <Txt as="span" variant="caption" tone="muted">
      Nov 3, 2026, 10:24 AM
    </Txt>
  </Metadata.Item>
  <Metadata.Item>
    <Txt as="span" variant="caption" tone="muted">
      (current)
    </Txt>
  </Metadata.Item>
</Metadata>;

Use normal sentences in tooltips, accessible names, and other plain-text APIs. Parentheses such as (current) and missing-value placeholders remain useful; avoid decorative separators or repeated spaces as a substitute for layout. Browser tab titles set through document.title keep the Page | Product convention.

Data sizes

Import formatBytes from the number utility:

import { formatBytes } from '@mastra/playground-ui/utils/number';

formatBytes(1536);
formatBytes(0.5, { unit: 'GB' });
formatBytes(2048, { unit: 'GB', autoScale: false });
formatBytes(0.5, { unit: 'GB', autoScale: true });
formatBytes(2048, { unit: 'GB', autoScale: true });

These calls return 1.5 KB, 0.5 GB, 2048 GB, 512 MB, and 2 TB, respectively.

With no options, formatBytes(bytes) keeps its existing automatic byte formatting and rounding. With a source unit, the formatter keeps the supplied value and unit unchanged unless autoScale: true. The supported units are B, KB, MB, GB, TB, and PB, also exported as the ByteUnit type.

Conversions use the helper's existing binary convention: each unit is 1024 of the previous unit, despite the legacy KB through PB labels. These are not decimal SI conversions, where each step is 1000. Convert decimal measurements to this convention before passing them in.

Automatic scaling stops at B and PB. It rounds bytes and values of 10 or more to whole numbers, and smaller values in larger units to one decimal place. When rounding reaches 1024, the opt-in mode promotes to the next unit, except at PB. Zero becomes 0 B in automatic mode and keeps its source unit otherwise. Negative, non-finite, null, and undefined measurements return undefined in every mode.

Subtle buttons

Use variant="subtle" for a persistent neutral fill, such as a selected view. It keeps the same dimensions as default, so switching between the two does not move surrounding controls. Set aria-pressed on toggle buttons to expose selection to assistive technology.

<Button variant={selected ? 'subtle' : 'default'} aria-pressed={selected}>
  My PRs
</Button>

Tool icons

presentTool from @mastra/playground-ui/components/ai/tool-call gives a tool call its label, detail, static icon, and animated AgentIndicator pose. Use it wherever a tool call is shown, so a running call and its finished card look the same.

import { AgentIndicator } from '@mastra/playground-ui/components/AgentIndicator';
import { presentTool } from '@mastra/playground-ui/components/ai/tool-call';

const { pose, label, detail } = presentTool(call.toolName, call.args);

<AgentIndicator state={pose} />;

Always pass the call's arguments. Tools such as knowledge_page take an operation (op or action), and the icon and label follow it, so deleting a page does not look like editing one. Workspace prefixes (mastra_workspace_), MCP names (mcp__server__tool), namespace.tool names, and known aliases resolve to the tool they wrap. Unknown tools and ambiguous names such as mcp__catalog__search keep the generic tool icon.

The AI / Activity / Tool Icon Families Storybook story shows every family and lets you switch actions to watch the morph.

Tool approvals

ToolApproval renders a standalone approval request in the shared activity layout: the tool name with its decision status, the full tool arguments (file previews included), and the Approve and Decline actions.

import { ToolApproval } from '@mastra/playground-ui/components/ai/tool-approval';

<ToolApproval
  toolName="write_file"
  args={{ path: 'src/agent.ts', content: 'export const name = "Assistant";' }}
  disabled={isSubmitting}
  status={decision}
  onApprove={approve}
  onDecline={decline}
/>;

A tool that already renders its own activity composes the parts instead: ToolApprovalStatus beside the tool name, ToolApprovalActions in the details while the request is pending.

import { ToolApprovalActions, ToolApprovalStatus } from '@mastra/playground-ui/components/ai/tool-approval';

<>
  <ActivityHeadline icon={icon} label={label} badges={<ToolApprovalStatus status={decision} />} />
  {!decision && <ToolApprovalActions toolName="write_file" onApprove={approve} onDecline={decline} />}
</>;

The consumer owns submission, error feedback, and the optional approved or declined status. A decision removes the actions; clearing it restores them for a retry. disabled blocks both decisions without implying server confirmation. autoFocus focuses Approve on mount. Custom children replace the default argument preview. Examples live under AI / Tool Approval in Storybook.

Agent questions

Use AskUser to render an agent's ask_user payload with shared answer handling:

import { AskUser } from '@mastra/playground-ui/components/ai/ask-user';

<AskUser
  payload={{ question: 'Choose a deployment target', options: [{ label: 'Staging' }] }}
  onSubmit={handleAnswerSubmit}
/>;

For custom layouts, compose the controls inside AskUser.Root. The root owns selection, custom text, validation, and submission. AskUser.Question names the group and its inputs for assistive technology.

import * as AskUser from '@mastra/playground-ui/components/ai/ask-user';

<AskUser.Root key={prompt.id} selectionMode="single_select" disabled={isSubmitting} onSubmit={handleAnswerSubmit}>
  <AskUser.Body>
    <AskUser.Question>Choose a deployment target</AskUser.Question>
    <AskUser.Options>
      <AskUser.Option value="Staging" description="Validate the release before production.">
        Staging
      </AskUser.Option>
      <AskUser.Option value="Production">Production</AskUser.Option>
      <AskUser.CustomAnswer />
    </AskUser.Options>
    <AskUser.Submit when="custom-answer" className="mt-2" />
  </AskUser.Body>
</AskUser.Root>;

Single-select options submit their value immediately. when="custom-answer" shows the submit control only while Other… is selected. For multi-select prompts, use selectionMode="multi_select" and omit when to keep the submit control visible. You can position the submit control anywhere inside the root.

Selecting Other… focuses an inline text field. Empty or whitespace-only text unselects it on blur. Non-empty drafts stay selected, and unchecking Other… excludes its text from submission. Answers remain string for single-select and free-text prompts, and string[] for multi-select prompts.

For a free-text prompt, replace AskUser.Options with AskUser.TextAnswer and omit when from the submit control. Use AskUser.Pending for a submitting message or AskUser.Output with a result to display an answer. Reset the draft by changing the root's key when switching prompts. The payload-based card handles question changes automatically.

Interactive examples live under AI / Ask User in Storybook, including composed layouts with the submit control outside the options.

Tables

Table variant="inset" renders a data table from the native table, thead, tbody, tr, th, and td elements with the same raised surface as DataList. Each part takes its element's props, so colSpan and aria-* work as they do in HTML, and any component can go in a cell.

import { Table } from '@mastra/playground-ui/components/Table';

export function CreditHistory({ credits }: { credits: Credit[] }) {
  return (
    <Table variant="inset" aria-labelledby="credit-history">
      <Table.Header>
        <Table.Row>
          <Table.Head>Type</Table.Head>
          <Table.Head className="w-full">Description</Table.Head>
          <Table.Head align="end">Balance</Table.Head>
        </Table.Row>
      </Table.Header>
      <Table.Body>
        {credits.map(credit => (
          <Table.Row key={credit.id}>
            <Table.Cell>
              <Table.RowLink href={`/billing/credits/${credit.id}`}>{credit.type}</Table.RowLink>
            </Table.Cell>
            <Table.Cell>{credit.title}</Table.Cell>
            <Table.Cell align="end">{credit.balance}</Table.Cell>
          </Table.Row>
        ))}
      </Table.Body>
    </Table>
  );
}
  • Table takes variant="inset" for the DataList surface. Omit variant to preserve the existing default appearance and sizing. columnDividers draws lines between columns in inset mode.
  • Table.Head takes align (start, center, or end).
  • Table.Cell takes align and tone (ink or muted).
  • Every column is the same color. Use Txt tone="muted" only for secondary text inside a cell, such as a second line, or mute every column except the first.
  • Table.SortButton goes inside a sortable Table.Head and shows the sort arrow.
  • Table.RowLink makes the whole row a link. Table.RowButton makes it a button, for opening a drawer or dialog. Pass render={<Link to="…" />} for a router link.
  • Table.Pagination goes below the table: Previous, numbered pages, and Next. It takes a zero-based page, pageCount, and onPageChange. The caller supplies the current page’s rows, from a local slice or a server query.
  • Text is left-aligned; numbers are right-aligned with align="end" on the head and cells. Negative amounts keep their minus sign and use tone="muted"; never red, since usage isn't an error.
  • Rows are at least 36px tall and grow with their content. Cells stay on one line unless you wrap their text in an element with whitespace-normal.

Use Table for data people read and compare, such as billing history or usage. Use DataList for lists of entities people click into, such as agents or traces, which need row keyboard navigation, sticky or reorderable columns, or virtualization. Search and filters go in an ActionRow above either one. Choose based on the rows rendered at once, not the total dataset size; large server-paginated datasets can use Table.

The full guide, with recipes for column dividers, editable cells, sorting, client-side and server-side pagination, loading, and empty states, is the DataDisplay / Table docs page in Storybook.

Legacy named parts remain supported. Thead creates its own row; Table.Header takes an explicit Table.Row. In inset mode, className applies to the outer surface and native props (including ref and style) apply to the table.

Pagination

Pagination is page navigation built from parts, shaped like shadcn's: Pagination, PaginationContent, PaginationItem, PaginationLink, PaginationPrevious, PaginationNext, and PaginationEllipsis. The current page wears a raised pill that slides between pages, and a fluid highlight follows the pointer. The caller owns the page.

import {
  Pagination,
  PaginationContent,
  PaginationEllipsis,
  PaginationItem,
  PaginationLink,
  PaginationNext,
  PaginationPrevious,
  getPaginationRange,
} from '@mastra/playground-ui/components/Pagination';

<Pagination aria-label="Credit history pages">
  <PaginationContent>
    <PaginationItem>
      <PaginationPrevious disabled={page === 0} onClick={() => setPage(page - 1)} />
    </PaginationItem>
    {getPaginationRange(page, pageCount).map(item => {
      if (item.kind === 'ellipsis') {
        return (
          <PaginationItem key={item.key}>
            <PaginationEllipsis />
          </PaginationItem>
        );
      }
      return (
        <PaginationItem key={item.page}>
          <PaginationLink isActive={item.page === page} onClick={() => setPage(item.page)}>
            {item.page + 1}
          </PaginationLink>
        </PaginationItem>
      );
    })}
    <PaginationItem>
      <PaginationNext disabled={page === pageCount - 1} onClick={() => setPage(page + 1)} />
    </PaginationItem>
  </PaginationContent>
</Pagination>;
  • Page indexes are zero-based. getPaginationRange(page, pageCount) returns the pages to show, with ellipses past seven pages.
  • PaginationLink renders a button. Pass render={<a href="?page=2" />}, or a router link, when each page has a URL.
  • disabled keeps Previous and Next in place and focusable, and ignores their clicks.
  • For a table, Table.Pagination takes page, pageCount, and onPageChange and renders this composition for you.

Semantic color tokens

theme.css declares the semantic color tokens (--background, --card, --foreground, and friends) at the document root, so utilities such as bg-card and text-foreground resolve anywhere in the app, portalled content included. Importing style.css once is enough to get both the compiled utilities and those tokens.

Semantic values follow the existing html.light mode; dark mode is the default. Override --card, --foreground, or another semantic variable on an element to recolor its subtree.

Surfaces

Token Utility Used for
--background bg-background The page canvas
--sidebar bg-sidebar App chrome, one step behind the canvas
--card bg-card Cards, panels, settings sections
--popover bg-popover Menus, dropdowns, tooltips
--dialog bg-dialog Dialogs, drawers, alert dialogs. Off-white in light mode so fields inside stand out
--muted bg-muted A quiet region inside a container

Fields

Text fields, textareas, input groups, and the default Select, Combobox, and DateTimePicker triggers read their fill and outline from these tokens. You don't set them at the call site: cards, overlays, and dialogs set them for every field inside, so a field is never darker than the surface it sits on.

Token Utility Used for
--field bg-field Field fill. --card on the page, --field-on-surface inside a card, overlay, or dialog
--field-on-surface none Field fill inside a surface: one step lighter in dark mode, white in light mode
--field-disabled bg-field-disabled Disabled field fill
--field-rim none Resting outline. Stronger inside white surfaces in light mode
--field-rim-focus none Focus outline

A field in an error state sets --field-rim and --field-rim-focus to --destructive-indicator, so the red outline shows on every surface and stays red while focused.

If your app keeps style.css and generates additional semantic utilities, import @mastra/playground-ui/theme.css into its Tailwind stylesheet so Tailwind can read the @theme inline mappings. components.css already includes it.

Brand colors

The fixed Mastra palette is available as --color-brand-green, --color-brand-orange, --color-brand-pink, --color-brand-purple, --color-brand-blue, --color-brand-red, and --color-brand-yellow. These values do not change with the theme. Utilities use names such as bg-brand-green.

Chromatic roles

Eight shared ramps (red, orange, amber, green, cyan, blue, purple, and pink) run from 50 to 950. Status roles select steps from those ramps for each theme:

.status {
  background: var(--success-subtle);
  border: 1px solid var(--success-edge);
  color: var(--success-subtle-foreground);
}

.status-dot {
  background: var(--success-indicator);
}

The same four suffixes apply to destructive, warning, and info. Backgrounds are opaque. Use -subtle-foreground only for text on a -subtle surface. Dots, bars, chart marks, and invalid-field borders use -indicator. Standalone destructive and warning text and icons use --destructive-foreground and --warning-foreground, because those indicator fills are too light to read as text in light mode. Success and info text use -indicator. The filled destructive button uses --fill-destructive and its hover, active, and disabled steps, with --fill-destructive-foreground for its text.

Product roles use --product-{name} and --product-{name}-foreground. Names are studio, server, observability, factory, workers, and persistent-server. Use ProductAvatar for the round icon and ProductBadge for the icon with its label. Both take a product prop and use the matching semantic colors.

import { ProductAvatar } from '@mastra/playground-ui/components/ProductAvatar';
import { ProductBadge } from '@mastra/playground-ui/components/ProductBadge';

<ProductAvatar product="studio" />
<ProductBadge product="persistent-server" />

Charts use hue-named roles for categories (--chart-blue, --chart-blue-deep, --chart-amber, --chart-green, --chart-purple, --chart-orange, --chart-pink, --chart-red) and --chart-sequential-1 through --chart-sequential-5 for ordered values. Span colors use --span-agent, --span-workflow, and the other span names. Pastel chart colors are fills, not text colors; keep labels on --foreground or --muted-foreground.

Numbered accent* tokens, positive1, negative1, warning1, notice-success/destructive/warning/info, and --brand-green-* are removed. The yellow ramp is now amber: --yellow-*, --yellow-soft-*, --badge-yellow-*, --chart-yellow, and the Badge yellow tone are removed in favor of their amber names. --color-brand-yellow is unchanged. Status consumers use the existing success, destructive, warning, or info roles. Focus styling uses border-focus; categorical charts and span icons use their own roles. CodeMirror reads five --syntax-* roles from theme/code.css, not a global palette.

Every badge hue (green, red, amber, blue, purple, orange, cyan, pink) is a categorical tone built from the ramps, with --badge-{hue}-strong, -subtle, -edge, -foreground, and -indicator. -strong and -subtle are the fills behind emphasis="strong" and emphasis="subtle". Badge backgrounds are translucent tints, so a badge follows the surface under it when a card or row changes on hover: --{hue}-600 at 32% (strong) and 13% (subtle) in dark mode, --{hue}-400 at 20% and 10% in light mode. On a resting card they match the solid fills they replaced. Product avatars stay solid (--{hue}-soft-900 / --{hue}-soft-950 in dark mode, --{hue}-100 / --{hue}-50 in light mode) because they overlap each other. The soft steps keep the lightness and hue of 900/950 at 75% chroma, and are available as utilities such as bg-green-soft-900. --badge-{hue}-indicator colors dots, icons, and labels for a category: --{hue}-soft-300 in dark mode and --{hue}-soft-600 in light mode, which hold every hue at the same 0.1 chroma so no hue shouts. Use the status role with -subtle, -edge, -subtle-foreground, or -indicator for its intended job. Notice variants are unchanged. Badge status variants are success, destructive, warning, and info, for states. green, red, amber, and blue are categorical tones like purple and orange, for labels that are not states. Badge takes emphasis="strong" (the default) or emphasis="subtle" (a quieter tinted fill). Use --green-* for the shared chromatic ramp.

Opacity and literal colors

Opaque surfaces, text, notices, product avatars, and chart colors use solid ramp steps in both themes. Span colors use solid values in data-viz.css. The theme also defines translucent fills and borders whose appearance intentionally depends on the surface beneath them.

Opacity is allowed only through design-system tokens, for layers whose job is to show what is underneath:

  • State layers over an existing surface: fill, fill-subtle, fill-hover, fill-active, and fill-strong.
  • Scrims and overlays: scrim.
  • Badge fills: badge-{hue}-strong and badge-{hue}-subtle, so a badge tints with the card or row it sits on.
  • Neutral hairlines: the border ladder, surface-rim, field/inset rims, and gray-alpha-*.
  • Effects that fade, glow, or animate inside a design-system component, such as the Composer ring and the sidebar meter bloom.

Product code does not add opacity modifiers (bg-green-500/20) or color-mix() to chromatic colors, and does not write literal colors (#hex, rgb(), oklch()) outside the theme. Masks, brand marks, and screens that render before the theme loads are the exceptions.

Border roles

Choose a role at its authored opacity. Avoid extra modifiers such as border-border/50 or border-border-strong/40. Existing roles cover the following uses without adding a new token value:

Role Token / utility Use
Surface edge --surface-rim / border-surface-rim App frame, panel and card edges; frame headers that meet them
Content divider --border / border-border Internal separators and filled control edges
Outlined control --border-strong / border-border-strong Transparent controls at rest
Hover / focus --border-hover, --border-focus Interactive control states
Field edge --field-rim, --field-rim-on-surface, --field-rim-focus Field recipes resolve the edge for their parent surface and focus state
Badge / avatar trim --inset-highlight, --inset-rim shadow-inset combines a top highlight and rim

border-surface-rim is an inline Tailwind alias of the existing --surface-rim, also exported in BorderColors. It resolves local overrides on the styled element. shadow-rim draws this same color inside the box; shadow-raised and shadow-overlay combine it with a lip and drop shadows. Do not add a border on an edge those recipes already draw. MainCard reserves 1px for its inset rim so child dividers cannot overlap it.

Header is a layout primitive: every instance uses border-surface-rim, matching the surrounding frame or panel. Call sites do not choose a tone. border={false} hides the edge. Internal content separators use border-border directly or a separator component.

Storybook's Foundations/Surface renders border tokens as isolated 1px edges on named backgrounds, with composed surfaces labeled separately. Foundations/Elevation shows the full recipes and each inset edge separately. Switch themes to inspect the actual token values in context; no extra opacity is applied to these previews.

To migrate removed tokens:

Removed token Replacement
--chart-soft-N --chart-sequential-N
--span-type-NAME --span-NAME
accent1, positive1 success-*
accent2, negative1 destructive-*
accent6, warning1 warning-*
accent3, accent5 info-*
error destructive-indicator
notice-STATUS STATUS-subtle, STATUS-subtle-foreground
--brand-green-N --green-N
destructive, destructive-foreground fill-destructive, fill-destructive-foreground
badge-HUE, badge-HUE-fg badge-HUE-strong, badge-HUE-foreground
notice-note, notice-note-fg muted, foreground
--ring, ring-ring --border-focus, ring-border-focus
--shadow-focus-ring, --focus-halo none; focus has no halo
--surface-rim-focus, --field-rim-focus-on-surface --border-focus
focusRing.visible and siblings focusRing, or focusRingInset in clipped rows

Keyboard focus is a 1px --border-focus outline on :focus-visible, and the base layer draws it on any focusable element that does not style its own. focusRing from primitives/transitions applies it explicitly, focusRingInset draws it inside a full-bleed row whose edge is clipped, and focusRingOffset sets it 2px out on checkboxes, radios, switches, and filled primary and destructive buttons, where a flush line vanishes into the fill. It is an outline, not a ring-*, because a ring rewrites box-shadow and would erase a raised surface's rim. Fields, buttons, and clickable cards show focus on that rim instead: surfaceRimFocus from primitives/form-element repaints it to --border-focus, the same colour and weight, and the surface keeps its elevation.

SankeyChart accepts getNodeColor and getLinkColor callbacks returning CSS colors. Explicit link colors keep the default link transparency and hover emphasis:

<SankeyChart getNodeColor={() => 'var(--span-agent)'} getLinkColor={() => 'var(--chart-blue)'} />

Foundations/Color has one story each for monochrome and chromatic ramps, semantic roles, products, charts, span types, and brand colors. Badge and avatar examples live in Elements/Products; the semantic Sankey example lives in Metrics/SankeyChart.

Typography

Text uses roles, not sizes. A role such as body-sm or caption sets size, line height, weight, and tracking together. Render text with Txt, or use the matching text-<role> utility inside a component's own markup.

Roles use two weights. Regular (--font-weight-normal, 465) is for anything read: body, body-sm, caption, lead, and menu. Strong (--font-weight-medium, 515) is for anything that labels or heads something: label, column, eyebrow, meta, and every heading role. Text without a role inherits regular. font-normal and font-medium resolve to the same two weights, so inline emphasis such as a highlighted name in a sentence stays on the scale. Before adding font-medium to a role, check whether another role already pairs that size with the strong weight: text-body font-medium is subheading, and text-body-sm font-medium is label.

Shared components own their typography. Use their existing size and semantic variant APIs, and let compound slots style direct children through inheritance. Use Txt for text that the call site owns. Do not add a generic text-role prop or wrap arbitrary children just to migrate a CSS class. A specialized surface can use the existing className escape hatch with a DS role when the component's defaults do not fit.

Floating menu rows, values, and search fields use menu: 13px text at the regular weight with a 20px line height and −0.01em tracking. DropdownMenu, ContextMenu, Select, and Combobox share this role; their triggers keep the button label role. Labels use the muted foreground tone, with lighter icons. Hover, keyboard highlight, and open submenus increase the contrast of both labels and icons together.

hero and lead share the responsive typography of welcome pages. eyebrow supplies the size, weight, tracking, and uppercase treatment of section labels. Use font="display" when the display family is needed independently of the role.

display-lg is the 28px role for plan prices and credit balances. display remains 22px. Use <Txt variant="display-lg">$250</Txt> without size or weight overrides.

Txt defaults to the body role. With as="strong" or as="b", omitting variant keeps the text bold; an explicit variant uses that role's weight.

Txt renders text elements: headings, paragraphs, inline text, labels, and timestamps. Use Code for preformatted code. Txt cannot render a button, input, link, table, list, or layout container, and has no render prop. Keep controls and layout on their own components and put Txt at the text leaf:

<div className="flex items-center gap-2">
  <Icon />
  <Txt as="span" variant="caption">Supporting copy</Txt>
</div>
<Link to="/runs">
  <Txt as="span" variant="caption">View runs</Txt>
</Link>
<Button onClick={run}>Run</Button>
<Input className="font-mono" aria-label="Setup command" />
<Tree.Label>src/index.ts</Tree.Label>

Input and Textarea derive typography from their size. DataPanel.SectionHeading owns its small-caps style and renders its icon and children directly; callers compose any custom label or action themselves. PageHeader.Meta and PageHeader.Eyebrow preserve their inherited text styles even for raw children. CodeEditor alone exposes a narrow font="body" | "mono" choice because its text lives inside CodeMirror: prose fields can use the body face while code defaults to mono.

import { Txt } from '@mastra/playground-ui/components/Txt';

<Txt variant="body-sm" tone="muted">
  Last run
</Txt>;

Card titles

Card titles use 13px text with a 150% line height. Choose the complete role rather than overriding a label’s weight or tracking.

Variant Weight Tracking Use
card-title 550 Normal Expanded card titles
card-title-tight 550 -0.025rem Compact work-item titles
card-title-strong 600 Normal Emphasized candidate titles
<Txt variant="card-title-tight" tone="ink">
  Review the deployment configuration
</Txt>

These roles preserve the existing Factory card typography. Control labels remain label at the strong weight.

Monospace

Monospace is a typeface, not another role. font="mono" swaps the family to --font-mono and keeps the role's size, line height, and weight, so a mono value lines up with the proportional text around it.

<Txt variant="caption" font="mono" tone="muted">
  run_01JQX8K2M4
</Txt>
Use mono for Keep in the body face
Model and resource IDs, versions, and hashes Labels, field names, and column headers
Timestamps and durations: Sep 23, 12:42, 412ms Counts, costs, scores, and percentages
Log lines Headings and page titles
Values a user copies or compares by character Status text and badges that name a state
Prose, descriptions, and empty-state copy

Time is mono: a timestamp marks a moment and a duration measures one, and both are machine values a user compares digit by digit. Other numbers (counts, costs, scores, percentages) stay in the body face; add tabular-nums where their digits should line up, such as table columns. Data visualization is the exception: KPI values, chart axes, and chart tooltips stay in the body face with tabular-nums, even for timestamps and durations, so a row of KPIs or a set of charts reads in one face.

Mono pairs with the text roles: body for logs, body-sm for values in tables and fields, caption for secondary identifiers, and meta for compact values such as versions. Heading roles stay proportional.

Product code never writes the font-mono class, and lint rejects it outside the design system. Use Txt font="mono" for identifiers, timestamps, and durations, InlineCode or CodeBlock for code, and tabular-nums for numbers. A raw <pre> or <code> element is already monospace.

--font-mono defaults to the system monospace stack, and fonts.css points it at Commit Mono. To use another face, override it in an unlayered rule in your own CSS, and every mono value follows.

At the same font size, a monospace face usually looks larger than the body face because its lowercase letters are taller. Set --font-mono-size-adjust to the body face's x-height ratio and mono text scales to match it. Measure the ratio for your body face; fonts.css sets 0.508 for Mona Sans. Keycaps (kbd) keep their full size, because they are single capitals and x-height matching would only shrink them.

:root {
  --font-mono: 'JetBrains Mono', ui-monospace, monospace;
  --font-mono-size-adjust: ex-height 0.508;
}

Code

Code is always marked as code, never plain mono text. Use InlineCode for a snippet, package name, variable, or command inside a sentence. It takes the size and color of the text around it, so it works in muted copy and inside a Notice. Use CodeBlock for anything longer than one line, and pass lang so it is syntax highlighted.

import { CodeBlock } from '@mastra/playground-ui/components/CodeBlock';
import { InlineCode } from '@mastra/playground-ui/components/InlineCode';

<Txt variant="body-sm" tone="muted">
  Set <InlineCode>OPENAI_API_KEY</InlineCode> to use this model.
</Txt>

<CodeBlock lang="ts" code={snippet} />

Billing usage meters

Meter keeps its red overage treatment by default. Set variant="over-allowance" for a warning segment and pass the amount charged in dollars through paidFromCredits:

import { Meter } from '@mastra/playground-ui/components/Meter';

<Meter
  variant="over-allowance"
  value={112}
  max={100}
  paidFromCredits={4.37}
  label="vCPU"
  aria-label="vCPU"
  aria-valuetext="112 of 100 vCPU-hours, 12 over"
/>;

The optional label slot accepts text or React content above the bar. Long labels truncate with an ellipsis to keep the label and caption on one line. The paid-from-credits caption sits on the right of that row, or above the bar on its own when no label is supplied. Keep supplying an accessible name through aria-label or aria-labelledby.

The caption reads “$4.37 paid from credits” only when usage exceeds the allowance and the charged amount is positive. It is linked to the meter’s accessible description, alongside any caller description and Meter.Source key. The meter does not calculate charges from usage. Meter.Source children still reveal the source breakdown on hover or keyboard focus.

See DataDisplay/Meter in Storybook for the billing states. Feedback/Dialog’s Resize while open story covers a full-size dialog and a form dialog crossing the 640px drawer breakpoint in either direction. Keep form drafts in caller-owned state when they must survive the popup remount.

Lint rules

The package ships its design-system lint rules as an oxlint JS plugin that apps on the design system can enable. Load the plugin and spread the recommended rules into your oxlint.config.ts:

import { copyRuleExclusions, recommended as playgroundUiRules } from '@mastra/playground-ui/oxlint';
import { defineConfig } from 'oxlint';

export default defineConfig({
  jsPlugins: ['@mastra/playground-ui/oxlint'],
  rules: { ...playgroundUiRules },
  overrides: [copyRuleExclusions],
});
Rule Flags
playground-ui/icon-button-size A <Button> holding only an icon without an icon-* size
playground-ui/text-role Tailwind text sizes (text-sm, text-[13px]) instead of a text role
playground-ui/txt-tone A text-foreground / text-muted-foreground / text-placeholder class on <Txt>
playground-ui/font-mono font-mono on <Txt>; { anywhere: true, allowIn: ['Input'] } checks every class string
playground-ui/no-barrel-imports Imports, re-exports and vi.mock() of the package root or a components/hooks/utils barrel
playground-ui/no-text-separators Decorative pipes, middots, bullets, spaced or double hyphens, and em dashes in authored UI copy
playground-ui/no-text-layout-spacing Repeated spaces, tabs, or nonbreaking spaces used to lay out UI copy

Turn rules off per glob in overrides, for example for tests and stories.

Copy rules

Use separate elements for metadata fields and normal punctuation for sentences. Parentheses such as (current) and standalone missing-value placeholders such as — are allowed.

The copy rules inspect JSX text, copy props, copy-named fields and helpers such as label, title, description, and meta, toast messages, and assignments to copy fields such as element.title. They follow local bindings and helper returns within the same file. Imported helper implementations and dynamic user content are not inspected.

Code, preformatted content, Markdown sources, agent prompts, tool descriptions, browser tab titles assigned to document.title, and technical style or schema fields are excluded. JSX source indentation is normalized before checking whitespace. The rules report without automatic fixes because a metadata row and a sentence need different replacements.

In this workspace, the copy rules apply only to the src trees in Playground, Playground UI, and Factory UI. Tests, stories, fixtures, and generated source are excluded.

Both rules are part of recommended. Consumers that need only these rules can use copyRules. Put copyRuleExclusions after the rule-enabling override to keep authored UI copy separate from test and story content.

The root pnpm lint command includes Playground, Playground UI, and Factory UI in regular CI linting. Run pnpm turbo lint --filter=@internal/playground to build its required dependency types and check Playground on its own. Documentation prose keeps its existing Vale and Remark checks.

Documentation

This README is the package guide. Import the global stylesheet once, then use the package's explicit components/*, domains/*, hooks/*, icons/*, primitives/*, store/*, tokens, and utils/* entry points rather than a package-root import.

Changelog

See the package changelog for version history and release notes.

Support

We have an open community Discord. Come and say hello and let us know if you have any questions or need any help getting things running.