React component library for building TetraScience applications.
Storybook | Contributing Guide
v1.0.0
This library provides:
- UI Components: shadcn/ui primitives (Radix UI) with Tailwind CSS
- Composed Components: TetraScience-specific compositions (AppHeader, Sidebar, etc.)
- Data Visualisation: Interactive charts powered by Plotly.js
- Theming: CSS custom properties (oklch) for light/dark mode
- TypeScript: Full type support with exported prop types
- React 19+
- Node.js 18+
- TypeScript 5.5+ (optional, but recommended)
| Library version | React | Node.js | TDP (server utilities) |
|---|---|---|---|
| v1.0.x | 19+ | 18+ | v4.x+ |
| v0.7.x | 19+ | 18+ | v4.x+ |
| v0.6.x | 19+ | 18+ | v4.x+ |
| v0.5.x | 19+ | 18+ | v4.x+ |
| v0.4.x | 19+ | 18+ | v4.x+ |
Note: The client-side components have no TDP version dependency. The
/serverutilities (JWT auth, provider helpers) require a running TDP instance of v4.x or later. Browser support follows React 19's matrix (modern evergreen browsers).As of v1.0.0, heavy dependencies are optional peer dependencies — see Optional peer dependencies below for what to install and when. Upgrading from v0.7.x? Chart components were renamed and four components were removed: read the v0.7.x → v1.0.0 migration guide first.
yarn add @tetrascience-npm/tetrascience-react-uiThe kit does not install heavy dependencies for you. Add only the ones your app uses:
| You use… | Install |
|---|---|
Any charts/ component |
plotly.js-dist |
MessageResponse / Reasoning (AI markdown) |
@streamdown/math, @streamdown/mermaid |
MoleculeStructure |
@rdkit/rdkit — plus a served WASM, see below |
| Any import from the package root | @streamdown/math, @streamdown/mermaid — see the caveat below |
/server Athena / Snowflake / Databricks provider |
@aws-sdk/client-athena / snowflake-sdk / @databricks/sql |
Root-entry imports pull in the streamdown peers whether or not you use them. The AI markdown plugins are loaded through a dynamic import, but a dynamic-import target is still part of your bundler's module graph and its named static imports must resolve. With
@streamdown/mathabsent, a root-entry build fails even when your only kit import isAreaPlot:dist/components/ai/streamdown-plugins.js (2:9): "math" is not exported by "__vite-optional-peer-dep:@streamdown/math:@tetrascience-npm/tetrascience-react-ui"Install the two packages, or use per-component imports, which avoid the barrel entirely. This fails at build time, so it can never reach production unnoticed. Tracked in SW-2472.
A missing plotly.js-dist behaves differently: it does not fail the build under Vite/Rollup — it
resolves to an empty stub and the chart fails at runtime with a console error from the loader
(Failed to load 'plotly.js-dist' …). If your charts render blank after upgrading, check this first.
// 1. Import the CSS once at your app root (required)
import "@tetrascience-npm/tetrascience-react-ui/index.css";
// 2. Import components
import { Button, Card, CardHeader, CardContent } from "@tetrascience-npm/tetrascience-react-ui";
function App() {
return (
<Card>
<CardHeader>Welcome</CardHeader>
<CardContent>
<p>My first TetraScience app!</p>
<Button variant="default">Get Started</Button>
</CardContent>
</Card>
);
}Only need a handful of components? Every one is also importable individually — see Per-Component Imports below.
Every component is also reachable at its own subpath, grouped by category:
ui/*, composed/*, charts/*, ai/*, utils/*:
import { Button } from "@tetrascience-npm/tetrascience-react-ui/ui/button";
import { StatCard } from "@tetrascience-npm/tetrascience-react-ui/composed/StatCard";
import { AreaPlot } from "@tetrascience-npm/tetrascience-react-ui/charts/AreaPlot";Importing this way only pulls in that component's own module graph — the main
@tetrascience-npm/tetrascience-react-ui import still works exactly as
before and pulls in everything. The difference matters most for Jest,
which has no tree-shaking and re-evaluates the full import graph on every
test file: a full-barrel import costs ~1.2s of module evaluation per test
file; a single-component subpath costs ~0.1s. For a production bundler
(Vite, webpack 5) the difference is smaller since unused components are
already tree-shaken from the main import.
The subpath name always matches the component's directory/file under
src/components/<category>/ — check DESIGN.md or the
Storybook sidebar for the
exact name.
Known gap in v1.0.0:
./ui/progressand./ui/snippetresolve their types but ship no runtime module, so importing either typechecks cleanly and then fails your build. Neither component is exported from the package root either, so nothing regressed — but the subpath makes them look available. Don't import them. Tracked in SW-2472.
This library uses Tailwind CSS 4 with design tokens defined as CSS custom properties (oklch color space). All CSS files are declared as sideEffects in package.json, so bundlers will preserve them while still tree-shaking unused JavaScript.
| Import path | Use case |
|---|---|
@tetrascience-npm/tetrascience-react-ui/index.css |
Pre-built CSS — use this for most apps. Import once at your app root. |
@tetrascience-npm/tetrascience-react-ui/index.tailwind.css |
Tailwind source — for apps that run their own Tailwind build and want to extend/override tokens. |
Most consumers only need index.css:
The design system is controlled via CSS custom properties in index.css. Override them to customise colours, spacing, and radii:
:root {
--primary: oklch(0.205 0 0);
--primary-foreground: oklch(0.985 0 0);
--radius: 0.625rem;
}Dark mode is supported via the .dark class on a parent element. See THEMING.md for details.
shadcn/ui components built on Radix UI with Tailwind CSS and CVA variants:
Accordion, Alert, AlertDialog, AspectRatio, Avatar, Badge, Breadcrumb, Button, ButtonGroup, Calendar, Card, Carousel, Checkbox, CodeEditor, Collapsible, ComboBox, Command, ContextMenu, Dialog, DropdownMenu, Field, HoverCard, Input, InputGroup, Item, KBD, Label, MenuBar, NavigationMenu, RadioGroup, ResizablePanel, ScrollArea, Select, Separator, Sheet, Sidebar, Skeleton, Slider, Sonner, Spinner, Switch, Table, Tabs, Textarea, TetraScience Icon, Toggle, ToggleGroup, Tooltip
TetraScience-specific compositions built from UI primitives:
AssistantLayout, Chat, ConfirmDialog, DataAppShell (with PrimaryNav, SecondaryNav, RightPanel), EmptyState, FormPatterns, MoleculeStructure, PlateMapEditor, ProcessFlow, RichListItem, StatCard, TdpLink, TdpSearch, TdpUrl, TopBar, UserMenu
Installing @rdkit/rdkit is not sufficient. RDKit is a ~6.6 MB WebAssembly module that the
package does not place anywhere your app serves it, so the loader's fetch for RDKit_minimal.wasm
falls through to your dev server's SPA fallback and gets index.html back. The component then
renders its errorContent — by default "Invalid structure" — for a perfectly valid SMILES.
Point the loader at a served copy once, at app startup:
import { configureRDKit } from "@tetrascience-npm/tetrascience-react-ui";
// Option A — let your bundler emit and fingerprint it (Vite):
import wasmSrc from "@rdkit/rdkit/dist/RDKit_minimal.wasm?url";
configureRDKit({ wasmSrc });
// Option B — copy node_modules/@rdkit/rdkit/dist/RDKit_minimal.wasm into public/
configureRDKit({ wasmSrc: "/RDKit_minimal.wasm" });To confirm it worked, the request for RDKit_minimal.wasm should return Content-Type: application/wasm at ~6.9 MB — not text/html at a few hundred bytes.
errorContentcurrently covers both an invalid SMILES and a failed RDKit load, so a molecule you trust showing as invalid almost always means the WASM isn't being served. Splitting the two messages is tracked in SW-2472.
Use ProcessFlow to render parent-owned multi-step workflow state such as uploads, validation pipelines, review flows, processing stages, and setup sequences. Import it from the package and keep all workflow transitions and side effects in the consuming app.
import {
PROCESS_FLOW_STEP_STATUSES,
ProcessFlow,
type ProcessFlowStep,
type ProcessFlowStepStatus,
} from "@tetrascience-npm/tetrascience-react-ui";
const steps: ProcessFlowStep[] = [
{ id: "upload", label: "Upload", description: "Choose source files", status: "completed" },
{ id: "validate", label: "Validate", description: "Check schema and lineage", status: "active" },
{ id: "publish", label: "Publish", description: "Send downstream", status: "pending" },
];
function WorkflowProgress() {
return (
<ProcessFlow
steps={steps}
selectedStepId="validate"
onStepSelect={(step, details) => {
console.log(step.id, details.status);
}}
/>
);
}
const allStatuses: readonly ProcessFlowStepStatus[] = PROCESS_FLOW_STEP_STATUSES;Expected contract:
statusis independently controlled per step:pending,active,completed,error, ordisabled.selectedStepIdmeans the step the user is viewing or has clicked; it is separate from theactiveworkflow state.onStepSelectemits user selection only. It does not mean a workflow step completed.- Parent workflow code owns completion, error handling, retries, analytics, and other side effects.
descriptionis shown by default. PassshowDescriptions={false}to hide all descriptions.- Descriptions auto-hide at narrow container widths (≤40rem) for mobile layouts.
- The component fills 100% of its container width — size it by controlling the container.
- Selected completed steps render with a green label; selected active steps render with a blue label.
- Use
connectionsand per-steppositiononly for simple branching/configurable flows.
For AI-assisted consuming apps, add a short instruction like this to the app's AGENTS.md or CLAUDE.md:
Use `ProcessFlow` from `@tetrascience-npm/tetrascience-react-ui` for multi-step workflow visualization. Do not build a custom stepper for upload, validation, review, approval, processing, or setup flows. Parent components own the workflow state and pass `steps: ProcessFlowStep[]`; each step status must be one of `PROCESS_FLOW_STEP_STATUSES`. Use `selectedStepId` only for the viewed/selected step. Keep completion/error side effects in the parent workflow code, not inside `ProcessFlow`.Plotly.js-based data visualisations:
AreaPlot, BarChart, BoxPlot, Chromatogram, StackedChromatogram, Electropherogram, Histogram, LinePlot, PieChart, PlateMap, ScatterPlot, ScatterPlotInteractive
Beyond UI components, this library includes server-side helper functions for building TetraScience applications. These are available via the /server subpath to avoid pulling Node.js dependencies into browser bundles.
JWT Token Manager - Manages JWT token retrieval for data apps:
import { jwtManager } from "@tetrascience-npm/tetrascience-react-ui/server";
// In Express middleware
app.use(async (req, res, next) => {
const token = await jwtManager.getTokenFromExpressRequest(req);
req.tdpAuth = { token, orgSlug: process.env.ORG_SLUG };
next();
});
// Or with raw cookies
const token = await jwtManager.getUserToken(req.cookies);Environment Variables:
ORG_SLUG- Organization slug (required)CONNECTOR_ID- Connector ID for ts-token-ref flowTDP_ENDPOINT- API base URLTS_AUTH_TOKEN- Service account token (fallback for local dev)
Note: The singleton
jwtManagerreads environment variables when the module is imported. Ensure these are set before importing the module.
TypeScript equivalents of the Python helpers from ts-lib-ui-kit-streamlit for connecting to database providers (Snowflake, Databricks, Athena).
Getting Provider Configurations:
import { TDPClient } from "@tetrascience-npm/ts-connectors-sdk";
import { getProviderConfigurations, buildProvider, jwtManager } from "@tetrascience-npm/tetrascience-react-ui/server";
// Get user's auth token from request (e.g., in Express middleware)
const userToken = await jwtManager.getTokenFromExpressRequest(req);
// Create TDPClient with the user's auth token
// Other fields (tdpEndpoint, connectorId, orgSlug) are read from environment variables
const client = new TDPClient({
authToken: userToken,
artifactType: "data-app",
});
await client.init();
// Get all configured providers for this data app
const providers = await getProviderConfigurations(client);
for (const config of providers) {
console.log(`Provider: ${config.name} (${config.type})`);
// Build a database connection from the config
const provider = await buildProvider(config);
const results = await provider.query("SELECT * FROM my_table LIMIT 10");
await provider.close();
}Using Specific Providers:
import {
buildSnowflakeProvider,
buildDatabricksProvider,
getTdpAthenaProvider,
type ProviderConfiguration,
} from "@tetrascience-npm/tetrascience-react-ui/server";
// Snowflake
const snowflakeProvider = await buildSnowflakeProvider(config);
const data = await snowflakeProvider.query("SELECT * FROM users");
await snowflakeProvider.close();
// Databricks
const databricksProvider = await buildDatabricksProvider(config);
const data = await databricksProvider.query("SELECT * FROM events");
await databricksProvider.close();
// TDP Athena (uses environment configuration)
const athenaProvider = await getTdpAthenaProvider();
const data = await athenaProvider.query("SELECT * FROM files");
await athenaProvider.close();Exception Handling:
import {
QueryError,
MissingTableError,
ProviderConnectionError,
InvalidProviderConfigurationError,
} from "@tetrascience-npm/tetrascience-react-ui/server";
try {
const results = await provider.query("SELECT * FROM missing_table");
} catch (error) {
if (error instanceof MissingTableError) {
console.error("Table not found:", error.message);
} else if (error instanceof QueryError) {
console.error("Query failed:", error.message);
}
}Environment Variables:
DATA_APP_PROVIDER_CONFIG- JSON override for local development onlyCONNECTOR_ID- Connector ID for fetching providers from TDPTDP_ENDPOINT- TDP API base URLORG_SLUG- Organization slugATHENA_S3_OUTPUT_LOCATION- S3 bucket for Athena query resultsAWS_REGION- AWS region for Athena
Note: Authentication tokens are obtained from the user's JWT via
jwtManager. TheTS_AUTH_TOKENenvironment variable is only for local development fallback.
The TDP connector key/value store lets data apps persist small pieces of state (user preferences, cached results, last-run timestamps, etc.) without an external database. The TDPClient from @tetrascience-npm/ts-connectors-sdk provides getValue, getValues, saveValue, and saveValues methods.
Reading and writing values with the user's JWT token:
import { TDPClient } from "@tetrascience-npm/ts-connectors-sdk";
import { jwtManager } from "@tetrascience-npm/tetrascience-react-ui/server";
// In an Express route handler:
app.get("/api/kv/:key", async (req, res) => {
// 1. Get the user's JWT from request cookies
const userToken = await jwtManager.getTokenFromExpressRequest(req);
if (!userToken) return res.status(401).json({ error: "Not authenticated" });
// 2. Create a TDPClient authenticated as the user
// (CONNECTOR_ID, TDP_ENDPOINT, ORG_SLUG are read from env vars)
const client = new TDPClient({
authToken: userToken,
artifactType: "data-app",
});
await client.init();
// 3. Read a value
const value = await client.getValue(req.params.key);
res.json({ key: req.params.key, value });
});
app.put("/api/kv/:key", async (req, res) => {
const userToken = await jwtManager.getTokenFromExpressRequest(req);
if (!userToken) return res.status(401).json({ error: "Not authenticated" });
const client = new TDPClient({
authToken: userToken,
artifactType: "data-app",
});
await client.init();
// Write a value (any JSON-serialisable type)
await client.saveValue(req.params.key, req.body.value, { secure: false });
res.json({ key: req.params.key, saved: true });
});Reading multiple values at once:
const values = await client.getValues(["theme", "locale", "last-run"]);
// values[0] → theme, values[1] → locale, values[2] → last-runSee the example app for a complete working server with KV store endpoints.
TdpSearchManager - Server-side handler for the TdpSearch component. Resolves auth from request cookies (via jwtManager), calls TDP searchEql, and returns the response so the frontend hook works with minimal wiring.
import { tdpSearchManager } from "@tetrascience-npm/tetrascience-react-ui/server";
// Express: mount a POST route (e.g. /api/search)
app.post("/api/search", express.json(), async (req, res) => {
try {
const body = req.body; // SearchEqlRequest (searchTerm, from, size, sort, order, ...)
const response = await tdpSearchManager.handleSearchRequest(req, body);
res.json(response);
} catch (err) {
res.status(401).json({ error: err instanceof Error ? err.message : "Search failed" });
}
});Frontend: use <TdpSearch columns={...} /> with default apiEndpoint="/api/search", or pass apiEndpoint if you use a different path. Auth is taken from cookies (ts-auth-token or ts-token-ref via jwtManager).
Full TypeScript support with exported types:
import { Button } from "@tetrascience-npm/tetrascience-react-ui";
import type { ButtonProps, BarChartProps, BarDataSeries } from "@tetrascience-npm/tetrascience-react-ui";The kit ships dual ESM + CJS output, so Jest's CommonJS runtime can load every component directly — no need to mock the package. What Jest can't load are a few third-party dependencies that publish ESM-only (the streamdown/markdown stack, shiki, use-stick-to-bottom, react-resizable-panels) and optional peers you may not have installed (plotly.js-dist, @rdkit/rdkit). The kit ships a single setup file that stubs exactly those, plus the jsdom shims Radix-based components need (ResizeObserver, matchMedia, pointer capture, …).
Add one line to jest.config.js:
module.exports = {
testEnvironment: "jsdom",
setupFiles: ["@tetrascience-npm/tetrascience-react-ui/jest-setup"],
};Requires Jest ≥ 28 (package exports support) and jest-environment-jsdom. To override any stub, register your own mock — jest.mock("<module>", …) in a test file or a later setup file replaces the kit's registration. If Jest runs with injectGlobals: false, import installUiKitJestMocks / installUiKitDomShims from the same module and call them from your own setup file with the jest object.
What the stubs do:
- Charts render their containers; Plotly calls resolve against an inert stub (jsdom has no WebGL). Assert on props/behavior, not pixels — visual assertions belong in a real browser.
MessageResponse/Reasoningrender the markdown source as plain text, so text-content assertions work without transpiling the markdown ecosystem.CodeBlockrenders unhighlighted code lines. Only the languages the kit ships by default are covered — a grammar you add yourself viaregisterCodeBlockLanguageisn't mockable by this setup file, since it isn't known ahead of time.MoleculeStructureresolves against a stub that always returns a valid, empty-SVG molecule. For real assertions (invalid-SMILES handling, actual rendered markup), use the kit's own override hook instead of relying on the stub:configureRDKit({ importFactory: () => Promise.resolve(myFakeRDKitModule) }), exported alongsideMoleculeStructure.
This repository uses component driven development with Storybook. To see the examples run the following.
# Clone the repository
git clone https://github.com/tetrascience/ts-lib-ui-kit.git
cd ts-lib-ui-kit
# Install dependencies
yarn
# Run the storybook
yarn devVisit http://localhost:6006.
- Storybook – Live Component Demos - Browse all components with interactive examples
- NPM Package - Installation and version info
- Migration Guide - Upgrading from v0.7.x to v1.0.0 (chart renames, removed components, optional peers)
- Changelog - What changed in each release, including v1.0.0's breaking changes
- Theming Guide - Customise the design system
- Contributing - Clone the repo and run
yarn storybook
This library exposes an MCP server so AI coding agents (Claude Code, Cursor, Claude Desktop) can query authoritative component lists, prop/variant options, and usage examples instead of guessing — reducing hallucinated component APIs when scaffolding a data app.
There are two endpoints. Pick whichever fits; you can add both.
| Endpoint | URL | Tools |
|---|---|---|
| Deployed (no local checkout needed) | https://ts-lib-ui-kit-storybook.vercel.app/api/mcp |
docs: list_components, get_component, search_components |
Local (needs yarn storybook running) |
http://localhost:6006/mcp |
full set: docs + write/preview/test stories |
Claude Code — register the deployed server (HTTP transport):
claude mcp add --transport http ts-ui-kit https://ts-lib-ui-kit-storybook.vercel.app/api/mcpUse --scope project to share it with your team via a checked-in .mcp.json, or
--scope user to make it available across all your projects. For the local
server, run yarn storybook first, then:
claude mcp add --transport http ts-ui-kit-local http://localhost:6006/mcpCursor / Claude Desktop / other clients — add an HTTP MCP server to the
client's MCP config (e.g. Cursor's .cursor/mcp.json, or Claude Desktop's
claude_desktop_config.json):
{
"mcpServers": {
"ts-ui-kit": {
"type": "http",
"url": "https://ts-lib-ui-kit-storybook.vercel.app/api/mcp"
}
}
}Any client (generic helper):
npx mcp-add --type http --url "https://ts-lib-ui-kit-storybook.vercel.app/api/mcp"Then ask your agent something like "using the ts-ui-kit MCP, list the available components" or "build a form using ts-ui-kit primitives" to confirm it's wired up.
- React 19
- TypeScript
- Tailwind CSS 4
- shadcn/ui (Radix UI)
- Vite 7
- Plotly.js (charts)
- Monaco Editor (code editing)
Licensed under the Apache License, Version 2.0 – see LICENSE for details.