An open source design system that's fully customizable and agent ready
TypeScript
feat(templates): add five dashboard page templates (#5245)
Kenton Quatman53db047c0472
diff --git a/packages/cli/assets/templates/pages/dashboard-cohort-funnel/page.tsx b/packages/cli/assets/templates/pages/dashboard-cohort-funnel/page.tsxnew file mode 100644index 0000000000..a6401bf105--- /dev/null+++ b/packages/cli/assets/templates/pages/dashboard-cohort-funnel/page.tsx@@ -0,0 +1,914 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * Funnel & Cohort Analytics — a growth / product-analytics dashboard.+ *+ * Content-only (root `Layout`); the host supplies the app shell. Composed of+ * distinct analytics widgets stacked in the content column:+ *+ * KPI row | conversion funnel (stage bars + step drop-off)+ * | conversion-over-time trend | cohort retention grid+ *+ * The segment control (All / Web / iOS / Android) and the funnel window+ * (7d / 30d / 90d) reshape the funnel, the trend chart, and the KPIs. Cohort+ * retention is a table of Token-colored cells (heatmap-by-value). All data is+ * deterministic (fixed fixtures, no clocks/random) so previews stay stable.+ */++import {useMemo, useState, type CSSProperties} from 'react';+import * as stylex from '@stylexjs/stylex';+import {+ VStack,+ HStack,+ Layout,+ LayoutContent,+ LayoutHeader,+} from '@astryxdesign/core/Layout';+import {Grid} from '@astryxdesign/core/Grid';+import {Text, Heading} from '@astryxdesign/core/Text';+import {Card} from '@astryxdesign/core/Card';+import {Button} from '@astryxdesign/core/Button';+import {Icon} from '@astryxdesign/core/Icon';+import {Divider} from '@astryxdesign/core/Divider';+import {Token} from '@astryxdesign/core/Token';+import {Selector} from '@astryxdesign/core/Selector';+import {+ SegmentedControl,+ SegmentedControlItem,+} from '@astryxdesign/core/SegmentedControl';+import {Table, pixel} from '@astryxdesign/core/Table';+import type {TableColumn} from '@astryxdesign/core/Table';+import {+ BarChart,+ Bar,+ Cell,+ LineChart,+ Line,+ XAxis,+ YAxis,+ CartesianGrid,+ Tooltip,+ ResponsiveContainer,+} from 'recharts';+import {+ ArrowUpIcon,+ ArrowDownIcon,+ ArrowDownTrayIcon,+ ArrowTrendingDownIcon,+} from '@heroicons/react/24/outline';+import {StopIcon} from '@heroicons/react/24/solid';++// ============= TYPES =============++type Segment = 'all' | 'web' | 'ios' | 'android';+type FunnelWindow = '7d' | '30d' | '90d';++interface FunnelStage {+ key: string;+ label: string;+ // Absolute users entering this stage, per segment.+ users: Record<Segment, number>;+}++// ============= COLORS (design tokens w/ hex fallbacks) =============++const COLORS = {+ blue: 'var(--color-data-categorical-blue, #0171E3)',+ green: 'var(--color-data-categorical-green, #0B991F)',+ orange: 'var(--color-data-categorical-orange, #EB6E00)',+ purple: 'var(--color-data-categorical-purple, #6B1EFD)',+ teal: 'var(--color-data-categorical-teal, #008E80)',+};+const GRID_STROKE = 'var(--color-border, rgba(5, 54, 89, 0.1))';+const AXIS_TICK = {+ fontSize: 'var(--font-size-sm, 12px)',+ fill: 'var(--color-text-secondary, #4E606F)',+};++// Funnel bars step through the categorical palette top-to-bottom.+const FUNNEL_COLORS = [+ COLORS.blue,+ COLORS.teal,+ COLORS.green,+ COLORS.orange,+ COLORS.purple,+];++// ============= STYLES =============++const styles = stylex.create({+ // Rules between the drop-off steps. Each step draws its own leading rule,+ // pulled half a gap to the left so it sits centred in the column gap. The+ // step that starts a row draws its rule outside the grid's content box,+ // where `overflowX: clip` hides it — so the separators stay correct as the+ // grid reflows from four columns down to one.+ //+ // The `--spacing-3` below must match the step Grid's `gap={3}`, otherwise+ // the rules sit off-centre. StyleX needs a literal here, so the two can't+ // share a constant — keep them in sync by hand.+ stepGrid: {+ overflowX: 'clip',+ },+ step: {+ borderInlineStartWidth: '1px',+ borderInlineStartStyle: 'solid',+ borderInlineStartColor: 'var(--color-border, rgba(5, 54, 89, 0.1))',+ marginInlineStart: 'calc(var(--spacing-3, 12px) / -2)',+ paddingInlineStart: 'calc(var(--spacing-3, 12px) / 2)',+ },+});++// ============= FUNNEL DATA =============++// Window multipliers applied to the base (30d) stage counts.+const WINDOW_FACTOR: Record<FunnelWindow, number> = {+ '7d': 0.24,+ '30d': 1,+ '90d': 3.1,+};++const FUNNEL_STAGES: FunnelStage[] = [+ {+ key: 'visit',+ label: 'Visited site',+ users: {all: 128400, web: 82600, ios: 27300, android: 18500},+ },+ {+ key: 'signup',+ label: 'Signed up',+ users: {all: 41200, web: 24800, ios: 9600, android: 6800},+ },+ {+ key: 'activate',+ label: 'Activated',+ users: {all: 22600, web: 12900, ios: 5900, android: 3800},+ },+ {+ key: 'subscribe',+ label: 'Subscribed',+ users: {all: 9100, web: 5100, ios: 2600, android: 1400},+ },+ {+ key: 'retain',+ label: 'Retained 30d',+ users: {all: 6300, web: 3600, ios: 1850, android: 850},+ },+];++// ============= CONVERSION-OVER-TIME =============++interface TrendPoint {+ t: number;+ label: string;+ signup: number;+ activate: number;+ subscribe: number;+}++// Weekly stage-conversion rates (%). Signup->activate->subscribe.+//+// Shaped as a plausible growth story rather than a smooth ramp, so the chart+// reads like real telemetry: a W7 pricing test lifts paid conversion, a W9-W10+// onboarding regression sinks activation until a fix ships, a W15 acquisition+// campaign spikes signups with low-intent traffic (activation dips as signup+// peaks, and the two series cross), W18 is an outage week that knocks all three+// down together, and W19+ recovers to a net-upward trend.+const TREND: TrendPoint[] = [+ {t: 0, label: 'W1', signup: 30.1, activate: 52.4, subscribe: 38.2},+ {t: 1, label: 'W2', signup: 31.4, activate: 54.1, subscribe: 36.9},+ {t: 2, label: 'W3', signup: 29.2, activate: 51.2, subscribe: 39.8},+ {t: 3, label: 'W4', signup: 32.6, activate: 55.8, subscribe: 37.1},+ {t: 4, label: 'W5', signup: 28.4, activate: 53.6, subscribe: 40.4},+ {t: 5, label: 'W6', signup: 31.8, activate: 56.2, subscribe: 38.3},+ {t: 6, label: 'W7', signup: 33.5, activate: 54.3, subscribe: 44.6},+ {t: 7, label: 'W8', signup: 30.2, activate: 57.1, subscribe: 42.1},+ {t: 8, label: 'W9', signup: 34.1, activate: 48.9, subscribe: 37.4},+ {t: 9, label: 'W10', signup: 29.6, activate: 46.2, subscribe: 35.2},+ {t: 10, label: 'W11', signup: 32.9, activate: 50.4, subscribe: 38.9},+ {t: 11, label: 'W12', signup: 35.4, activate: 55.6, subscribe: 41.3},+ {t: 12, label: 'W13', signup: 31.1, activate: 57.3, subscribe: 39.2},+ {t: 13, label: 'W14', signup: 33.8, activate: 54.8, subscribe: 42.8},+ {t: 14, label: 'W15', signup: 41.2, activate: 49.6, subscribe: 40.1},+ {t: 15, label: 'W16', signup: 38.6, activate: 47.8, subscribe: 36.4},+ {t: 16, label: 'W17', signup: 30.4, activate: 53.2, subscribe: 39.7},+ {t: 17, label: 'W18', signup: 26.8, activate: 44.1, subscribe: 34.2},+ {t: 18, label: 'W19', signup: 31.9, activate: 51.7, subscribe: 38.1},+ {t: 19, label: 'W20', signup: 34.7, activate: 56.4, subscribe: 41.9},+ {t: 20, label: 'W21', signup: 32.2, activate: 58.2, subscribe: 44.2},+ {t: 21, label: 'W22', signup: 36.1, activate: 55.1, subscribe: 40.6},+ {t: 22, label: 'W23', signup: 33.4, activate: 59.4, subscribe: 43.8},+ {t: 23, label: 'W24', signup: 37.2, activate: 56.8, subscribe: 46.1},+ {t: 24, label: 'W25', signup: 34.9, activate: 60.1, subscribe: 42.7},+ {t: 25, label: 'W26', signup: 38.4, activate: 58.6, subscribe: 45.3},+];++// One row per plotted series, so the chart lines and the legend below it can't+// drift apart — both are rendered from this list.+const TREND_SERIES = [+ {key: 'signup', name: 'Visit → signup', color: COLORS.blue},+ {key: 'activate', name: 'Signup → activation', color: COLORS.green},+ {key: 'subscribe', name: 'Activation → paid', color: COLORS.orange},+] as const;++// Label every fifth week. Derived from TREND so the axis stays in-domain when+// the fixture grows or shrinks.+const TREND_TICK_STEP = 5;+const TREND_TICKS = Array.from(+ {length: Math.ceil(TREND.length / TREND_TICK_STEP)},+ (_, i) => i * TREND_TICK_STEP,+);+const formatTrendTick = (v: number) => TREND[v]?.label ?? '';++// ============= COHORT RETENTION =============++interface Cohort {+ label: string;+ size: number;+ // Retention % by week index (week 0 = 100 by definition).+ retention: number[];+}++const COHORTS: Cohort[] = [+ {+ label: 'Apr 6 – Apr 12',+ size: 4820,+ retention: [100, 62, 48, 41, 37, 34, 32, 31],+ },+ {+ label: 'Apr 13 – Apr 19',+ size: 5140,+ retention: [100, 64, 50, 43, 39, 36, 34],+ },+ {label: 'Apr 20 – Apr 26', size: 5390, retention: [100, 66, 52, 45, 41, 38]},+ {label: 'Apr 27 – May 3', size: 5610, retention: [100, 63, 49, 42, 38]},+ {label: 'May 4 – May 10', size: 5980, retention: [100, 67, 54, 47]},+ {label: 'May 11 – May 17', size: 6240, retention: [100, 69, 56]},+ {label: 'May 18 – May 24', size: 6510, retention: [100, 71]},+ {label: 'May 25 – May 31', size: 6720, retention: [100]},+];++const MAX_WEEKS = 8;++// Map a retention percentage to a Token color (green = sticky, red = leaky).+function retentionColor(+ pct: number,+): 'green' | 'teal' | 'yellow' | 'orange' | 'red' {+ if (pct >= 70) {+ return 'green';+ }+ if (pct >= 50) {+ return 'teal';+ }+ if (pct >= 40) {+ return 'yellow';+ }+ if (pct >= 32) {+ return 'orange';+ }+ return 'red';+}++// ============= KPIS =============++interface Kpi {+ key: string;+ label: string;+ value: string;+ delta: number;+ higherIsBetter: boolean;+}++const KPIS: Record<Segment, Kpi[]> = {+ all: [+ {+ key: 'v2s',+ label: 'Visit → signup',+ value: '32.1%',+ delta: 1.8,+ higherIsBetter: true,+ },+ {+ key: 's2a',+ label: 'Signup → activation',+ value: '54.9%',+ delta: 2.4,+ higherIsBetter: true,+ },+ {+ key: 'a2s',+ label: 'Activation → paid',+ value: '40.3%',+ delta: -1.1,+ higherIsBetter: true,+ },+ {+ key: 'w4',+ label: 'Week-4 retention',+ value: '43.2%',+ delta: 3.6,+ higherIsBetter: true,+ },+ ],+ web: [+ {+ key: 'v2s',+ label: 'Visit → signup',+ value: '30.0%',+ delta: 1.2,+ higherIsBetter: true,+ },+ {+ key: 's2a',+ label: 'Signup → activation',+ value: '52.0%',+ delta: 1.9,+ higherIsBetter: true,+ },+ {+ key: 'a2s',+ label: 'Activation → paid',+ value: '39.5%',+ delta: -0.6,+ higherIsBetter: true,+ },+ {+ key: 'w4',+ label: 'Week-4 retention',+ value: '41.8%',+ delta: 2.9,+ higherIsBetter: true,+ },+ ],+ ios: [+ {+ key: 'v2s',+ label: 'Visit → signup',+ value: '35.2%',+ delta: 2.6,+ higherIsBetter: true,+ },+ {+ key: 's2a',+ label: 'Signup → activation',+ value: '61.5%',+ delta: 3.1,+ higherIsBetter: true,+ },+ {+ key: 'a2s',+ label: 'Activation → paid',+ value: '44.1%',+ delta: 0.8,+ higherIsBetter: true,+ },+ {+ key: 'w4',+ label: 'Week-4 retention',+ value: '47.5%',+ delta: 4.2,+ higherIsBetter: true,+ },+ ],+ android: [+ {+ key: 'v2s',+ label: 'Visit → signup',+ value: '36.8%',+ delta: 2.1,+ higherIsBetter: true,+ },+ {+ key: 's2a',+ label: 'Signup → activation',+ value: '55.9%',+ delta: 1.4,+ higherIsBetter: true,+ },+ {+ key: 'a2s',+ label: 'Activation → paid',+ value: '36.8%',+ delta: -2.3,+ higherIsBetter: true,+ },+ {+ key: 'w4',+ label: 'Week-4 retention',+ value: '38.4%',+ delta: -0.9,+ higherIsBetter: true,+ },+ ],+};++const SEGMENT_OPTIONS = [+ {value: 'all', label: 'All platforms'},+ {value: 'web', label: 'Web'},+ {value: 'ios', label: 'iOS'},+ {value: 'android', label: 'Android'},+];++// ============= SHARED PIECES =============++// Icon's `color` prop only takes semantic names, but the legend swatch must+// match the exact chart series color — inline color required (same pattern as+// the shipped dashboard templates).+function LegendDot({color, label}: {color: string; label: string}) {+ const dotStyle: CSSProperties = {color};+ return (+ <HStack gap={2} vAlign="center">+ <Icon icon={StopIcon} size="xsm" style={dotStyle} />+ <Text type="supporting" color="secondary">+ {label}+ </Text>+ </HStack>+ );+}++function nf(n: number): string {+ return n.toLocaleString();+}++// ============= KPI TILE =============++function KpiTile({kpi}: {kpi: Kpi}) {+ const favorable = kpi.higherIsBetter ? kpi.delta >= 0 : kpi.delta <= 0;+ return (+ <Card padding={4}>+ <VStack gap={1}>+ <Text type="label" color="secondary">+ {kpi.label}+ </Text>+ <HStack gap={3}>+ <Heading level={1}>{kpi.value}</Heading>+ <HStack gap={1} vAlign="center">+ <Icon+ icon={kpi.delta >= 0 ? ArrowUpIcon : ArrowDownIcon}+ size="xsm"+ color={favorable ? 'success' : 'error'}+ />+ <Text type="supporting" color="secondary">+ {kpi.delta >= 0 ? '+' : ''}+ {kpi.delta.toFixed(1)} pts vs. prior+ </Text>+ </HStack>+ </HStack>+ </VStack>+ </Card>+ );+}++// ============= FUNNEL =============++interface FunnelBar {+ key: string;+ label: string;+ users: number;+ pctOfTop: number;+ stepPct: number | null;+ color: string;+}++interface FunnelTooltipEntry {+ payload: FunnelBar;+}++function FunnelTooltip({+ active,+ payload,+}: {+ active?: boolean;+ payload?: FunnelTooltipEntry[];+}) {+ if (!active || !payload?.length) {+ return null;+ }+ const bar = payload[payload.length - 1].payload;+ return (+ <Card padding={3}>+ <VStack gap={1}>+ <Text type="body" weight="semibold">+ {bar.label}+ </Text>+ <Text type="supporting" color="secondary">+ {nf(bar.users)} users · {bar.pctOfTop.toFixed(1)}% of top+ </Text>+ {bar.stepPct != null && (+ <Text type="supporting" color="secondary">+ {bar.stepPct.toFixed(1)}% from previous step+ </Text>+ )}+ </VStack>+ </Card>+ );+}++function ConversionFunnel({segment}: {segment: Segment}) {+ const bars = useMemo<FunnelBar[]>(() => {+ const top = FUNNEL_STAGES[0].users[segment];+ return FUNNEL_STAGES.map((stage, i) => {+ const users = stage.users[segment];+ const prev = i > 0 ? FUNNEL_STAGES[i - 1].users[segment] : null;+ return {+ key: stage.key,+ label: stage.label,+ users,+ pctOfTop: (users / top) * 100,+ stepPct: prev != null ? (users / prev) * 100 : null,+ color: FUNNEL_COLORS[i % FUNNEL_COLORS.length],+ };+ });+ }, [segment]);++ return (+ <VStack gap={4}>+ <ResponsiveContainer width="100%" height={260}>+ <BarChart+ data={bars}+ layout="vertical"+ margin={{top: 0, right: 24, left: 8, bottom: 0}}+ barCategoryGap={10}>+ <CartesianGrid horizontal={false} vertical stroke={GRID_STROKE} />+ <XAxis+ type="number"+ tick={AXIS_TICK}+ axisLine={false}+ tickLine={false}+ />+ <YAxis+ type="category"+ dataKey="label"+ tick={AXIS_TICK}+ axisLine={false}+ tickLine={false}+ width={110}+ />+ <Tooltip content={<FunnelTooltip />} cursor={{fill: GRID_STROKE}} />+ <Bar dataKey="users" radius={4} isAnimationActive={false}>+ {bars.map(bar => (+ <Cell key={bar.key} fill={bar.color} />+ ))}+ </Bar>+ </BarChart>+ </ResponsiveContainer>+ </VStack>+ );+}++// Step-by-step drop-off cards beneath the funnel.+function FunnelSteps({segment}: {segment: Segment}) {+ const steps = useMemo(() => {+ return FUNNEL_STAGES.slice(1).map((stage, i) => {+ const prev = FUNNEL_STAGES[i];+ const from = prev.users[segment];+ const to = stage.users[segment];+ const conv = (to / from) * 100;+ const drop = 100 - conv;+ return {+ key: stage.key,+ label: `${prev.label} → ${stage.label}`,+ conv,+ drop,+ };+ });+ }, [segment]);++ return (+ <Grid+ columns={{minWidth: 200, repeat: 'fit'}}+ gap={3}+ xstyle={styles.stepGrid}>+ {steps.map(step => {+ const leaky = step.drop >= 55;+ return (+ <VStack key={step.key} gap={1} xstyle={styles.step}>+ <Text type="label" color="secondary">+ {step.label}+ </Text>+ <HStack gap={2} vAlign="center">+ <Heading level={2}>{step.conv.toFixed(1)}%</Heading>+ <Token+ size="sm"+ color={leaky ? 'red' : 'green'}+ icon={+ <Icon+ icon={ArrowTrendingDownIcon}+ size="xsm"+ color="inherit"+ />+ }+ label={`-${step.drop.toFixed(0)}%`}+ />+ </HStack>+ </VStack>+ );+ })}+ </Grid>+ );+}++// ============= CONVERSION TREND =============++interface TrendTooltipEntry {+ name: string;+ value: number;+ color: string;+}++function TrendTooltip({+ active,+ payload,+ label,+}: {+ active?: boolean;+ payload?: TrendTooltipEntry[];+ label?: number;+}) {+ if (!active || !payload?.length) {+ return null;+ }+ const wk = typeof label === 'number' ? (TREND[label]?.label ?? '') : '';+ return (+ <Card padding={3}>+ <VStack gap={1}>+ <Text type="supporting" color="secondary">+ {wk}+ </Text>+ {payload.map(entry => (+ <LegendDot+ key={entry.name}+ color={entry.color}+ label={`${entry.name}: ${entry.value.toFixed(1)}%`}+ />+ ))}+ </VStack>+ </Card>+ );+}++function ConversionTrend() {+ return (+ <VStack gap={3}>+ <ResponsiveContainer width="100%" height={260}>+ <LineChart+ data={TREND}+ margin={{top: 5, right: 12, left: 0, bottom: 5}}>+ <CartesianGrid horizontal vertical={false} stroke={GRID_STROKE} />+ <XAxis+ dataKey="t"+ type="number"+ domain={[0, TREND.length - 1]}+ ticks={TREND_TICKS}+ tickFormatter={formatTrendTick}+ tick={AXIS_TICK}+ axisLine={false}+ tickLine={false}+ />+ <YAxis+ tick={AXIS_TICK}+ axisLine={false}+ tickLine={false}+ width={40}+ unit="%"+ />+ <Tooltip content={<TrendTooltip />} cursor={{stroke: GRID_STROKE}} />+ {TREND_SERIES.map(series => (+ <Line+ key={series.key}+ type="linear"+ dataKey={series.key}+ name={series.name}+ stroke={series.color}+ strokeWidth={1.5}+ strokeLinejoin="miter"+ dot={false}+ isAnimationActive={false}+ />+ ))}+ </LineChart>+ </ResponsiveContainer>+ <HStack gap={5} vAlign="center" wrap="wrap">+ {TREND_SERIES.map(series => (+ <LegendDot+ key={series.key}+ color={series.color}+ label={series.name}+ />+ ))}+ </HStack>+ </VStack>+ );+}++// ============= COHORT RETENTION GRID =============++interface CohortRow extends Record<string, unknown> {+ id: string;+ label: string;+ size: number;+ retention: number[];+}++function buildCohortColumns(): TableColumn<CohortRow>[] {+ const cols: TableColumn<CohortRow>[] = [+ {+ key: 'label',+ header: 'Cohort',+ width: pixel(150),+ renderCell: (item: CohortRow) => (+ <Text type="body" weight="semibold">+ {item.label}+ </Text>+ ),+ },+ {+ key: 'size',+ header: 'Users',+ width: pixel(90),+ renderCell: (item: CohortRow) => (+ <Text type="body" color="secondary">+ {nf(item.size)}+ </Text>+ ),+ },+ ];+ for (let week = 0; week < MAX_WEEKS; week++) {+ cols.push({+ key: `w${week}`,+ header: `W${week}`,+ width: pixel(72),+ renderCell: (item: CohortRow) => {+ const pct = item.retention[week];+ if (pct == null) {+ return (+ <Text type="supporting" color="secondary">+ —+ </Text>+ );+ }+ return (+ <Token size="sm" color={retentionColor(pct)} label={`${pct}%`} />+ );+ },+ });+ }+ return cols;+}++const cohortColumns = buildCohortColumns();+const cohortRows: CohortRow[] = COHORTS.map((c, i) => ({+ id: `c${i}`,+ label: c.label,+ size: c.size,+ retention: c.retention,+}));++// ============= SECTION HEADING =============++function SectionHeading({title, hint}: {title: string; hint?: string}) {+ return (+ <VStack>+ <Heading level={2}>{title}</Heading>+ {hint ? (+ <Text type="supporting" color="secondary">+ {hint}+ </Text>+ ) : null}+ </VStack>+ );+}++// ============= MAIN =============++export default function FunnelCohortAnalyticsPage() {+ const [segment, setSegment] = useState<Segment>('all');+ const [funnelWindow, setFunnelWindow] = useState<FunnelWindow>('30d');++ const kpis = KPIS[segment];+ const topOfFunnel = useMemo(() => {+ const base = FUNNEL_STAGES[0].users[segment];+ return Math.round(base * WINDOW_FACTOR[funnelWindow]);+ }, [segment, funnelWindow]);++ const overallConversion = useMemo(() => {+ const top = FUNNEL_STAGES[0].users[segment];+ const bottom = FUNNEL_STAGES[FUNNEL_STAGES.length - 1].users[segment];+ return ((bottom / top) * 100).toFixed(1);+ }, [segment]);++ return (+ <Layout+ height="fill"+ padding={4}+ contentWidth={1440}+ header={+ <LayoutHeader hasDivider>+ <HStack gap={3} vAlign="center" hAlign="between" wrap="wrap">+ <VStack gap={0}>+ <Heading level={1}>Funnel & cohort analytics</Heading>+ <Text type="supporting" color="secondary">+ {nf(topOfFunnel)} visitors · {overallConversion}% end-to-end+ conversion+ </Text>+ </VStack>+ <HStack gap={2}>+ <SegmentedControl+ label="Funnel window"+ value={funnelWindow}+ onChange={value => setFunnelWindow(value as FunnelWindow)}>+ <SegmentedControlItem label="7d" value="7d" />+ <SegmentedControlItem label="30d" value="30d" />+ <SegmentedControlItem label="90d" value="90d" />+ </SegmentedControl>+ <Selector+ label="Segment"+ isLabelHidden+ options={SEGMENT_OPTIONS}+ value={segment}+ onChange={value => setSegment(value as Segment)}+ />+ <Button+ label="Export"+ variant="secondary"+ icon={<Icon icon={ArrowDownTrayIcon} size="sm" />}+ />+ </HStack>+ </HStack>+ </LayoutHeader>+ }+ content={+ <LayoutContent>+ <VStack gap={10}>+ <VStack gap={4}>+ {/* KPI row */}+ <Grid columns={{minWidth: 240, repeat: 'fit'}} gap={3}>+ {kpis.map(kpi => (+ <KpiTile key={kpi.key} kpi={kpi} />+ ))}+ </Grid>++ {/* Conversion funnel */}+ <Card padding={6}>+ <VStack gap={6}>+ <SectionHeading+ title="Conversion funnel"+ hint={`${SEGMENT_OPTIONS.find(o => o.value === segment)?.label} · ${funnelWindow}`}+ />+ <ConversionFunnel segment={segment} />+ <Divider />+ <FunnelSteps segment={segment} />+ </VStack>+ </Card>++ {/* Conversion over time */}+ <Card padding={6}>+ <VStack gap={6}>+ <SectionHeading+ title="Conversion over time"+ hint={`Stage conversion rates · trailing ${TREND.length} weeks`}+ />+ <ConversionTrend />+ </VStack>+ </Card>+ </VStack>++ <Divider />++ {/* Cohort retention grid */}+ <VStack gap={6}>+ <SectionHeading+ title="Weekly retention cohorts"+ hint="Signup week × weeks since signup"+ />+ <Card padding={6}>+ <VStack gap={8}>+ <Table<CohortRow>+ data={cohortRows}+ columns={cohortColumns}+ idKey="id"+ density="balanced"+ dividers="rows"+ />+ <HStack gap={4} vAlign="center" wrap="wrap">+ <Text type="supporting" color="secondary">+ Retention:+ </Text>+ <HStack gap={2} vAlign="center">+ <Token size="sm" color="red" label="< 32%" />+ <Token size="sm" color="orange" label="32–40%" />+ <Token size="sm" color="yellow" label="40–50%" />+ <Token size="sm" color="teal" label="50–70%" />+ <Token size="sm" color="green" label="≥ 70%" />+ </HStack>+ </HStack>+ </VStack>+ </Card>+ </VStack>+ </VStack>+ </LayoutContent>+ }+ />+ );+}diff --git a/packages/cli/assets/templates/pages/dashboard-cohort-funnel/template.doc.mjs b/packages/cli/assets/templates/pages/dashboard-cohort-funnel/template.doc.mjsnew file mode 100644index 0000000000..485b26c6b2--- /dev/null+++ b/packages/cli/assets/templates/pages/dashboard-cohort-funnel/template.doc.mjs@@ -0,0 +1,12 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */+export const doc = {+ type: 'page',+ name: 'Funnel & Cohort Dashboard',+ displayName: 'Funnel & Cohort Dashboard',+ description:+ 'Growth analytics dashboard: conversion-rate KPIs, a multi-stage conversion funnel with step-by-step drop-off cards, a conversion-over-time trend chart, and a weekly cohort retention grid rendered as a color-coded heatmap table. Segment and funnel-window controls reshape the funnel, trend, and KPIs.',+ isReady: false,+ category: 'Dashboard - Funnel & Cohort',+};diff --git a/packages/cli/assets/templates/pages/dashboard-data/page.tsx b/packages/cli/assets/templates/pages/dashboard-data/page.tsxnew file mode 100644index 0000000000..1687fd1c5a--- /dev/null+++ b/packages/cli/assets/templates/pages/dashboard-data/page.tsx@@ -0,0 +1,894 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * Data Dashboard — a generic user-analytics dashboard.+ *+ * Content-only (root `Layout`); the host supplies the app shell. Modeled after+ * dense metric-monitoring dashboards: a filter bar and grids of small metric+ * cards — each with a sparkline and multi-period deltas (d/d, w/w, m/m, y/y)+ * with red/green direction coloring.+ *+ * filter bar | key metrics | devices trend | demographics | acquisition+ *+ * Every metric is generic and self-contained (no real users, no proprietary+ * data). All figures are deterministic (fixed fixtures, no clocks/random) so+ * previews stay stable.+ */++import {useState, type CSSProperties} from 'react';+import * as stylex from '@stylexjs/stylex';+import {+ VStack,+ HStack,+ Layout,+ LayoutContent,+ LayoutHeader,+} from '@astryxdesign/core/Layout';+import {Grid} from '@astryxdesign/core/Grid';+import {AspectRatio} from '@astryxdesign/core/AspectRatio';+import {Text, Heading} from '@astryxdesign/core/Text';+import {Card} from '@astryxdesign/core/Card';+import {Button} from '@astryxdesign/core/Button';+import {Icon} from '@astryxdesign/core/Icon';+import {Divider} from '@astryxdesign/core/Divider';+import {Badge} from '@astryxdesign/core/Badge';+import {ProgressBar} from '@astryxdesign/core/ProgressBar';+import {Selector} from '@astryxdesign/core/Selector';+import {Table, proportional, pixel} from '@astryxdesign/core/Table';+import type {TableColumn} from '@astryxdesign/core/Table';+import {+ BarChart,+ Bar,+ LineChart,+ Line,+ AreaChart,+ Area,+ XAxis,+ YAxis,+ CartesianGrid,+ Tooltip,+ ResponsiveContainer,+} from 'recharts';+import {+ ArrowUpIcon,+ ArrowDownIcon,+ ArrowDownTrayIcon,+ UsersIcon,+ CursorArrowRaysIcon,+} from '@heroicons/react/24/outline';+import {StopIcon} from '@heroicons/react/24/solid';++// ============= TYPES =============++type Segment = 'all' | 'new' | 'returning';+type DateRange = '7d' | '30d' | '90d';+type DeviceFilter = 'all' | 'mobile' | 'desktop' | 'tablet';++// Period-over-period change, in percent: day, week, month, and year.+interface Deltas {+ dd: number;+ ww: number;+ mm: number;+ yy: number;+}++// One point of a sparkline, pre-shaped for recharts so the fixtures do the+// work once at module load instead of on every render of every card.+interface SparkPoint {+ i: number;+ v: number;+}++interface Metric {+ key: string;+ label: string;+ value: string;+ // Whether a rising value is good (engagement) or bad (bounce rate).+ higherIsBetter: boolean;+ deltas: Deltas;+ spark: SparkPoint[];+}++// ============= COLORS (design tokens w/ hex fallbacks) =============++const COLORS = {+ blue: 'var(--color-data-categorical-blue, #0171E3)',+ green: 'var(--color-data-categorical-green, #0B991F)',+ orange: 'var(--color-data-categorical-orange, #EB6E00)',+ purple: 'var(--color-data-categorical-purple, #6B1EFD)',+ teal: 'var(--color-data-categorical-teal, #008E80)',+ neutral: 'var(--color-data-neutral, #8494A3)',+};+const GRID_STROKE = 'var(--color-border, rgba(5, 54, 89, 0.1))';+const AXIS_TICK = {+ fontSize: 'var(--font-size-sm, 12px)',+ fill: 'var(--color-text-secondary, #4E606F)',+};++// ============= DETERMINISTIC SERIES =============++// A full quarter. The sparklines and the active-users trend both span this+// window, so the card-level and chart-level views of the data agree.+const TREND_DAYS = 90;++// Hash-based noise in [0, 1) — deterministic, so previews never shift.+// Shared by the metric sparklines and the active-users trend below.+function noise(i: number, seed: number): number {+ const x = Math.sin(i * 127.1 + seed * 311.7) * 43758.5453;+ return x - Math.floor(x);+}++// Build a stable but spiky sparkline series: a trend line, a weekly rhythm, a+// mean-reverting drift, per-point jitter, and the occasional outlier burst.+function spark(seed: number, trend: number): SparkPoint[] {+ const out: SparkPoint[] = [];+ let drift = 0;+ for (let i = 0; i < TREND_DAYS; i++) {+ const base = 50 + (trend * i * 24) / TREND_DAYS;+ const weekly = Math.sin((i * Math.PI * 2) / 7 + seed) * 2.5;+ drift = drift * 0.72 + (noise(i, seed) - 0.5) * 7;+ const jitter = (noise(i, seed + 17) - 0.5) * 8;+ const burst =+ noise(i, seed + 91) > 0.9 ? (noise(i, seed + 43) - 0.4) * 20 : 0;+ out.push({i, v: Math.round(base + weekly + drift + jitter + burst)});+ }+ return out;+}++// ============= OVERVIEW METRICS =============++const OVERVIEW_METRICS: Metric[] = [+ {+ key: 'active-users',+ label: 'Active users',+ value: '1.28M',+ higherIsBetter: true,+ deltas: {dd: 0.4, ww: 2.1, mm: 6.4, yy: 18.2},+ spark: spark(1, 1.1),+ },+ {+ key: 'new-users',+ label: 'New users',+ value: '184.2K',+ higherIsBetter: true,+ deltas: {dd: 1.2, ww: 3.8, mm: 9.1, yy: 24.6},+ spark: spark(2, 1.4),+ },+ {+ key: 'sessions',+ label: 'Sessions',+ value: '4.62M',+ higherIsBetter: true,+ deltas: {dd: 0.2, ww: 1.4, mm: 5.2, yy: 15.9},+ spark: spark(3, 0.9),+ },+ {+ key: 'avg-session',+ label: 'Avg. session',+ value: '6m 42s',+ higherIsBetter: true,+ deltas: {dd: -0.3, ww: 0.8, mm: 2.1, yy: -4.3},+ spark: spark(4, 0.3),+ },+ {+ key: 'pages-session',+ label: 'Pages / session',+ value: '5.3',+ higherIsBetter: true,+ deltas: {dd: 0.1, ww: -0.6, mm: 1.2, yy: 3.7},+ spark: spark(5, 0.4),+ },+ {+ key: 'bounce',+ label: 'Bounce rate',+ value: '38.6%',+ higherIsBetter: false,+ deltas: {dd: -0.2, ww: -1.1, mm: -2.4, yy: -6.8},+ spark: spark(6, -0.5),+ },+ {+ key: 'dau-mau',+ label: 'DAU / MAU',+ value: '52.1%',+ higherIsBetter: true,+ deltas: {dd: 0.3, ww: 1.0, mm: 3.2, yy: 8.4},+ spark: spark(7, 0.7),+ },+ {+ key: 'conversion',+ label: 'Conversion rate',+ value: '3.84%',+ higherIsBetter: true,+ deltas: {dd: -0.1, ww: 0.9, mm: 2.6, yy: 11.2},+ spark: spark(8, 0.6),+ },+ {+ key: 'activation',+ label: 'Activation rate',+ value: '61.4%',+ higherIsBetter: true,+ deltas: {dd: 0.2, ww: 1.3, mm: 4.1, yy: 12.7},+ spark: spark(9, 0.8),+ },+ {+ key: 'retention-30',+ label: '30-day retention',+ value: '27.4%',+ higherIsBetter: true,+ deltas: {dd: 0.1, ww: -0.4, mm: 1.8, yy: 5.3},+ spark: spark(10, -0.3),+ },+ {+ key: 'churn',+ label: 'Churn rate',+ value: '4.7%',+ higherIsBetter: false,+ deltas: {dd: -0.1, ww: -0.5, mm: -1.3, yy: -3.9},+ spark: spark(11, -0.6),+ },+ {+ key: 'load-time',+ label: 'Avg. load time',+ value: '1.4s',+ higherIsBetter: false,+ deltas: {dd: 0.2, ww: 0.6, mm: -2.2, yy: -8.1},+ spark: spark(12, 0.35),+ },+];++// Active-users trend: the desktop/mobile/tablet split across TREND_DAYS.+// Weekends swing traffic from desktop to mobile, and each day carries its own+// jitter plus the occasional spike, so the series reads like real telemetry.+const ACTIVE_TREND = (() => {+ const out: {+ t: number;+ label: string;+ desktop: number;+ mobile: number;+ tablet: number;+ }[] = [];+ for (let i = 0; i < TREND_DAYS; i++) {+ const weekend = i % 7 === 5 || i % 7 === 6;+ const spike = noise(i, 61) > 0.88 ? 1 : 0;+ // Slopes are expressed as total drift across the window, so the shape+ // holds if TREND_DAYS changes.+ out.push({+ t: i,+ label: `Day ${i + 1}`,+ desktop: Math.round(+ 520 ++ (i * 90) / TREND_DAYS ++ (weekend ? -110 : 20) ++ (noise(i, 11) - 0.5) * 80,+ ),+ mobile: Math.round(+ 680 ++ (i * 150) / TREND_DAYS ++ (weekend ? 85 : -15) ++ (noise(i, 23) - 0.5) * 125 ++ spike * 130,+ ),+ tablet: Math.round(+ 140 + (weekend ? 24 : -5) + (noise(i, 37) - 0.5) * 40 + spike * 18,+ ),+ });+ }+ return out;+})();++// Four evenly spaced labels (roughly month boundaries), derived so the axis+// stays readable if TREND_DAYS changes.+const ACTIVE_TICK_COUNT = 4;+const ACTIVE_TICKS = Array.from({length: ACTIVE_TICK_COUNT}, (_, i) =>+ Math.round((i * (TREND_DAYS - 1)) / (ACTIVE_TICK_COUNT - 1)),+);++// ============= DEMOGRAPHICS =============++interface BreakdownSegment {+ label: string;+ value: number;+ color: string;+}++const AGE_DATA: BreakdownSegment[] = [+ {label: '18–24', value: 26, color: COLORS.blue},+ {label: '25–34', value: 34, color: COLORS.teal},+ {label: '35–44', value: 21, color: COLORS.green},+ {label: '45–54', value: 12, color: COLORS.orange},+ {label: '55+', value: 7, color: COLORS.neutral},+];++const GENDER_DATA: BreakdownSegment[] = [+ {label: 'Female', value: 48, color: COLORS.purple},+ {label: 'Male', value: 46, color: COLORS.blue},+ {label: 'Other / undisclosed', value: 6, color: COLORS.neutral},+];++const DEVICE_DATA: BreakdownSegment[] = [+ {label: 'Mobile', value: 58, color: COLORS.blue},+ {label: 'Desktop', value: 34, color: COLORS.teal},+ {label: 'Tablet', value: 8, color: COLORS.orange},+];++interface AcqRow extends Record<string, unknown> {+ id: string;+ channel: string;+ users: number;+ share: number;+ delta: number;+}++const ACQUISITION: AcqRow[] = [+ {id: 'a1', channel: 'Organic search', users: 486200, share: 38, delta: 4.2},+ {id: 'a2', channel: 'Direct', users: 295400, share: 23, delta: 1.1},+ {id: 'a3', channel: 'Social', users: 217800, share: 17, delta: 8.6},+ {id: 'a4', channel: 'Referral', users: 141900, share: 11, delta: -2.3},+ {id: 'a5', channel: 'Email', users: 89200, share: 7, delta: 3.4},+ {id: 'a6', channel: 'Paid ads', users: 51300, share: 4, delta: -1.8},+];++const ACQ_MAX = Math.max(...ACQUISITION.map(a => a.users));++// ============= FILTER OPTIONS =============++const RANGE_OPTIONS = [+ {value: '7d', label: 'Last 7 days'},+ {value: '30d', label: 'Last 30 days'},+ {value: '90d', label: 'Last 90 days'},+];+const SEGMENT_OPTIONS = [+ {value: 'all', label: 'All users'},+ {value: 'new', label: 'New users'},+ {value: 'returning', label: 'Returning users'},+];+const DEVICE_OPTIONS = [+ {value: 'all', label: 'All devices'},+ {value: 'mobile', label: 'Mobile'},+ {value: 'desktop', label: 'Desktop'},+ {value: 'tablet', label: 'Tablet'},+];++// ============= SHARED PIECES =============++// Icon's `color` prop only takes semantic names, but the legend swatch must+// match the exact chart series color — inline color required (same pattern as+// the shipped dashboard templates).+function LegendDot({color, label}: {color: string; label: string}) {+ const dotStyle: CSSProperties = {color};+ return (+ <HStack gap={2} vAlign="center">+ <Icon icon={StopIcon} size="xsm" style={dotStyle} />+ <Text type="supporting" color="secondary">+ {label}+ </Text>+ </HStack>+ );+}++// Locale is pinned: this is a client component, and letting the server and the+// browser pick different default locales produces a hydration mismatch (and+// breaks the deterministic previews this template promises).+function formatNumber(n: number): string {+ return n.toLocaleString('en-US');+}++// ============= METRIC MINI-CARD (with sparkline + 4 deltas) =============++// Direction is carried by the arrow next to the metric value; the delta+// figures themselves stay neutral so a card with four of them doesn't turn+// into a wall of red and green.+function DeltaValue({label, value}: {label: string; value: number}) {+ const flat = value === 0;+ const sign = value > 0 ? '+' : '';+ return (+ <Text type="body" weight="bold" color="primary" hasTabularNumbers>+ {flat ? '—' : `${sign}${value.toFixed(1)}%`}{' '}+ <Text type="inherit" weight="normal" color="secondary">+ {label}+ </Text>+ </Text>+ );+}++// The sparkline restates the trend the value and arrow already convey, so it+// is decorative: hidden from assistive tech rather than announced as an+// unlabelled chart.+function MiniSparkline({data, color}: {data: SparkPoint[]; color: string}) {+ return (+ <div aria-hidden="true">+ <ResponsiveContainer width="100%" height={48}>+ <LineChart data={data} margin={{top: 4, right: 0, left: 0, bottom: 0}}>+ <Line+ type="linear"+ dataKey="v"+ stroke={color}+ strokeWidth={1.25}+ strokeLinecap="butt"+ strokeLinejoin="miter"+ dot={false}+ isAnimationActive={false}+ />+ </LineChart>+ </ResponsiveContainer>+ </div>+ );+}++// Deltas sit in a 2x2 grid rather than a wrapping row so the four figures line+// up across every card regardless of how wide the number renders.+function MetricCard({metric}: {metric: Metric}) {+ const trendUp = metric.deltas.ww >= 0;+ const favorable = metric.higherIsBetter ? trendUp : !trendUp;+ const sparkColor = favorable ? COLORS.green : COLORS.orange;+ return (+ <Card padding={4}>+ <VStack gap={4}>+ <VStack gap={1}>+ <Text type="label" color="secondary">+ {metric.label}+ </Text>+ <HStack gap={2} vAlign="center">+ {/* Sized as the card's hero number, but demoted in the document+ outline: these sit under the section's h2, not beside the+ page's h1. */}+ <Heading level={1} accessibilityLevel={3}>+ {metric.value}+ </Heading>+ <Icon+ icon={trendUp ? ArrowUpIcon : ArrowDownIcon}+ size="sm"+ color={favorable ? 'success' : 'error'}+ />+ </HStack>+ </VStack>+ <MiniSparkline data={metric.spark} color={sparkColor} />+ <Grid columns={2} gap={2}>+ <DeltaValue label="d/d" value={metric.deltas.dd} />+ <DeltaValue label="w/w" value={metric.deltas.ww} />+ <DeltaValue label="m/m" value={metric.deltas.mm} />+ <DeltaValue label="y/y" value={metric.deltas.yy} />+ </Grid>+ </VStack>+ </Card>+ );+}++// Grid's `columns` prop carries a single minWidth, so the roomier track floor+// for wide viewports rides in as an xstyle override: Grid routes its track+// template through a CSS var and applies `xstyle` last, so this wins. Below+// the breakpoint the value is left unset and the `columns` prop stands.+const METRICS_WIDE = '@media (min-width: 900px)';++const metricsGridStyles = stylex.create({+ grid: {+ gridTemplateColumns: {+ default: null,+ [METRICS_WIDE]: 'repeat(auto-fit, minmax(320px, 1fr))',+ },+ },+});++// ============= ACTIVE USERS TREND =============++interface TrendTooltipEntry {+ name: string;+ value: number;+ color: string;+}++function ActiveTrendTooltip({+ active,+ payload,+ label,+}: {+ active?: boolean;+ payload?: TrendTooltipEntry[];+ label?: number;+}) {+ if (!active || !payload?.length) {+ return null;+ }+ const day =+ typeof label === 'number' ? (ACTIVE_TREND[label]?.label ?? '') : '';+ return (+ <Card padding={3}>+ <VStack gap={1}>+ <Text type="supporting" color="secondary">+ {day}+ </Text>+ {payload.map(entry => (+ <LegendDot+ key={entry.name}+ color={entry.color}+ label={`${entry.name}: ${formatNumber(entry.value)}K`}+ />+ ))}+ </VStack>+ </Card>+ );+}++function ActiveUsersTrend() {+ return (+ <VStack gap={3}>+ <ResponsiveContainer width="100%" height={280}>+ <AreaChart+ data={ACTIVE_TREND}+ margin={{top: 5, right: 12, left: 0, bottom: 5}}>+ <defs>+ <linearGradient id="au-mobile" x1="0" y1="0" x2="0" y2="1">+ <stop offset="5%" stopColor={COLORS.blue} stopOpacity={0.3} />+ <stop offset="95%" stopColor={COLORS.blue} stopOpacity={0.04} />+ </linearGradient>+ <linearGradient id="au-desktop" x1="0" y1="0" x2="0" y2="1">+ <stop offset="5%" stopColor={COLORS.teal} stopOpacity={0.3} />+ <stop offset="95%" stopColor={COLORS.teal} stopOpacity={0.04} />+ </linearGradient>+ </defs>+ <CartesianGrid horizontal vertical={false} stroke={GRID_STROKE} />+ <XAxis+ dataKey="t"+ type="number"+ domain={[0, TREND_DAYS - 1]}+ ticks={ACTIVE_TICKS}+ tickFormatter={(v: number) => ACTIVE_TREND[v]?.label ?? ''}+ tick={AXIS_TICK}+ axisLine={false}+ tickLine={false}+ />+ <YAxis+ tick={AXIS_TICK}+ axisLine={false}+ tickLine={false}+ width={40}+ unit="K"+ />+ <Tooltip+ content={<ActiveTrendTooltip />}+ cursor={{stroke: GRID_STROKE}}+ />+ <Area+ type="linear"+ dataKey="mobile"+ name="Mobile"+ stroke={COLORS.blue}+ strokeWidth={1.5}+ strokeLinejoin="miter"+ fill="url(#au-mobile)"+ dot={false}+ isAnimationActive={false}+ />+ <Area+ type="linear"+ dataKey="desktop"+ name="Desktop"+ stroke={COLORS.teal}+ strokeWidth={1.5}+ strokeLinejoin="miter"+ fill="url(#au-desktop)"+ dot={false}+ isAnimationActive={false}+ />+ <Area+ type="linear"+ dataKey="tablet"+ name="Tablet"+ stroke={COLORS.orange}+ strokeWidth={1.5}+ strokeLinejoin="miter"+ fill="none"+ dot={false}+ isAnimationActive={false}+ />+ </AreaChart>+ </ResponsiveContainer>+ <HStack gap={5} vAlign="center" wrap="wrap">+ <LegendDot color={COLORS.blue} label="Mobile" />+ <LegendDot color={COLORS.teal} label="Desktop" />+ <LegendDot color={COLORS.orange} label="Tablet" />+ </HStack>+ </VStack>+ );+}++// ============= BREAKDOWN (horizontal stacked bar) =============++function BreakdownCard({+ title,+ data,+}: {+ title: string;+ data: BreakdownSegment[];+}) {+ const total = data.reduce((s, d) => s + d.value, 0);+ const chartData = [Object.fromEntries(data.map(d => [d.label, d.value]))];+ return (+ <Card>+ <VStack gap={4}>+ {/* Card-title sizing, but h3 in the outline — these sit under the+ "Audience demographics" h2, so level 4 would skip a rank. */}+ <Heading level={4} accessibilityLevel={3}>+ {title}+ </Heading>+ <ResponsiveContainer width="100%" height={24}>+ <BarChart+ data={chartData}+ layout="vertical"+ margin={{top: 0, right: 0, bottom: 0, left: 0}}+ barCategoryGap={0}>+ <XAxis type="number" hide domain={[0, total]} />+ <YAxis type="category" hide />+ {data.map((d, i) => (+ <Bar+ key={d.label}+ dataKey={d.label}+ stackId="s"+ fill={d.color}+ isAnimationActive={false}+ radius={+ i === 0+ ? [4, 0, 0, 4]+ : i === data.length - 1+ ? [0, 4, 4, 0]+ : [0, 0, 0, 0]+ }+ />+ ))}+ </BarChart>+ </ResponsiveContainer>+ <VStack gap={2}>+ {data.map(d => (+ <HStack key={d.label} hAlign="between" vAlign="center">+ <LegendDot color={d.color} label={d.label} />+ <Text type="supporting" weight="semibold" hasTabularNumbers>+ {d.value}%+ </Text>+ </HStack>+ ))}+ </VStack>+ </VStack>+ </Card>+ );+}++// ============= TABLES =============++function DeltaBadge({value}: {value: number}) {+ const flat = value === 0;+ return (+ <Badge+ variant={flat ? 'neutral' : value > 0 ? 'green' : 'red'}+ label={`${value > 0 ? '+' : ''}${value.toFixed(1)}%`}+ />+ );+}++const acquisitionColumns: TableColumn<AcqRow>[] = [+ {+ key: 'channel',+ header: 'Channel',+ width: pixel(160),+ renderCell: (item: AcqRow) => (+ <Text type="body" weight="semibold">+ {item.channel}+ </Text>+ ),+ },+ {+ key: 'users',+ header: 'Users',+ width: proportional(1),+ renderCell: (item: AcqRow) => (+ <VStack gap={1}>+ <ProgressBar+ value={item.users}+ max={ACQ_MAX}+ label={`${item.channel} users`}+ isLabelHidden+ />+ <Text type="supporting" color="secondary" hasTabularNumbers>+ {formatNumber(item.users)}+ </Text>+ </VStack>+ ),+ },+ {+ key: 'share',+ header: 'Share',+ width: pixel(90),+ renderCell: (item: AcqRow) => (+ <Text type="body" hasTabularNumbers>+ {item.share}%+ </Text>+ ),+ },+ {+ key: 'delta',+ header: 'w/w',+ width: pixel(100),+ renderCell: (item: AcqRow) => <DeltaBadge value={item.delta} />,+ },+];++// ============= SECTION HEADING =============++// AspectRatio takes its width from the container, and as a flex child its own+// `width: 100%` would resolve against the whole header row. Pinning a width+// here gives it the definite box it needs and makes the tile a 32px square.+const sectionIconStyles = stylex.create({+ tile: {+ width: 'var(--spacing-8)',+ backgroundColor: 'var(--color-background-muted)',+ borderRadius: 'var(--radius-element)',+ },+});++function SectionHeading({+ title,+ hint,+ icon,+}: {+ title: string;+ hint?: string;+ icon?: typeof UsersIcon;+}) {+ return (+ <HStack hAlign="between" vAlign="center" gap={3}>+ <HStack gap={3} vAlign="center">+ {icon ? (+ <AspectRatio ratio={1} fit="center" xstyle={sectionIconStyles.tile}>+ <Icon icon={icon} size="sm" color="secondary" />+ </AspectRatio>+ ) : null}+ <Heading level={2}>{title}</Heading>+ </HStack>+ {hint ? (+ <Text type="supporting" color="secondary">+ {hint}+ </Text>+ ) : null}+ </HStack>+ );+}++// ============= MAIN =============++// The filters are presentational: the fixtures are a fixed snapshot, so the+// controls annotate the view rather than re-slicing the data. Swapping the+// fixtures for a query is the seam a consumer replaces.+function labelFor(+ options: readonly {value: string; label: string}[],+ value: string,+): string {+ return options.find(o => o.value === value)?.label ?? '';+}++export default function DataDashboardPage() {+ // Matches TREND_DAYS — the fixtures render a full quarter.+ const [range, setRange] = useState<DateRange>('90d');+ const [segment, setSegment] = useState<Segment>('all');+ const [device, setDevice] = useState<DeviceFilter>('all');++ const summary = [+ labelFor(SEGMENT_OPTIONS, segment),+ labelFor(DEVICE_OPTIONS, device),+ labelFor(RANGE_OPTIONS, range),+ ].join(' · ');++ return (+ <Layout+ height="fill"+ contentWidth={1440}+ header={+ <LayoutHeader hasDivider>+ <HStack gap={3} vAlign="center" hAlign="between" wrap="wrap">+ <VStack gap={0}>+ <Heading level={1}>Data Dashboard</Heading>+ <Text type="supporting" color="secondary">+ User analytics overview · {summary}+ </Text>+ </VStack>+ <HStack gap={1}>+ <Selector+ label="Date range"+ isLabelHidden+ options={RANGE_OPTIONS}+ value={range}+ onChange={value => setRange(value as DateRange)}+ />+ <Selector+ label="Segment"+ isLabelHidden+ options={SEGMENT_OPTIONS}+ value={segment}+ onChange={value => setSegment(value as Segment)}+ />+ <Selector+ label="Device"+ isLabelHidden+ options={DEVICE_OPTIONS}+ value={device}+ onChange={value => setDevice(value as DeviceFilter)}+ />+ <Button+ label="Export"+ variant="secondary"+ icon={<Icon icon={ArrowDownTrayIcon} size="sm" />}+ />+ </HStack>+ </HStack>+ </LayoutHeader>+ }+ content={+ <LayoutContent padding={6}>+ <VStack gap={10}>+ <VStack gap={6}>+ <SectionHeading+ title="Key metrics"+ hint="Change vs. prior day, week, month, and year"+ icon={UsersIcon}+ />+ <Grid+ columns={{minWidth: 240, repeat: 'fit'}}+ gap={3}+ xstyle={metricsGridStyles.grid}>+ {OVERVIEW_METRICS.map(metric => (+ <MetricCard key={metric.key} metric={metric} />+ ))}+ </Grid>+ </VStack>++ <VStack gap={6}>+ <SectionHeading+ title="Devices"+ hint="Daily active users (thousands)"+ icon={CursorArrowRaysIcon}+ />+ <Card padding={6}>+ <VStack gap={6}>+ <Text type="label">Daily active users by device type</Text>+ <ActiveUsersTrend />+ </VStack>+ </Card>+ </VStack>++ <Divider />++ <VStack gap={6}>+ <SectionHeading+ title="Audience demographics"+ hint="Share of active users"+ icon={UsersIcon}+ />+ <Grid columns={{minWidth: 320, repeat: 'fit'}} gap={4}>+ <BreakdownCard title="Age" data={AGE_DATA} />+ <BreakdownCard title="Gender" data={GENDER_DATA} />+ <BreakdownCard title="Device" data={DEVICE_DATA} />+ </Grid>+ </VStack>++ <VStack gap={6}>+ <SectionHeading+ title="Acquisition channels"+ hint="How users find the product"+ />+ <Card>+ <Table<AcqRow>+ data={ACQUISITION}+ columns={acquisitionColumns}+ idKey="id"+ density="balanced"+ dividers="rows"+ hasHover+ />+ </Card>+ </VStack>+ </VStack>+ </LayoutContent>+ }+ />+ );+}diff --git a/packages/cli/assets/templates/pages/dashboard-data/template.doc.mjs b/packages/cli/assets/templates/pages/dashboard-data/template.doc.mjsnew file mode 100644index 0000000000..b683cdfcef--- /dev/null+++ b/packages/cli/assets/templates/pages/dashboard-data/template.doc.mjs@@ -0,0 +1,13 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */+export const doc = {+ type: 'page',+ name: 'Data Dashboard',+ displayName: 'Data Dashboard',+ description:+ 'User-analytics dashboard with a filter bar, overview KPI cards with sparklines and d/d, w/w, m/m, y/y deltas, an active-users-by-device trend, and audience demographics and acquisition channels.',+ isReady: false,+ category: 'Dashboard - Analytics',+ isHiddenFromOverview: true,+};diff --git a/packages/cli/assets/templates/pages/dashboard-executive-summary/page.tsx b/packages/cli/assets/templates/pages/dashboard-executive-summary/page.tsxnew file mode 100644index 0000000000..69d6db5556--- /dev/null+++ b/packages/cli/assets/templates/pages/dashboard-executive-summary/page.tsx@@ -0,0 +1,874 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++import {useMemo, useState, type CSSProperties} from 'react';+import * as stylex from '@stylexjs/stylex';+import {+ VStack,+ HStack,+ StackItem,+ Layout,+ LayoutContent,+ LayoutHeader,+ LayoutPanel,+} from '@astryxdesign/core/Layout';+import {useMediaQuery} from '@astryxdesign/core/hooks';+import {Grid} from '@astryxdesign/core/Grid';+import {Text, Heading} from '@astryxdesign/core/Text';+import {Card} from '@astryxdesign/core/Card';+import {Button} from '@astryxdesign/core/Button';+import {Icon} from '@astryxdesign/core/Icon';+import {Divider} from '@astryxdesign/core/Divider';+import {Avatar} from '@astryxdesign/core/Avatar';+import {ProgressBar} from '@astryxdesign/core/ProgressBar';+import {+ SegmentedControl,+ SegmentedControlItem,+} from '@astryxdesign/core/SegmentedControl';+import {Timestamp} from '@astryxdesign/core/Timestamp';+import {+ AreaChart,+ Area,+ LineChart,+ Line,+ XAxis,+ YAxis,+ CartesianGrid,+ Tooltip,+ ResponsiveContainer,+} from 'recharts';+import {ArrowDownTrayIcon} from '@heroicons/react/24/outline';+import {+ ArrowUpIcon,+ ArrowDownIcon,+ ArrowRightIcon,+ StopIcon,+} from '@heroicons/react/24/solid';++// ============= TYPES =============++type Period = 'WoW' | 'MoM' | 'QoQ';+type Rag = 'green' | 'amber' | 'red';++interface Kpi {+ key: string;+ label: string;+ value: string;+ unit?: string;+ // Delta percentage per period; sign drives arrow + RAG.+ delta: Record<Period, number>;+ // Whether an increase is good (revenue) or bad (churn, cost).+ higherIsBetter: boolean;+}++interface Okr {+ objective: string;+ owner: string;+ actual: number;+ target: number;+ unit: string;+}++interface TrendSeries {+ key: string;+ title: string;+ unit: string;+ kind: 'area' | 'line';+ color: string;+ // 12 periods of [current, prior] pairs.+ data: {t: number; label: string; current: number; prior: number}[];+}++// ============= RAG COLOR MAPPING =============++const RAG_ICON: Record<Rag, 'success' | 'warning' | 'error'> = {+ green: 'success',+ amber: 'warning',+ red: 'error',+};++// A delta becomes RAG by magnitude + whether the direction is favorable.+function ragFor(deltaPct: number, higherIsBetter: boolean): Rag {+ const favorable = higherIsBetter ? deltaPct >= 0 : deltaPct <= 0;+ const mag = Math.abs(deltaPct);+ if (favorable) {+ return mag >= 1 ? 'green' : 'amber';+ }+ return mag >= 3 ? 'red' : 'amber';+}++// ============= CHART COLORS (design tokens w/ hex fallbacks) =============++const COLORS = {+ blue: 'var(--color-data-categorical-blue, #0171E3)',+ green: 'var(--color-data-categorical-green, #0B991F)',+ orange: 'var(--color-data-categorical-orange, #EB6E00)',+ purple: 'var(--color-data-categorical-purple, #6B1EFD)',+ prior: 'var(--color-text-secondary, #737373)',+};+const GRID_STROKE = 'var(--color-border, rgba(5, 54, 89, 0.1))';+const AXIS_TICK = {+ fontSize: 'var(--font-size-sm, 12px)',+ fill: 'var(--color-text-secondary, #4E606F)',+};++// ============= SCORECARD DATA =============++const KPIS: Kpi[] = [+ {+ key: 'revenue',+ label: 'Net revenue',+ value: '$4.82M',+ delta: {WoW: 2.4, MoM: 6.1, QoQ: 14.3},+ higherIsBetter: true,+ },+ {+ key: 'arr',+ label: 'ARR',+ value: '$58.1M',+ delta: {WoW: 1.1, MoM: 3.8, QoQ: 11.2},+ higherIsBetter: true,+ },+ {+ key: 'nrr',+ label: 'Net revenue retention',+ value: '112%',+ delta: {WoW: 0.3, MoM: -0.8, QoQ: 2.1},+ higherIsBetter: true,+ },+ {+ key: 'churn',+ label: 'Gross churn',+ value: '1.9%',+ delta: {WoW: 0.4, MoM: 1.6, QoQ: -0.7},+ higherIsBetter: false,+ },+ {+ key: 'cac',+ label: 'CAC payback',+ value: '14.2 mo',+ delta: {WoW: -0.2, MoM: -3.4, QoQ: -8.1},+ higherIsBetter: false,+ },+ {+ key: 'nps',+ label: 'NPS',+ value: '48',+ delta: {WoW: 1.0, MoM: 4.0, QoQ: 6.0},+ higherIsBetter: true,+ },+];++// The scorecard is one flat grid of 6 tiles: 1 column (small), 2 (medium),+// 3 (large) — i.e. 1x6, 2x3, 3x2. The tiers are pinned to viewport width+// rather than derived from tile width via auto-fill, so the breakpoints are+// explicit. The ranges are non-overlapping, so exactly one ever matches and+// the result can't depend on StyleX's at-rule ordering or on source order.+const SCORECARD_MEDIUM = '@media (min-width: 768px) and (max-width: 1199.98px)';+const SCORECARD_LARGE = '@media (min-width: 1200px)';++// Overrides Grid's own grid-template-columns. Grid routes its track template+// through a CSS var and applies `xstyle` last, so this wins.+const scorecardStyles = stylex.create({+ grid: {+ gridTemplateColumns: {+ default: '1fr',+ [SCORECARD_MEDIUM]: 'repeat(2, 1fr)',+ [SCORECARD_LARGE]: 'repeat(3, 1fr)',+ },+ },+});++// ============= OKR / GOAL ATTAINMENT =============++const OKRS: Okr[] = [+ {+ objective: 'Reach $60M ARR',+ owner: 'Dana Whitfield · CRO',+ actual: 58.1,+ target: 60,+ unit: 'M',+ },+ {+ objective: 'Expand into 3 new enterprise verticals',+ owner: 'Marcus Lin · VP Sales',+ actual: 2,+ target: 3,+ unit: '',+ },+ {+ objective: 'Ship AI copilot GA',+ owner: 'Priya Raman · VP Product',+ actual: 82,+ target: 100,+ unit: '%',+ },+ {+ objective: 'Improve gross margin to 78%',+ owner: 'Tom Okafor · CFO',+ actual: 75.4,+ target: 78,+ unit: '%',+ },+];++function okrRag(pct: number): Rag {+ if (pct >= 90) {+ return 'green';+ }+ if (pct >= 70) {+ return 'amber';+ }+ return 'red';+}++const RAG_PROGRESS: Record<Rag, 'success' | 'warning' | 'error'> = {+ green: 'success',+ amber: 'warning',+ red: 'error',+};++// ============= TREND DATA (period-over-period) =============++const WEEK_LABELS = [+ 'W1',+ 'W2',+ 'W3',+ 'W4',+ 'W5',+ 'W6',+ 'W7',+ 'W8',+ 'W9',+ 'W10',+ 'W11',+ 'W12',+];++function makeTrend(+ base: number,+ growth: number,+ priorGap: number,+ wobble: number,+): {t: number; label: string; current: number; prior: number}[] {+ return WEEK_LABELS.map((label, i) => {+ const drift = base * (1 + (growth * i) / 11);+ const wob = Math.sin(i * 1.3) * base * wobble;+ const current = Math.round(drift + wob);+ const prior = Math.round((drift + wob) * (1 - priorGap));+ return {t: i, label, current, prior};+ });+}++const TRENDS: TrendSeries[] = [+ {+ key: 'revenue',+ title: 'Net revenue',+ unit: 'k',+ kind: 'area',+ color: COLORS.blue,+ data: makeTrend(980, 0.24, 0.12, 0.03),+ },+ {+ key: 'pipeline',+ title: 'Qualified pipeline',+ unit: 'k',+ kind: 'area',+ color: COLORS.green,+ data: makeTrend(3200, 0.31, 0.18, 0.05),+ },+ {+ key: 'activation',+ title: 'Activation rate',+ unit: '%',+ kind: 'line',+ color: COLORS.purple,+ data: makeTrend(42, 0.28, 0.09, 0.04),+ },+ {+ key: 'support',+ title: 'Support CSAT',+ unit: '%',+ kind: 'line',+ color: COLORS.orange,+ data: makeTrend(88, 0.06, 0.03, 0.02),+ },+];++// ============= AUTO-GENERATED NARRATIVE =============++type CalloutStatus = 'success' | 'warning' | 'info';++interface Callout {+ status: CalloutStatus;+ title: string;+ detail: string;+}++const NARRATIVE: Record<Period, Callout[]> = {+ WoW: [+ {+ status: 'success',+ title: 'Net revenue up 2.4% week-over-week',+ detail:+ 'Driven by three enterprise renewals closing early in the East region; expansion ARR contributed 60% of the lift.',+ },+ {+ status: 'warning',+ title: 'Gross churn ticked up 0.4 points',+ detail:+ 'Two mid-market logos churned on price; both flagged in QBRs last month. Save-play in motion for the remaining at-risk cohort.',+ },+ {+ status: 'info',+ title: 'CAC payback holding at 14.2 months',+ detail:+ 'Paid acquisition efficiency steady; the shift toward partner-sourced pipeline is starting to show in blended CAC.',+ },+ ],+ MoM: [+ {+ status: 'success',+ title: 'Revenue accelerating: +6.1% month-over-month',+ detail:+ 'Second consecutive month of accelerating growth. New-logo bookings and expansion both above plan; net-new pipeline covers 3.2x of next quarter target.',+ },+ {+ status: 'warning',+ title: 'NRR dipped 0.8 points to 112%',+ detail:+ 'A seasonal downgrade cycle in the SMB segment pulled retention down slightly. Enterprise NRR remains above 120%.',+ },+ {+ status: 'success',+ title: 'CAC payback improved 3.4 points',+ detail:+ 'Sales efficiency gains from the new SDR playbook are compounding; payback now inside the 15-month board target.',+ },+ ],+ QoQ: [+ {+ status: 'success',+ title: 'Strong quarter: revenue +14.3%, ARR +11.2%',+ detail:+ 'Best quarter on record for net-new ARR. Two of three new verticals landed anchor customers; the AI copilot beta is converting at 2x the baseline trial rate.',+ },+ {+ status: 'success',+ title: 'Churn down 0.7 points quarter-over-quarter',+ detail:+ 'Retention initiatives launched in Q1 are paying off; gross churn at a two-year low and NRR up 2.1 points.',+ },+ {+ status: 'warning',+ title: 'Gross margin at 75.4%, short of the 78% goal',+ detail:+ 'Infrastructure cost from the AI copilot GA ramp is the primary drag. Finance projects margin recovery once usage-based pricing lands next quarter.',+ },+ ],+};++const PERIOD_SUBTITLE: Record<Period, string> = {+ WoW: 'Week of Jun 23 – Jun 29, 2026 vs. prior week',+ MoM: 'June 2026 vs. May 2026',+ QoQ: 'Q2 2026 vs. Q1 2026',+};++// ============= SHARED PIECES =============++// Icon's `color` prop only accepts semantic names, but the legend swatch must+// match the exact data-categorical stroke of its chart line — so an inline+// color is required here (same pattern as the shipped dashboard templates).+function LegendDot({color, label}: {color: string; label: string}) {+ const dotStyle: CSSProperties = {color};+ return (+ <HStack gap={2} vAlign="center">+ <Icon icon={StopIcon} size="xsm" style={dotStyle} />+ <Text type="supporting" color="secondary">+ {label}+ </Text>+ </HStack>+ );+}++// Up / down for movement, right for flat — the solid arrow set keeps the delta+// marker as visually weighty as the value it sits next to.+const DELTA_ICON = {+ up: ArrowUpIcon,+ down: ArrowDownIcon,+ flat: ArrowRightIcon,+};++function DeltaIndicator({deltaPct, rag}: {deltaPct: number; rag: Rag}) {+ const sign = deltaPct > 0 ? '+' : '';+ const direction = deltaPct === 0 ? 'flat' : deltaPct < 0 ? 'down' : 'up';+ return (+ <HStack gap={2} vAlign="center">+ <Text type="body" color="secondary">+ {sign}+ {deltaPct.toFixed(1)}%+ </Text>+ <Icon icon={DELTA_ICON[direction]} size="xsm" color={RAG_ICON[rag]} />+ </HStack>+ );+}++interface TrendTooltipEntry {+ name: string;+ value: number;+ color: string;+}++function makeTrendTooltip(unit: string) {+ return function TrendTooltip({+ active,+ payload,+ label,+ }: {+ active?: boolean;+ payload?: TrendTooltipEntry[];+ label?: number;+ }) {+ if (!active || !payload?.length) {+ return null;+ }+ const wk =+ typeof label === 'number'+ ? (WEEK_LABELS[label] ?? '')+ : String(label ?? '');+ return (+ <Card padding={3}>+ <VStack gap={1}>+ <Text type="supporting" color="secondary">+ {wk}+ </Text>+ {payload.map(entry => (+ <LegendDot+ key={entry.name}+ color={entry.color}+ label={`${entry.name}: ${entry.value.toLocaleString()}${unit}`}+ />+ ))}+ </VStack>+ </Card>+ );+ };+}++// ============= SCORECARD =============++function ScorecardTile({kpi, period}: {kpi: Kpi; period: Period}) {+ const deltaPct = kpi.delta[period];+ const rag = ragFor(deltaPct, kpi.higherIsBetter);+ return (+ <Card padding={5}>+ <VStack gap={1}>+ <Text type="label" color="secondary">+ {kpi.label}+ </Text>+ <HStack gap={4} vAlign="center">+ <Heading level={2}>{kpi.value}</Heading>+ <DeltaIndicator deltaPct={deltaPct} rag={rag} />+ </HStack>+ </VStack>+ </Card>+ );+}++// ============= OKR ATTAINMENT =============++function OkrRow({okr}: {okr: Okr}) {+ const pct = Math.round((okr.actual / okr.target) * 100);+ const rag = okrRag(pct);+ // `owner` is "Name · Title"; the avatar wants the person, not the title.+ const ownerName = okr.owner.split('·')[0].trim();+ return (+ <VStack gap={2}>+ <HStack hAlign="between" vAlign="center" gap={3}>+ <StackItem size="fill">+ <Heading level={4}>{okr.objective}</Heading>+ </StackItem>+ <Text type="supporting" color="secondary">+ {pct}%+ </Text>+ </HStack>+ <ProgressBar+ value={okr.actual}+ max={okr.target}+ variant={RAG_PROGRESS[rag]}+ label={okr.objective}+ isLabelHidden+ />+ <HStack hAlign="between" vAlign="center" gap={4}>+ <HStack gap={2} vAlign="center">+ <Avatar size="sm" name={ownerName} />+ <Text type="supporting" color="secondary">+ {okr.owner}+ </Text>+ </HStack>+ <Text type="supporting" color="secondary">+ {okr.actual}+ {okr.unit} / {okr.target}+ {okr.unit} target+ </Text>+ </HStack>+ </VStack>+ );+}++// ============= TREND CHART =============++function TrendChart({trend}: {trend: TrendSeries}) {+ const gradientId = `grad-${trend.key}`;+ const TrendTooltip = useMemo(+ () => makeTrendTooltip(trend.unit),+ [trend.unit],+ );+ const latest = trend.data[trend.data.length - 1];+ const deltaPct = Math.round(+ ((latest.current - latest.prior) / latest.prior) * 100,+ );+ return (+ <Card padding={5}>+ <VStack gap={6}>+ <HStack hAlign="between" vAlign="center">+ <HStack gap={2}>+ <Heading level={3}>{trend.title}</Heading>+ <Heading level={3} color="secondary">+ {latest.current.toLocaleString()}+ {trend.unit}+ </Heading>+ </HStack>+ <Text type="supporting" color="secondary">+ {deltaPct >= 0 ? '+' : ''}+ {deltaPct}% vs prior+ </Text>+ </HStack>+ <ResponsiveContainer width="100%" height={200}>+ {trend.kind === 'area' ? (+ <AreaChart+ data={trend.data}+ margin={{top: 5, right: 8, left: 0, bottom: 0}}>+ <defs>+ <linearGradient id={gradientId} x1="0" y1="0" x2="0" y2="1">+ <stop offset="5%" stopColor={trend.color} stopOpacity={0.3} />+ <stop+ offset="95%"+ stopColor={trend.color}+ stopOpacity={0.04}+ />+ </linearGradient>+ </defs>+ <CartesianGrid horizontal vertical={false} stroke={GRID_STROKE} />+ <XAxis+ dataKey="t"+ type="number"+ domain={[0, 11]}+ ticks={[0, 3, 7, 11]}+ tickFormatter={(v: number) => WEEK_LABELS[v] ?? ''}+ tick={AXIS_TICK}+ axisLine={false}+ tickLine={false}+ />+ <YAxis+ tick={AXIS_TICK}+ axisLine={false}+ tickLine={false}+ width={40}+ />+ <Tooltip+ content={<TrendTooltip />}+ cursor={{stroke: GRID_STROKE}}+ />+ <Area+ type="monotone"+ dataKey="prior"+ name="Prior"+ stroke={COLORS.prior}+ strokeWidth={1}+ strokeDasharray="4 4"+ fill="none"+ dot={false}+ isAnimationActive={false}+ />+ <Area+ type="monotone"+ dataKey="current"+ name="Current"+ stroke={trend.color}+ strokeWidth={2}+ fill={`url(#${gradientId})`}+ dot={false}+ isAnimationActive={false}+ />+ </AreaChart>+ ) : (+ <LineChart+ data={trend.data}+ margin={{top: 5, right: 8, left: 0, bottom: 0}}>+ <CartesianGrid horizontal vertical={false} stroke={GRID_STROKE} />+ <XAxis+ dataKey="t"+ type="number"+ domain={[0, 11]}+ ticks={[0, 3, 7, 11]}+ tickFormatter={(v: number) => WEEK_LABELS[v] ?? ''}+ tick={AXIS_TICK}+ axisLine={false}+ tickLine={false}+ />+ <YAxis+ tick={AXIS_TICK}+ axisLine={false}+ tickLine={false}+ width={40}+ />+ <Tooltip+ content={<TrendTooltip />}+ cursor={{stroke: GRID_STROKE}}+ />+ <Line+ type="monotone"+ dataKey="prior"+ name="Prior"+ stroke={COLORS.prior}+ strokeWidth={1}+ strokeDasharray="4 4"+ dot={false}+ isAnimationActive={false}+ />+ <Line+ type="monotone"+ dataKey="current"+ name="Current"+ stroke={trend.color}+ strokeWidth={2}+ dot={false}+ isAnimationActive={false}+ />+ </LineChart>+ )}+ </ResponsiveContainer>+ <HStack gap={5} vAlign="center">+ <LegendDot color={trend.color} label="Current" />+ <LegendDot color={COLORS.prior} label="Prior" />+ </HStack>+ </VStack>+ </Card>+ );+}++// ============= NARRATIVE =============++// Each callout is a discrete, independently-removable observation, so Card is+// the right container. Card variants are for categorization, not status — the+// status reads from the leading icon (glyph + semantic color + accessible+// name), never from the card surface.+const CALLOUT_ICON: Record<CalloutStatus, 'success' | 'warning' | 'info'> = {+ success: 'success',+ warning: 'warning',+ info: 'info',+};++const CALLOUT_ICON_COLOR: Record<+ CalloutStatus,+ 'success' | 'warning' | 'accent'+> = {+ success: 'success',+ warning: 'warning',+ info: 'accent',+};++const CALLOUT_LABEL: Record<CalloutStatus, string> = {+ success: 'Positive',+ warning: 'Needs attention',+ info: 'Context',+};++function NarrativeCard({callout}: {callout: Callout}) {+ return (+ <Card padding={5}>+ <HStack gap={3} vAlign="start">+ <Icon+ icon={CALLOUT_ICON[callout.status]}+ color={CALLOUT_ICON_COLOR[callout.status]}+ size="md"+ label={CALLOUT_LABEL[callout.status]}+ />+ <StackItem size="fill">+ <VStack gap={1}>+ <Heading level={4}>{callout.title}</Heading>+ <Text type="body" color="secondary">+ {callout.detail}+ </Text>+ </VStack>+ </StackItem>+ </HStack>+ </Card>+ );+}++function NarrativeBlock({period}: {period: Period}) {+ return (+ <VStack gap={2}>+ {NARRATIVE[period].map(callout => (+ <NarrativeCard key={callout.title} callout={callout} />+ ))}+ </VStack>+ );+}++// ============= SECTION HEADING =============++function SectionHeading({title, hint}: {title: string; hint?: string}) {+ return (+ <HStack hAlign="between" vAlign="center" gap={3}>+ <Heading level={2}>{title}</Heading>+ {hint ? (+ <Text type="supporting" color="secondary">+ {hint}+ </Text>+ ) : null}+ </HStack>+ );+}++// ============= PAGE CHROME =============++const pageStyles = stylex.create({+ // Deepen the scroll container's bottom gutter past the padding={6} default so+ // the last section doesn't butt against the edge. The matching container var+ // is updated too, since bleed children (Divider, Section) read it to pull+ // themselves back out to the content edge.+ contentBottomPad: {+ paddingBlockEnd: 'var(--spacing-10)',+ '--container-padding-block-end': 'var(--spacing-10)',+ },+});++// ============= MAIN =============++export default function ExecutiveReviewPage() {+ const [period, setPeriod] = useState<Period>('WoW');+ // The narrative rail needs ~400px of its own; below that the content column+ // would be too cramped for the 2-up trend grid, so the rail folds inline.+ const isNarrow = useMediaQuery('(max-width: 1024px)');++ const okrSummary = useMemo(() => {+ const pcts = OKRS.map(o => (o.actual / o.target) * 100);+ const onTrack = pcts.filter(p => p >= 90).length;+ return `${onTrack} of ${OKRS.length} on track`;+ }, []);++ return (+ <Layout+ height="fill"+ contentWidth={1440}+ header={+ <LayoutHeader padding={6} hasDivider>+ <HStack gap={3} vAlign="center" hAlign="between" wrap="wrap">+ <VStack gap={1}>+ <Heading level={1}>Weekly Business Review</Heading>+ <HStack gap={2} vAlign="center">+ <Text type="body" color="secondary">+ {PERIOD_SUBTITLE[period]}+ </Text>+ <Text type="body" color="secondary">+ · Generated+ </Text>+ <Timestamp+ value="2026-06-30T08:00:00Z"+ format="date"+ type="body"+ color="secondary"+ />+ </HStack>+ </VStack>+ <HStack gap={3}>+ <SegmentedControl+ label="Comparison period"+ value={period}+ onChange={value => setPeriod(value as Period)}>+ <SegmentedControlItem label="WoW" value="WoW" />+ <SegmentedControlItem label="MoM" value="MoM" />+ <SegmentedControlItem label="QoQ" value="QoQ" />+ </SegmentedControl>+ <Button+ label="Export"+ variant="secondary"+ icon={<Icon icon={ArrowDownTrayIcon} size="sm" />}+ />+ </HStack>+ </HStack>+ </LayoutHeader>+ }+ content={+ <LayoutContent padding={6} xstyle={pageStyles.contentBottomPad}>+ <VStack gap={10}>+ {/* Narrative lives in the end rail; it folds in here when narrow. */}+ {isNarrow && (+ <VStack gap={6}>+ <SectionHeading title="What changed & why" hint="AI summary" />+ <NarrativeBlock period={period} />+ </VStack>+ )}++ {/* Scorecard row */}+ <VStack gap={6}>+ <SectionHeading title="Scorecards" hint="Performance metrics" />+ <Grid gap={2} xstyle={scorecardStyles.grid}>+ {KPIS.map(kpi => (+ <ScorecardTile key={kpi.key} kpi={kpi} period={period} />+ ))}+ </Grid>+ </VStack>++ {/* OKR attainment */}+ <VStack gap={6}>+ <SectionHeading title="Goal attainment" hint={okrSummary} />+ <Card padding={6}>+ <VStack gap={6}>+ {OKRS.map((okr, i) => (+ <VStack gap={6} key={okr.objective}>+ {i > 0 && <Divider />}+ <OkrRow okr={okr} />+ </VStack>+ ))}+ </VStack>+ </Card>+ </VStack>++ {/* Trend section: 2x2 grid */}+ <VStack gap={6}>+ <SectionHeading+ title="Trends"+ hint="Current vs. prior period · trailing 12 weeks"+ />+ <Grid columns={{minWidth: 330, repeat: 'fit'}} gap={3}>+ {TRENDS.map(trend => (+ <TrendChart key={trend.key} trend={trend} />+ ))}+ </Grid>+ </VStack>+ </VStack>+ </LayoutContent>+ }+ end={+ isNarrow ? undefined : (+ <LayoutPanel+ width={400}+ padding={6}+ hasDivider+ role="complementary"+ label="What changed and why">+ <VStack gap={6}>+ <SectionHeading title="What changed & why" hint="AI summary" />+ <NarrativeBlock period={period} />+ </VStack>+ </LayoutPanel>+ )+ }+ />+ );+}diff --git a/packages/cli/assets/templates/pages/dashboard-executive-summary/template.doc.mjs b/packages/cli/assets/templates/pages/dashboard-executive-summary/template.doc.mjsnew file mode 100644index 0000000000..64915f49c4--- /dev/null+++ b/packages/cli/assets/templates/pages/dashboard-executive-summary/template.doc.mjs@@ -0,0 +1,13 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */+export const doc = {+ type: 'page',+ name: 'Executive Summary Dashoard',+ displayName: 'Executive Summary Dashboard',+ description:+ 'Executive weekly/quarterly business review: a headline KPI scorecard with WoW/MoM/QoQ deltas and RAG status, OKR goal-attainment progress bars, a 2x2 period-over-period trend grid (line + area charts), and an auto-generated "what changed & why" narrative in a right-hand rail that folds into the main column on narrow screens.',+ isReady: true,+ category: 'Dashboard - Executive Summary',+ isHiddenFromOverview: true,+};diff --git a/packages/cli/assets/templates/pages/dashboard-project-status/page.tsx b/packages/cli/assets/templates/pages/dashboard-project-status/page.tsxnew file mode 100644index 0000000000..dc58b919ac--- /dev/null+++ b/packages/cli/assets/templates/pages/dashboard-project-status/page.tsx@@ -0,0 +1,1139 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * Project Status Dashboard — a program / launch status tracker.+ *+ * Content-only (root `Layout`); the host supplies the app shell. Widgets stack+ * down a content column capped at 1440px:+ *+ * page header (title, program status, phase filter)+ * | milestone Gantt with a "today" marker+ * | progress donut + scope burndown + blockers & risks, an equal-width+ * three-up that steps down to two columns, then one+ * | workstream table+ *+ * The release-phase control (All / Build / Beta / GA) filters milestones,+ * workstreams and risks, each of which falls back to an empty state. Donut+ * arcs are weighted by story points rather than task count. All data is+ * deterministic (fixed fixtures, no clocks/random) so previews stay stable.+ */++import {useMemo, useState, type CSSProperties} from 'react';+import * as stylex from '@stylexjs/stylex';+import {+ VStack,+ HStack,+ Layout,+ LayoutContent,+ LayoutHeader,+} from '@astryxdesign/core/Layout';+import {Text, Heading} from '@astryxdesign/core/Text';+import {Card} from '@astryxdesign/core/Card';+import {Grid} from '@astryxdesign/core/Grid';+import {Section} from '@astryxdesign/core/Section';+import {Button} from '@astryxdesign/core/Button';+import {Icon} from '@astryxdesign/core/Icon';+import type {IconType} from '@astryxdesign/core/Icon';+import {Badge} from '@astryxdesign/core/Badge';+import {ProgressBar} from '@astryxdesign/core/ProgressBar';+import {Avatar} from '@astryxdesign/core/Avatar';+import {List, ListItem} from '@astryxdesign/core/List';+import {useHoverCard} from '@astryxdesign/core/HoverCard';+import {+ SegmentedControl,+ SegmentedControlItem,+} from '@astryxdesign/core/SegmentedControl';+import {Table, proportional} from '@astryxdesign/core/Table';+import type {TableColumn} from '@astryxdesign/core/Table';+import {Timestamp} from '@astryxdesign/core/Timestamp';+import {EmptyState} from '@astryxdesign/core/EmptyState';+import {+ BarChart,+ Bar,+ Cell,+ PieChart,+ Pie,+ ReferenceLine,+ LineChart,+ Line,+ XAxis,+ YAxis,+ CartesianGrid,+ Tooltip,+ ResponsiveContainer,+} from 'recharts';+import {+ CheckCircleIcon,+ ExclamationTriangleIcon,+ ArrowDownTrayIcon,+ FlagIcon,+} from '@heroicons/react/24/outline';+import {StopIcon} from '@heroicons/react/24/solid';++// ============= TYPES =============++type Rag = 'onTrack' | 'atRisk' | 'blocked';+type Phase = 'all' | 'build' | 'beta' | 'ga';+type ReleasePhase = Exclude<Phase, 'all'>;++interface Milestone {+ id: string;+ name: string;+ phase: ReleasePhase;+ // Day offsets on the shared TIMELINE_DAYS scale (project day 0 = kickoff).+ start: number;+ end: number;+ status: Rag;+ dateLabel: string;+}++interface Workstream extends Record<string, unknown> {+ id: string;+ name: string;+ owner: string;+ phase: ReleasePhase;+ percent: number;+ due: string;+ status: Rag;+}++interface Risk {+ id: string;+ title: string;+ workstream: string;+ phase: ReleasePhase;+ severity: Rag;+ owner: string;+ detail: string;+}++interface TaskStatusSegment {+ key: string;+ label: string;+ tasks: number;+ // Effort, not head count: `points` is what sizes the donut arc.+ points: number;+ color: string;+}++// ============= LABEL & TONE MAPPING =============++const PHASE_LABEL: Record<ReleasePhase, string> = {+ build: 'Build',+ beta: 'Beta',+ ga: 'GA',+};++const RAG_LABEL: Record<Rag, string> = {+ onTrack: 'On track',+ atRisk: 'At risk',+ blocked: 'Blocked',+};++const RAG_BADGE: Record<Rag, 'green' | 'yellow' | 'red'> = {+ onTrack: 'green',+ atRisk: 'yellow',+ blocked: 'red',+};++// Leading icon for the program-status badge in the page header, the one badge+// loud enough to earn one.+const RAG_ICON: Record<Rag, IconType> = {+ onTrack: CheckCircleIcon,+ atRisk: ExclamationTriangleIcon,+ blocked: ExclamationTriangleIcon,+};++// Chart fills for RAG status: the data-viz semantic anchors, not the UI status+// tokens (--color-success/warning/error), so a milestone bar and a "blocked"+// donut slice land on the same red.+const RAG_FILL: Record<Rag, string> = {+ onTrack: 'var(--color-data-categorical-green, #0B991F)',+ atRisk: 'var(--color-data-categorical-orange, #EB6E00)',+ blocked: 'var(--color-data-categorical-red, #F5394F)',+};++// ============= CHART CHROME (design tokens w/ hex fallbacks) =============++// The same slots `getChartColors()` resolves in @astryxdesign/charts, as CSS+// vars rather than the hook because page templates depend only on core ++// recharts. CHART_NEUTRAL is the reference-line / not-started tone.+const CHART_GRID = 'var(--color-border, rgba(5, 54, 89, 0.1))';+const CHART_LABEL = 'var(--color-text-secondary, #4E606F)';+const CHART_NEUTRAL = 'var(--color-data-neutral, #8494A3)';++const IDEAL_COLOR = CHART_NEUTRAL;+const ACTUAL_COLOR = 'var(--color-data-categorical-blue, #0171E3)';+const AXIS_TICK = {+ fontSize: 'var(--font-size-sm, 12px)',+ fill: CHART_LABEL,+};++// ============= TIMELINE SCALE =============++const TIMELINE_DAYS = 90;+const TIMELINE_TICK_STEP = 15;+const TIMELINE_TICKS = Array.from(+ {length: TIMELINE_DAYS / TIMELINE_TICK_STEP + 1},+ (_, i) => i * TIMELINE_TICK_STEP,+);++// "Today" marker, as a day offset on the same scale.+const PROJECT_DAY = 58;++// ============= DATA =============++// Task backlog by status. Tasks are not equally sized, so the fixture makes+// count and effort diverge deliberately; points sum to the 320 the burndown+// starts from. Statuses are categories rather than a scale, so the fills come+// from the categorical palette, reusing the Gantt's anchors so one status means+// one color everywhere on the page.+const TASK_STATUS: TaskStatusSegment[] = [+ {+ key: 'closed',+ label: 'Closed',+ tasks: 86,+ points: 190,+ color: 'var(--color-data-categorical-blue, #0171E3)',+ },+ {+ key: 'inProgress',+ label: 'In progress',+ tasks: 24,+ points: 58,+ color: 'var(--color-data-categorical-green, #0B991F)',+ },+ {+ key: 'inReview',+ label: 'In review',+ tasks: 12,+ points: 24,+ color: 'var(--color-data-categorical-orange, #EB6E00)',+ },+ {+ key: 'blocked',+ label: 'Blocked',+ tasks: 5,+ points: 22,+ color: 'var(--color-data-categorical-red, #F5394F)',+ },+ {+ key: 'planned',+ label: 'Planned',+ tasks: 21,+ points: 26,+ color: CHART_NEUTRAL,+ },+];++const MILESTONES: Milestone[] = [+ {+ id: 'm1',+ name: 'Kickoff & scoping',+ phase: 'build',+ start: 0,+ end: 8,+ status: 'onTrack',+ dateLabel: 'Apr 1 – Apr 9',+ },+ {+ id: 'm2',+ name: 'Architecture sign-off',+ phase: 'build',+ start: 8,+ end: 20,+ status: 'onTrack',+ dateLabel: 'Apr 9 – Apr 21',+ },+ {+ id: 'm3',+ name: 'Feature complete',+ phase: 'build',+ start: 20,+ end: 44,+ status: 'atRisk',+ dateLabel: 'Apr 21 – May 15',+ },+ {+ id: 'm4',+ name: 'Private beta',+ phase: 'beta',+ start: 44,+ end: 62,+ status: 'atRisk',+ dateLabel: 'May 15 – Jun 2',+ },+ {+ id: 'm5',+ name: 'Bug bash & hardening',+ phase: 'beta',+ start: 58,+ end: 72,+ status: 'blocked',+ dateLabel: 'May 29 – Jun 12',+ },+ {+ id: 'm6',+ name: 'GA readiness review',+ phase: 'ga',+ start: 72,+ end: 82,+ status: 'onTrack',+ dateLabel: 'Jun 12 – Jun 22',+ },+ {+ id: 'm7',+ name: 'Public launch',+ phase: 'ga',+ start: 82,+ end: 90,+ status: 'onTrack',+ dateLabel: 'Jun 22 – Jun 30',+ },+];++const WORKSTREAMS: Workstream[] = [+ {+ id: 'w1',+ name: 'Core platform',+ owner: 'Priya Raman',+ phase: 'build',+ percent: 100,+ due: '2026-04-21',+ status: 'onTrack',+ },+ {+ id: 'w2',+ name: 'Data pipeline',+ owner: 'Marcus Webb',+ phase: 'build',+ percent: 92,+ due: '2026-05-15',+ status: 'atRisk',+ },+ {+ id: 'w3',+ name: 'Web client',+ owner: 'Ana Duarte',+ phase: 'build',+ percent: 88,+ due: '2026-05-15',+ status: 'onTrack',+ },+ {+ id: 'w4',+ name: 'Beta onboarding',+ owner: 'Tom Okafor',+ phase: 'beta',+ percent: 64,+ due: '2026-06-02',+ status: 'atRisk',+ },+ {+ id: 'w5',+ name: 'Load & reliability',+ owner: 'Dana Whitfield',+ phase: 'beta',+ percent: 38,+ due: '2026-06-12',+ status: 'blocked',+ },+ {+ id: 'w6',+ name: 'Docs & enablement',+ owner: 'Sofia Marín',+ phase: 'ga',+ percent: 55,+ due: '2026-06-22',+ status: 'onTrack',+ },+ {+ id: 'w7',+ name: 'Launch marketing',+ owner: 'Kenji Watanabe',+ phase: 'ga',+ percent: 41,+ due: '2026-06-22',+ status: 'onTrack',+ },+ {+ id: 'w8',+ name: 'Go-to-market ops',+ owner: 'Lena Fischer',+ phase: 'ga',+ percent: 30,+ due: '2026-06-30',+ status: 'atRisk',+ },+];++const RISKS: Risk[] = [+ {+ id: 'r1',+ title: 'Load tests failing at 3x target concurrency',+ workstream: 'Load & reliability',+ phase: 'beta',+ severity: 'blocked',+ owner: 'Dana Whitfield',+ detail:+ 'p99 latency degrades past SLO above 12k concurrent sessions. Root cause traced to connection-pool saturation; fix depends on the data-pipeline retry change landing first.',+ },+ {+ id: 'r2',+ title: 'Data pipeline backfill slower than planned',+ workstream: 'Data pipeline',+ phase: 'build',+ severity: 'atRisk',+ owner: 'Marcus Webb',+ detail:+ 'Historical backfill is tracking two days behind. Mitigation: parallelizing the backfill workers; feature-complete date at risk if not recovered this week.',+ },+ {+ id: 'r3',+ title: 'Beta onboarding email deliverability',+ workstream: 'Beta onboarding',+ phase: 'beta',+ severity: 'atRisk',+ owner: 'Tom Okafor',+ detail:+ 'Invite emails landing in spam for two enterprise domains. Working with IT to allowlist sending IPs before the private beta opens.',+ },+];++// Ideal vs. actual remaining scope (story points), one entry per week. Actual+// trails ideal mid-project (scope discovery), then recovers late.+const BURNDOWN = (() => {+ const total = 320;+ const actualRemaining = [+ 320, 300, 286, 262, 240, 226, 210, 182, 150, 132, 96, 54, 20,+ ];+ const idealStep = total / (actualRemaining.length - 1);+ return actualRemaining.map((actual, i) => ({+ week: i,+ label: `W${i + 1}`,+ ideal: Math.max(0, Math.round(total - idealStep * i)),+ actual,+ }));+})();++const BURNDOWN_TICKS = [0, 3, 6, 9, 12];++// ============= DERIVED FROM DATA =============++// Program-wide aggregates: unaffected by the phase filter, so computed once.+const TASK_POINTS_TOTAL = TASK_STATUS.reduce((sum, s) => sum + s.points, 0);+const TASK_COUNT_TOTAL = TASK_STATUS.reduce((sum, s) => sum + s.tasks, 0);++// Worst status across every workstream wins.+const PROGRAM_STATUS: Rag = WORKSTREAMS.some(w => w.status === 'blocked')+ ? 'blocked'+ : WORKSTREAMS.some(w => w.status === 'atRisk')+ ? 'atRisk'+ : 'onTrack';++function byPhase<T extends {phase: ReleasePhase}>(+ items: T[],+ phase: Phase,+): T[] {+ return phase === 'all' ? items : items.filter(item => item.phase === phase);+}++// ============= DONUT GEOMETRY =============++const DONUT_SIZE = 208;+const DONUT_OUTER_RADIUS = 104;+const DONUT_INNER_RADIUS = 70;++// The standard 2px gap between touching marks, which Recharts wants as an+// angle: 2px of arc at the middle of the ring.+const DONUT_GAP_ANGLE =+ (2 / ((DONUT_OUTER_RADIUS + DONUT_INNER_RADIUS) / 2)) * (180 / Math.PI);++// ============= SHARED PIECES =============++const pageStyles = stylex.create({+ contentBottomPad: {+ paddingBlockEnd: 'var(--spacing-10)',+ },+ // The header and each Section run full-bleed so their dividers reach the+ // viewport edges; the column inside them is what gets capped and centered.+ contentColumn: {+ width: '100%',+ maxWidth: 1440,+ marginInline: 'auto',+ },+ // Risk rows carry no action, so ListItem's interactive treatment (pointer+ // cursor, pressed state) would be a lie. This is the hover half only — a hint+ // that the hover card exists — guarded so it never sticks on touch.+ riskRow: {+ transitionProperty: 'background-color',+ transitionDuration: 'var(--duration-fast-min)',+ transitionTimingFunction: 'var(--ease-standard)',+ backgroundColor: 'transparent',+ ':hover': {+ backgroundColor: {+ default: null,+ '@media (hover: hover)': 'var(--color-overlay-hover)',+ },+ },+ },+ // Rows run the full width of the card, so the hover card has to cap itself.+ riskDetail: {+ maxWidth: 320,+ },+ // Fixed frame so the ring's px radii stay exact.+ donutFrame: {+ width: DONUT_SIZE,+ height: DONUT_SIZE,+ flexShrink: 0,+ },+});++// Icon's `color` prop takes semantic names only, but a legend swatch has to+// match its series color exactly, so this one reaches for an inline color.+function LegendDot({color, label}: {color: string; label: string}) {+ const dotStyle: CSSProperties = {color};+ return (+ <HStack gap={2} vAlign="center">+ <Icon icon={StopIcon} size="xsm" style={dotStyle} />+ <Text type="supporting" color="secondary">+ {label}+ </Text>+ </HStack>+ );+}++function SectionHeading({title, hint}: {title: string; hint?: string}) {+ return (+ <HStack hAlign="between" vAlign="center" gap={3}>+ <Heading level={2}>{title}</Heading>+ {hint ? (+ <Text type="supporting" color="secondary">+ {hint}+ </Text>+ ) : null}+ </HStack>+ );+}++// Card titles are visually level 3 but sit at level 2 in the outline, as peers+// of the section headings. `hint` describes the card, `meta` is the count or+// figure that trails on the opposite edge.+function CardHeading({+ title,+ hint,+ meta,+}: {+ title: string;+ hint?: string;+ meta?: string;+}) {+ return (+ <HStack gap={3} hAlign="between" vAlign="center" wrap="wrap">+ <VStack>+ <Heading level={3} accessibilityLevel={2}>+ {title}+ </Heading>+ {hint ? (+ <Text type="supporting" color="secondary">+ {hint}+ </Text>+ ) : null}+ </VStack>+ {meta ? (+ <Text type="body" color="secondary">+ {meta}+ </Text>+ ) : null}+ </HStack>+ );+}++function PhaseEmptyState({noun}: {noun: string}) {+ return (+ <EmptyState+ title={`No ${noun} in this phase`}+ description={`Switch phases to see other ${noun}.`}+ icon={<Icon icon={FlagIcon} size="lg" />}+ isCompact+ />+ );+}++// ============= PAGE HEADER =============++function ProgramHeader({+ phase,+ onPhaseChange,+}: {+ phase: Phase;+ onPhaseChange: (phase: Phase) => void;+}) {+ return (+ <LayoutHeader padding={6} hasDivider>+ <HStack+ gap={3}+ vAlign="center"+ hAlign="between"+ wrap="wrap"+ xstyle={pageStyles.contentColumn}>+ <VStack gap={1}>+ <Heading level={1}>Aurora Launch</Heading>+ <HStack gap={2} vAlign="center">+ <Text type="body" color="secondary">+ Target GA ·+ </Text>+ <Timestamp+ value="2026-06-30T00:00:00Z"+ format="date"+ type="body"+ color="secondary"+ />+ <Badge+ variant={RAG_BADGE[PROGRAM_STATUS]}+ label={RAG_LABEL[PROGRAM_STATUS]}+ icon={<Icon icon={RAG_ICON[PROGRAM_STATUS]} size="sm" />}+ />+ </HStack>+ </VStack>+ <HStack gap={2}>+ <SegmentedControl+ label="Release phase"+ value={phase}+ onChange={value => onPhaseChange(value as Phase)}>+ <SegmentedControlItem label="All" value="all" />+ <SegmentedControlItem label="Build" value="build" />+ <SegmentedControlItem label="Beta" value="beta" />+ <SegmentedControlItem label="GA" value="ga" />+ </SegmentedControl>+ <Button+ label="Export status"+ variant="secondary"+ icon={<Icon icon={ArrowDownTrayIcon} size="sm" />}+ />+ </HStack>+ </HStack>+ </LayoutHeader>+ );+}++// ============= GANTT (milestone timeline) =============++const GANTT_MIN_HEIGHT = 160;+const GANTT_ROW_HEIGHT = 44;++interface GanttTooltipEntry {+ payload: Milestone & {offset: number; duration: number};+}++function GanttTooltip({+ active,+ payload,+}: {+ active?: boolean;+ payload?: GanttTooltipEntry[];+}) {+ if (!active || !payload?.length) {+ return null;+ }+ // The colored duration segment is stacked last, so it carries the milestone.+ const milestone = payload[payload.length - 1].payload;+ return (+ <Card padding={3}>+ <VStack gap={1}>+ <Text type="body" weight="semibold">+ {milestone.name}+ </Text>+ <Text type="supporting" color="secondary">+ {milestone.dateLabel} · {PHASE_LABEL[milestone.phase]}+ </Text>+ </VStack>+ </Card>+ );+}++function GanttChart({milestones}: {milestones: Milestone[]}) {+ // Recharts renders a floating bar as a transparent offset segment plus a+ // colored duration segment stacked on top.+ const data = milestones.map(m => ({+ ...m,+ offset: m.start,+ duration: m.end - m.start,+ }));+ const height = Math.max(GANTT_MIN_HEIGHT, data.length * GANTT_ROW_HEIGHT);++ return (+ <VStack gap={3}>+ <ResponsiveContainer width="100%" height={height}>+ <BarChart+ data={data}+ layout="vertical"+ margin={{top: 4, right: 16, left: 8, bottom: 4}}+ barCategoryGap={12}>+ <CartesianGrid horizontal={false} vertical stroke={CHART_GRID} />+ <XAxis+ type="number"+ domain={[0, TIMELINE_DAYS]}+ ticks={TIMELINE_TICKS}+ tickFormatter={(v: number) => `D${v}`}+ tick={AXIS_TICK}+ axisLine={false}+ tickLine={false}+ />+ <YAxis+ type="category"+ dataKey="name"+ tick={AXIS_TICK}+ axisLine={false}+ tickLine={false}+ width={148}+ />+ <Tooltip content={<GanttTooltip />} cursor={{fill: CHART_GRID}} />+ {/* An annotation rather than a series, so it takes the neutral tone+ instead of a categorical color. */}+ <ReferenceLine+ x={PROJECT_DAY}+ stroke={CHART_NEUTRAL}+ strokeDasharray="4 4"+ label={{+ value: 'Today',+ position: 'top',+ fontSize: 11,+ fill: CHART_NEUTRAL,+ }}+ />+ <Bar+ dataKey="offset"+ stackId="gantt"+ fill="transparent"+ isAnimationActive={false}+ />+ <Bar+ dataKey="duration"+ stackId="gantt"+ radius={4}+ isAnimationActive={false}>+ {data.map(m => (+ <Cell key={m.id} fill={RAG_FILL[m.status]} />+ ))}+ </Bar>+ </BarChart>+ </ResponsiveContainer>+ <HStack gap={4} vAlign="center" wrap="wrap">+ <LegendDot color={RAG_FILL.onTrack} label={RAG_LABEL.onTrack} />+ <LegendDot color={RAG_FILL.atRisk} label={RAG_LABEL.atRisk} />+ <LegendDot color={RAG_FILL.blocked} label={RAG_LABEL.blocked} />+ </HStack>+ </VStack>+ );+}++// ============= TASK PROGRESS (weighted donut) =============++function percentOfPoints(points: number): number {+ return Math.round((points / TASK_POINTS_TOTAL) * 100);+}++interface DonutTooltipEntry {+ payload: TaskStatusSegment;+}++function TaskDonutTooltip({+ active,+ payload,+}: {+ active?: boolean;+ payload?: DonutTooltipEntry[];+}) {+ if (!active || !payload?.length) {+ return null;+ }+ const segment = payload[0].payload;+ return (+ <Card padding={3}>+ <VStack gap={1}>+ <LegendDot color={segment.color} label={segment.label} />+ <Text type="supporting" color="secondary" hasTabularNumbers>+ {percentOfPoints(segment.points)}% · {segment.points} pts ·{' '}+ {segment.tasks} tasks+ </Text>+ </VStack>+ </Card>+ );+}++function TaskProgressDonut() {+ return (+ <HStack gap={8} vAlign="center" wrap="wrap">+ {/* Fixed size rather than a ResponsiveContainer: the ring geometry is+ deliberate, and the card wraps the legend under it rather than+ shrinking it. */}+ <div {...stylex.props(pageStyles.donutFrame)}>+ <PieChart+ width={DONUT_SIZE}+ height={DONUT_SIZE}+ margin={{top: 0, right: 0, bottom: 0, left: 0}}>+ <Pie+ data={TASK_STATUS}+ dataKey="points"+ nameKey="label"+ cx="50%"+ cy="50%"+ innerRadius={DONUT_INNER_RADIUS}+ outerRadius={DONUT_OUTER_RADIUS}+ paddingAngle={DONUT_GAP_ANGLE}+ // Noon start, running clockwise, which puts "Closed" at the top.+ startAngle={90}+ endAngle={-270}+ // The gap separates the arcs; a stroke would add non-data ink.+ stroke="none"+ isAnimationActive={false}>+ {TASK_STATUS.map(s => (+ <Cell key={s.key} fill={s.color} />+ ))}+ </Pie>+ <Tooltip content={<TaskDonutTooltip />} />+ </PieChart>+ </div>+ {/* A key, not a table: per-segment figures live in the tooltip. */}+ <VStack gap={2}>+ {TASK_STATUS.map(s => (+ <LegendDot key={s.key} color={s.color} label={s.label} />+ ))}+ </VStack>+ </HStack>+ );+}++// ============= BURN-DOWN CHART =============++interface BurndownTooltipEntry {+ name: string;+ value: number;+ color: string;+}++function BurndownTooltip({+ active,+ payload,+ label,+}: {+ active?: boolean;+ payload?: BurndownTooltipEntry[];+ label?: number;+}) {+ if (!active || !payload?.length) {+ return null;+ }+ const week = typeof label === 'number' ? (BURNDOWN[label]?.label ?? '') : '';+ return (+ <Card padding={3}>+ <VStack gap={1}>+ <Text type="supporting" color="secondary">+ {week}+ </Text>+ {payload.map(entry => (+ <LegendDot+ key={entry.name}+ color={entry.color}+ label={`${entry.name}: ${entry.value} pts`}+ />+ ))}+ </VStack>+ </Card>+ );+}++// Matches the donut frame so the two plots sharing the summary row read as one+// band.+const BURNDOWN_HEIGHT = DONUT_SIZE;++function BurndownChart() {+ return (+ <VStack gap={3}>+ <ResponsiveContainer width="100%" height={BURNDOWN_HEIGHT}>+ <LineChart+ data={BURNDOWN}+ margin={{top: 16, right: 4, left: 4, bottom: 4}}>+ <CartesianGrid horizontal vertical={false} stroke={CHART_GRID} />+ <XAxis+ dataKey="week"+ type="number"+ domain={[0, BURNDOWN.length - 1]}+ ticks={BURNDOWN_TICKS}+ tickFormatter={(v: number) => BURNDOWN[v]?.label ?? ''}+ tick={AXIS_TICK}+ axisLine={false}+ tickLine={false}+ />+ <YAxis+ tick={AXIS_TICK}+ axisLine={false}+ tickLine={false}+ width={40}+ unit=" pts"+ />+ <Tooltip+ content={<BurndownTooltip />}+ cursor={{stroke: CHART_GRID}}+ />+ <Line+ type="monotone"+ dataKey="ideal"+ name="Ideal"+ stroke={IDEAL_COLOR}+ strokeWidth={1}+ strokeDasharray="4 4"+ dot={false}+ isAnimationActive={false}+ />+ <Line+ type="monotone"+ dataKey="actual"+ name="Actual"+ stroke={ACTUAL_COLOR}+ strokeWidth={2}+ dot={false}+ isAnimationActive={false}+ />+ </LineChart>+ </ResponsiveContainer>+ <HStack gap={4} vAlign="center" wrap="wrap">+ <LegendDot color={ACTUAL_COLOR} label="Actual remaining" />+ <LegendDot color={IDEAL_COLOR} label="Ideal burndown" />+ </HStack>+ </VStack>+ );+}++// ============= RISKS LIST =============++function RiskRow({risk}: {risk: Risk}) {+ // The `<HoverCard>` wrapper is not usable here: it wraps its trigger in a+ // `display: contents` span, and a span between `<ul>` and `<li>` is invalid+ // markup that drops the row out of the list in the accessibility tree. The+ // hook puts the trigger ref straight on the `<li>` instead.+ const hoverCard = useHoverCard({+ placement: 'below',+ alignment: 'start',+ // The row is a plain `<li>` made focusable below, so leave nothing to+ // `auto` trigger detection.+ focusTrigger: 'always',+ });++ return (+ <ListItem+ ref={hoverCard.ref}+ // The row has no action of its own; this tab stop exists so the detail is+ // reachable without a pointer, and `aria-describedby` reads it out.+ tabIndex={0}+ aria-describedby={hoverCard.describedBy}+ xstyle={pageStyles.riskRow}+ label={risk.title}+ description={`${risk.workstream} · ${PHASE_LABEL[risk.phase]} · ${risk.owner}`}+ endContent={+ <>+ <Badge+ variant={RAG_BADGE[risk.severity]}+ label={RAG_LABEL[risk.severity]}+ />+ {/* Inside the row, where the popover `<span>` is valid markup and+ out of flow; a sibling of the `<li>` would not be. */}+ {hoverCard.renderHoverCard(+ <VStack gap={2} xstyle={pageStyles.riskDetail}>+ <Text type="body" weight="semibold">+ {risk.title}+ </Text>+ <Text type="supporting" color="secondary">+ {risk.detail}+ </Text>+ <HStack gap={2} vAlign="center">+ <Avatar name={risk.owner} size="sm" />+ <Text type="supporting" color="secondary">+ {risk.owner}+ </Text>+ </HStack>+ </VStack>,+ )}+ </>+ }+ />+ );+}++function RisksPanel({risks}: {risks: Risk[]}) {+ return (+ <Card padding={6}>+ <VStack gap={4}>+ <CardHeading+ title="Blockers & risks"+ hint="Hover or focus a row for detail"+ />+ {risks.length === 0 ? (+ <EmptyState+ title="No open blockers or risks"+ description="Nothing flagged for the selected phase. Keep it up."+ icon={<Icon icon={CheckCircleIcon} size="lg" color="success" />}+ isCompact+ />+ ) : (+ <List hasDividers>+ {risks.map(risk => (+ <RiskRow key={risk.id} risk={risk} />+ ))}+ </List>+ )}+ </VStack>+ </Card>+ );+}++// ============= WORKSTREAM TABLE =============++const WORKSTREAM_COLUMNS: TableColumn<Workstream>[] = [+ {+ key: 'name',+ header: 'Workstream',+ width: proportional(1, {minWidth: 160}),+ renderCell: (item: Workstream) => (+ <VStack gap={0}>+ <Text type="body" weight="semibold">+ {item.name}+ </Text>+ <Text type="supporting" color="secondary">+ {PHASE_LABEL[item.phase]}+ </Text>+ </VStack>+ ),+ },+ {+ key: 'owner',+ header: 'Owner',+ width: proportional(1, {minWidth: 160}),+ renderCell: (item: Workstream) => (+ <HStack gap={2} vAlign="center">+ <Avatar name={item.owner} size="sm" />+ <Text type="body">{item.owner}</Text>+ </HStack>+ ),+ },+ {+ key: 'percent',+ header: '% complete',+ width: proportional(2, {minWidth: 200}),+ renderCell: (item: Workstream) => (+ <VStack gap={1}>+ <ProgressBar+ value={item.percent}+ max={100}+ label={`${item.name} progress`}+ isLabelHidden+ />+ <Text type="supporting" color="secondary">+ {item.percent}%+ </Text>+ </VStack>+ ),+ },+ {+ key: 'due',+ header: 'Due',+ width: proportional(1, {minWidth: 120}),+ renderCell: (item: Workstream) => (+ <Timestamp value={item.due} format="date" />+ ),+ },+ {+ key: 'status',+ header: 'Status',+ width: proportional(1, {minWidth: 120}),+ renderCell: (item: Workstream) => (+ <Badge variant={RAG_BADGE[item.status]} label={RAG_LABEL[item.status]} />+ ),+ },+];++// ============= MAIN =============++export default function ProjectStatusPage() {+ const [phase, setPhase] = useState<Phase>('all');++ const milestones = useMemo(() => byPhase(MILESTONES, phase), [phase]);+ const workstreams = useMemo(() => byPhase(WORKSTREAMS, phase), [phase]);+ const risks = useMemo(() => byPhase(RISKS, phase), [phase]);++ return (+ <Layout+ height="fill"+ header={<ProgramHeader phase={phase} onPhaseChange={setPhase} />}+ content={+ <LayoutContent padding={0} xstyle={pageStyles.contentBottomPad}>+ <Section padding={6} dividers={['bottom']}>+ <VStack gap={6} xstyle={pageStyles.contentColumn}>+ <SectionHeading+ title="Milestone timeline"+ hint={`Project days 0–${TIMELINE_DAYS} · dashed line marks today`}+ />+ {milestones.length === 0 ? (+ <PhaseEmptyState noun="milestones" />+ ) : (+ <GanttChart milestones={milestones} />+ )}+ </VStack>+ </Section>++ <Section padding={6} paddingBlock={10}>+ <VStack gap={6} xstyle={pageStyles.contentColumn}>+ <Grid gap={4} columns={{minWidth: 320, max: 3}}>+ <Card padding={6}>+ <VStack gap={5}>+ <CardHeading+ title="Overall progress"+ hint={`${TASK_COUNT_TOTAL} tasks · ${TASK_POINTS_TOTAL} story points`}+ />+ <TaskProgressDonut />+ </VStack>+ </Card>++ <Card padding={6}>+ <VStack gap={5}>+ <CardHeading+ title="Scope burndown"+ hint={`Remaining story points · ${BURNDOWN.length} weeks`}+ />+ <BurndownChart />+ </VStack>+ </Card>++ <RisksPanel risks={risks} />+ </Grid>++ <Card padding={6}>+ <VStack gap={4}>+ <CardHeading+ title="Workstreams"+ meta={`${workstreams.length} of ${WORKSTREAMS.length}`}+ />+ {workstreams.length === 0 ? (+ <PhaseEmptyState noun="workstreams" />+ ) : (+ <Table<Workstream>+ data={workstreams}+ columns={WORKSTREAM_COLUMNS}+ idKey="id"+ density="balanced"+ dividers="rows"+ hasHover+ />+ )}+ </VStack>+ </Card>+ </VStack>+ </Section>+ </LayoutContent>+ }+ />+ );+}diff --git a/packages/cli/assets/templates/pages/dashboard-project-status/template.doc.mjs b/packages/cli/assets/templates/pages/dashboard-project-status/template.doc.mjsnew file mode 100644index 0000000000..7ff21690bc--- /dev/null+++ b/packages/cli/assets/templates/pages/dashboard-project-status/template.doc.mjs@@ -0,0 +1,13 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */+export const doc = {+ type: 'page',+ name: 'Project Status Dashboard',+ displayName: 'Project Status Dashboard',+ description:+ 'Project / program / launch status tracker: a task progress donut (breaking overall completion down by task status, weighted by story points rather than task count), a milestone Gantt timeline with a today marker, a full-width workstream table with owner, %-complete, due date and status pill, a blockers & risks card listing each open item as a row that reveals its detail in a hover card, and a scope burndown chart. A release-phase control filters milestones, workstreams, and risks.',+ isReady: true,+ category: 'Dashboard - Project Status',+ isHiddenFromOverview: true,+};diff --git a/packages/cli/assets/templates/pages/dashboard-service-monitoring/page.tsx b/packages/cli/assets/templates/pages/dashboard-service-monitoring/page.tsxnew file mode 100644index 0000000000..98108dda0e--- /dev/null+++ b/packages/cli/assets/templates/pages/dashboard-service-monitoring/page.tsx@@ -0,0 +1,1590 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * Service Health Monitor — a live-ops / SRE dashboard.+ *+ * Content-only (root `Layout`); the host supplies the app shell. Frame:+ * header (global controls) | content (KPIs, charts, uptime) | triage rail 400+ *+ * The page is anchored to the viewport height, so the header stays put while+ * the content column and the rail scroll within it — never the window.+ *+ * The rail is one scroll region holding two sections — active alerts over a+ * per-service breakdown — each with a header that pins while its list scrolls+ * under it. Below 1024px the rail folds into the content column as two cards.+ *+ * The time-window control (1h/1d/7d), environment, and region selectors are+ * real: they reshape the charts, KPI sparklines, and the rail's service rows.+ * All data is deterministic (fixed fixtures, no clocks/random) so previews+ * stay stable.+ */++import {+ Fragment,+ useMemo,+ useState,+ type CSSProperties,+ type ReactNode,+} from 'react';+import * as stylex from '@stylexjs/stylex';+import {+ VStack,+ HStack,+ StackItem,+ Layout,+ LayoutContent,+ LayoutHeader,+ LayoutPanel,+} from '@astryxdesign/core/Layout';+import {Grid} from '@astryxdesign/core/Grid';+import {Text, Heading} from '@astryxdesign/core/Text';+import {Card} from '@astryxdesign/core/Card';+import {Icon} from '@astryxdesign/core/Icon';+import type {IconType} from '@astryxdesign/core/Icon';+import {Divider} from '@astryxdesign/core/Divider';+import {Badge} from '@astryxdesign/core/Badge';+import {Token} from '@astryxdesign/core/Token';+import {StatusDot} from '@astryxdesign/core/StatusDot';+import type {StatusDotVariant} from '@astryxdesign/core/StatusDot';+import {Selector} from '@astryxdesign/core/Selector';+import {+ SegmentedControl,+ SegmentedControlItem,+} from '@astryxdesign/core/SegmentedControl';+import {List, ListItem} from '@astryxdesign/core/List';+import {Timestamp} from '@astryxdesign/core/Timestamp';+import {EmptyState} from '@astryxdesign/core/EmptyState';+import {useMediaQuery} from '@astryxdesign/core/hooks';+import {+ LineChart,+ Line,+ XAxis,+ YAxis,+ CartesianGrid,+ Tooltip,+ ResponsiveContainer,+} from 'recharts';+import {+ ArrowUpIcon,+ ArrowDownIcon,+ BellAlertIcon,+ CheckCircleIcon,+ ServerStackIcon,+} from '@heroicons/react/24/outline';+import {StopIcon} from '@heroicons/react/24/solid';++// ============= TYPES =============++type TimeWindow = '1h' | '1d' | '7d';+type Environment = 'production' | 'staging' | 'development';+type HealthStatus = 'healthy' | 'warning' | 'critical';+type MetricKey = 'p50' | 'p95' | 'p99' | 'useast' | 'uswest' | 'euwest';++type SeriesPoint = Record<MetricKey, number> & {+ t: number;+ label: string;+};++interface WindowSeries {+ points: SeriesPoint[];+ ticks: number[];+ tickLabels: Record<number, string>;+}++const STATUS_STROKE: Record<HealthStatus, string> = {+ healthy: 'var(--color-success, #0B991F)',+ warning: 'var(--color-warning, #B25000)',+ critical: 'var(--color-error, #D6002A)',+};++const STATUS_DOT: Record<HealthStatus, StatusDotVariant> = {+ healthy: 'success',+ warning: 'warning',+ critical: 'error',+};++// Accessible label wherever a StatusDot is the only carrier of state.+const STATUS_LABEL: Record<HealthStatus, string> = {+ healthy: 'Healthy',+ warning: 'Degraded',+ critical: 'Down',+};++const SEVERITY_RANK: Record<HealthStatus, number> = {+ critical: 0,+ warning: 1,+ healthy: 2,+};++// ============= DETERMINISTIC TIME-SERIES =============++// Staging and dev carry a fraction of prod's load, and run leaner with it.+const ENV_FACTOR: Record<Environment, number> = {+ production: 1,+ staging: 0.16,+ development: 0.04,+};++const ENV_LATENCY_FACTOR: Record<Environment, number> = {+ production: 1,+ staging: 0.82,+ development: 0.7,+};++const DAY_LABELS = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];++function pad2(n: number): string {+ return n < 10 ? `0${n}` : `${n}`;+}++// Pseudo-noise in [0, 1) — a hash, not a PRNG, so every render is identical.+function hashNoise(i: number, seed: number): number {+ const x = Math.sin(i * 127.1 + seed * 311.7) * 43758.5453;+ return x - Math.floor(x);+}++// Signed jitter in [-1, 1) — the per-sample wobble every real metric carries.+function jitter(i: number, seed: number): number {+ return hashNoise(i, seed) * 2 - 1;+}++// Sparse heavy-tail burst in [0, 1], zero most of the time: metrics sit near+// baseline and occasionally kick rather than wandering smoothly.+function burstAt(i: number, seed: number, rate: number): number {+ const gate = hashNoise(i, seed);+ if (gate < 1 - rate) {+ return 0;+ }+ const t = (gate - (1 - rate)) / rate;+ return t * t;+}++// A diurnal baseline under constant jitter, punctuated by sparse bursts, with a+// sustained latency spike mid-window to match the SEV2 alert in the rail.+function buildWindow(kind: TimeWindow): WindowSeries {+ const config: Record<+ TimeWindow,+ {n: number; stepSec: number; cycles: number}+ > = {+ '1h': {n: 120, stepSec: 30, cycles: 1.2},+ '1d': {n: 144, stepSec: 600, cycles: 2},+ '7d': {n: 168, stepSec: 3600, cycles: 7},+ };+ const {n, stepSec, cycles} = config[kind];+ const points: SeriesPoint[] = [];+ const spikeCenter = Math.round(n * 0.62);+ const spikeWidth = Math.max(3, Math.round(n * 0.05));++ for (let i = 0; i < n; i++) {+ const phase = (i / n) * Math.PI * 2 * cycles;+ const diurnal = Math.sin(phase);+ const diurnal2 = Math.sin(phase + 1.1);+ const diurnal3 = Math.sin(phase + 2.3);++ const dist = Math.abs(i - spikeCenter);+ const spike = dist <= spikeWidth ? (1 - dist / (spikeWidth + 1)) * 170 : 0;++ // A real slowdown hits the whole distribution, hardest at the tail.+ const burst = burstAt(i, 3.1, 0.14);+ const p50 = 46 + 9 * diurnal + spike * 0.15 + burst * 11 + jitter(i, 1) * 4;+ const p95 =+ 158 + 38 * diurnal + spike * 0.6 + burst * 58 + jitter(i, 2) * 15;+ const p99 =+ 312 + 88 * diurnal + spike * 1.6 + burst * 195 + jitter(i, 3) * 38;++ // Deploys and outages move every region together.+ const pulse = burstAt(i, 7.3, 0.18) - burstAt(i, 9.7, 0.12);+ const useast = 9200 + 2600 * diurnal + pulse * 1500 + jitter(i, 11) * 520;+ const uswest = 6100 + 1500 * diurnal2 + pulse * 900 + jitter(i, 13) * 380;+ const euwest = 3900 + 1200 * diurnal3 + pulse * 620 + jitter(i, 17) * 260;++ const totalMin = Math.floor((i * stepSec) / 60);+ let label: string;+ if (kind === '7d') {+ label = DAY_LABELS[Math.floor(totalMin / (60 * 24)) % 7];+ } else {+ const hh = Math.floor(totalMin / 60) % 24;+ const mm = totalMin % 60;+ label = `${pad2(hh)}:${pad2(mm)}`;+ }++ points.push({+ t: i,+ label,+ p50: Math.round(p50),+ p95: Math.round(p95),+ p99: Math.round(p99),+ useast: Math.round(useast),+ uswest: Math.round(uswest),+ euwest: Math.round(euwest),+ });+ }++ // A fixed handful of ticks, so dense sampling can't crowd the axis.+ const ticks: number[] = [];+ if (kind === '7d') {+ const perDay = Math.round((60 * 60 * 24) / stepSec);+ for (let d = 0; d < 7; d++) {+ ticks.push(d * perDay);+ }+ } else {+ for (let k = 0; k < 6; k++) {+ ticks.push(Math.round((k / 5) * (n - 1)));+ }+ }+ const tickLabels: Record<number, string> = {};+ for (const tk of ticks) {+ tickLabels[tk] = points[Math.min(tk, points.length - 1)]?.label ?? '';+ }++ return {points, ticks, tickLabels};+}++const SERIES: Record<TimeWindow, WindowSeries> = {+ '1h': buildWindow('1h'),+ '1d': buildWindow('1d'),+ '7d': buildWindow('7d'),+};++// ============= KPI DATA (per environment) =============++interface Kpi {+ key: string;+ label: string;+ value: string;+ status: HealthStatus;+ statusLabel: string;+ delta: string;+ /** Whether the delta direction is a good thing — drives the arrow + color. */+ deltaPositive: boolean;+}++const KPI_BY_ENV: Record<Environment, Kpi[]> = {+ production: [+ {+ key: 'health',+ label: 'Overall health',+ value: '98.6%',+ status: 'healthy',+ statusLabel: 'Healthy',+ delta: '+0.3%',+ deltaPositive: true,+ },+ {+ key: 'error',+ label: 'Error rate',+ value: '1.84%',+ status: 'warning',+ statusLabel: 'Elevated',+ delta: '+0.9%',+ deltaPositive: false,+ },+ {+ key: 'latency',+ label: 'p99 latency',+ value: '512 ms',+ status: 'warning',+ statusLabel: 'Above target',+ delta: '+84 ms',+ deltaPositive: false,+ },+ {+ key: 'availability',+ label: 'Availability',+ value: '99.98%',+ status: 'healthy',+ statusLabel: 'Operational',+ delta: '+0.01%',+ deltaPositive: true,+ },+ ],+ staging: [+ {+ key: 'health',+ label: 'Overall health',+ value: '99.4%',+ status: 'healthy',+ statusLabel: 'Healthy',+ delta: '+0.1%',+ deltaPositive: true,+ },+ {+ key: 'error',+ label: 'Error rate',+ value: '0.42%',+ status: 'healthy',+ statusLabel: 'Nominal',+ delta: '-0.2%',+ deltaPositive: true,+ },+ {+ key: 'latency',+ label: 'p99 latency',+ value: '338 ms',+ status: 'healthy',+ statusLabel: 'Within target',+ delta: '-12 ms',+ deltaPositive: true,+ },+ {+ key: 'availability',+ label: 'Availability',+ value: '99.95%',+ status: 'healthy',+ statusLabel: 'Operational',+ delta: '0.00%',+ deltaPositive: true,+ },+ ],+ development: [+ {+ key: 'health',+ label: 'Overall health',+ value: '96.1%',+ status: 'warning',+ statusLabel: 'Flaky',+ delta: '-1.8%',+ deltaPositive: false,+ },+ {+ key: 'error',+ label: 'Error rate',+ value: '3.10%',+ status: 'critical',+ statusLabel: 'High',+ delta: '+1.4%',+ deltaPositive: false,+ },+ {+ key: 'latency',+ label: 'p99 latency',+ value: '274 ms',+ status: 'healthy',+ statusLabel: 'Within target',+ delta: '-30 ms',+ deltaPositive: true,+ },+ {+ key: 'availability',+ label: 'Availability',+ value: '99.20%',+ status: 'warning',+ statusLabel: 'Degraded',+ delta: '-0.6%',+ deltaPositive: false,+ },+ ],+};++// 120 samples per KPI, tail-sliced to the active window so it ends "now".+const SPARKLINES: Record<string, number[]> = {+ // prettier-ignore+ health: [97.6, 97.6, 97.7, 97.6, 98, 97.4, 96.5, 97.3, 97.3, 97, 97, 97.6, 96.8, 97.2, 91.7, 92.2, 95, 96.3, 96.5, 96.4, 96.8, 95.9, 96.7, 96.7, 96.4, 97.1, 97, 97, 96.1, 96.7, 96, 95.7, 96.9, 97.3, 96.1, 95.8, 96.9, 96.2, 96.6, 96.7, 97.2, 92.7, 96.5, 97.2, 96.5, 95.8, 96, 97.4, 96.8, 96.9, 96.4, 96.9, 97.3, 96.2, 97.3, 96.2, 97, 97.3, 89.5, 90.1, 91.8, 95.1, 96.4, 97.7, 97.2, 97.8, 97, 97.5, 97.1, 98, 96.8, 96.8, 97.7, 97.7, 96.8, 97.2, 93.2, 95.3, 97.2, 97.7, 97.3, 98.2, 97.6, 97.3, 97, 97.4, 96.5, 98, 96.9, 97.1, 96.5, 96.4, 97.6, 87.4, 90, 94.1, 97.1, 97.1, 97.5, 97.6, 96.9, 96.9, 96.8, 96.5, 95.8, 96.7, 96.7, 97.2, 91.7, 91.5, 92.3, 95.3, 96.9, 97.4, 96.8, 97.9, 97.5, 98.3, 97.9, 98.6],+ // prettier-ignore+ error: [0.62, 0.64, 0.98, 0.82, 0.86, 0.83, 1.02, 1.29, 1.24, 2.41, 1.57, 0.96, 0.91, 1.43, 1.36, 1.16, 1.33, 0.95, 1.18, 1.3, 1.48, 1.05, 1.41, 1.06, 1.03, 1.36, 1, 3.71, 2.85, 1.7, 1.41, 1.29, 1.35, 1.35, 1.19, 1.27, 1.2, 0.91, 0.95, 1.06, 1.26, 1.28, 1.19, 1.09, 2.21, 1.52, 0.83, 0.94, 1.17, 0.81, 1.11, 1.24, 1.18, 0.76, 1.09, 1.08, 1.22, 1.02, 1, 5.18, 4.39, 3.74, 2.23, 1, 1.3, 1.53, 1.42, 1.16, 1.18, 1.52, 1.45, 1.34, 3.13, 2.1, 1.66, 1.74, 1.69, 1.33, 1.43, 1.73, 1.73, 1.51, 1.63, 1.55, 1.56, 1.74, 2, 1.46, 5.44, 4.33, 2.3, 1.99, 1.77, 1.82, 1.98, 1.86, 1.88, 1.51, 1.42, 1.82, 1.71, 3.88, 2.22, 1.72, 1.65, 1.64, 1.42, 1.69, 1.39, 1.81, 1.66, 1.3, 1.32, 1.75, 6.22, 5.03, 2.35, 1.39, 1.25, 1.84],+ // prettier-ignore+ latency: [322, 371, 287, 357, 313, 353, 320, 617, 421, 363, 377, 399, 350, 401, 421, 420, 430, 365, 401, 797, 635, 477, 365, 412, 380, 421, 380, 411, 393, 401, 436, 378, 376, 569, 389, 419, 417, 342, 347, 376, 385, 347, 393, 328, 328, 367, 304, 871, 812, 707, 411, 317, 316, 367, 331, 320, 354, 349, 326, 309, 323, 631, 396, 306, 295, 293, 355, 334, 324, 372, 1012, 850, 489, 355, 324, 346, 353, 406, 365, 362, 377, 348, 437, 423, 664, 437, 397, 413, 402, 427, 404, 438, 491, 479, 447, 500, 440, 903, 776, 555, 476, 506, 439, 461, 502, 496, 485, 474, 470, 503, 1198, 1080, 930, 609, 456, 507, 426, 451, 427, 512],+ // prettier-ignore+ availability: [99.891, 99.956, 99.885, 99.964, 99.882, 99.92, 99.696, 99.897, 99.913, 99.948, 99.918, 99.942, 99.921, 99.928, 99.94, 99.902, 99.551, 99.853, 99.853, 99.891, 99.887, 99.926, 99.912, 99.911, 99.739, 99.873, 99.877, 99.85, 99.844, 99.895, 99.854, 99.851, 99.912, 99.426, 99.593, 99.821, 99.851, 99.928, 99.767, 99.852, 99.854, 99.866, 99.87, 99.929, 99.856, 99.925, 99.672, 99.882, 99.926, 99.865, 99.944, 99.941, 99.807, 99.91, 99.892, 99.922, 99.937, 99.338, 99.491, 99.743, 99.925, 99.871, 99.95, 99.909, 99.949, 99.687, 99.844, 99.911, 99.93, 99.882, 99.894, 99.536, 99.833, 99.867, 99.927, 99.88, 99.883, 99.926, 99.895, 99.653, 99.827, 99.906, 99.941, 99.893, 99.863, 99.916, 99.781, 99.885, 99.846, 99.896, 99.876, 99.485, 99.534, 99.738, 99.832, 99.241, 99.321, 99.422, 99.698, 99.828, 99.824, 99.837, 99.828, 99.61, 99.761, 99.878, 99.843, 99.845, 99.529, 99.75, 99.838, 99.83, 99.423, 99.728, 99.817, 99.827, 99.811, 99.871, 99.925, 99.98],+};++// ============= DRILL-DOWN ROWS =============++interface HostRow {+ id: string;+ service: string;+ environment: Environment;+ region: string;+ instances: number;+ rpm: number;+ errorRate: number;+ p99: number;+ status: HealthStatus;+}++const HOST_ROWS: HostRow[] = [+ {+ id: '1',+ service: 'checkout-api',+ environment: 'production',+ region: 'us-east-1',+ instances: 24,+ rpm: 9240,+ errorRate: 2.1,+ p99: 512,+ status: 'warning',+ },+ {+ id: '2',+ service: 'checkout-api',+ environment: 'production',+ region: 'us-west-2',+ instances: 18,+ rpm: 6110,+ errorRate: 0.3,+ p99: 214,+ status: 'healthy',+ },+ {+ id: '3',+ service: 'checkout-api',+ environment: 'production',+ region: 'eu-west-1',+ instances: 12,+ rpm: 3980,+ errorRate: 0.4,+ p99: 236,+ status: 'healthy',+ },+ {+ id: '4',+ service: 'search-indexer',+ environment: 'production',+ region: 'us-east-1',+ instances: 16,+ rpm: 4120,+ errorRate: 5.8,+ p99: 1180,+ status: 'critical',+ },+ {+ id: '5',+ service: 'search-indexer',+ environment: 'production',+ region: 'ap-southeast-1',+ instances: 8,+ rpm: 2040,+ errorRate: 0.9,+ p99: 342,+ status: 'healthy',+ },+ {+ id: '6',+ service: 'payments',+ environment: 'production',+ region: 'us-east-1',+ instances: 20,+ rpm: 5310,+ errorRate: 0.2,+ p99: 188,+ status: 'healthy',+ },+ {+ id: '7',+ service: 'payments',+ environment: 'production',+ region: 'eu-west-1',+ instances: 10,+ rpm: 2760,+ errorRate: 0.2,+ p99: 205,+ status: 'healthy',+ },+ {+ id: '8',+ service: 'edge-cdn',+ environment: 'production',+ region: 'eu-west-1',+ instances: 30,+ rpm: 14820,+ errorRate: 1.6,+ p99: 402,+ status: 'warning',+ },+ {+ id: '9',+ service: 'auth',+ environment: 'production',+ region: 'us-west-2',+ instances: 14,+ rpm: 4530,+ errorRate: 0.1,+ p99: 96,+ status: 'healthy',+ },+ {+ id: '10',+ service: 'notifications',+ environment: 'production',+ region: 'ap-southeast-1',+ instances: 6,+ rpm: 1210,+ errorRate: 0.5,+ p99: 268,+ status: 'healthy',+ },+ {+ id: '11',+ service: 'checkout-api',+ environment: 'staging',+ region: 'us-east-1',+ instances: 3,+ rpm: 420,+ errorRate: 0.4,+ p99: 198,+ status: 'healthy',+ },+ {+ id: '12',+ service: 'search-indexer',+ environment: 'staging',+ region: 'us-east-1',+ instances: 2,+ rpm: 180,+ errorRate: 1.1,+ p99: 356,+ status: 'warning',+ },+ {+ id: '13',+ service: 'checkout-api',+ environment: 'development',+ region: 'us-west-2',+ instances: 1,+ rpm: 44,+ errorRate: 3.2,+ p99: 274,+ status: 'warning',+ },+ {+ id: '14',+ service: 'auth',+ environment: 'development',+ region: 'us-west-2',+ instances: 1,+ rpm: 38,+ errorRate: 6.4,+ p99: 512,+ status: 'critical',+ },+];++// ============= ALERTS =============++type AlertState = 'firing' | 'acknowledged' | 'resolved';++interface Alert {+ id: string;+ severity: HealthStatus;+ title: string;+ service: string;+ at: string;+ state: AlertState;+}++const ALERT_STATE_TOKEN: Record<+ AlertState,+ {label: string; color: 'red' | 'yellow' | 'green'}+> = {+ firing: {label: 'Firing', color: 'red'},+ acknowledged: {label: 'Ack', color: 'yellow'},+ resolved: {label: 'Resolved', color: 'green'},+};++const ALERTS: Alert[] = [+ {+ id: 'AL-8842',+ severity: 'critical',+ title: 'search-indexer 5xx rate above 5%',+ service: 'search-indexer · us-east-1',+ at: '2026-06-30T21:14:00Z',+ state: 'firing',+ },+ {+ id: 'AL-8841',+ severity: 'warning',+ title: 'checkout-api p99 latency above 500ms',+ service: 'checkout-api · us-east-1',+ at: '2026-06-30T21:02:00Z',+ state: 'firing',+ },+ {+ id: 'AL-8840',+ severity: 'warning',+ title: 'edge-cdn cache hit ratio degraded',+ service: 'edge-cdn · eu-west-1',+ at: '2026-06-30T20:41:00Z',+ state: 'acknowledged',+ },+ {+ id: 'AL-8839',+ severity: 'critical',+ title: 'auth error rate spike in dev cluster',+ service: 'auth · us-west-2',+ at: '2026-06-30T20:18:00Z',+ state: 'acknowledged',+ },+ {+ id: 'AL-8838',+ severity: 'warning',+ title: 'notifications queue depth climbing',+ service: 'notifications · ap-southeast-1',+ at: '2026-06-30T19:55:00Z',+ state: 'firing',+ },+ {+ id: 'AL-8837',+ severity: 'warning',+ title: 'payments settlement job heartbeat missed',+ service: 'payments · us-east-1',+ at: '2026-06-30T18:30:00Z',+ state: 'resolved',+ },+];++const ALERT_ORDER: AlertState[] = ['firing', 'acknowledged', 'resolved'];++// ============= SHARED CHART PIECES =============++// Inline color — Icon's `color` prop only takes semantic names.+function LegendDot({color, label}: {color: string; label: string}) {+ const dotStyle: CSSProperties = {color};+ return (+ <HStack gap={2} vAlign="center">+ <Icon icon={StopIcon} size="xsm" style={dotStyle} />+ <Text type="supporting" color="secondary">+ {label}+ </Text>+ </HStack>+ );+}++interface TooltipEntry {+ name: string;+ value: number;+ color: string;+}++// Recharts passes the point index as `label`; map it back to a time.+function ChartTooltip({+ active,+ payload,+ label,+ series,+ unit,+}: {+ active?: boolean;+ payload?: TooltipEntry[];+ label?: number;+ series: WindowSeries;+ unit: string;+}) {+ if (!active || !payload?.length) {+ return null;+ }+ const timeLabel =+ typeof label === 'number' ? (series.points[label]?.label ?? '') : '';+ return (+ <Card padding={3}>+ <VStack gap={1}>+ <Text type="supporting" color="secondary">+ {timeLabel}+ </Text>+ {payload.map(entry => (+ <LegendDot+ key={entry.name}+ color={entry.color}+ label={`${entry.name}: ${entry.value.toLocaleString()}${unit}`}+ />+ ))}+ </VStack>+ </Card>+ );+}++const AXIS_TICK = {+ fontSize: 'var(--font-size-sm, 12px)',+ fill: 'var(--color-text-secondary, #4E606F)',+};+const GRID_STROKE = 'var(--color-border, rgba(5, 54, 89, 0.1))';++// Shared so both cards in the grid row align. The margins reserve the overhang+// of centered axis ticks, without which the tallest y-label is clipped.+const CHART_HEIGHT = 280;+const CHART_MARGIN = {top: 12, right: 16, left: 0, bottom: 4};+const Y_AXIS_WIDTH = 56;++// `linear` + miter joins keep every sample a straight segment — `monotone`+// would round the spikes into a curve no real metric produces.+const LINE_PROPS = {+ type: 'linear',+ strokeLinejoin: 'miter',+ strokeLinecap: 'butt',+ dot: false,+ isAnimationActive: false,+} as const;++// ============= CHART CARDS =============++interface ChartLine {+ key: MetricKey;+ name: string;+ color: string;+}++const BLUE = 'var(--color-data-categorical-blue, #0171E3)';+const ORANGE = 'var(--color-data-categorical-orange, #EB6E00)';+const PURPLE = 'var(--color-data-categorical-purple, #6B1EFD)';+const TEAL = 'var(--color-data-categorical-teal, #008E80)';++const LATENCY_LINES: ChartLine[] = [+ {key: 'p50', name: 'p50', color: BLUE},+ {key: 'p95', name: 'p95', color: ORANGE},+ {key: 'p99', name: 'p99', color: PURPLE},+];++const TRAFFIC_LINES: ChartLine[] = [+ {key: 'useast', name: 'us-east-1', color: BLUE},+ {key: 'uswest', name: 'us-west-2', color: TEAL},+ {key: 'euwest', name: 'eu-west-1', color: ORANGE},+];++/**+ * One time-series card — title, plot, legend — driven by a line config. `scale`+ * applies the active environment's multiplier; `hasAxisUnit` is opt-in because+ * rpm ticks are already wide enough without a suffix.+ */+function MetricChart({+ title,+ subtitle,+ series,+ lines,+ scale,+ unit,+ hasAxisUnit = false,+}: {+ title: string;+ subtitle: string;+ series: WindowSeries;+ lines: ChartLine[];+ scale: number;+ unit: string;+ hasAxisUnit?: boolean;+}) {+ const data = useMemo(+ () =>+ series.points.map(point => {+ const row: Record<string, number> = {t: point.t};+ for (const line of lines) {+ row[line.key] = Math.round(point[line.key] * scale);+ }+ return row;+ }),+ [series, lines, scale],+ );++ return (+ <Card padding={6}>+ <VStack gap={4}>+ <VStack gap={1}>+ <Heading level={3}>{title}</Heading>+ <Text type="supporting" color="secondary">+ {subtitle}+ </Text>+ </VStack>+ <ResponsiveContainer width="100%" height={CHART_HEIGHT}>+ <LineChart data={data} margin={CHART_MARGIN}>+ <CartesianGrid horizontal vertical={false} stroke={GRID_STROKE} />+ <XAxis+ dataKey="t"+ type="number"+ domain={[0, series.points.length - 1]}+ ticks={series.ticks}+ tickFormatter={(v: number) => series.tickLabels[v] ?? ''}+ tick={AXIS_TICK}+ axisLine={false}+ tickLine={false}+ />+ <YAxis+ tick={AXIS_TICK}+ axisLine={false}+ tickLine={false}+ width={Y_AXIS_WIDTH}+ unit={hasAxisUnit ? unit : undefined}+ />+ <Tooltip+ content={<ChartTooltip series={series} unit={unit} />}+ cursor={{stroke: GRID_STROKE}}+ />+ {lines.map(line => (+ <Line+ {...LINE_PROPS}+ key={line.key}+ dataKey={line.key}+ name={line.name}+ stroke={line.color}+ strokeWidth={1.5}+ />+ ))}+ </LineChart>+ </ResponsiveContainer>+ <HStack gap={6} vAlign="center" wrap="wrap">+ {lines.map(line => (+ <LegendDot key={line.key} color={line.color} label={line.name} />+ ))}+ </HStack>+ </VStack>+ </Card>+ );+}++// ============= KPI TILE =============++function Sparkline({data, color}: {data: number[]; color: string}) {+ const chartData = data.map((v, i) => ({i, v}));+ return (+ <ResponsiveContainer width="100%" height={40}>+ <LineChart+ data={chartData}+ margin={{top: 4, right: 0, left: 0, bottom: 2}}>+ {/* Fit the scale to the data. Recharts' implicit axis anchors the+ domain at 0, which flattens any metric living far from zero —+ availability (99.2–100%) collapses to a quarter-pixel of travel. */}+ <YAxis hide domain={['dataMin', 'dataMax']} />+ <Line {...LINE_PROPS} dataKey="v" stroke={color} strokeWidth={1.25} />+ </LineChart>+ </ResponsiveContainer>+ );+}++function KpiTile({kpi, spark}: {kpi: Kpi; spark: number[]}) {+ return (+ <Card padding={4}>+ <VStack gap={2}>+ <HStack gap={2} vAlign="center">+ <StatusDot+ variant={STATUS_DOT[kpi.status]}+ label={kpi.statusLabel}+ tooltip={kpi.statusLabel}+ isPulsing={kpi.status === 'critical'}+ />+ <Text type="label" color="secondary">+ {kpi.label}+ </Text>+ </HStack>+ <HStack gap={2} vAlign="center">+ <Heading level={2}>{kpi.value}</Heading>+ <HStack gap={1} vAlign="center">+ <Icon+ icon={kpi.deltaPositive ? ArrowUpIcon : ArrowDownIcon}+ size="xsm"+ color={kpi.deltaPositive ? 'success' : 'error'}+ />+ <Text type="supporting" color="secondary">+ {kpi.delta}+ </Text>+ </HStack>+ </HStack>+ <Sparkline data={spark} color={STATUS_STROKE[kpi.status]} />+ </VStack>+ </Card>+ );+}++// ============= RAIL SECTIONS =============++const railStyles = stylex.create({+ // Translucent, so the band reads the same on a card and on the panel.+ header: {+ backgroundColor: 'var(--color-background-muted)',+ },+ // The opaque layer the translucent band needs; without it the rows read+ // through the header as they scroll past.+ stickyHeader: {+ position: 'sticky',+ insetBlockStart: 0,+ zIndex: 1,+ backgroundColor: 'var(--color-background-surface)',+ },+});++/**+ * One labelled region of the triage rail. `hasStickyHeader` is the rail form:+ * the panel is a single scroll region shared with the sibling section, so the+ * header pins to its top. Folded inline, each section gets its own card.+ */+function RailSection({+ icon,+ iconColor,+ title,+ subtitle,+ badge,+ hasStickyHeader = false,+ children,+}: {+ icon: IconType;+ iconColor: 'error' | 'secondary';+ title: string;+ subtitle: string;+ badge: ReactNode;+ hasStickyHeader?: boolean;+ children: ReactNode;+}) {+ return (+ <VStack gap={0}>+ <VStack+ gap={0}+ xstyle={hasStickyHeader ? railStyles.stickyHeader : undefined}>+ <VStack gap={1} padding={4} xstyle={railStyles.header}>+ <HStack gap={2} vAlign="center">+ <Icon icon={icon} size="sm" color={iconColor} />+ <StackItem size="fill">+ <Heading level={3}>{title}</Heading>+ </StackItem>+ {badge}+ </HStack>+ <Text type="supporting" color="secondary">+ {subtitle}+ </Text>+ </VStack>+ <Divider />+ </VStack>+ {children}+ </VStack>+ );+}++// ============= ALERTS FEED =============++function AlertsFeed({hasStickyHeader = false}: {hasStickyHeader?: boolean}) {+ const groups = ALERT_ORDER.map(state => ({+ state,+ items: ALERTS.filter(a => a.state === state),+ })).filter(g => g.items.length > 0);++ const firing = ALERTS.filter(a => a.state === 'firing').length;++ return (+ <RailSection+ icon={BellAlertIcon}+ iconColor={firing > 0 ? 'error' : 'secondary'}+ title="Active alerts"+ subtitle={`${ALERTS.length} in the last 24h · newest first`}+ badge={+ <Badge+ label={`${firing} firing`}+ variant={firing > 0 ? 'error' : 'neutral'}+ />+ }+ hasStickyHeader={hasStickyHeader}>+ {groups.length === 0 ? (+ <EmptyState+ title="All clear"+ description="No active alerts across the selected environment."+ icon={<Icon icon={CheckCircleIcon} size="lg" color="success" />}+ isCompact+ />+ ) : (+ groups.map(group => (+ <List key={group.state} density="compact" hasDividers>+ {group.items.map(alert => (+ <ListItem+ key={alert.id}+ label={alert.title}+ description={alert.service}+ startContent={+ <StatusDot+ variant={STATUS_DOT[alert.severity]}+ label={alert.severity}+ isPulsing={+ alert.state === 'firing' && alert.severity === 'critical'+ }+ />+ }+ endContent={+ <VStack gap={1} hAlign="end">+ <Token+ size="sm"+ color={ALERT_STATE_TOKEN[alert.state].color}+ label={ALERT_STATE_TOKEN[alert.state].label}+ />+ <Timestamp+ value={alert.at}+ format="relative"+ color="secondary"+ />+ </VStack>+ }+ />+ ))}+ </List>+ ))+ )}+ </RailSection>+ );+}++// ============= SERVICE BREAKDOWN =============++function errorColor(rate: number): 'red' | 'yellow' | 'green' {+ if (rate >= 5) {+ return 'red';+ }+ return rate >= 1.5 ? 'yellow' : 'green';+}++// Abbreviated — the traffic chart carries the exact figures.+function formatRpm(rpm: number): string {+ return rpm >= 1000 ? `${(rpm / 1000).toFixed(1)}k rpm` : `${rpm} rpm`;+}++function NoServices() {+ return (+ <EmptyState+ title="No services in this view"+ description="Nothing reports in the selected environment and region. Try widening the region filter."+ icon={<Icon icon={ServerStackIcon} size="lg" />}+ isCompact+ />+ );+}++/**+ * Per-service drill-down as rail rows rather than a wide table: a rail has room+ * for about two of the seven columns this data would need. Rows sort+ * worst-first, since a scrolling rail can't be scanned like a grid.+ */+function ServiceBreakdown({+ rows,+ contextLabel,+ hasStickyHeader = false,+}: {+ rows: HostRow[];+ contextLabel: string;+ hasStickyHeader?: boolean;+}) {+ const sorted = useMemo(+ () =>+ [...rows].sort(+ (a, b) =>+ SEVERITY_RANK[a.status] - SEVERITY_RANK[b.status] ||+ b.errorRate - a.errorRate,+ ),+ [rows],+ );++ return (+ <RailSection+ icon={ServerStackIcon}+ iconColor="secondary"+ title="Service breakdown"+ subtitle={contextLabel}+ badge={<Badge label={`${rows.length}`} variant="neutral" />}+ hasStickyHeader={hasStickyHeader}>+ {sorted.length === 0 ? (+ <NoServices />+ ) : (+ <List density="compact" hasDividers>+ {sorted.map(row => (+ <ListItem+ key={row.id}+ label={row.service}+ description={`${row.region} · ${row.instances} hosts · ${formatRpm(row.rpm)}`}+ startContent={+ <StatusDot+ variant={STATUS_DOT[row.status]}+ label={STATUS_LABEL[row.status]}+ isPulsing={row.status === 'critical'}+ />+ }+ endContent={+ <VStack gap={1} hAlign="end">+ <HStack gap={1} vAlign="center">+ <Text type="supporting" color="secondary">+ p99+ </Text>+ <Text type="body" weight="semibold">+ {row.p99} ms+ </Text>+ </HStack>+ <Token+ size="sm"+ color={errorColor(row.errorRate)}+ label={`${row.errorRate.toFixed(1)}% err`}+ />+ </VStack>+ }+ />+ ))}+ </List>+ )}+ </RailSection>+ );+}++// ============= UPTIME HISTORY =============++// Deliberately on its own time base, not the header's 1h/1d/7d control: uptime+// is measured in days. Environment and region still filter the roster.+const UPTIME_DAYS = 90;++type UptimeStatus = 'operational' | 'degraded' | 'down';++// Mirrors `uptimeStyles` below — the legend needs values, the bars need static+// StyleX rules. Keep the two in sync by hand.+const UPTIME_COLOR: Record<UptimeStatus, string> = {+ operational: 'var(--color-success, #0D8626)',+ degraded: 'var(--color-warning, #E9AF08)',+ down: 'var(--color-error, #E3193B)',+};++const UPTIME_LABEL: Record<UptimeStatus, string> = {+ operational: 'Operational',+ degraded: 'Partial degradation',+ down: 'Downtime',+};++const UPTIME_ORDER: UptimeStatus[] = ['operational', 'degraded', 'down'];++// Percentage of the day served — a down day is a partial outage, not 24h lost.+const DAY_UPTIME: Record<UptimeStatus, number> = {+ operational: 100,+ degraded: 98.4,+ down: 82,+};++// How much rougher each environment's history runs than production's.+const UPTIME_ENV_RISK: Record<Environment, number> = {+ production: 1,+ staging: 1.6,+ development: 3,+};++// An unhealthy service didn't get there in a day; its record reads worse.+const UPTIME_STATUS_RISK: Record<HealthStatus, number> = {+ healthy: 1,+ warning: 3.5,+ critical: 7,+};++// The strip's last bar has to agree with what the rest of the page reports.+const UPTIME_TODAY: Record<HealthStatus, UptimeStatus> = {+ healthy: 'operational',+ warning: 'degraded',+ critical: 'down',+};++interface ServiceUptime {+ service: string;+ status: HealthStatus;+ days: UptimeStatus[];+ uptime: number;+ degradedDays: number;+ downDays: number;+}++// Stable per service, so a history doesn't reshuffle as the roster is filtered.+function seedForService(service: string): number {+ let h = 7;+ for (let i = 0; i < service.length; i++) {+ h = (h * 31 + service.charCodeAt(i)) % 9973;+ }+ return h;+}++function buildUptime(+ service: string,+ environment: Environment,+ status: HealthStatus,+): ServiceUptime {+ const seed = seedForService(service);+ const risk = UPTIME_ENV_RISK[environment] * UPTIME_STATUS_RISK[status];++ // Fixed quotas rather than a per-day coin flip: over 90 draws the variance of+ // independent rolls swamps the risk signal. The ±40% wobble keeps same-status+ // peers from rendering identically without reordering the bands.+ const downWobble = 0.6 + 0.8 * hashNoise(seed, 3.7);+ const degradedWobble = 0.6 + 0.8 * hashNoise(seed, 5.9);+ const downCount = Math.round(+ UPTIME_DAYS * Math.min(0.09, 0.005 * risk) * downWobble,+ );+ const degradedCount = Math.round(+ UPTIME_DAYS * Math.min(0.32, 0.02 * risk) * degradedWobble,+ );++ const ranked = [...Array(UPTIME_DAYS).keys()].sort(+ (a, b) => hashNoise(b, seed) - hashNoise(a, seed),+ );+ const days: UptimeStatus[] = new Array(UPTIME_DAYS).fill('operational');+ for (let k = 0; k < downCount; k++) {+ days[ranked[k]] = 'down';+ }+ for (let k = downCount; k < downCount + degradedCount; k++) {+ days[ranked[k]] = 'degraded';+ }+ days[UPTIME_DAYS - 1] = UPTIME_TODAY[status];++ // Per-service, not per-day: a per-day wobble averages out to the same figure+ // for every service, leaving equal-quota peers showing an identical number.+ const cleanDay = DAY_UPTIME.operational - 0.02 - hashNoise(seed, 11.3) * 0.06;++ let served = 0;+ let degradedDays = 0;+ let downDays = 0;+ for (let i = 0; i < UPTIME_DAYS; i++) {+ const day = days[i];+ if (day === 'operational') {+ served += cleanDay - hashNoise(i, seed + 1) * 0.02;+ } else {+ served += DAY_UPTIME[day];+ if (day === 'degraded') {+ degradedDays++;+ } else {+ downDays++;+ }+ }+ }++ return {+ service,+ status,+ days,+ uptime: served / UPTIME_DAYS,+ degradedDays,+ downDays,+ };+}++// Index 0 is the oldest day, UPTIME_DAYS - 1 is today.+function dayLabel(i: number): string {+ const ago = UPTIME_DAYS - 1 - i;+ if (ago === 0) {+ return 'Today';+ }+ return ago === 1 ? 'Yesterday' : `${ago} days ago`;+}++const uptimeStyles = stylex.create({+ // Below ~420px the row can't honor the 3px bar floor, so it scrolls rather+ // than thinning bars — that would hide the outage days this strip shows.+ strip: {+ display: 'flex',+ gap: '2px',+ overflowX: 'auto',+ overscrollBehaviorX: 'contain',+ scrollbarWidth: 'thin',+ },+ // No radius: at 3–8px wide the smallest token (4px) rounds a bar away.+ bar: {+ flexBasis: 0,+ flexGrow: 1,+ minWidth: '3px',+ height: '30px',+ },+ // Mirrors UPTIME_COLOR above.+ operational: {backgroundColor: 'var(--color-success, #0D8626)'},+ degraded: {backgroundColor: 'var(--color-warning, #E9AF08)'},+ down: {backgroundColor: 'var(--color-error, #E3193B)'},+});++/**+ * One service's 90-day strip — a single image to assistive tech, not 90+ * unlabelled boxes. Per-day detail rides on `title` rather than 90 Tooltips.+ */+function UptimeStrip({entry}: {entry: ServiceUptime}) {+ const summary =+ entry.downDays === 0 && entry.degradedDays === 0+ ? `${UPTIME_DAYS}-day uptime for ${entry.service}: no incidents.`+ : `${UPTIME_DAYS}-day uptime for ${entry.service}: ${entry.degradedDays} degraded ${+ entry.degradedDays === 1 ? 'day' : 'days'+ }, ${entry.downDays} with downtime.`;++ return (+ <div {...stylex.props(uptimeStyles.strip)} role="img" aria-label={summary}>+ {entry.days.map((day, i) => (+ <div+ key={i}+ {...stylex.props(uptimeStyles.bar, uptimeStyles[day])}+ title={`${dayLabel(i)} — ${UPTIME_LABEL[day]}`}+ />+ ))}+ </div>+ );+}++function UptimeRow({entry}: {entry: ServiceUptime}) {+ return (+ <VStack gap={2}>+ <HStack gap={3} vAlign="center" hAlign="between">+ <HStack gap={2} vAlign="center">+ <StatusDot+ variant={STATUS_DOT[entry.status]}+ label={STATUS_LABEL[entry.status]}+ isPulsing={entry.status === 'critical'}+ />+ <Heading level={4}>{entry.service}</Heading>+ </HStack>+ <Text type="supporting" color="secondary">+ {entry.uptime.toFixed(2)}% uptime+ </Text>+ </HStack>+ <UptimeStrip entry={entry} />+ </VStack>+ );+}++/**+ * The "All services" roster — one strip per *service*, not per deployment. The+ * rail already lists service × region rows; each strip here takes the worst+ * status across a service's regions.+ */+function AllServicesUptime({+ rows,+ environment,+ contextLabel,+}: {+ rows: HostRow[];+ environment: Environment;+ contextLabel: string;+}) {+ const entries = useMemo(() => {+ const worst = new Map<string, HealthStatus>();+ for (const row of rows) {+ const prev = worst.get(row.service);+ if (+ prev === undefined ||+ SEVERITY_RANK[row.status] < SEVERITY_RANK[prev]+ ) {+ worst.set(row.service, row.status);+ }+ }+ // Alphabetical, not worst-first — the rail already triages by severity.+ return [...worst.entries()]+ .sort((a, b) => a[0].localeCompare(b[0]))+ .map(([service, status]) => buildUptime(service, environment, status));+ }, [rows, environment]);++ return (+ <VStack gap={6}>+ <HStack gap={3} vAlign="center" hAlign="between" wrap="wrap">+ <VStack>+ <Heading level={2}>All services</Heading>+ <Text type="supporting" color="secondary">+ Daily uptime over the last {UPTIME_DAYS} days · {contextLabel}+ </Text>+ </VStack>+ <HStack gap={4} vAlign="center" wrap="wrap">+ {UPTIME_ORDER.map(state => (+ <LegendDot+ key={state}+ color={UPTIME_COLOR[state]}+ label={UPTIME_LABEL[state]}+ />+ ))}+ </HStack>+ </HStack>+ <Card padding={6}>+ {entries.length === 0 ? (+ <NoServices />+ ) : (+ <VStack gap={6}>+ {entries.map((entry, index) => (+ <Fragment key={entry.service}>+ {index > 0 && <Divider />}+ <UptimeRow entry={entry} />+ </Fragment>+ ))}+ </VStack>+ )}+ </Card>+ </VStack>+ );+}++// ============= CONTROL OPTIONS =============++const ENV_OPTIONS = [+ {value: 'production', label: 'Production'},+ {value: 'staging', label: 'Staging'},+ {value: 'development', label: 'Development'},+];++const REGION_OPTIONS = [+ {value: 'all', label: 'All regions'},+ {value: 'us-east-1', label: 'us-east-1'},+ {value: 'us-west-2', label: 'us-west-2'},+ {value: 'eu-west-1', label: 'eu-west-1'},+ {value: 'ap-southeast-1', label: 'ap-southeast-1'},+];++// Layout height="fill" is height:100%, which needs a definite height the host's+// <html>/<body> don't set. Without this the rail grows instead of scrolling.+const pageStyle: CSSProperties = {height: '100dvh'};++// Every window stays densely sampled — a thinned sparkline smooths its spikes.+const SPARK_LEN: Record<TimeWindow, number> = {'1h': 60, '1d': 90, '7d': 120};++// ============= MAIN =============++export default function ServiceHealthMonitorPage() {+ const [timeWindow, setTimeWindow] = useState<TimeWindow>('1d');+ const [environment, setEnvironment] = useState<Environment>('production');+ const [region, setRegion] = useState('all');++ const isNarrow = useMediaQuery('(max-width: 1024px)');++ const series = SERIES[timeWindow];+ const kpis = KPI_BY_ENV[environment];+ const sparkLen = SPARK_LEN[timeWindow];++ const rows = useMemo(+ () =>+ HOST_ROWS.filter(+ r =>+ r.environment === environment &&+ (region === 'all' || r.region === region),+ ),+ [environment, region],+ );++ // Restates the active filters, since the rail rows carry no column headers.+ const breakdownContext = `${ENV_OPTIONS.find(e => e.value === environment)?.label} · ${REGION_OPTIONS.find(r => r.value === region)?.label}`;++ return (+ <Layout+ height="fill"+ style={pageStyle}+ header={+ <LayoutHeader padding={6} hasDivider>+ <HStack gap={3} vAlign="center" hAlign="between" wrap="wrap">+ <VStack gap={0} vAlign="center">+ <Heading level={1}>Service Health Monitor</Heading>+ <HStack gap={2} vAlign="center">+ <StatusDot+ variant="success"+ label="Live"+ isPulsing+ tooltip="Auto-refreshing every 30s"+ />+ <Text type="supporting" color="secondary">+ Updated{' '}+ <Timestamp+ value="2026-06-30T21:15:00Z"+ format="relative"+ type="inherit"+ color="inherit"+ />+ </Text>+ </HStack>+ </VStack>+ <HStack gap={2} vAlign="center">+ <SegmentedControl+ label="Time window"+ value={timeWindow}+ onChange={value => setTimeWindow(value as TimeWindow)}+ size="lg">+ <SegmentedControlItem label="1h" value="1h" />+ <SegmentedControlItem label="1d" value="1d" />+ <SegmentedControlItem label="7d" value="7d" />+ </SegmentedControl>+ <Selector+ label="Environment"+ isLabelHidden+ size="lg"+ options={ENV_OPTIONS}+ value={environment}+ onChange={value => setEnvironment(value as Environment)}+ />+ <Selector+ label="Region"+ isLabelHidden+ size="lg"+ options={REGION_OPTIONS}+ value={region}+ onChange={setRegion}+ />+ </HStack>+ </HStack>+ </LayoutHeader>+ }+ content={+ <LayoutContent padding={6}>+ <VStack gap={10}>+ <VStack gap={6}>+ {/* Traffic-light KPI tiles */}+ <Grid columns={{minWidth: 240, repeat: 'fit'}} gap={3}>+ {kpis.map(kpi => (+ <KpiTile+ key={kpi.key}+ kpi={kpi}+ spark={SPARKLINES[kpi.key].slice(-sparkLen)}+ />+ ))}+ </Grid>++ {/* Time-series charts */}+ <Grid columns={{minWidth: 320, repeat: 'fit'}} gap={3}>+ <MetricChart+ title="Response latency"+ subtitle="Percentile latency across all services (ms)"+ series={series}+ lines={LATENCY_LINES}+ scale={ENV_LATENCY_FACTOR[environment]}+ unit=" ms"+ hasAxisUnit+ />+ <MetricChart+ title="Request volume by region"+ subtitle="Requests per minute (rpm)"+ series={series}+ lines={TRAFFIC_LINES}+ scale={ENV_FACTOR[environment]}+ unit=" rpm"+ />+ </Grid>+ </VStack>++ <Divider />++ {/* 90-day uptime roster */}+ <AllServicesUptime+ rows={rows}+ environment={environment}+ contextLabel={breakdownContext}+ />++ {/* Below 1024px the rail folds in here, one card per section */}+ {isNarrow && (+ <VStack gap={4}>+ <Card padding={0}>+ <AlertsFeed />+ </Card>+ <Card padding={0}>+ <ServiceBreakdown+ rows={rows}+ contextLabel={breakdownContext}+ />+ </Card>+ </VStack>+ )}+ </VStack>+ </LayoutContent>+ }+ end={+ isNarrow ? undefined : (+ <LayoutPanel+ width={400}+ padding={0}+ hasDivider+ role="complementary"+ label="Alerts and service breakdown"+ // One scroll region for the whole rail; the sticky section headers+ // keep the boundary between the two feeds legible.+ isScrollable>+ <VStack gap={0}>+ <AlertsFeed hasStickyHeader />+ <Divider />+ <ServiceBreakdown+ rows={rows}+ contextLabel={breakdownContext}+ hasStickyHeader+ />+ </VStack>+ </LayoutPanel>+ )+ }+ />+ );+}diff --git a/packages/cli/assets/templates/pages/dashboard-service-monitoring/template.doc.mjs b/packages/cli/assets/templates/pages/dashboard-service-monitoring/template.doc.mjsnew file mode 100644index 0000000000..a7fc96b164--- /dev/null+++ b/packages/cli/assets/templates/pages/dashboard-service-monitoring/template.doc.mjs@@ -0,0 +1,12 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */+export const doc = {+ type: 'page',+ name: 'Service Monitoring Dashboard',+ displayName: 'Service Monitoring Dashboard',+ description:+ 'Live-ops service-health dashboard: traffic-light KPI tiles with sparklines, and multi-line latency and request-volume charts with a 1h/1d/7d window, beside a triage rail split into two independently scrolling sections — active alerts over a worst-first per-service breakdown with inline status coloring. Global environment, region, and auto-refresh controls; the rail folds into the content column as two cards below 1024px.',+ isReady: false,+ category: 'Dashboard - Monitoring',+};diff --git a/packages/cli/authoring/doctypes/template/type.ts b/packages/cli/authoring/doctypes/template/type.tsindex fb0ad71e9f..b354f1055f 100644--- a/packages/cli/authoring/doctypes/template/type.ts+++ b/packages/cli/authoring/doctypes/template/type.ts@@ -94,6 +94,8 @@ export type TemplateCategory =| 'Dashboard - Tabbed'| 'Dashboard - Filterable'| 'Dashboard - Portfolio'+ | 'Dashboard - Project Status'+ | 'Dashboard - Funnel & Cohort'// Table| 'Table - Basic'| 'Table - Grouped'