Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

feat(lab,cli): LogStream component + logs-explorer and deployment-detail templates (#3330)

David Petersen500d0c7f45d2
diff --git a/apps/sandbox/src/app/globals.css b/apps/sandbox/src/app/globals.css
index 274192dea6..3d7a72d76e 100644
--- a/apps/sandbox/src/app/globals.css
+++ b/apps/sandbox/src/app/globals.css
@@ -3,6 +3,7 @@
@import "./layers.css";
@import "@astryxdesign/core/reset.css";
@import "@astryxdesign/core/astryx.css";
+@import "@astryxdesign/lab/lab.css";
@import "@astryxdesign/theme-neutral/theme.css";
@import "@astryxdesign/theme-matcha/theme.css";
@import "@astryxdesign/theme-stone/theme.css";
diff --git a/apps/storybook/stories/LogStream.stories.tsx b/apps/storybook/stories/LogStream.stories.tsx
new file mode 100644
index 0000000000..42897f8c64
--- /dev/null
+++ b/apps/storybook/stories/LogStream.stories.tsx
@@ -0,0 +1,285 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import type {Meta, StoryObj} from '@storybook/react';
+import {useState, type CSSProperties} from 'react';
+import {LogStream, type LogEntry} from '@astryxdesign/lab';
+import {Button} from '@astryxdesign/core/Button';
+import {Card} from '@astryxdesign/core/Card';
+import {Heading} from '@astryxdesign/core/Heading';
+import {HStack, VStack, StackItem} from '@astryxdesign/core/Stack';
+import {StatusDot} from '@astryxdesign/core/StatusDot';
+import {Text} from '@astryxdesign/core/Text';
+
+const meta: Meta<typeof LogStream> = {
+ title: 'Lab/LogStream',
+ component: LogStream,
+ tags: ['autodocs'],
+ parameters: {
+ layout: 'centered',
+ },
+ decorators: [
+ Story => (
+ <div style={{width: 880, padding: 32}}>
+ <Story />
+ </div>
+ ),
+ ],
+};
+
+export default meta;
+type Story = StoryObj<typeof LogStream>;
+
+const detailStyle: CSSProperties = {
+ margin: 0,
+ fontFamily: 'var(--font-family-code)',
+ fontSize: 'var(--font-size-sm)',
+ lineHeight: 1.7,
+ whiteSpace: 'pre-wrap',
+};
+
+const buildEntries: LogEntry[] = [
+ {
+ id: 'b-01',
+ timestamp: '12:04:16.002',
+ level: 'info',
+ source: 'build',
+ message: 'Build machine: 4 cores, 8 GB RAM (iad1)',
+ },
+ {
+ id: 'b-02',
+ timestamp: '12:04:16.089',
+ level: 'info',
+ source: 'build',
+ message: 'Cloning github.com/acme/astryx-console (branch: main)',
+ },
+ {
+ id: 'b-03',
+ timestamp: '12:04:18.021',
+ level: 'info',
+ source: 'stage',
+ message: 'Install',
+ },
+ {
+ id: 'b-04',
+ timestamp: '12:04:18.144',
+ level: 'info',
+ source: 'install',
+ message: '$ pnpm install --frozen-lockfile',
+ },
+ {
+ id: 'b-05',
+ timestamp: '12:04:23.348',
+ level: 'info',
+ source: 'build',
+ message: '$ next build',
+ },
+ {
+ id: 'b-06',
+ timestamp: '12:04:38.207',
+ level: 'warn',
+ source: 'build',
+ message: 'Compiled with warnings (1)',
+ detail: (
+ <pre style={detailStyle}>
+ {
+ './app/logs/page.tsx\n42:9 Warning: "range" is assigned a value but never used.'
+ }
+ </pre>
+ ),
+ },
+ {
+ id: 'b-07',
+ timestamp: '12:04:45.201',
+ level: 'info',
+ source: 'deploy',
+ message: 'Uploading build outputs (23.4 MB)',
+ },
+ {
+ id: 'b-08',
+ timestamp: '12:04:50.004',
+ level: 'info',
+ source: 'deploy',
+ message: 'Build completed in 34s',
+ },
+];
+
+const monitoringEntries: LogEntry[] = [
+ {
+ id: 'l-01',
+ timestamp: '14:02:08.114',
+ level: 'info',
+ source: 'api-gateway',
+ message: 'GET /v1/projects 200 in 42ms',
+ },
+ {
+ id: 'l-02',
+ timestamp: '14:02:08.371',
+ level: 'debug',
+ source: 'auth',
+ message: 'token cache hit for key sess_7f31',
+ },
+ {
+ id: 'l-03',
+ timestamp: '14:02:09.243',
+ level: 'warn',
+ source: 'billing',
+ message: 'upstream latency 1840ms exceeds 1500ms budget',
+ detail: (
+ <pre style={detailStyle}>
+ {
+ '{\n "upstream": "payments.stripe",\n "latencyMs": 1840,\n "budgetMs": 1500,\n "traceId": "tr_9c41b2"\n}'
+ }
+ </pre>
+ ),
+ },
+ {
+ id: 'l-04',
+ timestamp: '14:02:10.037',
+ level: 'error',
+ source: 'billing',
+ message: 'charge failed: upstream returned 502',
+ detail: (
+ <pre style={detailStyle}>
+ {
+ '{\n "error": "UpstreamBadGateway",\n "attempt": 1,\n "retryInMs": 400,\n "invoice": "inv_20418"\n}'
+ }
+ </pre>
+ ),
+ },
+ {
+ id: 'l-05',
+ timestamp: '14:02:11.305',
+ level: 'info',
+ source: 'billing',
+ message: 'charge succeeded for inv_20418 in 322ms',
+ },
+ {
+ id: 'l-06',
+ timestamp: '14:02:13.078',
+ level: 'debug',
+ source: 'api-gateway',
+ message: 'route table reloaded (37 routes)',
+ },
+];
+
+const liveScript: Omit<LogEntry, 'id'>[] = [
+ {
+ timestamp: '14:02:14.102',
+ level: 'info',
+ source: 'api-gateway',
+ message: 'GET /v1/projects 200 in 38ms',
+ },
+ {
+ timestamp: '14:02:15.310',
+ level: 'debug',
+ source: 'auth',
+ message: 'token cache hit for key sess_9a02',
+ },
+ {
+ timestamp: '14:02:17.708',
+ level: 'warn',
+ source: 'billing',
+ message: 'webhook delivery slow: 2210ms to partner.acme',
+ },
+ {
+ timestamp: '14:02:20.131',
+ level: 'error',
+ source: 'worker',
+ message: 'job usage-rollup-0415 failed: table locked',
+ },
+];
+
+export const TerminalBuild: Story = {
+ render: () => (
+ <VStack gap={2}>
+ <HStack gap={2} vAlign="center">
+ <StatusDot variant="success" label="Ready" />
+ <Heading level={3}>Build logs</Heading>
+ </HStack>
+ <LogStream
+ entries={buildEntries}
+ variant="terminal"
+ maxHeight={360}
+ label="Build logs"
+ />
+ </VStack>
+ ),
+};
+
+export const MonitoringRows: Story = {
+ render: () => (
+ <Card padding={4}>
+ <VStack gap={3}>
+ <VStack gap={0}>
+ <Heading level={3}>Log results</Heading>
+ <Text type="supporting" color="secondary">
+ {monitoringEntries.length} events indexed / env:prod / UTC
+ </Text>
+ </VStack>
+ <LogStream
+ entries={monitoringEntries}
+ maxHeight={360}
+ label="Log results stream"
+ />
+ </VStack>
+ </Card>
+ ),
+};
+
+export const ControlledFollow: Story = {
+ render: () => {
+ const [entries, setEntries] = useState<LogEntry[]>(monitoringEntries);
+ const [isFollowing, setIsFollowing] = useState(true);
+ const nextIndex = entries.length - monitoringEntries.length;
+ const canAppend = nextIndex < liveScript.length;
+
+ const appendEntry = () => {
+ if (!canAppend) {
+ return;
+ }
+ setEntries(current => [
+ ...current,
+ {...liveScript[nextIndex], id: `live-${nextIndex}`},
+ ]);
+ setIsFollowing(true);
+ };
+
+ return (
+ <VStack gap={3}>
+ <HStack gap={2} vAlign="center">
+ <StatusDot
+ variant={isFollowing ? 'success' : 'neutral'}
+ label={isFollowing ? 'Following latest' : 'Not following'}
+ isPulsing={isFollowing}
+ />
+ <StackItem size="fill">
+ <Text type="supporting" color="secondary">
+ {entries.length} rows
+ </Text>
+ </StackItem>
+ <Button
+ label="Append line"
+ variant="secondary"
+ onClick={appendEntry}
+ isDisabled={!canAppend}
+ />
+ <Button
+ label="Reset"
+ variant="ghost"
+ onClick={() => {
+ setEntries(monitoringEntries);
+ setIsFollowing(true);
+ }}
+ />
+ </HStack>
+ <LogStream
+ entries={entries}
+ maxHeight={320}
+ isFollowing={isFollowing}
+ onFollowChange={setIsFollowing}
+ label="Live log stream"
+ />
+ </VStack>
+ );
+ },
+};
diff --git a/packages/lab/src/LogStream/LogStream.doc.mjs b/packages/lab/src/LogStream/LogStream.doc.mjs
new file mode 100644
index 0000000000..267c2c7b74
--- /dev/null
+++ b/packages/lab/src/LogStream/LogStream.doc.mjs
@@ -0,0 +1,17 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('../../core/src/docs-types').ComponentDoc} */
+
+export const docs = {
+ name: 'LogStream',
+ displayName: 'Log Stream',
+ group: 'LogStream',
+ category: 'Content',
+
+ usage: {
+ description:
+ 'Experimental streaming log viewer: mono grid rows (timestamp | level | source | message) with token-derived level accents, expandable per-row detail panels, follow-scroll live tailing with a "Jump to latest" affordance, and an always-dark terminal variant. Appended rows fade in via @starting-style (instant under prefers-reduced-motion). No virtualization — window streams beyond a few thousand rows in the caller.',
+ },
+
+ props: [],
+};
diff --git a/packages/lab/src/LogStream/LogStream.test.tsx b/packages/lab/src/LogStream/LogStream.test.tsx
new file mode 100644
index 0000000000..7d1310a579
--- /dev/null
+++ b/packages/lab/src/LogStream/LogStream.test.tsx
@@ -0,0 +1,238 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {describe, it, expect, vi} from 'vitest';
+import {render, screen, fireEvent} from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import {LogStream, type LogEntry} from './LogStream';
+
+const ENTRIES: LogEntry[] = [
+ {
+ id: 'a',
+ timestamp: '14:02:11.482',
+ level: 'info',
+ source: 'api-gateway',
+ message: 'request accepted',
+ },
+ {
+ id: 'b',
+ timestamp: '14:02:11.617',
+ level: 'warn',
+ source: 'billing',
+ message: 'retrying upstream call',
+ },
+ {
+ id: 'c',
+ timestamp: '14:02:12.044',
+ level: 'error',
+ source: 'billing',
+ message: 'upstream call failed',
+ detail: <div>stack: billing.charge failed with 502</div>,
+ },
+ {
+ id: 'd',
+ timestamp: '14:02:12.371',
+ level: 'debug',
+ source: 'api-gateway',
+ message: 'connection pool at 40%',
+ },
+];
+
+/** jsdom has no layout: fake the scroll geometry on the log scroller. */
+function setScrollMetrics(
+ el: HTMLElement,
+ {scrollHeight, clientHeight}: {scrollHeight: number; clientHeight: number},
+) {
+ Object.defineProperty(el, 'scrollHeight', {
+ value: scrollHeight,
+ configurable: true,
+ });
+ Object.defineProperty(el, 'clientHeight', {
+ value: clientHeight,
+ configurable: true,
+ });
+}
+
+describe('LogStream', () => {
+ it('renders one row per entry with level and message', () => {
+ render(<LogStream entries={ENTRIES} />);
+ expect(screen.getByText('request accepted')).toBeInTheDocument();
+ expect(screen.getByText('retrying upstream call')).toBeInTheDocument();
+ expect(screen.getByText('upstream call failed')).toBeInTheDocument();
+ expect(screen.getByText('connection pool at 40%')).toBeInTheDocument();
+ expect(screen.getByText('info')).toBeInTheDocument();
+ expect(screen.getByText('warn')).toBeInTheDocument();
+ expect(screen.getByText('error')).toBeInTheDocument();
+ expect(screen.getByText('debug')).toBeInTheDocument();
+ // Level lands on the row element for theming hooks.
+ expect(
+ screen.getByText('upstream call failed').closest('[data-level]'),
+ ).toHaveAttribute('data-level', 'error');
+ });
+
+ it('exposes the scroller as an accessible log region', () => {
+ render(<LogStream entries={ENTRIES} label="Build output" />);
+ expect(screen.getByRole('log', {name: 'Build output'})).toBeInTheDocument();
+ });
+
+ it('renders timestamps by default and hides them with hasTimestamps={false}', () => {
+ const {rerender} = render(<LogStream entries={ENTRIES} />);
+ expect(screen.getByText('14:02:11.482')).toBeInTheDocument();
+ rerender(<LogStream entries={ENTRIES} hasTimestamps={false} />);
+ expect(screen.queryByText('14:02:11.482')).not.toBeInTheDocument();
+ });
+
+ it('expands and collapses detail rows via the row button', async () => {
+ const user = userEvent.setup();
+ render(<LogStream entries={ENTRIES} />);
+ // Only the entry with `detail` renders as a disclosure button.
+ const row = screen.getByRole('button', {expanded: false});
+ expect(row).toHaveTextContent('upstream call failed');
+ expect(
+ screen.queryByText('stack: billing.charge failed with 502'),
+ ).not.toBeInTheDocument();
+
+ await user.click(row);
+ expect(row).toHaveAttribute('aria-expanded', 'true');
+ expect(
+ screen.getByText('stack: billing.charge failed with 502'),
+ ).toBeInTheDocument();
+
+ await user.click(row);
+ expect(row).toHaveAttribute('aria-expanded', 'false');
+ expect(
+ screen.queryByText('stack: billing.charge failed with 502'),
+ ).not.toBeInTheDocument();
+ });
+
+ it('pins scroll to the bottom on append while following', () => {
+ const {rerender} = render(
+ <LogStream entries={ENTRIES} isFollowing maxHeight={200} />,
+ );
+ const scroller = screen.getByRole('log');
+ setScrollMetrics(scroller, {scrollHeight: 1000, clientHeight: 200});
+
+ const appended: LogEntry[] = [
+ ...ENTRIES,
+ {
+ id: 'e',
+ timestamp: '14:02:13.005',
+ level: 'info',
+ source: 'api-gateway',
+ message: 'request completed',
+ },
+ ];
+ rerender(<LogStream entries={appended} isFollowing maxHeight={200} />);
+ expect(scroller.scrollTop).toBe(1000);
+ });
+
+ it('unpins when the user scrolls away from the bottom', () => {
+ const onFollowChange = vi.fn();
+ render(
+ <LogStream
+ entries={ENTRIES}
+ isFollowing
+ onFollowChange={onFollowChange}
+ maxHeight={200}
+ />,
+ );
+ const scroller = screen.getByRole('log');
+ setScrollMetrics(scroller, {scrollHeight: 1000, clientHeight: 200});
+
+ // User drags the scrollbar far above the tail.
+ scroller.scrollTop = 100;
+ fireEvent.scroll(scroller);
+ expect(onFollowChange).toHaveBeenCalledWith(false);
+ });
+
+ it('does not unpin on scroll events that stay at the bottom', () => {
+ const onFollowChange = vi.fn();
+ render(
+ <LogStream
+ entries={ENTRIES}
+ isFollowing
+ onFollowChange={onFollowChange}
+ maxHeight={200}
+ />,
+ );
+ const scroller = screen.getByRole('log');
+ setScrollMetrics(scroller, {scrollHeight: 1000, clientHeight: 200});
+
+ scroller.scrollTop = 800; // exactly at the bottom
+ fireEvent.scroll(scroller);
+ expect(onFollowChange).not.toHaveBeenCalled();
+ });
+
+ it('re-pins via the "Jump to latest" affordance', () => {
+ const onFollowChange = vi.fn();
+ render(
+ <LogStream
+ entries={ENTRIES}
+ isFollowing={false}
+ onFollowChange={onFollowChange}
+ maxHeight={200}
+ />,
+ );
+ const scroller = screen.getByRole('log');
+ setScrollMetrics(scroller, {scrollHeight: 1000, clientHeight: 200});
+
+ // No affordance while the viewport is (assumed) at the bottom.
+ expect(
+ screen.queryByRole('button', {name: /jump to latest/i}),
+ ).not.toBeInTheDocument();
+
+ scroller.scrollTop = 0;
+ fireEvent.scroll(scroller);
+ const jump = screen.getByRole('button', {name: /jump to latest/i});
+ fireEvent.click(jump);
+ expect(onFollowChange).toHaveBeenCalledWith(true);
+ expect(scroller.scrollTop).toBe(1000);
+ });
+
+ it('supports uncontrolled follow state', () => {
+ const {rerender} = render(<LogStream entries={ENTRIES} maxHeight={200} />);
+ const scroller = screen.getByRole('log');
+ setScrollMetrics(scroller, {scrollHeight: 1000, clientHeight: 200});
+
+ // Unfollowed by default: appends do not move the viewport.
+ scroller.scrollTop = 100;
+ fireEvent.scroll(scroller);
+ rerender(
+ <LogStream
+ entries={[
+ ...ENTRIES,
+ {id: 'e', timestamp: '14:02:13.005', level: 'info', message: 'tick'},
+ ]}
+ maxHeight={200}
+ />,
+ );
+ expect(scroller.scrollTop).toBe(100);
+
+ // Jump to latest pins; the next append follows.
+ fireEvent.click(screen.getByRole('button', {name: /jump to latest/i}));
+ expect(scroller.scrollTop).toBe(1000);
+ rerender(
+ <LogStream
+ entries={[
+ ...ENTRIES,
+ {id: 'e', timestamp: '14:02:13.005', level: 'info', message: 'tick'},
+ {id: 'f', timestamp: '14:02:14.005', level: 'info', message: 'tock'},
+ ]}
+ maxHeight={200}
+ />,
+ );
+ expect(scroller.scrollTop).toBe(1000);
+ });
+
+ it('renderEntry replaces the default row', () => {
+ render(
+ <LogStream
+ entries={ENTRIES}
+ renderEntry={entry => <div>CUSTOM {entry.id}</div>}
+ />,
+ );
+ expect(screen.getByText('CUSTOM a')).toBeInTheDocument();
+ expect(screen.getByText('CUSTOM c')).toBeInTheDocument();
+ expect(screen.queryByText('request accepted')).not.toBeInTheDocument();
+ expect(screen.queryByRole('button')).not.toBeInTheDocument();
+ });
+});
diff --git a/packages/lab/src/LogStream/LogStream.tsx b/packages/lab/src/LogStream/LogStream.tsx
new file mode 100644
index 0000000000..400905b23c
--- /dev/null
+++ b/packages/lab/src/LogStream/LogStream.tsx
@@ -0,0 +1,564 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file LogStream.tsx
+ * @input Uses React, StyleX, theme tokens (color/spacing/radius/typography vars)
+ * @output Exports LogStream component, LogStreamProps, LogEntry, LogStreamLevel
+ * @position Lab implementation; experimental streaming log viewer
+ *
+ * Mono grid rows (timestamp | level | source? | message) with level color
+ * accents, expandable detail panels, a follow-scroll live-tail mode, and an
+ * always-dark "terminal" variant.
+ *
+ * Known limit: rows are plain DOM (content-visibility: auto for offscreen
+ * skip) — there is NO virtualization. Streams beyond a few thousand rows
+ * should be windowed by the caller.
+ *
+ * SYNC: When modified, update these files to stay in sync:
+ * - /packages/lab/src/LogStream/LogStream.doc.mjs (props table, notes)
+ * - /packages/lab/src/LogStream/LogStream.test.tsx (behavior tests)
+ * - /packages/lab/src/LogStream/index.ts (exports if types change)
+ * - /apps/storybook/stories/LogStream.stories.tsx (examples and visual coverage)
+ */
+
+'use client';
+
+import {
+ Fragment,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+ type ReactNode,
+} from 'react';
+import * as stylex from '@stylexjs/stylex';
+
+import type {BaseProps} from '@astryxdesign/core';
+import {mergeProps, themeProps} from '@astryxdesign/core/utils';
+import {
+ borderVars,
+ colorVars,
+ durationVars,
+ fontWeightVars,
+ radiusVars,
+ shadowVars,
+ spacingVars,
+ textSizeVars,
+ typographyVars,
+} from '@astryxdesign/core/theme/tokens.stylex';
+
+/** Severity of one log entry. */
+export type LogStreamLevel = 'info' | 'warn' | 'error' | 'debug';
+
+/** One row in the stream; all strings are pre-formatted by the caller. */
+export interface LogEntry {
+ /** Stable unique key, e.g. `"req-1042"`. */
+ id: string;
+ /** Pre-formatted timestamp, e.g. `"14:02:11.482"`. Deterministic. */
+ timestamp: string;
+ level: LogStreamLevel;
+ message: string;
+ /** Emitting service/component, e.g. `"api-gateway"`. */
+ source?: string;
+ /** When set, the row becomes a disclosure button for this panel. */
+ detail?: ReactNode;
+}
+
+export interface LogStreamProps extends Omit<
+ BaseProps<HTMLDivElement>,
+ 'children'
+> {
+ /** Ref forwarded to the root element */
+ ref?: React.Ref<HTMLDivElement>;
+ /** Log rows, oldest first (live tails append at the end). */
+ entries: LogEntry[];
+ /**
+ * Visual treatment. `'terminal'` renders dark chrome regardless of the
+ * active color scheme (terminal output is a brand surface, like a real
+ * shell — light-mode terminals read as broken builds).
+ * @default 'default'
+ */
+ variant?: 'default' | 'terminal';
+ /**
+ * Pin scroll to the newest entry as entries append. Unpins when the user
+ * scrolls up; re-pin via the "Jump to latest" affordance. Controlled when
+ * provided; uncontrolled (initially unpinned) otherwise.
+ */
+ isFollowing?: boolean;
+ /** Called when follow-pinning changes (user scroll-up or "Jump to latest"). */
+ onFollowChange?: (following: boolean) => void;
+ /** Max height of the scroll area before it scrolls. */
+ maxHeight?: number | string;
+ /** Show the timestamp column. @default true */
+ hasTimestamps?: boolean;
+ /** Accessible label for the log region. @default 'Log stream' */
+ label?: string;
+ /** Escape hatch: fully replace the default row for an entry. */
+ renderEntry?: (entry: LogEntry) => ReactNode;
+}
+
+/** User counts as "scrolled away" beyond this distance from the bottom. */
+const FOLLOW_THRESHOLD_PX = 24;
+
+const REDUCE = '@media (prefers-reduced-motion: reduce)';
+const HOVER = '@media (hover: hover)';
+
+// The terminal variant is intentionally always-dark (terminal chrome is a
+// brand surface, mirroring real shells), so it uses fixed near-black grays
+// rather than light-dark() theme tokens, which would flip with the scheme.
+const TERM = {
+ surface: '#0a0a0a',
+ surfaceRaised: '#141417',
+ border: '#26262a',
+ textDim: '#8b8b94',
+ text: '#b9b9c0',
+ textBright: '#e8e8ea',
+ warn: '#f2c00b',
+ error: '#ff6166',
+};
+
+const styles = stylex.create({
+ root: {
+ position: 'relative',
+ display: 'flex',
+ flexDirection: 'column',
+ borderRadius: radiusVars['--radius-element'],
+ borderWidth: borderVars['--border-width'],
+ borderStyle: 'solid',
+ borderColor: colorVars['--color-border'],
+ backgroundColor: colorVars['--color-background-surface'],
+ overflow: 'hidden',
+ fontFamily: typographyVars['--font-family-code'],
+ fontSize: textSizeVars['--font-size-sm'],
+ },
+ rootTerminal: {
+ borderColor: TERM.border,
+ backgroundColor: TERM.surface,
+ },
+ scroller: (maxHeight: number | string | null) => ({
+ overflowY: 'auto',
+ maxHeight,
+ scrollbarWidth: 'thin',
+ overscrollBehavior: 'contain',
+ }),
+ row: {
+ display: 'grid',
+ alignItems: 'baseline',
+ columnGap: spacingVars['--spacing-3'],
+ paddingBlock: spacingVars['--spacing-1'],
+ paddingInline: spacingVars['--spacing-3'],
+ lineHeight: 1.7,
+ color: colorVars['--color-text-primary'],
+ borderBottomWidth: {
+ default: borderVars['--border-width'],
+ ':last-child': 0,
+ },
+ borderBottomStyle: 'solid',
+ borderBottomColor: colorVars['--color-border'],
+ // Offscreen rows skip layout/paint; the intrinsic size keeps the
+ // scrollbar stable. No virtualization — see the file header.
+ contentVisibility: 'auto',
+ containIntrinsicBlockSize: 'auto 28px',
+ // Appended tail lines fade in; opacity-only, instant under reduced motion.
+ opacity: 1,
+ transitionProperty: 'opacity',
+ transitionDuration: {
+ default: durationVars['--duration-fast-min'],
+ [REDUCE]: '0.01ms',
+ },
+ transitionTimingFunction: 'ease-out',
+ '@starting-style': {opacity: 0},
+ },
+ rowTerminal: {
+ color: TERM.text,
+ borderBottomWidth: 0,
+ paddingBlock: 1,
+ },
+ // Grid templates per visible column set (timestamp / source optional).
+ colsFull: {gridTemplateColumns: '96px 52px 128px minmax(0, 1fr)'},
+ colsNoSource: {gridTemplateColumns: '96px 52px minmax(0, 1fr)'},
+ colsNoTimestamp: {gridTemplateColumns: '52px 128px minmax(0, 1fr)'},
+ colsMessageOnly: {gridTemplateColumns: '52px minmax(0, 1fr)'},
+ rowButton: {
+ width: '100%',
+ textAlign: 'left',
+ borderTopWidth: 0,
+ borderInlineWidth: 0,
+ fontFamily: typographyVars['--font-family-code'],
+ fontSize: textSizeVars['--font-size-sm'],
+ cursor: 'pointer',
+ backgroundColor: {
+ default: 'transparent',
+ ':hover': {[HOVER]: colorVars['--color-overlay-hover']},
+ },
+ },
+ rowButtonTerminal: {
+ backgroundColor: {
+ default: 'transparent',
+ ':hover': {[HOVER]: TERM.surfaceRaised},
+ },
+ },
+ // Level tints: faint full-row wash for error/warn (color-mix keeps the
+ // tint derived from the theme token instead of a parallel palette).
+ rowError: {
+ backgroundColor: `color-mix(in srgb, ${colorVars['--color-error']} 6%, transparent)`,
+ },
+ rowWarn: {
+ backgroundColor: `color-mix(in srgb, ${colorVars['--color-warning']} 5%, transparent)`,
+ },
+ timestamp: {
+ color: colorVars['--color-text-secondary'],
+ whiteSpace: 'nowrap',
+ fontVariantNumeric: 'tabular-nums',
+ },
+ timestampTerminal: {
+ color: TERM.textDim,
+ },
+ level: {
+ fontSize: textSizeVars['--font-size-xs'],
+ fontWeight: fontWeightVars['--font-weight-semibold'],
+ letterSpacing: '0.08em',
+ textTransform: 'uppercase',
+ },
+ levelInfo: {color: colorVars['--color-text-secondary']},
+ levelDebug: {color: colorVars['--color-text-disabled']},
+ // Token amber/red are tuned for fills; as small text they miss 4.5:1.
+ // light-dark() darkens the amber in light mode and lifts the red in dark
+ // mode, both derived from the tokens.
+ levelWarn: {
+ color: `light-dark(color-mix(in srgb, ${colorVars['--color-warning']} 58%, black), ${colorVars['--color-warning']})`,
+ },
+ levelError: {
+ color: `light-dark(${colorVars['--color-error']}, color-mix(in srgb, ${colorVars['--color-error']} 82%, white))`,
+ },
+ levelInfoTerminal: {color: TERM.text},
+ levelDebugTerminal: {color: TERM.textDim},
+ levelWarnTerminal: {color: TERM.warn},
+ levelErrorTerminal: {color: TERM.error},
+ source: {
+ color: colorVars['--color-text-secondary'],
+ overflow: 'hidden',
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ minWidth: 0,
+ },
+ sourceTerminal: {
+ color: TERM.textDim,
+ },
+ message: {
+ minWidth: 0,
+ overflowWrap: 'anywhere',
+ whiteSpace: 'pre-wrap',
+ },
+ messageTerminal: {
+ color: TERM.text,
+ },
+ messageErrorTerminal: {color: TERM.error},
+ messageWarnTerminal: {color: TERM.warn},
+ detail: {
+ paddingBlock: spacingVars['--spacing-3'],
+ paddingInline: spacingVars['--spacing-3'],
+ backgroundColor: colorVars['--color-background-muted'],
+ borderBottomWidth: borderVars['--border-width'],
+ borderBottomStyle: 'solid',
+ borderBottomColor: colorVars['--color-border'],
+ },
+ detailTerminal: {
+ backgroundColor: '#0e0e10',
+ borderBottomColor: TERM.border,
+ color: TERM.text,
+ },
+ jumpToLatest: {
+ position: 'absolute',
+ bottom: spacingVars['--spacing-3'],
+ insetInlineEnd: spacingVars['--spacing-3'],
+ paddingBlock: spacingVars['--spacing-1'],
+ paddingInline: spacingVars['--spacing-3'],
+ borderRadius: radiusVars['--radius-full'],
+ borderWidth: borderVars['--border-width'],
+ borderStyle: 'solid',
+ borderColor: colorVars['--color-border-emphasized'],
+ backgroundColor: {
+ default: colorVars['--color-background-surface'],
+ ':hover': {[HOVER]: colorVars['--color-background-muted']},
+ },
+ color: colorVars['--color-text-primary'],
+ fontFamily: typographyVars['--font-family-code'],
+ fontSize: textSizeVars['--font-size-sm'],
+ fontWeight: fontWeightVars['--font-weight-medium'],
+ cursor: 'pointer',
+ boxShadow: shadowVars['--shadow-med'],
+ outline: {
+ default: 'none',
+ ':focus-visible': `2px solid ${colorVars['--color-accent']}`,
+ },
+ outlineOffset: 2,
+ },
+ jumpToLatestTerminal: {
+ borderColor: TERM.border,
+ backgroundColor: {
+ default: TERM.surfaceRaised,
+ ':hover': {[HOVER]: '#1d1d21'},
+ },
+ color: TERM.textBright,
+ },
+});
+
+const LEVEL_STYLE: Record<LogStreamLevel, stylex.StyleXStyles> = {
+ info: styles.levelInfo,
+ warn: styles.levelWarn,
+ error: styles.levelError,
+ debug: styles.levelDebug,
+};
+
+const LEVEL_STYLE_TERMINAL: Record<LogStreamLevel, stylex.StyleXStyles> = {
+ info: styles.levelInfoTerminal,
+ warn: styles.levelWarnTerminal,
+ error: styles.levelErrorTerminal,
+ debug: styles.levelDebugTerminal,
+};
+
+/**
+ * Experimental streaming log viewer: mono grid rows
+ * (timestamp | level | source | message) with token-derived level accents,
+ * expandable per-row detail panels, follow-scroll live tailing with a
+ * "Jump to latest" affordance, and an always-dark terminal variant.
+ *
+ * Appended rows fade in via `@starting-style` (instant under
+ * prefers-reduced-motion). Follow pinning uses a scroll listener — no
+ * polling; rows use `content-visibility: auto` for offscreen skip but are
+ * NOT virtualized (window large streams in the caller).
+ *
+ * @example
+ * ```
+ * <LogStream
+ * entries={entries}
+ * maxHeight={480}
+ * isFollowing={isFollowing}
+ * onFollowChange={setIsFollowing}
+ * />
+ * ```
+ */
+export function LogStream({
+ entries,
+ variant = 'default',
+ isFollowing,
+ onFollowChange,
+ maxHeight,
+ hasTimestamps = true,
+ label = 'Log stream',
+ renderEntry,
+ xstyle,
+ className,
+ style,
+ ref,
+ ...rest
+}: LogStreamProps) {
+ const isTerminal = variant === 'terminal';
+ const scrollerRef = useRef<HTMLDivElement | null>(null);
+
+ // Follow pinning: controlled when the prop is provided, else internal.
+ const [internalFollowing, setInternalFollowing] = useState(
+ isFollowing ?? false,
+ );
+ const following = isFollowing ?? internalFollowing;
+ const setFollowing = (next: boolean) => {
+ if (next === following) {
+ return;
+ }
+ if (isFollowing == null) {
+ setInternalFollowing(next);
+ }
+ onFollowChange?.(next);
+ };
+
+ // Whether the viewport currently sits at the bottom; drives the
+ // "Jump to latest" affordance. Updated from scroll events only.
+ const [isAtBottom, setIsAtBottom] = useState(true);
+
+ const [expandedIds, setExpandedIds] = useState<ReadonlySet<string>>(
+ () => new Set(),
+ );
+ const toggleExpanded = (id: string) => {
+ setExpandedIds(prev => {
+ const next = new Set(prev);
+ if (next.has(id)) {
+ next.delete(id);
+ } else {
+ next.add(id);
+ }
+ return next;
+ });
+ };
+
+ const hasSource = useMemo(
+ () => entries.some(entry => entry.source != null),
+ [entries],
+ );
+
+ // Pin to the newest row while following. Direct scrollTop assignment (not
+ // smooth scrollTo) so rapid appends never queue competing animations.
+ useEffect(() => {
+ const el = scrollerRef.current;
+ if (!following || el == null) {
+ return;
+ }
+ el.scrollTop = el.scrollHeight;
+ setIsAtBottom(true);
+ }, [following, entries.length]);
+
+ // No programmatic-scroll guard is needed: pinning always lands the
+ // viewport at the bottom, and the unpin branch below only fires when the
+ // viewport is AWAY from the bottom — a programmatic echo is a no-op.
+ const handleScroll = (event: React.UIEvent<HTMLDivElement>) => {
+ const el = event.currentTarget;
+ const distanceFromBottom = el.scrollHeight - el.scrollTop - el.clientHeight;
+ const atBottom = distanceFromBottom <= FOLLOW_THRESHOLD_PX;
+ setIsAtBottom(atBottom);
+ // User scrolled away from the tail: unpin. Re-pinning is explicit via
+ // the "Jump to latest" affordance (never implicit on scroll-down).
+ if (following && !atBottom) {
+ setFollowing(false);
+ }
+ };
+
+ const handleJumpToLatest = () => {
+ setFollowing(true);
+ const el = scrollerRef.current;
+ if (el != null) {
+ el.scrollTop = el.scrollHeight;
+ setIsAtBottom(true);
+ }
+ };
+
+ const colsStyle = hasTimestamps
+ ? hasSource
+ ? styles.colsFull
+ : styles.colsNoSource
+ : hasSource
+ ? styles.colsNoTimestamp
+ : styles.colsMessageOnly;
+
+ const renderDefaultRow = (entry: LogEntry) => {
+ const isExpandable = entry.detail != null;
+ const isExpanded = isExpandable && expandedIds.has(entry.id);
+ const cells = (
+ <>
+ {hasTimestamps && (
+ <span
+ {...stylex.props(
+ styles.timestamp,
+ isTerminal && styles.timestampTerminal,
+ )}>
+ {entry.timestamp}
+ </span>
+ )}
+ <span
+ {...stylex.props(
+ styles.level,
+ (isTerminal ? LEVEL_STYLE_TERMINAL : LEVEL_STYLE)[entry.level],
+ )}>
+ {entry.level}
+ </span>
+ {hasSource && (
+ <span
+ {...stylex.props(
+ styles.source,
+ isTerminal && styles.sourceTerminal,
+ )}
+ title={entry.source}>
+ {entry.source}
+ </span>
+ )}
+ <span
+ {...stylex.props(
+ styles.message,
+ isTerminal && styles.messageTerminal,
+ isTerminal &&
+ entry.level === 'error' &&
+ styles.messageErrorTerminal,
+ isTerminal && entry.level === 'warn' && styles.messageWarnTerminal,
+ )}>
+ {entry.message}
+ </span>
+ </>
+ );
+ const rowStyles = [
+ styles.row,
+ colsStyle,
+ isTerminal && styles.rowTerminal,
+ !isTerminal && entry.level === 'error' && styles.rowError,
+ !isTerminal && entry.level === 'warn' && styles.rowWarn,
+ ] as const;
+ if (!isExpandable) {
+ return (
+ <div data-level={entry.level} {...stylex.props(...rowStyles)}>
+ {cells}
+ </div>
+ );
+ }
+ return (
+ <>
+ <button
+ type="button"
+ aria-expanded={isExpanded}
+ data-level={entry.level}
+ onClick={() => toggleExpanded(entry.id)}
+ {...stylex.props(
+ ...rowStyles,
+ styles.rowButton,
+ isTerminal && styles.rowButtonTerminal,
+ )}>
+ {cells}
+ </button>
+ {isExpanded && (
+ <div
+ {...stylex.props(
+ styles.detail,
+ isTerminal && styles.detailTerminal,
+ )}>
+ {entry.detail}
+ </div>
+ )}
+ </>
+ );
+ };
+
+ return (
+ <div
+ ref={ref}
+ {...rest}
+ {...mergeProps(
+ themeProps('log-stream', {variant}),
+ stylex.props(styles.root, isTerminal && styles.rootTerminal, xstyle),
+ className,
+ style,
+ )}>
+ <div
+ ref={scrollerRef}
+ role="log"
+ aria-label={label}
+ onScroll={handleScroll}
+ {...stylex.props(styles.scroller(maxHeight ?? null))}>
+ {entries.map(entry => (
+ <Fragment key={entry.id}>
+ {renderEntry != null ? renderEntry(entry) : renderDefaultRow(entry)}
+ </Fragment>
+ ))}
+ </div>
+ {!following && !isAtBottom && entries.length > 0 && (
+ <button
+ type="button"
+ onClick={handleJumpToLatest}
+ {...stylex.props(
+ styles.jumpToLatest,
+ isTerminal && styles.jumpToLatestTerminal,
+ )}>
+ Jump to latest ↓
+ </button>
+ )}
+ </div>
+ );
+}
+
+LogStream.displayName = 'LogStream';
diff --git a/packages/lab/src/LogStream/index.ts b/packages/lab/src/LogStream/index.ts
new file mode 100644
index 0000000000..11225721a8
--- /dev/null
+++ b/packages/lab/src/LogStream/index.ts
@@ -0,0 +1,6 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+export {LogStream} from './LogStream';
+export type {LogStreamProps, LogEntry, LogStreamLevel} from './LogStream';
diff --git a/packages/lab/src/index.ts b/packages/lab/src/index.ts
index 84bb162bc2..e3caed21a0 100644
--- a/packages/lab/src/index.ts
+++ b/packages/lab/src/index.ts
@@ -211,3 +211,11 @@ export {
// It is no longer re-exported from @astryxdesign/lab.
export * from './Stepper';
export * from './CircularProgress';
+
+// LogStream — experimental streaming log viewer
+export {
+ LogStream,
+ type LogStreamProps,
+ type LogEntry,
+ type LogStreamLevel,
+} from './LogStream';