Skip to content

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

TypeScript

feat(sandbox): add component and template audit dashboards (#4923)

Ernestc65d10189339
diff --git a/apps/sandbox/src/app/(sandbox)/page.tsx b/apps/sandbox/src/app/(sandbox)/page.tsx
index ed4c2a8f19..e2061fde47 100644
--- a/apps/sandbox/src/app/(sandbox)/page.tsx
+++ b/apps/sandbox/src/app/(sandbox)/page.tsx
@@ -1,5 +1,12 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
+/**
+ * @file Searchable home catalog for the Astryx sandbox.
+ * @input The central sandbox category registry and shared project cards.
+ * @output A searchable, category-filtered catalog of non-template pages.
+ * @position Root page for discovering sandbox projects and tools.
+ */
+
'use client';
import {useState, useMemo} from 'react';
@@ -16,9 +23,13 @@ import {categories} from '../sandboxPages';
import {ProjectCard} from '../ProjectCard';
import {SearchIcon} from '../icons';
-const CATEGORY_FILTERS = ['All', ...categories.map(c => c.label)];
+const homeCategories = categories.filter(
+ category => category.slug !== 'templates',
+);
+
+const CATEGORY_FILTERS = ['All', ...homeCategories.map(c => c.label)];
-const allPages = categories.flatMap(c =>
+const allPages = homeCategories.flatMap(c =>
c.pages.map(p => ({...p, category: c.label})),
);
@@ -74,7 +85,7 @@ export default function Home() {
}
items.push(page);
}
- return categories
+ return homeCategories
.filter(c => map.has(c.label))
.map(c => ({category: c.label, pages: map.get(c.label) ?? []}));
}, [activeTab, filtered]);
@@ -104,12 +115,7 @@ export default function Home() {
value={activeTab}
onChange={v => setActiveTab(v ?? 'All')}>
{CATEGORY_FILTERS.map(cat => (
- <ToggleButton
- key={cat}
- label={cat}
- value={cat}
- size="lg"
- />
+ <ToggleButton key={cat} label={cat} value={cat} size="lg" />
))}
</ToggleButtonGroup>
</VStack>
diff --git a/apps/sandbox/src/app/(sandbox)/pages/component-scores/page.tsx b/apps/sandbox/src/app/(sandbox)/pages/component-scores/page.tsx
index 94f0f34cfd..f7ba0ae7ea 100644
--- a/apps/sandbox/src/app/(sandbox)/pages/component-scores/page.tsx
+++ b/apps/sandbox/src/app/(sandbox)/pages/component-scores/page.tsx
@@ -1,21 +1,43 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
+/**
+ * @file Component audit ledger with filtered metrics and audit details.
+ * @input Generated component roster and wiki-backed audit ledger snapshot.
+ * @output Full-width audit table with filtered metrics, actions, and a drawer.
+ * @position Sandbox audit surface at /pages/component-scores/.
+ */
+
'use client';
-import {useEffect, useMemo, useState} from 'react';
+import {useCallback, useEffect, useMemo, useRef, useState} from 'react';
import * as stylex from '@stylexjs/stylex';
import {VStack, HStack} from '@astryxdesign/core/Layout';
import {Text, Heading} from '@astryxdesign/core/Text';
import {TextInput} from '@astryxdesign/core/TextInput';
import {Button} from '@astryxdesign/core/Button';
+import {Selector} from '@astryxdesign/core/Selector';
+import {Toolbar} from '@astryxdesign/core/Toolbar';
+import {MoreMenu} from '@astryxdesign/core/MoreMenu';
+import {Icon} from '@astryxdesign/core/Icon';
+import {useToast} from '@astryxdesign/core/Toast';
import {Badge} from '@astryxdesign/core/Badge';
import type {BadgeVariant} from '@astryxdesign/core/Badge';
import {Card} from '@astryxdesign/core/Card';
+import {Grid} from '@astryxdesign/core/Grid';
import {Link} from '@astryxdesign/core/Link';
import {Code} from '@astryxdesign/core/Code';
+import {Divider} from '@astryxdesign/core/Divider';
+import {MetadataList, MetadataListItem} from '@astryxdesign/core/MetadataList';
+import {Section} from '@astryxdesign/core/Section';
import {Table, proportional, pixel} from '@astryxdesign/core/Table';
-import type {TableColumn} from '@astryxdesign/core/Table';
+import type {TableColumn, TablePlugin} from '@astryxdesign/core/Table';
+import {
+ colorVars,
+ radiusVars,
+ spacingVars,
+} from '@astryxdesign/core/theme/tokens.stylex';
+import {Drawer, Stat} from '@astryxdesign/lab';
import {
AUDIT_PROMPT,
@@ -25,12 +47,13 @@ import {
REPO,
RUBRIC_URL,
SECTION_TITLES,
+ SECTION_WEIGHTS,
roster,
snapshot,
- snapshotFetchedAt,
type Ledger,
type LedgerBlock,
type LedgerEntry,
+ type LedgerSection,
} from '../../../../generated/componentScores';
// =============================================================================
@@ -60,6 +83,21 @@ const GRADE_VARIANT: Record<string, BadgeVariant> = {
F: 'error',
};
+const AUDIT_PANEL_ID = 'component-audit-details';
+
+const AUDIT_MODE_LABELS: Record<string, string> = {
+ N: 'Nightly',
+ P: 'Promotion',
+ O: 'On-demand',
+ R: 'Review',
+};
+
+const INTERACTIVE_ROW_DESCENDANT =
+ 'a, button, input, select, textarea, [role="button"], [role="link"], ' +
+ '[role="checkbox"], [role="menu"], [role="menuitem"], ' +
+ '[role="menuitemcheckbox"], [role="menuitemradio"], [role="listbox"], ' +
+ '[role="option"], [contenteditable="true"]';
+
/** The lowest section carrying a published per-section score. */
function weakestSection(entry: LedgerEntry): string | null {
let worst: {id: string; score: number} | null = null;
@@ -108,93 +146,409 @@ function buildRows(ledger: Ledger | null): ScoreRow[] {
);
}
-// =============================================================================
-// Copy-to-clipboard
-// =============================================================================
+/** The audit request for one component, with the placeholder filled in. */
+const promptFor = (component: string) =>
+ AUDIT_PROMPT.replaceAll('<Component>', component);
-function CopyButton({
- text,
- label = 'Copy',
- size = 'sm',
+function RowActions({
+ row,
+ onViewAudit,
}: {
- text: string;
- label?: string;
- size?: 'sm' | 'md';
+ row: ScoreRow;
+ onViewAudit: (row: ScoreRow, trigger: HTMLButtonElement | null) => void;
}) {
- const [copied, setCopied] = useState(false);
+ const triggerRef = useRef<HTMLButtonElement>(null);
+ const toast = useToast();
+
+ const copyAuditPrompt = async () => {
+ try {
+ await navigator.clipboard.writeText(promptFor(row.component));
+ toast({
+ body: `Audit prompt copied for ${row.component}.`,
+ uniqueID: 'component-audit-prompt-copied',
+ });
+ } catch {
+ toast({
+ body: `Could not copy the audit prompt for ${row.component}.`,
+ type: 'error',
+ uniqueID: 'component-audit-prompt-copy-error',
+ });
+ }
+ };
+
return (
- <Button
- variant="secondary"
- size={size}
- label={copied ? 'Copied' : label}
- onClick={() => {
- void navigator.clipboard.writeText(text).then(() => {
- setCopied(true);
- setTimeout(() => setCopied(false), 1600);
- });
- }}
+ <MoreMenu
+ ref={triggerRef}
+ label={`Actions for ${row.component} (${row.package})`}
+ size="sm"
+ items={[
+ {
+ label: 'Copy audit prompt',
+ onClick: () => {
+ void copyAuditPrompt();
+ },
+ },
+ ...(row.entry
+ ? [
+ {
+ label: 'View audit',
+ onClick: () => onViewAudit(row, triggerRef.current),
+ },
+ ]
+ : []),
+ ]}
/>
);
}
-/** The audit request for one component, with the placeholder filled in. */
-const promptFor = (component: string) =>
- AUDIT_PROMPT.replaceAll('<Component>', component);
+type AuditEvidence = NonNullable<LedgerEntry['evidence']>[number];
-// =============================================================================
-// Freshness
-// =============================================================================
+function isInteractiveRowTarget(target: EventTarget | null): boolean {
+ return (
+ target instanceof Element &&
+ target.closest(INTERACTIVE_ROW_DESCENDANT) != null
+ );
+}
-/**
- * Which copy is on screen, said out loud. A stale page that looks live is worse
- * than one that admits it, so this is a Badge next to the numbers rather than a
- * line of small print underneath them.
- */
-function FreshnessBadge({
- source,
- updated,
+function formatOptionalCount(value: number | null): string {
+ return typeof value === 'number' ? String(value) : 'Not published';
+}
+
+function formatAuditMode(mode: string | null): string {
+ if (!mode) {
+ return 'Not published';
+ }
+ const label = AUDIT_MODE_LABELS[mode];
+ return label ? mode + ' · ' + label : mode;
+}
+
+function readAuditSection(entry: LedgerEntry, id: string): LedgerSection {
+ return (
+ entry.sections?.[id] ?? {
+ score: null,
+ weight: SECTION_WEIGHTS[id] ?? 0,
+ state: 'not_measured',
+ }
+ );
+}
+
+function sectionResultLabel(section: LedgerSection): string {
+ const score =
+ typeof section.score === 'number'
+ ? section.score.toFixed(1) + ' / 5'
+ : null;
+
+ if (section.state === 'scored') {
+ return score ?? 'Score unavailable';
+ }
+ if (section.state === 'limited') {
+ return score
+ ? score + ' · Limited, informational only'
+ : 'Limited, informational only';
+ }
+ if (section.state === 'na') {
+ return 'N/A';
+ }
+ if (section.state === 'unpublished') {
+ return 'Audited · breakdown unpublished';
+ }
+ return 'Not measured';
+}
+
+function EvidenceReference({
+ value,
+ commit,
}: {
- source: LedgerSource;
- updated: string | null;
+ value: string;
+ commit: string | null;
}) {
- const snapshotDate = snapshotFetchedAt?.slice(0, 10) ?? null;
- const state = {
- loading: {
- variant: 'neutral' as BadgeVariant,
- label: 'Checking the wiki…',
- detail:
- 'Reading the ledger from the wiki. The build-time copy is showing meanwhile.',
- },
- live: {
- variant: 'success' as BadgeVariant,
- label: 'Live',
- detail: updated
- ? `Fetched from the wiki ledger just now; the ledger was last written ${updated}.`
- : 'Fetched from the wiki ledger just now.',
- },
- snapshot: {
- variant: 'warning' as BadgeVariant,
- label: snapshotDate ? `Snapshot from ${snapshotDate}` : 'Snapshot',
- detail:
- 'The wiki could not be reached, so this is the copy taken when the site was built. ' +
- 'Scores recorded since then are not on this page.',
- },
- none: {
- variant: 'error' as BadgeVariant,
- label: 'No ledger',
- detail:
- 'Neither the live fetch nor a build-time snapshot resolved. Every component reads TBD — ' +
- 'that is this page failing, not 118 unaudited components.',
- },
- }[source];
+ if (value.startsWith('https://') || value.startsWith('http://')) {
+ return (
+ <Link href={value} isExternalLink type="supporting">
+ {value}
+ </Link>
+ );
+ }
+
+ if (!value.startsWith('/')) {
+ return (
+ <Link
+ href={
+ 'https://github.com/' +
+ REPO +
+ '/blob/' +
+ (commit ?? 'main') +
+ '/' +
+ value
+ }
+ isExternalLink
+ type="supporting">
+ {value}
+ </Link>
+ );
+ }
+
+ return <Code>{value}</Code>;
+}
+
+function AuditEvidenceItem({
+ evidence,
+ commit,
+}: {
+ evidence: AuditEvidence;
+ commit: string | null;
+}) {
+ return (
+ <Section variant="muted" padding={3}>
+ <VStack gap={2}>
+ <Text weight="medium">{evidence.label}</Text>
+ {evidence.path ? (
+ <EvidenceReference value={evidence.path} commit={commit} />
+ ) : null}
+ {evidence.note ? (
+ <Text type="supporting" color="secondary">
+ {evidence.note}
+ </Text>
+ ) : null}
+ </VStack>
+ </Section>
+ );
+}
+function AuditBlockDetails({
+ block,
+ rowId,
+ index,
+}: {
+ block: LedgerBlock;
+ rowId: string;
+ index: number;
+}) {
return (
- <HStack gap={2} vAlign="center" wrap="wrap">
- <Badge variant={state.variant} label={state.label} />
- <Text type="supporting" color="secondary">
- {state.detail}
- </Text>
- </HStack>
+ <Card key={rowId + '-' + block.id + '-' + String(index)}>
+ <VStack gap={2}>
+ <HStack gap={2} vAlign="center" wrap="wrap">
+ <Text weight="medium">{block.id}</Text>
+ {block.issue ? (
+ <Link
+ href={
+ 'https://github.com/' + REPO + '/issues/' + String(block.issue)
+ }
+ isExternalLink
+ type="supporting">
+ Issue #{block.issue}
+ </Link>
+ ) : (
+ <Text type="supporting" color="secondary">
+ No issue filed
+ </Text>
+ )}
+ </HStack>
+ {block.section ? (
+ <Text type="supporting" color="secondary">
+ {block.section}
+ </Text>
+ ) : null}
+ <Text>{block.summary}</Text>
+ {block.evidence ? (
+ <VStack gap={1}>
+ <Text type="label">Evidence</Text>
+ <Text type="supporting" color="secondary">
+ {block.evidence}
+ </Text>
+ </VStack>
+ ) : null}
+ </VStack>
+ </Card>
+ );
+}
+
+function AuditDetails({
+ row,
+ currentRubricVersion,
+}: {
+ row: ScoreRow;
+ currentRubricVersion: string | null;
+}) {
+ const entry = row.entry;
+ if (!entry) {
+ return null;
+ }
+
+ const blockCount = entry.blocks?.count ?? 0;
+ const knownBlocks = entry.blocks?.open ?? [];
+ const unpublishedBlockCount = Math.max(0, blockCount - knownBlocks.length);
+ const evidence = entry.evidence ?? [];
+ const isHistoricalRubric =
+ entry.rubricVersion != null &&
+ currentRubricVersion != null &&
+ entry.rubricVersion !== currentRubricVersion;
+
+ return (
+ <VStack gap={5} padding={5}>
+ <VStack gap={2} xstyle={styles.drawerHeader}>
+ <Heading level={2} tabIndex={-1} data-autofocus>
+ {row.component}
+ </Heading>
+ <Text type="supporting" color="secondary">
+ {row.package} component audit
+ </Text>
+ <HStack gap={2} vAlign="center" wrap="wrap">
+ <Badge
+ variant={
+ entry.grade
+ ? (GRADE_VARIANT[entry.grade] ?? 'neutral')
+ : 'neutral'
+ }
+ label={entry.grade ?? 'Unscored'}
+ />
+ <Text type="large" xstyle={styles.tabularValue}>
+ {typeof entry.score === 'number'
+ ? entry.score.toFixed(1) + ' / 100'
+ : 'Score unavailable'}
+ </Text>
+ {blockCount > 0 ? (
+ <Badge
+ variant="error"
+ label={
+ String(blockCount) +
+ ' open BLOCK' +
+ (blockCount === 1 ? '' : 's')
+ }
+ />
+ ) : null}
+ </HStack>
+ </VStack>
+
+ {isHistoricalRubric ? (
+ <Section variant="muted" padding={3}>
+ <Text type="supporting">
+ This audit used rubric v{entry.rubricVersion}; the current ledger
+ uses v{currentRubricVersion}. Scores across rubric versions may not
+ be directly comparable.
+ </Text>
+ </Section>
+ ) : null}
+
+ <VStack gap={3}>
+ <Heading level={3}>Audit metadata</Heading>
+ <MetadataList columns="multi" label={{position: 'top'}}>
+ <MetadataListItem label="Last audited">
+ {entry.lastAudited ?? 'Not published'}
+ </MetadataListItem>
+ <MetadataListItem label="Audit mode">
+ {formatAuditMode(entry.mode)}
+ </MetadataListItem>
+ <MetadataListItem label="Rubric version">
+ {entry.rubricVersion ?? 'Not published'}
+ </MetadataListItem>
+ <MetadataListItem label="Audited commit">
+ {entry.commit ? (
+ <Link
+ href={'https://github.com/' + REPO + '/commit/' + entry.commit}
+ isExternalLink>
+ <Code>{entry.commit}</Code>
+ </Link>
+ ) : (
+ 'Not published'
+ )}
+ </MetadataListItem>
+ <MetadataListItem label="Distinct defects">
+ {formatOptionalCount(entry.distinct_defects)}
+ </MetadataListItem>
+ <MetadataListItem label="FIXes">
+ {formatOptionalCount(entry.fixes)}
+ </MetadataListItem>
+ <MetadataListItem label="NITs">
+ {formatOptionalCount(entry.nits)}
+ </MetadataListItem>
+ </MetadataList>
+ </VStack>
+
+ <Divider />
+
+ <VStack gap={3}>
+ <Heading level={3}>Open BLOCKs</Heading>
+ {blockCount === 0 ? (
+ <Text color="secondary">No open BLOCKs recorded.</Text>
+ ) : (
+ knownBlocks.map((block, index) => (
+ <AuditBlockDetails
+ key={row.id + '-' + block.id + '-' + String(index)}
+ block={block}
+ rowId={row.id}
+ index={index}
+ />
+ ))
+ )}
+ {unpublishedBlockCount > 0 ? (
+ <Text type="supporting" color="secondary">
+ +{unpublishedBlockCount} BLOCK detail
+ {unpublishedBlockCount === 1 ? '' : 's'} not individually published.
+ The total above is authoritative.
+ </Text>
+ ) : null}
+ </VStack>
+
+ <Divider />
+
+ <VStack gap={4}>
+ <Heading level={3}>Rubric sections</Heading>
+ {Object.keys(SECTION_TITLES).map((id, index) => {
+ const section = readAuditSection(entry, id);
+ return (
+ <VStack key={id} gap={2}>
+ {index > 0 ? <Divider /> : null}
+ <VStack gap={1}>
+ <Heading level={4}>{SECTION_TITLES[id]}</Heading>
+ <HStack gap={3} wrap="wrap">
+ <Text weight="medium" xstyle={styles.tabularValue}>
+ {sectionResultLabel(section)}
+ </Text>
+ <Text type="supporting" color="secondary">
+ {section.weight}% weight
+ </Text>
+ </HStack>
+ </VStack>
+ {section.state === 'limited' ? (
+ <Text type="supporting" color="secondary">
+ Fewer than one third of the section produced a non-vacuous
+ verdict, so this score is informational and its weight was
+ redistributed.
+ </Text>
+ ) : null}
+ {section.note ? <Text>{section.note}</Text> : null}
+ </VStack>
+ );
+ })}
+ </VStack>
+
+ {evidence.length > 0 ? (
+ <>
+ <Divider />
+ <VStack gap={3}>
+ <Heading level={3}>Evidence</Heading>
+ {evidence.map((item, index) => (
+ <AuditEvidenceItem
+ key={item.label + '-' + String(index)}
+ evidence={item}
+ commit={entry.commit}
+ />
+ ))}
+ </VStack>
+ </>
+ ) : null}
+
+ {entry.notes ? (
+ <>
+ <Divider />
+ <VStack gap={2}>
+ <Heading level={3}>Audit notes</Heading>
+ <Text>{entry.notes}</Text>
+ </VStack>
+ </>
+ ) : null}
+ </VStack>
);
}
@@ -222,41 +576,35 @@ function FreshnessBadge({
// Page
// =============================================================================
-type Filter = 'all' | 'audited' | 'tbd' | 'blocks';
+type AuditFilter = 'audited' | 'tbd';
+type PackageFilter = 'core' | 'lab';
-const FILTERS: Array<{value: Filter; label: string}> = [
- {value: 'all', label: 'All'},
+const AUDIT_FILTER_OPTIONS = [
{value: 'audited', label: 'Audited'},
{value: 'tbd', label: 'TBD'},
- {value: 'blocks', label: 'With open BLOCKs'},
];
-
-/**
- * Which copy of the ledger is on screen. `loading` matters: without it the page
- * claims "snapshot" for the few hundred milliseconds before the fetch lands,
- * which is the same lie in the other direction.
- */
-type LedgerSource = 'loading' | 'live' | 'snapshot' | 'none';
+const PACKAGE_FILTER_OPTIONS = [
+ {value: 'core', label: 'Core'},
+ {value: 'lab', label: 'Lab'},
+];
export default function ComponentScoresPage() {
const [ledger, setLedger] = useState<Ledger | null>(snapshot);
- const [source, setSource] = useState<LedgerSource>('loading');
const [query, setQuery] = useState('');
- const [filter, setFilter] = useState<Filter>('all');
-
- // The ledger is a wiki file served with `access-control-allow-origin: *`, so
- // this page reads current scores without a rebuild. The build-time snapshot
- // is only there so nothing is ever blank while this resolves — and so the
- // page still works when the wiki is unreachable.
- //
- // `no-store`: raw.githubusercontent serves the ledger with `max-age=300`, so
- // the default cache would happily hand back a five-minute-old copy and the
- // page would call it live. A page that says "live" has to have asked.
- //
- // Bounded, for the same reason the indicator exists at all: a stalled
- // connection never rejects, so without this the badge would sit on
- // "Checking the wiki…" forever rather than admitting it is showing the
- // snapshot. One controller serves both the timeout and unmount.
+ const [auditFilter, setAuditFilter] = useState<AuditFilter | null>(null);
+ const [packageFilter, setPackageFilter] = useState<PackageFilter | null>(
+ null,
+ );
+ const [selectedRowId, setSelectedRowId] = useState<string | null>(null);
+ const [isAuditPanelOpen, setIsAuditPanelOpen] = useState(false);
+ const drawerRef = useRef<HTMLDialogElement>(null);
+ const auditTriggerRef = useRef<HTMLElement | null>(null);
+ const filterInputRef = useRef<HTMLInputElement>(null);
+
+ // The live wiki fetch keeps the ledger current without requiring a rebuild.
+ // The build-time snapshot keeps the page useful while it resolves and when
+ // the wiki is unavailable. `no-store` avoids the upstream five-minute cache,
+ // and one controller bounds both the request timeout and unmount.
useEffect(() => {
let cancelled = false;
const controller = new AbortController();
@@ -274,13 +622,8 @@ export default function ComponentScoresPage() {
throw new Error('not a ledger');
}
setLedger(data);
- setSource('live');
- })
- .catch(() => {
- if (!cancelled) {
- setSource(snapshot ? 'snapshot' : 'none');
- }
})
+ .catch(() => undefined)
.finally(() => clearTimeout(timer));
return () => {
@@ -291,48 +634,154 @@ export default function ComponentScoresPage() {
}, []);
const rows = useMemo(() => buildRows(ledger), [ledger]);
+ const selectedRow = useMemo(
+ () => rows.find(row => row.id === selectedRowId) ?? null,
+ [rows, selectedRowId],
+ );
- const stats = useMemo(() => {
- const audited = rows.filter(r => r.audited);
- const grades: Record<string, number> = {A: 0, B: 0, C: 0, D: 0, F: 0};
- for (const r of audited) {
- if (r.grade && r.grade in grades) {
- grades[r.grade] += 1;
+ const openAudit = useCallback(
+ (row: ScoreRow, trigger?: HTMLElement | null) => {
+ if (!row.entry) {
+ return;
+ }
+ if (trigger) {
+ auditTriggerRef.current = trigger;
+ }
+ setSelectedRowId(row.id);
+ setIsAuditPanelOpen(true);
+ },
+ [],
+ );
+
+ // Switching rows keeps the non-modal drawer open. Reset its reading
+ // position and move focus to the new heading so the changed audit is
+ // announced and Escape continues to reach the drawer's key handler.
+ useEffect(() => {
+ if (!isAuditPanelOpen || !selectedRowId) {
+ return;
+ }
+
+ const frame = window.requestAnimationFrame(() => {
+ const dialog = drawerRef.current;
+ const scrollContainer = dialog?.firstElementChild;
+ if (scrollContainer instanceof HTMLElement) {
+ scrollContainer.scrollTop = 0;
}
+ dialog?.querySelector<HTMLElement>('[data-autofocus]')?.focus();
+ });
+
+ return () => window.cancelAnimationFrame(frame);
+ }, [isAuditPanelOpen, selectedRowId]);
+
+ // Drawer remembers the trigger from its initial open. For master-detail
+ // row switching, return focus to the most recently selected row instead.
+ useEffect(() => {
+ const dialog = drawerRef.current;
+ if (!dialog) {
+ return;
}
- return {
- total: rows.length,
- audited: audited.length,
- percent: rows.length
- ? Math.round((audited.length / rows.length) * 1000) / 10
- : 0,
- grades,
- openBlocks: audited.reduce((sum, r) => sum + r.blocks, 0),
- filedIssues: audited.reduce(
- (sum, r) => sum + r.blockList.filter(b => b.issue).length,
- 0,
- ),
+
+ const restoreLatestTrigger = () => {
+ const trigger = auditTriggerRef.current;
+ if (trigger?.isConnected) {
+ trigger.focus();
+ } else {
+ filterInputRef.current?.focus();
+ }
};
- }, [rows]);
+ dialog.addEventListener('close', restoreLatestTrigger);
+ return () => dialog.removeEventListener('close', restoreLatestTrigger);
+ }, []);
const visible = useMemo(() => {
const q = query.trim().toLowerCase();
return rows.filter(r => {
- if (q && !r.component.toLowerCase().includes(q)) {
+ if (
+ q &&
+ !r.component.toLowerCase().includes(q) &&
+ !r.package.toLowerCase().includes(q)
+ ) {
return false;
}
- if (filter === 'audited') {
- return r.audited;
+ if (auditFilter === 'audited' && !r.audited) {
+ return false;
}
- if (filter === 'tbd') {
- return !r.audited;
+ if (auditFilter === 'tbd' && r.audited) {
+ return false;
}
- if (filter === 'blocks') {
- return r.blocks > 0;
+ if (packageFilter && r.package !== packageFilter) {
+ return false;
}
return true;
});
- }, [rows, query, filter]);
+ }, [rows, query, auditFilter, packageFilter]);
+
+ const stats = useMemo(() => {
+ const audited = visible.filter(row => row.audited).length;
+ const scores = visible
+ .map(row => row.score)
+ .filter((score): score is number => typeof score === 'number');
+
+ return {
+ total: visible.length,
+ audited,
+ percent: visible.length
+ ? Math.round((audited / visible.length) * 1000) / 10
+ : 0,
+ average:
+ scores.length > 0
+ ? scores.reduce((sum, score) => sum + score, 0) / scores.length
+ : null,
+ scored: scores.length,
+ };
+ }, [visible]);
+
+ const lastUpdatedLabel = ledger?.updated
+ ? 'Last updated ' + ledger.updated
+ : 'Last updated unavailable';
+
+ const hasActiveFilters =
+ auditFilter != null || packageFilter != null || query.length > 0;
+ const auditRowPlugin = useMemo<TablePlugin<ScoreRow>>(
+ () => ({
+ transformBodyRow(props, row) {
+ if (!row.entry) {
+ return props;
+ }
+
+ const previousOnClick = props.htmlProps.onClick;
+ return {
+ ...props,
+ htmlProps: {
+ ...props.htmlProps,
+ onClick: event => {
+ previousOnClick?.(event);
+ if (
+ event.defaultPrevented ||
+ isInteractiveRowTarget(event.target) ||
+ window.getSelection()?.toString()
+ ) {
+ return;
+ }
+
+ const trigger = event.currentTarget.querySelector<HTMLElement>(
+ 'button[aria-haspopup="menu"]',
+ );
+ trigger?.focus();
+ openAudit(row, trigger);
+ },
+ },
+ xstyle: [...props.xstyle, styles.auditRow],
+ };
+ },
+ }),
+ [openAudit],
+ );
+
+ const tablePlugins = useMemo(
+ () => ({auditDetails: auditRowPlugin}),
+ [auditRowPlugin],
+ );
const columns: TableColumn<ScoreRow>[] = [
{
@@ -372,53 +821,9 @@ export default function ComponentScoresPage() {
</Text>
),
},
- {
- key: 'blocks',
- header: 'Open BLOCKs',
- width: proportional(2),
- renderCell: (row: ScoreRow) => {
- if (!row.audited) {
- return <Text color="secondary">—</Text>;
- }
- if (row.blocks === 0) {
- return <Text>0</Text>;
- }
- const filed = row.blockList.filter(b => b.issue);
- const unattributed = row.blocks - row.blockList.length;
- return (
- <HStack gap={2} vAlign="center" wrap="wrap">
- <Badge variant="error" label={String(row.blocks)} />
- {filed.map(block => (
- <Link
- key={`${row.id}-${block.id}`}
- href={`https://github.com/${REPO}/issues/${block.issue}`}
- isExternalLink
- type="supporting">
- {block.id} #{block.issue}
- </Link>
- ))}
- {row.blockList
- .filter(b => !b.issue)
- .map(block => (
- <Text
- key={`${row.id}-${block.id}`}
- type="supporting"
- color="secondary">
- {block.id} (no issue)
- </Text>
- ))}
- {unattributed > 0 ? (
- <Text type="supporting" color="secondary">
- +{unattributed} unattributed
- </Text>
- ) : null}
- </HStack>
- );
- },
- },
{
key: 'weakest',
- header: 'Weakest section',
+ header: 'Weakest rubric area',
width: proportional(2),
renderCell: (row: ScoreRow) => (
<Text type="supporting" color="secondary">
@@ -445,126 +850,226 @@ export default function ComponentScoresPage() {
),
},
{
- key: 'action',
- header: 'Audit',
- // Wide enough for the button plus the cell's own padding: at pixel(150)
- // the 162px control was clipped on every row.
- width: pixel(190),
+ key: 'actions',
+ header: 'Actions',
+ width: pixel(72),
+ align: 'end',
renderCell: (row: ScoreRow) => (
- <CopyButton
- text={promptFor(row.component)}
- label={row.audited ? 'Copy re-audit prompt' : 'Copy audit prompt'}
+ <RowActions
+ row={row}
+ onViewAudit={(auditRow, trigger) => openAudit(auditRow, trigger)}
/>
),
},
];
+ // AppShell supplies no content padding, so this page owns its gutters while
+ // the audit table uses the full available content width.
return (
- // AppShell renders sandbox pages with `contentPadding={0}`, so the page owns
- // its own gutters — without them the content ran flush to both viewport
- // edges and the last column's button was clipped off the right. `maxWidth`
- // caps the measure: unconstrained, the table stretched to 2300px on a
- // 2560px monitor, which puts a component's name and its grade a foot apart.
- <VStack gap={5} padding={6} maxWidth={1600} width="100%">
- <VStack gap={2} maxWidth="72ch">
- <Heading level={1}>Component scores</Heading>
- <Text>
- Every component in <Code>packages/core/src</Code> and{' '}
- <Code>packages/lab/src</Code>, joined with the audit ledger kept in{' '}
- <Link href={LEDGER_WIKI_URL} isExternalLink>
- the wiki
- </Link>
- . <strong>TBD</strong> means nobody has audited it yet — not that the
- component is bad.
- </Text>
- <Link href={RUBRIC_URL} isExternalLink>
- How components are graded, and how to get one audited
- </Link>
- </VStack>
-
- <VStack gap={2}>
- <HStack gap={6} wrap="wrap" vAlign="center">
- <Stat label="Audited" value={`${stats.audited} / ${stats.total}`} />
- <Stat label="Coverage" value={`${stats.percent}%`} />
- <Stat label="Open BLOCKs" value={String(stats.openBlocks)} />
- <Stat
- label="BLOCKs with an issue"
- value={String(stats.filedIssues)}
- />
- <Stat
- label="Grades"
- value={`A ${stats.grades.A} · B ${stats.grades.B} · C ${stats.grades.C} · D ${stats.grades.D} · F ${stats.grades.F}`}
- />
- </HStack>
- <FreshnessBadge source={source} updated={ledger?.updated ?? null} />
- </VStack>
+ <>
+ <VStack gap={0} width="100%">
+ <Section variant="transparent" padding={4}>
+ <VStack gap={5}>
+ <HStack gap={4} justify="between" vAlign="start" wrap="wrap">
+ <VStack gap={2} maxWidth="72ch">
+ <Heading level={1}>Component Audits</Heading>
+ <Text>
+ To audit a component, open its <strong>Actions</strong> menu,
+ choose <strong>Copy audit prompt</strong>, run the prompt
+ against the component in the repository, then record and
+ publish the completed result to the{' '}
+ <Link href={LEDGER_WIKI_URL} isExternalLink>
+ central audit ledger
+ </Link>
+ . This page automatically shows recorded scores and evidence;
+ components without a recorded result remain{' '}
+ <strong>TBD</strong>.
+ </Text>
+ <Link href={RUBRIC_URL} isExternalLink>
+ How components are graded, and how to get one audited
+ </Link>
+ </VStack>
+ <Text type="supporting" color="secondary">
+ {lastUpdatedLabel}
+ </Text>
+ </HStack>
- <VStack gap={3}>
- <HStack gap={3} vAlign="end" wrap="wrap">
- <TextInput
- label="Filter components"
- isLabelHidden
- placeholder="Filter components…"
- value={query}
- onChange={setQuery}
- />
- {FILTERS.map(({value, label}) => (
- <Button
- key={value}
+ <Toolbar
+ label="Filter components"
size="sm"
- variant={filter === value ? 'primary' : 'ghost'}
- label={label}
- onClick={() => setFilter(value)}
+ gap={2}
+ startContent={
+ <HStack gap={1} vAlign="center">
+ <Selector
+ label="Audit status"
+ isLabelHidden
+ placeholder="Audit status"
+ options={AUDIT_FILTER_OPTIONS}
+ value={auditFilter}
+ onChange={value =>
+ setAuditFilter(
+ value ? (value.toLowerCase() as AuditFilter) : null,
+ )
+ }
+ hasClear
+ variant="ghost"
+ size="sm"
+ xstyle={styles.filterToken}
+ />
+ <Selector
+ label="Package"
+ isLabelHidden
+ placeholder="Package"
+ options={PACKAGE_FILTER_OPTIONS}
+ value={packageFilter}
+ onChange={value =>
+ setPackageFilter(
+ value ? (value.toLowerCase() as PackageFilter) : null,
+ )
+ }
+ hasClear
+ variant="ghost"
+ size="sm"
+ xstyle={styles.filterToken}
+ />
+ <Text type="supporting" color="secondary">
+ {visible.length}{' '}
+ {visible.length === 1 ? 'result' : 'results'}
+ </Text>
+ {hasActiveFilters ? (
+ <>
+ <Text type="supporting" color="secondary" aria-hidden>
+ ·
+ </Text>
+ <Button
+ label="Clear all"
+ variant="ghost"
+ size="sm"
+ onClick={() => {
+ setAuditFilter(null);
+ setPackageFilter(null);
+ setQuery('');
+ }}
+ />
+ </>
+ ) : null}
+ </HStack>
+ }
+ endContent={
+ <TextInput
+ ref={filterInputRef}
+ label="Search components"
+ isLabelHidden
+ placeholder="Search components…"
+ value={query}
+ onChange={setQuery}
+ hasClear
+ startIcon={<Icon icon="search" size="sm" color="secondary" />}
+ width={240}
+ size="sm"
+ />
+ }
/>
- ))}
- <Text type="supporting" color="secondary">
- {visible.length} of {rows.length}
- </Text>
- </HStack>
- <Table<ScoreRow>
- data={visible}
- columns={columns}
- idKey="id"
- density="balanced"
- dividers="rows"
- hasHover
- />
- </VStack>
+ <Grid columns={{minWidth: 240, max: 2, repeat: 'fit'}} gap={4}>
+ <Card padding={4}>
+ <Stat
+ size="sm"
+ label="Audited"
+ value={String(stats.percent) + '%'}
+ description={
+ String(stats.audited) +
+ ' of ' +
+ String(stats.total) +
+ ' components'
+ }
+ />
+ </Card>
+ <Card padding={4}>
+ <Stat
+ size="sm"
+ label="Average score"
+ value={stats.average == null ? '—' : stats.average.toFixed(1)}
+ description={
+ stats.scored > 0
+ ? 'Across ' + String(stats.scored) + ' scored components'
+ : 'No scored components'
+ }
+ />
+ </Card>
+ </Grid>
+ </VStack>
+ </Section>
- {ledger?.caveats?.length ? (
- <Card>
- <VStack gap={3}>
- <Heading level={2}>Caveats on the recorded rows</Heading>
- <VStack gap={2}>
- {ledger.caveats.map(caveat => (
- <Text key={caveat} type="supporting" color="secondary">
- {caveat}
- </Text>
- ))}
- </VStack>
+ <Section variant="transparent" padding={4} paddingBlock={0}>
+ <Table<ScoreRow>
+ data={visible}
+ columns={columns}
+ plugins={tablePlugins}
+ idKey="id"
+ density="balanced"
+ dividers="rows"
+ hasHover
+ />
+ </Section>
+
+ {ledger?.caveats?.length ? (
+ <VStack padding={4}>
+ <Card>
+ <VStack gap={3}>
+ <Heading level={2}>Caveats on the recorded rows</Heading>
+ <VStack gap={2}>
+ {ledger.caveats.map(caveat => (
+ <Text key={caveat} type="supporting" color="secondary">
+ {caveat}
+ </Text>
+ ))}
+ </VStack>
+ </VStack>
+ </Card>
</VStack>
- </Card>
- ) : null}
- </VStack>
- );
-}
+ ) : null}
+ </VStack>
-function Stat({label, value}: {label: string; value: string}) {
- return (
- <VStack gap={1}>
- <Text type="supporting" color="secondary">
- {label}
- </Text>
- <Text type="large" xstyle={styles.statValue}>
- {value}
- </Text>
- </VStack>
+ <Drawer
+ ref={drawerRef}
+ id={AUDIT_PANEL_ID}
+ isOpen={isAuditPanelOpen && selectedRow?.entry != null}
+ onClose={() => setIsAuditPanelOpen(false)}
+ label={
+ selectedRow
+ ? selectedRow.component +
+ ' ' +
+ selectedRow.package +
+ ' audit details'
+ : 'Component audit details'
+ }
+ hasScrim={false}
+ hasCloseButton
+ size={560}>
+ {selectedRow ? (
+ <AuditDetails
+ row={selectedRow}
+ currentRubricVersion={ledger?.rubricVersion ?? null}
+ />
+ ) : null}
+ </Drawer>
+ </>
);
}
const styles = stylex.create({
- statValue: {
+ auditRow: {
+ cursor: 'pointer',
+ },
+ filterToken: {
+ backgroundColor: colorVars['--color-neutral'],
+ borderRadius: radiusVars['--radius-inner'],
+ },
+ drawerHeader: {
+ paddingInlineEnd: spacingVars['--spacing-10'],
+ },
+ tabularValue: {
fontVariantNumeric: 'tabular-nums',
},
});
diff --git a/apps/sandbox/src/app/(sandbox)/templates/page.tsx b/apps/sandbox/src/app/(sandbox)/templates/page.tsx
index 923ce4367e..82f538508a 100644
--- a/apps/sandbox/src/app/(sandbox)/templates/page.tsx
+++ b/apps/sandbox/src/app/(sandbox)/templates/page.tsx
@@ -1,36 +1,65 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
+/**
+ * @file Filterable template audit roster with live summary metrics and details.
+ * @input Generated page/block registries and the sandbox template audit data.
+ * @output Page-prefiltered audit table with filter-aware stats and a drawer.
+ * @position Sandbox template catalog at /templates/.
+ */
+
'use client';
-import {useState, useCallback, useMemo, Suspense} from 'react';
+import {useCallback, useEffect, useMemo, useRef, useState} from 'react';
+import * as stylex from '@stylexjs/stylex';
import NextLink from 'next/link';
-import {useSearchParams, useRouter} from 'next/navigation';
-import {Heading} from '@astryxdesign/core/Text';
-import {Layout, LayoutHeader, LayoutContent} from '@astryxdesign/core/Layout';
-import {
- Table,
- useTableSortableState,
- useTableSortable,
- useTableColumnResize,
- useTableFiltering,
- toSearchFilters,
- pixel,
-} from '@astryxdesign/core/Table';
-import type {TableColumn, TableSortState} from '@astryxdesign/core/Table';
-import type {
- TableFilterState,
- TableFilterValue,
-} from '@astryxdesign/core/Table';
-import {usePowerSearchConfig} from '@astryxdesign/core/PowerSearch';
-import type {PowerSearchFilter} from '@astryxdesign/core/PowerSearch';
-import {Link} from '@astryxdesign/core/Link';
+
import {Badge} from '@astryxdesign/core/Badge';
+import type {BadgeVariant} from '@astryxdesign/core/Badge';
import {Button} from '@astryxdesign/core/Button';
-import {CopyIcon} from '../../icons';
-import {templates} from '../../../generated/templateRegistry';
+import {Card} from '@astryxdesign/core/Card';
+import {Code} from '@astryxdesign/core/Code';
+import {Divider} from '@astryxdesign/core/Divider';
+import {Grid} from '@astryxdesign/core/Grid';
+import {HStack, VStack} from '@astryxdesign/core/Layout';
+import {Link} from '@astryxdesign/core/Link';
+import {MetadataList, MetadataListItem} from '@astryxdesign/core/MetadataList';
+import {MoreMenu} from '@astryxdesign/core/MoreMenu';
+import {Section} from '@astryxdesign/core/Section';
+import {Selector} from '@astryxdesign/core/Selector';
+import {Table, pixel, proportional} from '@astryxdesign/core/Table';
+import type {TableColumn, TablePlugin} from '@astryxdesign/core/Table';
+import {Heading, Text} from '@astryxdesign/core/Text';
+import {TextInput} from '@astryxdesign/core/TextInput';
+import {
+ colorVars,
+ radiusVars,
+ spacingVars,
+} from '@astryxdesign/core/theme/tokens.stylex';
+import {Toolbar} from '@astryxdesign/core/Toolbar';
+import {useToast} from '@astryxdesign/core/Toast';
+import {Drawer, Stat} from '@astryxdesign/lab';
+
+import {
+ TEMPLATE_AUDIT_CATEGORIES,
+ TEMPLATE_LEDGER_FETCH_TIMEOUT_MS,
+ TEMPLATE_LEDGER_URL,
+ TEMPLATE_RUBRIC_URL,
+ isTemplateAuditLedger,
+ templateAuditsById,
+ templateAuditPrompt,
+ templateLedgerSeed,
+} from '../../../data/templateAudits';
+import type {
+ TemplateAudit,
+ TemplateAuditCategoryStatus,
+ TemplateAuditGrade,
+ TemplateAuditLedger,
+} from '../../../data/templateAudits';
import {blocks} from '../../../generated/blockRegistry';
+import {templates} from '../../../generated/templateRegistry';
+import {SearchIcon} from '../../icons';
-type TemplateRow = {
+interface TemplateRow extends Record<string, unknown> {
id: string;
name: string;
description: string;
@@ -41,296 +70,946 @@ type TemplateRow = {
docPath: string;
isReady: boolean;
isShowcase: boolean;
+ audit: TemplateAudit | null;
+ audited: boolean;
+ grade: TemplateAuditGrade | 'TBD';
+ score: number | null;
+ weakest: string | null;
+ lastAudited: string | null;
+}
+
+const GRADE_VARIANT: Record<TemplateAuditGrade, BadgeVariant> = {
+ A: 'success',
+ B: 'success',
+ C: 'warning',
+ D: 'warning',
+ F: 'error',
+};
+
+const CATEGORY_STATUS_LABELS: Record<TemplateAuditCategoryStatus, string> = {
+ published: 'Published',
+ inferred: 'Inferred',
+ intermediate: 'Intermediate',
+ unresolved: 'Unresolved',
+};
+
+const CATEGORY_STATUS_VARIANTS: Record<
+ TemplateAuditCategoryStatus,
+ BadgeVariant
+> = {
+ published: 'success',
+ inferred: 'info',
+ intermediate: 'warning',
+ unresolved: 'neutral',
};
-const rows: TemplateRow[] = [
- ...templates.map(t => ({
- id: `page-${t.slug}`,
- name: t.name,
- description: t.description,
- href: t.href,
+const AUDIT_PANEL_ID = 'template-audit-details';
+const REPO_URL = 'https://github.com/facebook/astryx';
+const INTERACTIVE_ROW_DESCENDANT =
+ 'a, button, input, select, textarea, [role="button"], [role="link"], ' +
+ '[role="checkbox"], [role="menu"], [role="menuitem"], ' +
+ '[contenteditable="true"]';
+
+function weakestCategory(audit: TemplateAudit | null): string | null {
+ if (!audit) {
+ return null;
+ }
+
+ let weakest: {title: string; score: number; max: number} | null = null;
+ for (const definition of TEMPLATE_AUDIT_CATEGORIES) {
+ const category = audit.categories[definition.id];
+ if (
+ typeof category?.score !== 'number' ||
+ (category.status !== 'published' && category.status !== 'inferred')
+ ) {
+ continue;
+ }
+ if (
+ !weakest ||
+ category.score / definition.max < weakest.score / weakest.max
+ ) {
+ weakest = {
+ title: definition.title,
+ score: category.score,
+ max: definition.max,
+ };
+ }
+ }
+
+ return weakest
+ ? weakest.title + ' (' + weakest.score + '/' + weakest.max + ')'
+ : null;
+}
+
+interface TemplateRowInput {
+ id: string;
+ name: string;
+ description: string;
+ href: string;
+ type: 'Page' | 'Block';
+ component: string;
+ codePath: string;
+ docPath: string;
+ isReady: boolean;
+ isShowcase: boolean;
+}
+
+function makeRow(
+ {
+ id,
+ name,
+ description,
+ href,
+ type,
+ component,
+ codePath,
+ docPath,
+ isReady,
+ isShowcase,
+ }: TemplateRowInput,
+ audit: TemplateAudit | null,
+): TemplateRow {
+ return {
+ id,
+ name,
+ description,
+ href,
+ type,
+ component,
+ codePath,
+ docPath,
+ isReady,
+ isShowcase,
+ audit,
+ audited: audit != null,
+ grade: audit?.grade ?? 'TBD',
+ score: audit?.score ?? null,
+ weakest: weakestCategory(audit),
+ lastAudited: audit?.lastAudited ?? null,
+ };
+}
+
+const templateRoster: TemplateRowInput[] = [
+ ...templates.map(template => ({
+ id: 'page/' + template.slug,
+ name: template.name,
+ description: template.description,
+ href: template.href,
type: 'Page' as const,
component: 'n/a',
- codePath: `packages/cli/assets/templates/pages/${t.slug}/page.tsx`,
- docPath: `packages/cli/assets/templates/pages/${t.slug}/template.doc.mjs`,
- isReady: t.isReady,
+ codePath:
+ 'packages/cli/assets/templates/pages/' + template.slug + '/page.tsx',
+ docPath:
+ 'packages/cli/assets/templates/pages/' +
+ template.slug +
+ '/template.doc.mjs',
+ isReady: template.isReady,
isShowcase: false,
})),
- ...blocks.map(b => ({
- id: `block-${b.slug}`,
- name: b.name,
- description: b.description,
- href: b.href,
+ ...blocks.map(block => ({
+ id: 'block/' + block.slug,
+ name: block.name,
+ description: block.description,
+ href: block.href,
type: 'Block' as const,
- component: b.component,
- codePath: `packages/cli/assets/templates/blocks/components/${b.component}/${b.slug}.tsx`,
- docPath: `packages/cli/assets/templates/blocks/components/${b.component}/${b.slug}.doc.mjs`,
- isReady: b.isReady,
- isShowcase: b.isShowcase,
+ component: block.component,
+ codePath:
+ 'packages/cli/assets/templates/blocks/components/' +
+ block.component +
+ '/' +
+ block.slug +
+ '.tsx',
+ docPath:
+ 'packages/cli/assets/templates/blocks/components/' +
+ block.component +
+ '/' +
+ block.slug +
+ '.doc.mjs',
+ isReady: block.isReady,
+ isShowcase: block.isShowcase,
})),
];
-const FILTER_PREFIX = 'filter.';
-
-function parseSortFromParams(
- params: URLSearchParams,
-): TableSortState | undefined {
- const raw = params.get('sort');
- if (!raw) {
- return undefined;
- }
- const [sortKey, dir] = raw.split(':');
- if (!sortKey || (dir !== 'asc' && dir !== 'desc')) {
- return undefined;
- }
- return [{sortKey, direction: dir === 'asc' ? 'ascending' : 'descending'}];
+function buildRows(ledger: TemplateAuditLedger | null): TemplateRow[] {
+ const audits = templateAuditsById(ledger);
+ return templateRoster
+ .map(template => makeRow(template, audits[template.id] ?? null))
+ .sort((a, b) => a.name.localeCompare(b.name) || a.id.localeCompare(b.id));
}
-function serializeSort(sort: TableSortState): string | null {
- if (sort.length === 0) {
- return null;
- }
- const {sortKey, direction} = sort[0];
- return `${sortKey}:${direction === 'ascending' ? 'asc' : 'desc'}`;
+type TemplateAuditFilter = 'audited' | 'tbd';
+type TemplateTypeFilter = 'page' | 'block';
+
+const TEMPLATE_AUDIT_FILTER_OPTIONS = [
+ {value: 'audited', label: 'Audited'},
+ {value: 'tbd', label: 'TBD'},
+];
+
+const TEMPLATE_TYPE_FILTER_OPTIONS = [
+ {value: 'page', label: 'Page'},
+ {value: 'block', label: 'Block'},
+];
+
+const ACTIONS_TRIGGER_TEST_ID = 'template-audit-row-actions';
+
+function CopyButton({text, label}: {text: string; label: string}) {
+ const [copied, setCopied] = useState(false);
+ return (
+ <Button
+ variant="secondary"
+ size="sm"
+ label={copied ? 'Copied' : label}
+ onClick={() => {
+ void navigator.clipboard.writeText(text).then(() => {
+ setCopied(true);
+ setTimeout(() => setCopied(false), 1600);
+ });
+ }}
+ />
+ );
}
-function parseFiltersFromParams(params: URLSearchParams): TableFilterState {
- const filters: TableFilterState = {};
- params.forEach((value, key) => {
- if (key.startsWith(FILTER_PREFIX)) {
- filters[key.slice(FILTER_PREFIX.length)] = value;
- }
+function promptFor(row: TemplateRow): string {
+ return templateAuditPrompt({
+ name: row.name,
+ type: row.type,
+ codePath: row.codePath,
+ docPath: row.docPath,
});
- return filters;
}
-function buildSearchParams(
- sort: TableSortState,
- filters: TableFilterState,
-): string {
- const params = new URLSearchParams();
- const sortStr = serializeSort(sort);
- if (sortStr) {
- params.set('sort', sortStr);
- }
- for (const [key, value] of Object.entries(filters)) {
- if (value != null) {
- params.set(`${FILTER_PREFIX}${key}`, String(value));
+function TemplateRowActions({
+ row,
+ onViewAudit,
+}: {
+ row: TemplateRow;
+ onViewAudit: (row: TemplateRow, trigger: HTMLElement | null) => void;
+}) {
+ const triggerRef = useRef<HTMLButtonElement>(null);
+ const toast = useToast();
+
+ const copyAuditPrompt = async () => {
+ try {
+ await navigator.clipboard.writeText(promptFor(row));
+ toast({
+ body: 'Audit prompt copied',
+ uniqueID: 'template-audit-prompt-copied',
+ });
+ } catch {
+ toast({
+ body: 'Could not copy the audit prompt',
+ type: 'error',
+ uniqueID: 'template-audit-prompt-copy-error',
+ });
}
- }
- const str = params.toString();
- return str ? `?${str}` : '';
+ };
+
+ return (
+ <MoreMenu
+ ref={triggerRef}
+ size="sm"
+ label={'Actions for ' + row.name}
+ data-testid={ACTIONS_TRIGGER_TEST_ID}
+ items={[
+ {
+ label: 'Copy audit prompt',
+ onClick: () => {
+ void copyAuditPrompt();
+ },
+ },
+ ...(row.audit
+ ? [
+ {
+ label: 'View audit',
+ onClick: () => onViewAudit(row, triggerRef.current),
+ },
+ ]
+ : []),
+ ]}
+ />
+ );
+}
+
+function isInteractiveRowTarget(target: EventTarget | null): boolean {
+ return (
+ target instanceof Element &&
+ target.closest(INTERACTIVE_ROW_DESCENDANT) != null
+ );
}
-function useTableSearchParams() {
- const searchParams = useSearchParams();
- const router = useRouter();
+function githubSource(path: string, commit = 'main'): string {
+ return REPO_URL + '/blob/' + commit + '/' + path;
+}
- const sort = useMemo(
- () =>
- parseSortFromParams(searchParams) ?? [
- {sortKey: 'name', direction: 'ascending' as const},
- ],
- [searchParams],
+function TemplateAuditDetails({row}: {row: TemplateRow}) {
+ const audit = row.audit;
+ if (!audit) {
+ return null;
+ }
+ const screenshotEvidence = audit.evidence.filter(evidence =>
+ evidence.label.toLowerCase().includes('screenshot'),
);
- const filters = useMemo(
- () => parseFiltersFromParams(searchParams),
- [searchParams],
+ return (
+ <VStack gap={5} padding={5}>
+ <VStack gap={2} xstyle={styles.drawerHeader}>
+ <Heading level={2} tabIndex={-1} data-autofocus>
+ {row.name}
+ </Heading>
+ <HStack gap={2} vAlign="center" wrap="wrap">
+ <Badge
+ label={row.type}
+ variant={row.type === 'Page' ? 'info' : 'neutral'}
+ />
+ {row.isShowcase ? <Badge label="Showcase" variant="info" /> : null}
+ </HStack>
+ <HStack gap={2} vAlign="center" wrap="wrap">
+ <Badge variant={GRADE_VARIANT[audit.grade]} label={audit.grade} />
+ <Text type="large" xstyle={styles.tabularValue}>
+ {audit.score} / 100
+ </Text>
+ </HStack>
+ <Link href={row.href} as={NextLink} target="_blank">
+ Open template preview
+ </Link>
+ </VStack>
+
+ {audit.status === 'historical' ? (
+ <Section variant="muted" padding={3}>
+ <Text type="supporting">
+ This score was recovered from a historical merge record. It has not
+ been re-run against the current template at HEAD, so use it as
+ provenance rather than a fresh certification.
+ </Text>
+ </Section>
+ ) : null}
+
+ <VStack gap={3}>
+ <Heading level={3}>Audit metadata</Heading>
+ <MetadataList columns="multi" label={{position: 'top'}}>
+ <MetadataListItem label="Last audited">
+ {audit.lastAudited}
+ </MetadataListItem>
+ <MetadataListItem label="Audit status">
+ {audit.status === 'current' ? 'Current' : 'Historical'}
+ </MetadataListItem>
+ <MetadataListItem label="Rubric">
+ {audit.rubricVersion}
+ </MetadataListItem>
+ <MetadataListItem label="Current grade threshold">
+ B starts at 75
+ </MetadataListItem>
+ <MetadataListItem label="For component">
+ {row.component === 'n/a' ? 'Page template' : row.component}
+ </MetadataListItem>
+ <MetadataListItem label="Audited commit">
+ <Link href={REPO_URL + '/commit/' + audit.commit} isExternalLink>
+ <Code>{audit.commit.slice(0, 12)}</Code>
+ </Link>
+ </MetadataListItem>
+ {audit.recordedGrade ? (
+ <MetadataListItem label="Recorded grade wording">
+ {audit.recordedGrade}
+ </MetadataListItem>
+ ) : null}
+ </MetadataList>
+ </VStack>
+
+ <Divider />
+
+ <VStack gap={4}>
+ <VStack gap={1}>
+ <Heading level={3}>Rubric categories</Heading>
+ <Text type="supporting" color="secondary">
+ Unpublished category scores stay blank; they are not reconstructed
+ from the total.
+ </Text>
+ </VStack>
+ {TEMPLATE_AUDIT_CATEGORIES.map(definition => {
+ const category = audit.categories[definition.id];
+ return (
+ <Section key={definition.id} variant="muted" padding={3}>
+ <VStack gap={2}>
+ <HStack gap={2} vAlign="center" wrap="wrap">
+ <Text weight="medium">{definition.title}</Text>
+ <Text xstyle={styles.tabularValue}>
+ {typeof category?.score === 'number'
+ ? category.score + ' / ' + definition.max
+ : '— / ' + definition.max}
+ </Text>
+ <Badge
+ variant={
+ category
+ ? CATEGORY_STATUS_VARIANTS[category.status]
+ : 'neutral'
+ }
+ label={
+ category
+ ? CATEGORY_STATUS_LABELS[category.status]
+ : 'Not published'
+ }
+ />
+ </HStack>
+ {category?.note ? (
+ <Text type="supporting" color="secondary">
+ {category.note}
+ </Text>
+ ) : null}
+ </VStack>
+ </Section>
+ );
+ })}
+ </VStack>
+
+ <Divider />
+
+ <VStack gap={3}>
+ <Heading level={3}>Findings</Heading>
+ {audit.findings.length ? (
+ audit.findings.map((finding, index) => (
+ <Text key={row.id + '-finding-' + String(index)}>• {finding}</Text>
+ ))
+ ) : (
+ <Text color="secondary">No findings were published.</Text>
+ )}
+ </VStack>
+
+ <VStack gap={3}>
+ <Heading level={3}>Top fixes</Heading>
+ {audit.topFixes.length ? (
+ audit.topFixes.map((fix, index) => (
+ <Text key={row.id + '-fix-' + String(index)}>
+ {index + 1}. {fix}
+ </Text>
+ ))
+ ) : (
+ <Text color="secondary">
+ No ordered fix list was published with this historical score.
+ </Text>
+ )}
+ </VStack>
+
+ <VStack gap={3}>
+ <Heading level={3}>Screenshot tests</Heading>
+ {screenshotEvidence.length ? (
+ screenshotEvidence.map(evidence =>
+ evidence.href ? (
+ <Link key={evidence.label} href={evidence.href} isExternalLink>
+ {evidence.label}
+ </Link>
+ ) : (
+ <Text key={evidence.label}>{evidence.label}</Text>
+ ),
+ )
+ ) : (
+ <Text color="secondary">
+ No screenshot-test evidence was published in the recovered record.
+ The re-audit prompt requests light, dark, and responsive browser
+ coverage.
+ </Text>
+ )}
+ </VStack>
+
+ <VStack gap={3}>
+ <Heading level={3}>Evidence</Heading>
+ {audit.evidence.map(evidence =>
+ evidence.href ? (
+ <Link key={evidence.label} href={evidence.href} isExternalLink>
+ {evidence.label}
+ </Link>
+ ) : (
+ <Text key={evidence.label}>{evidence.label}</Text>
+ ),
+ )}
+ </VStack>
+
+ <Section variant="muted" padding={3}>
+ <VStack gap={2}>
+ <Text weight="medium">Audit notes</Text>
+ <Text type="supporting">{audit.notes}</Text>
+ </VStack>
+ </Section>
+
+ <Divider />
+
+ <VStack gap={3}>
+ <Heading level={3}>Source and re-audit</Heading>
+ <Link
+ href={githubSource(row.codePath, audit.commit)}
+ isExternalLink
+ type="supporting">
+ {row.codePath}
+ </Link>
+ <Link
+ href={githubSource(row.docPath, audit.commit)}
+ isExternalLink
+ type="supporting">
+ {row.docPath}
+ </Link>
+ <HStack gap={2} wrap="wrap">
+ <CopyButton text={promptFor(row)} label="Copy re-audit prompt" />
+ <CopyButton text={row.codePath} label="Copy code path" />
+ <CopyButton text={row.docPath} label="Copy doc path" />
+ </HStack>
+ </VStack>
+ </VStack>
);
+}
- const updateURL = useCallback(
- (newSort: TableSortState, newFilters: TableFilterState) => {
- router.replace(buildSearchParams(newSort, newFilters), {scroll: false});
- },
- [router],
+export default function TemplatesPage() {
+ const [ledger, setLedger] = useState<TemplateAuditLedger | null>(
+ templateLedgerSeed,
+ );
+ const [query, setQuery] = useState('');
+ const [auditFilter, setAuditFilter] = useState<TemplateAuditFilter | null>(
+ null,
);
+ const [typeFilter, setTypeFilter] = useState<TemplateTypeFilter | null>(
+ 'page',
+ );
+ const [selectedRowId, setSelectedRowId] = useState<string | null>(null);
+ const [isAuditPanelOpen, setIsAuditPanelOpen] = useState(false);
+ const drawerRef = useRef<HTMLDialogElement>(null);
+ const auditTriggerRef = useRef<HTMLElement | null>(null);
+ const filterInputRef = useRef<HTMLInputElement>(null);
- const onSortChange = useCallback(
- (newSort: TableSortState) => updateURL(newSort, filters),
- [updateURL, filters],
+ const rows = useMemo(() => buildRows(ledger), [ledger]);
+ const selectedRow = useMemo(
+ () => rows.find(row => row.id === selectedRowId) ?? null,
+ [rows, selectedRowId],
);
- const onFilterChange = useCallback(
- (key: string, value: TableFilterValue | null) => {
- const next = {...filters};
- if (value == null) {
- delete next[key];
- } else {
- next[key] = value;
+ useEffect(() => {
+ let cancelled = false;
+ const controller = new AbortController();
+ const timer = setTimeout(
+ () => controller.abort(),
+ TEMPLATE_LEDGER_FETCH_TIMEOUT_MS,
+ );
+
+ fetch(TEMPLATE_LEDGER_URL, {
+ cache: 'no-store',
+ signal: controller.signal,
+ })
+ .then(response =>
+ response.ok
+ ? response.json()
+ : Promise.reject(new Error(String(response.status))),
+ )
+ .then((data: unknown) => {
+ if (cancelled) {
+ return;
+ }
+ if (!isTemplateAuditLedger(data)) {
+ throw new Error('not a template audit ledger');
+ }
+ setLedger(data);
+ })
+ .catch(() => undefined)
+ .finally(() => clearTimeout(timer));
+
+ return () => {
+ cancelled = true;
+ clearTimeout(timer);
+ controller.abort();
+ };
+ }, []);
+
+ const openAudit = useCallback(
+ (row: TemplateRow, trigger?: HTMLElement | null) => {
+ if (!row.audit) {
+ return;
}
- updateURL(sort, next);
+ if (trigger) {
+ auditTriggerRef.current = trigger;
+ }
+ setSelectedRowId(row.id);
+ setIsAuditPanelOpen(true);
},
- [updateURL, sort, filters],
+ [],
);
- return {sort, onSortChange, filters, onFilterChange};
-}
-
-function CopyPath({path, label}: {path: string; label: string}) {
- return (
- <Button
- label={label}
- icon={<CopyIcon />}
- variant="ghost"
- size="sm"
- isIconOnly
- tooltip={label}
- clickAction={() => navigator.clipboard.writeText(path)}
- />
- );
-}
+ useEffect(() => {
+ if (!isAuditPanelOpen || !selectedRowId) {
+ return;
+ }
+ const frame = window.requestAnimationFrame(() => {
+ const dialog = drawerRef.current;
+ const scrollContainer = dialog?.firstElementChild;
+ if (scrollContainer instanceof HTMLElement) {
+ scrollContainer.scrollTop = 0;
+ }
+ dialog?.querySelector<HTMLElement>('[data-autofocus]')?.focus();
+ });
+ return () => window.cancelAnimationFrame(frame);
+ }, [isAuditPanelOpen, selectedRowId]);
-const uniqueComponents = [...new Set(blocks.map(b => b.component))].sort();
+ useEffect(() => {
+ const dialog = drawerRef.current;
+ if (!dialog) {
+ return;
+ }
+ const restoreLatestTrigger = () => {
+ const trigger = auditTriggerRef.current;
+ if (trigger?.isConnected) {
+ trigger.focus();
+ } else {
+ filterInputRef.current?.focus();
+ }
+ };
+ dialog.addEventListener('close', restoreLatestTrigger);
+ return () => dialog.removeEventListener('close', restoreLatestTrigger);
+ }, []);
-const fieldDefs = [
- {key: 'name', type: 'string', label: 'Name'},
- {
- key: 'type',
- type: 'enum',
- label: 'Type',
- enumValues: [
- {value: 'Page', label: 'Page'},
- {value: 'Block', label: 'Block'},
- ],
- },
- {
- key: 'component',
- type: 'enum',
- label: 'Component',
- enumValues: [
- {value: 'n/a', label: 'n/a'},
- ...uniqueComponents.map(c => ({value: c, label: c})),
+ const columns = useMemo<TableColumn<TemplateRow>[]>(
+ () => [
+ {
+ key: 'name',
+ header: 'Template',
+ width: proportional(3),
+ renderCell: row => (
+ <VStack gap={1}>
+ <Link href={row.href} as={NextLink} target="_blank">
+ {row.name}
+ </Link>
+ <HStack gap={2} vAlign="center">
+ <Text type="supporting" color="secondary">
+ {row.type}
+ </Text>
+ </HStack>
+ </VStack>
+ ),
+ },
+ {
+ key: 'grade',
+ header: 'Grade',
+ width: pixel(88),
+ renderCell: row =>
+ row.audit ? (
+ <Badge
+ variant={GRADE_VARIANT[row.audit.grade]}
+ label={row.audit.grade}
+ />
+ ) : (
+ <Badge label="TBD" />
+ ),
+ },
+ {
+ key: 'score',
+ header: 'Score',
+ width: pixel(80),
+ renderCell: row => (
+ <Text xstyle={styles.tabularValue}>{row.score ?? '—'}</Text>
+ ),
+ },
+ {
+ key: 'weakest',
+ header: 'Weakest rubric area',
+ width: proportional(2),
+ renderCell: row => (
+ <Text type="supporting" color="secondary">
+ {row.weakest ?? '—'}
+ </Text>
+ ),
+ },
+ {
+ key: 'lastAudited',
+ header: 'Last audited',
+ width: pixel(120),
+ renderCell: row =>
+ row.audit ? (
+ <Text type="supporting">{row.audit.lastAudited}</Text>
+ ) : (
+ <Text type="supporting" color="secondary">
+ never
+ </Text>
+ ),
+ },
+ {
+ key: 'actions',
+ header: 'Actions',
+ align: 'end',
+ width: pixel(88),
+ renderCell: row => (
+ <TemplateRowActions row={row} onViewAudit={openAudit} />
+ ),
+ },
],
- },
- {key: 'isShowcase', type: 'boolean', label: 'Showcase'},
-] as const;
-
-const columns: TableColumn<TemplateRow>[] = [
- {
- key: 'type',
- header: 'Type',
- sortable: true,
- filter: 'type',
- width: pixel(100),
- renderCell: (row: TemplateRow) => (
- <Badge
- label={row.type}
- variant={row.type === 'Page' ? 'info' : 'neutral'}
- />
- ),
- },
- {
- key: 'name',
- header: 'Name',
- sortable: true,
- filter: 'name',
- width: pixel(250),
- renderCell: (row: TemplateRow) => (
- <Link href={row.href} as={NextLink} target="_blank">
- {row.name}
- </Link>
- ),
- },
- {
- key: 'component',
- header: 'Component',
- sortable: true,
- filter: 'component',
- width: pixel(150),
- },
- {
- key: 'isShowcase',
- header: 'Showcase',
- sortable: true,
- filter: 'isShowcase',
- width: pixel(100),
- renderCell: (row: TemplateRow) =>
- row.isShowcase ? <Badge label="Showcase" variant="info" /> : null,
- },
- {
- key: 'description',
- header: 'Summary',
- sortable: true,
- },
- {
- key: 'codePath',
- header: 'Code',
- width: pixel(60),
- renderCell: (row: TemplateRow) => (
- <CopyPath path={row.codePath} label="Copy code path" />
- ),
- },
- {
- key: 'docPath',
- header: 'Doc',
- width: pixel(60),
- renderCell: (row: TemplateRow) => (
- <CopyPath path={row.docPath} label="Copy doc path" />
- ),
- },
-];
+ [openAudit],
+ );
-export default function TemplatesPage() {
- return (
- <Suspense>
- <TemplatesPageInner />
- </Suspense>
+ const auditRowPlugin = useMemo<TablePlugin<TemplateRow>>(
+ () => ({
+ transformBodyRow(props, row) {
+ if (!row.audit) {
+ return props;
+ }
+ const previousOnClick = props.htmlProps.onClick;
+ return {
+ ...props,
+ htmlProps: {
+ ...props.htmlProps,
+ onClick: event => {
+ previousOnClick?.(event);
+ if (
+ event.defaultPrevented ||
+ isInteractiveRowTarget(event.target) ||
+ window.getSelection()?.toString()
+ ) {
+ return;
+ }
+ const trigger = event.currentTarget.querySelector<HTMLElement>(
+ `[data-testid="${ACTIONS_TRIGGER_TEST_ID}"]`,
+ );
+ trigger?.focus();
+ openAudit(row, trigger);
+ },
+ },
+ xstyle: [...props.xstyle, styles.auditRow],
+ };
+ },
+ }),
+ [openAudit],
);
-}
-function TemplatesPageInner() {
- const {sort, onSortChange, filters, onFilterChange} = useTableSearchParams();
+ const visible = useMemo(() => {
+ const normalizedQuery = query.trim().toLowerCase();
+ return rows.filter(row => {
+ if (
+ normalizedQuery &&
+ ![row.name, row.description, row.component, row.type].some(value =>
+ value.toLowerCase().includes(normalizedQuery),
+ )
+ ) {
+ return false;
+ }
+ if (auditFilter === 'audited' && !row.audited) {
+ return false;
+ }
+ if (auditFilter === 'tbd' && row.audited) {
+ return false;
+ }
+ if (typeFilter && row.type.toLowerCase() !== typeFilter) {
+ return false;
+ }
+ return true;
+ });
+ }, [auditFilter, query, rows, typeFilter]);
+
+ const stats = useMemo(() => {
+ const audited = visible.filter(row => row.audit != null);
+ const scores = audited.flatMap(row =>
+ typeof row.score === 'number' ? [row.score] : [],
+ );
+ const averageScore = scores.length
+ ? scores.reduce((sum, score) => sum + score, 0) / scores.length
+ : null;
- const {config, applyFilters} = usePowerSearchConfig(fieldDefs);
- const filterPlugin = useTableFiltering<TemplateRow>({
- filters,
- onFilterChange,
- searchConfig: config,
- });
+ return {
+ audited: audited.length,
+ total: visible.length,
+ coverage: visible.length
+ ? Math.round((audited.length / visible.length) * 1000) / 10
+ : 0,
+ averageScore:
+ averageScore == null ? null : Math.round(averageScore * 10) / 10,
+ };
+ }, [visible]);
- const filteredData = applyFilters(
- toSearchFilters(filters, columns, config) as PowerSearchFilter[],
- rows,
- );
+ const hasActiveFilters =
+ auditFilter != null || typeFilter != null || query !== '';
- const {sortedData, sortConfig} = useTableSortableState({
- data: filteredData,
- sort,
- onSortChange,
- });
- const sortPlugin = useTableSortable<TemplateRow>(sortConfig);
-
- const [columnWidths, setColumnWidths] = useState<Record<string, number>>({});
- const resizePlugin = useTableColumnResize<TemplateRow>({
- columnWidths,
- columns: columns as TableColumn<Record<string, unknown>>[],
- onColumnResizeEnd: updates =>
- setColumnWidths(prev => ({...prev, ...updates})),
- });
+ const clearAllFilters = () => {
+ setAuditFilter(null);
+ setTypeFilter(null);
+ setQuery('');
+ };
return (
- <Layout
- header={
- <LayoutHeader hasDivider padding={6}>
- <Heading level={1}>Official Templates</Heading>
- </LayoutHeader>
- }
- content={
- <LayoutContent padding={6}>
- <Table
- data={sortedData}
+ <>
+ <VStack gap={0} width="100%">
+ <Section variant="transparent" padding={4}>
+ <VStack gap={5}>
+ <HStack gap={4} hAlign="between" vAlign="start" wrap="wrap">
+ <VStack gap={2} maxWidth="76ch">
+ <Heading level={1}>Template Audits</Heading>
+ <Text>
+ Choose Actions → Copy audit prompt, then run it against the
+ template in the repository. Record and publish the completed
+ audit to the central template ledger. Its score, date, and
+ details appear here automatically; templates without a ledger
+ record remain TBD.
+ </Text>
+ <Link href={TEMPLATE_RUBRIC_URL} isExternalLink>
+ How official templates are graded
+ </Link>
+ </VStack>
+ <Text type="supporting" color="secondary">
+ Last updated {ledger?.updated ?? 'not available'}
+ </Text>
+ </HStack>
+
+ <Toolbar
+ label="Template table filters"
+ size="sm"
+ gap={2}
+ xstyle={styles.filterToolbar}
+ startContent={
+ <>
+ <Selector
+ label="Audit status"
+ isLabelHidden
+ placeholder="Audit status"
+ variant="ghost"
+ hasClear
+ value={auditFilter}
+ onChange={value =>
+ setAuditFilter(
+ value === 'audited' || value === 'tbd' ? value : null,
+ )
+ }
+ options={TEMPLATE_AUDIT_FILTER_OPTIONS}
+ xstyle={styles.filterToken}
+ />
+ <Selector
+ label="Template type"
+ isLabelHidden
+ placeholder="Type"
+ variant="ghost"
+ hasClear
+ value={typeFilter}
+ onChange={value =>
+ setTypeFilter(
+ value === 'page' || value === 'block' ? value : null,
+ )
+ }
+ options={TEMPLATE_TYPE_FILTER_OPTIONS}
+ xstyle={styles.filterToken}
+ />
+ <Text type="supporting" color="secondary">
+ {visible.length}{' '}
+ {visible.length === 1 ? 'result' : 'results'}
+ </Text>
+ {hasActiveFilters ? (
+ <>
+ <Text type="supporting" color="secondary">
+ ·
+ </Text>
+ <Button
+ variant="ghost"
+ label="Clear all"
+ onClick={clearAllFilters}
+ />
+ </>
+ ) : null}
+ </>
+ }
+ endContent={
+ <TextInput
+ ref={filterInputRef}
+ label="Search templates"
+ isLabelHidden
+ placeholder="Search templates…"
+ value={query}
+ onChange={setQuery}
+ startIcon={SearchIcon}
+ hasClear
+ width={240}
+ />
+ }
+ />
+
+ <Grid columns={{minWidth: 240, max: 2, repeat: 'fit'}} gap={4}>
+ <Card padding={4}>
+ <Stat
+ size="sm"
+ label="Audited"
+ value={`${stats.coverage}%`}
+ description={`${stats.audited} of ${stats.total} templates`}
+ />
+ </Card>
+ <Card padding={4}>
+ <Stat
+ size="sm"
+ label="Average score"
+ value={
+ stats.averageScore == null
+ ? '—'
+ : stats.averageScore.toFixed(1)
+ }
+ description={
+ stats.audited
+ ? 'Across audited templates'
+ : 'No audited templates'
+ }
+ />
+ </Card>
+ </Grid>
+ </VStack>
+ </Section>
+
+ <Section variant="transparent" padding={4} paddingBlock={0}>
+ <Table<TemplateRow>
+ data={visible}
columns={columns}
idKey="id"
+ density="balanced"
+ dividers="rows"
hasHover
- plugins={{
- filter: filterPlugin,
- sort: sortPlugin,
- resize: resizePlugin,
- }}
+ plugins={{auditDetails: auditRowPlugin}}
/>
- </LayoutContent>
- }
- />
+ </Section>
+
+ {ledger?.caveats?.length ? (
+ <Section variant="transparent" padding={4}>
+ <Card>
+ <VStack gap={3}>
+ <Heading level={2}>Caveats on the recorded rows</Heading>
+ {ledger.caveats.map(caveat => (
+ <Text key={caveat} type="supporting" color="secondary">
+ {caveat}
+ </Text>
+ ))}
+ </VStack>
+ </Card>
+ </Section>
+ ) : null}
+ </VStack>
+
+ <Drawer
+ ref={drawerRef}
+ id={AUDIT_PANEL_ID}
+ isOpen={isAuditPanelOpen && selectedRow?.audit != null}
+ onClose={() => setIsAuditPanelOpen(false)}
+ label={
+ selectedRow
+ ? selectedRow.name + ' template audit details'
+ : 'Template audit details'
+ }
+ hasScrim={false}
+ hasCloseButton
+ size={560}>
+ {selectedRow ? <TemplateAuditDetails row={selectedRow} /> : null}
+ </Drawer>
+ </>
);
}
+
+const styles = stylex.create({
+ auditRow: {
+ cursor: 'pointer',
+ },
+ filterToolbar: {
+ width: '100%',
+ },
+ filterToken: {
+ backgroundColor: colorVars['--color-neutral'],
+ borderRadius: radiusVars['--radius-inner'],
+ },
+ drawerHeader: {
+ paddingInlineEnd: spacingVars['--spacing-10'],
+ },
+ tabularValue: {
+ fontVariantNumeric: 'tabular-nums',
+ },
+});
diff --git a/apps/sandbox/src/app/SandboxNav.tsx b/apps/sandbox/src/app/SandboxNav.tsx
index 5a31fabe67..7a099c4c29 100644
--- a/apps/sandbox/src/app/SandboxNav.tsx
+++ b/apps/sandbox/src/app/SandboxNav.tsx
@@ -1,17 +1,28 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
+/**
+ * @file Shared resizable and collapsible sandbox navigation.
+ * @input Current route, sandbox navigation registry, and theme controls.
+ * @output Grouped SideNav for the AppShell's Sandbox and Audits sections.
+ * @position Persistent navigation for the sandbox route group.
+ */
+
'use client';
import * as stylex from '@stylexjs/stylex';
import {usePathname} from 'next/navigation';
import Link from 'next/link';
-import {SideNav, SideNavItem, SideNavSection} from '@astryxdesign/core/SideNav';
+import {
+ SideNav,
+ SideNavHeading,
+ SideNavItem,
+ SideNavSection,
+} from '@astryxdesign/core/SideNav';
import {DropdownMenu} from '@astryxdesign/core/DropdownMenu';
-import {Text} from '@astryxdesign/core/Text';
import {useThemeControls, SANDBOX_THEMES} from './providers';
import type {ThemeMode} from '@astryxdesign/core/theme';
import type {IconName, IconType} from '@astryxdesign/core/Icon';
-import {categories, topLevelPages} from './sandboxPages';
+import {auditPages, categories, homePage} from './sandboxPages';
import {
HomeIcon,
WrenchIcon,
@@ -22,7 +33,6 @@ import {
AppWindowIcon,
BlocksIcon,
} from './icons';
-import {spacingVars, colorVars} from '@astryxdesign/core/theme/tokens.stylex';
const categoryIcons: Record<
string,
@@ -36,8 +46,8 @@ const categoryIcons: Record<
};
/**
- * Icons for `topLevelPages`, kept here so that module stays JSX-free — the
- * same split the categories already use.
+ * Icons for persistent nav pages, kept here so sandboxPages stays JSX-free —
+ * the same split the categories already use.
*
* These are icon *types* and semantic *names*, never rendered elements.
* `SideNavItem` passes its icon through `renderIconSlot`, which applies the
@@ -47,23 +57,13 @@ const categoryIcons: Record<
* black glyph over the whole sidebar. `scores` is a registry name (T17), not a
* hand-written SVG.
*/
-const topLevelIcons: Record<string, IconType | IconName> = {
+const navPageIcons: Record<string, IconType | IconName> = {
home: HomeIcon,
templates: AppWindowIcon,
scores: 'checkDouble',
};
const styles = stylex.create({
- header: {
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'space-between',
- paddingInline: spacingVars['--spacing-4'],
- paddingBlock: spacingVars['--spacing-3'],
- borderBottomWidth: 1,
- borderBottomStyle: 'solid',
- borderBottomColor: colorVars['--color-border'],
- },
controls: {
display: 'flex',
gap: 2,
@@ -84,58 +84,55 @@ function SandboxHeader() {
];
return (
- <div {...stylex.props(styles.header)}>
- <Text type="body" weight="bold">
- Sandbox
- </Text>
- <div {...stylex.props(styles.controls)}>
- <DropdownMenu
- button={{
- label: 'Theme',
-
- icon: (
- <PaletteIcon
- width={16}
- height={16}
- style={{color: 'var(--color-icon-secondary)'}}
- />
- ),
-
- variant: 'ghost',
- size: 'sm',
- isIconOnly: true,
- }}
- menuWidth={160}
- items={themeItems}
- />
- <DropdownMenu
- button={{
- label: mode === 'dark' ? 'Dark mode' : 'Light mode',
-
- icon:
- mode === 'dark' ? (
- <MoonIcon
- width={16}
- height={16}
- style={{color: 'var(--color-icon-secondary)'}}
- />
- ) : (
- <SunIcon
+ <SideNavHeading
+ heading="Sandbox"
+ icon={<BoxIcon width={20} height={20} />}
+ headerEndContent={
+ <div {...stylex.props(styles.controls)}>
+ <DropdownMenu
+ button={{
+ label: 'Theme',
+ icon: (
+ <PaletteIcon
width={16}
height={16}
style={{color: 'var(--color-icon-secondary)'}}
/>
),
-
- variant: 'ghost',
- size: 'sm',
- isIconOnly: true,
- }}
- menuWidth={160}
- items={modeItems}
- />
- </div>
- </div>
+ variant: 'ghost',
+ size: 'sm',
+ isIconOnly: true,
+ }}
+ menuWidth={160}
+ items={themeItems}
+ />
+ <DropdownMenu
+ button={{
+ label: mode === 'dark' ? 'Dark mode' : 'Light mode',
+ icon:
+ mode === 'dark' ? (
+ <MoonIcon
+ width={16}
+ height={16}
+ style={{color: 'var(--color-icon-secondary)'}}
+ />
+ ) : (
+ <SunIcon
+ width={16}
+ height={16}
+ style={{color: 'var(--color-icon-secondary)'}}
+ />
+ ),
+ variant: 'ghost',
+ size: 'sm',
+ isIconOnly: true,
+ }}
+ menuWidth={160}
+ items={modeItems}
+ />
+ </div>
+ }
+ />
);
}
@@ -143,41 +140,56 @@ export function SandboxNav() {
const pathname = usePathname();
return (
- <SideNav header={<SandboxHeader />}>
- <SideNavSection title="Home" isHeaderHidden>
- {topLevelPages.map(page => (
- <SideNavItem
- key={page.href}
- label={page.label}
- href={page.href}
- isSelected={
- page.matchesChildren
- ? pathname.startsWith(page.href)
- : pathname === page.href
- }
- as={Link}
- icon={topLevelIcons[page.icon]}
- />
- ))}
- </SideNavSection>
- <SideNavSection title="Projects">
+ <SideNav
+ header={<SandboxHeader />}
+ collapsible
+ resizable={{
+ defaultWidth: 300,
+ minWidth: 220,
+ maxWidth: 420,
+ autoSaveId: 'sandbox-side-nav',
+ }}>
+ <SideNavSection title="Sandbox">
+ <SideNavItem
+ label={homePage.label}
+ href={homePage.href}
+ isSelected={pathname === homePage.href}
+ as={Link}
+ icon={navPageIcons[homePage.icon]}
+ />
{categories
.filter(c => c.slug !== 'templates')
.map(category => {
- const isActive = pathname === `/${category.slug}/`;
+ const href = '/' + category.slug + '/';
const IconComponent = categoryIcons[category.slug];
return (
<SideNavItem
key={category.slug}
label={category.label}
- href={`/${category.slug}/`}
- isSelected={isActive}
+ href={href}
+ isSelected={pathname === href}
as={Link}
icon={IconComponent}
/>
);
})}
</SideNavSection>
+ <SideNavSection title="Audits">
+ {auditPages.map(page => (
+ <SideNavItem
+ key={page.href}
+ label={page.label}
+ href={page.href}
+ isSelected={
+ page.matchesChildren
+ ? pathname.startsWith(page.href)
+ : pathname === page.href
+ }
+ as={Link}
+ icon={navPageIcons[page.icon]}
+ />
+ ))}
+ </SideNavSection>
</SideNav>
);
}
diff --git a/apps/sandbox/src/app/sandboxPages.ts b/apps/sandbox/src/app/sandboxPages.ts
index c2f11f6d50..9fc54e5c1b 100644
--- a/apps/sandbox/src/app/sandboxPages.ts
+++ b/apps/sandbox/src/app/sandboxPages.ts
@@ -1,7 +1,9 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
/**
- * @file sandboxPages.ts
+ * @file Central registry of sandbox categories and persistent navigation.
+ * @input Authored sandbox metadata and the generated template registry.
+ * @output Typed category, home, and audit navigation entries.
* @position Central registry of all sandbox pages, grouped by category.
*
* The "Templates" category is auto-populated from packages/cli/assets/templates/
@@ -45,15 +47,10 @@ export interface SandboxCategory {
}
/**
- * Sidebar entries that sit ABOVE the `Projects` section, alongside Home —
- * destinations in their own right rather than pages inside a category.
- *
- * These used to be written out in `SandboxNav`; they are data so the next one
- * is an entry here rather than another branch in the nav component. `icon` is
- * a key into that file's icon map for the same reason the categories use one:
- * this module stays JSX-free.
+ * Persistent sidebar destinations that are not generated category pages.
+ * `icon` is a key into SandboxNav's icon map so this module stays JSX-free.
*/
-export interface SandboxTopLevelPage {
+export interface SandboxNavPage {
/** Label shown in the sidebar */
label: string;
/** Route path (with trailing slash) */
@@ -67,11 +64,16 @@ export interface SandboxTopLevelPage {
matchesChildren?: boolean;
}
-export const topLevelPages: SandboxTopLevelPage[] = [
- {label: 'Home', href: '/', icon: 'home'},
- {label: 'Official Templates', href: '/templates/', icon: 'templates'},
+export const homePage: SandboxNavPage = {
+ label: 'Home',
+ href: '/',
+ icon: 'home',
+};
+
+export const auditPages: SandboxNavPage[] = [
+ {label: 'Template Audits', href: '/templates/', icon: 'templates'},
{
- label: 'Component Scores',
+ label: 'Component Audits',
href: '/pages/component-scores/',
icon: 'scores',
matchesChildren: true,
diff --git a/apps/sandbox/src/data/templateAudits.ts b/apps/sandbox/src/data/templateAudits.ts
new file mode 100644
index 0000000000..fad04af545
--- /dev/null
+++ b/apps/sandbox/src/data/templateAudits.ts
@@ -0,0 +1,647 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Template score-ledger schema, historical seed, and audit prompt.
+ * @input Recoverable merge-commit score claims plus the wiki template rubric.
+ * @output Versioned template ledger consumed by the Templates audit page.
+ * @position Local seed and schema for the proposed wiki template ledger.
+ *
+ * The page checks the expected wiki copy at runtime and falls back to this
+ * bundled seed, matching the component page's live-ledger behavior without
+ * claiming the still-unpublished wiki file is canonical. The seed preserves
+ * only explicitly published details and remains historical until re-audited.
+ */
+
+export const TEMPLATE_LEDGER_URL =
+ 'https://raw.githubusercontent.com/wiki/facebook/astryx/template-scores.json';
+
+export const TEMPLATE_LEDGER_FETCH_TIMEOUT_MS = 10_000;
+
+export const TEMPLATE_RUBRIC_URL =
+ 'https://github.com/facebook/astryx/wiki/Contributing-Templates#template-grading-rubric';
+
+export type TemplateAuditGrade = 'A' | 'B' | 'C' | 'D' | 'F';
+
+export type TemplateAuditCategoryId =
+ | 'component_purity'
+ | 'icon_purity'
+ | 'custom_css'
+ | 'layout_structure'
+ | 'doc_metadata'
+ | 'image_handling'
+ | 'code_quality';
+
+export type TemplateAuditCategoryStatus =
+ 'published' | 'inferred' | 'intermediate' | 'unresolved';
+
+export interface TemplateAuditCategory {
+ score: number | null;
+ status: TemplateAuditCategoryStatus;
+ note?: string;
+}
+
+export interface TemplateAuditEvidence {
+ label: string;
+ href?: string;
+}
+
+export interface TemplateAudit {
+ id: string;
+ score: number;
+ /** Grade derived from the current template-rubric thresholds. */
+ grade: TemplateAuditGrade;
+ /** Grade wording in the historical record, when it differs. */
+ recordedGrade?: string;
+ status: 'historical' | 'current';
+ lastAudited: string;
+ commit: string;
+ pr?: number;
+ rubricVersion: string;
+ categories: Partial<Record<TemplateAuditCategoryId, TemplateAuditCategory>>;
+ findings: string[];
+ topFixes: string[];
+ evidence: TemplateAuditEvidence[];
+ notes: string;
+}
+
+export interface TemplateAuditLedger {
+ ledgerVersion: number;
+ rubricVersion: string;
+ updated: string;
+ about?: string;
+ caveats?: string[];
+ /** Absence from this collection is the only meaning of "not audited". */
+ templates: TemplateAudit[];
+}
+
+export const TEMPLATE_AUDIT_CATEGORIES: ReadonlyArray<{
+ id: TemplateAuditCategoryId;
+ title: string;
+ max: number;
+}> = [
+ {id: 'component_purity', title: 'Astryx component purity', max: 30},
+ {id: 'icon_purity', title: 'Icon purity', max: 15},
+ {id: 'custom_css', title: 'Custom CSS', max: 15},
+ {id: 'layout_structure', title: 'Layout & structure', max: 15},
+ {id: 'doc_metadata', title: 'Doc metadata', max: 10},
+ {id: 'image_handling', title: 'Image handling', max: 5},
+ {id: 'code_quality', title: 'Code quality', max: 10},
+];
+
+export function templateGrade(score: number): TemplateAuditGrade {
+ if (score >= 90) {
+ return 'A';
+ }
+ if (score >= 75) {
+ return 'B';
+ }
+ if (score >= 60) {
+ return 'C';
+ }
+ if (score >= 40) {
+ return 'D';
+ }
+ return 'F';
+}
+
+interface HistoricalAuditInput {
+ id: string;
+ score: number;
+ sha: string;
+ date: string;
+ pr: number;
+ recordedGrade?: string;
+ categories?: TemplateAudit['categories'];
+ findings: string[];
+}
+
+function historicalAudit({
+ id,
+ score,
+ sha,
+ date,
+ pr,
+ recordedGrade,
+ categories = {},
+ findings,
+}: HistoricalAuditInput): TemplateAudit {
+ const grade = templateGrade(score);
+ const gradeNote =
+ recordedGrade && recordedGrade !== grade
+ ? ` The historical record called this ${recordedGrade}; the table derives ${grade} from the current thresholds.`
+ : '';
+
+ return {
+ id,
+ score,
+ grade,
+ recordedGrade,
+ status: 'historical',
+ lastAudited: date.slice(0, 10),
+ commit: sha,
+ pr,
+ rubricVersion: 'Historical template rubric · unversioned',
+ categories,
+ findings,
+ topFixes: [],
+ evidence: [
+ {
+ label: 'Historical merge-commit audit claim',
+ href: `https://github.com/facebook/astryx/commit/${sha}`,
+ },
+ {
+ label: `Pull request #${pr}`,
+ href: `https://github.com/facebook/astryx/pull/${pr}`,
+ },
+ ],
+ notes:
+ 'Recovered from merge-commit prose, not a structured ledger. The score has not been re-run against the current template at HEAD, and unpublished category details must not be inferred.' +
+ gradeNote,
+ };
+}
+
+const audits = [
+ historicalAudit({
+ id: 'page/centered-hero',
+ score: 95,
+ sha: '4348786581c77255909acf4055d919771ad6f66b',
+ date: '2026-06-10T02:23:39-05:00',
+ pr: 2583,
+ findings: [
+ 'Remaining custom CSS is image fill, cap, and radius styling with no component-prop equivalent; tracked by #2582.',
+ ],
+ }),
+ historicalAudit({
+ id: 'page/contact-form',
+ score: 92,
+ sha: '09be607225ce7bdefdcdce31e6f238dd38a26900',
+ date: '2026-05-02T21:02:26Z',
+ pr: 1967,
+ findings: [
+ 'Improved from 75 to 92 with a responsive Grid, fewer page-level styles, and better card semantics.',
+ 'Three justified image declarations remained because no general image component existed.',
+ ],
+ }),
+ historicalAudit({
+ id: 'page/detail-page',
+ score: 97,
+ sha: 'c065d978ddaaa914f258d392c25440aee853468a',
+ date: '2026-06-10T14:01:25-05:00',
+ pr: 2624,
+ findings: [
+ 'Zero raw HTML, proper Layout slots, Thumbnail usage, and responsive panels.',
+ 'The only recorded deduction was negative-margin tab-row CSS without a component prop; tracked by #2622.',
+ ],
+ }),
+ historicalAudit({
+ id: 'page/documentation',
+ score: 97,
+ sha: '568f239a0a4b4e3c42fd3eb4132fe31f01b885bd',
+ date: '2026-04-20T01:54:26Z',
+ pr: 1509,
+ findings: [
+ 'Custom CSS fell from six to three justified declarations; centering and wrapping moved to Astryx props.',
+ ],
+ }),
+ historicalAudit({
+ id: 'page/editor',
+ score: 87,
+ sha: '42db6476fb6150c3a9f8d893314c117d87d6d1ae',
+ date: '2026-06-19T04:52:30-07:00',
+ pr: 2627,
+ categories: {
+ component_purity: {score: 30, status: 'published'},
+ layout_structure: {score: 15, status: 'published'},
+ custom_css: {
+ score: 5,
+ status: 'intermediate',
+ note: 'An intermediate pass reported 5/15 at ten declarations; the final implementation had eleven and did not publish final category points.',
+ },
+ },
+ findings: [
+ 'Improved from 68 to 87 with a proper Layout root and removal of the raw sidebar structure.',
+ 'Responsive and mobile-dialog behavior still required custom CSS; tracked by #2623.',
+ ],
+ }),
+ historicalAudit({
+ id: 'page/file-explorer',
+ score: 90,
+ sha: '55693c176f5d0d1e953d733721d42680aca41510',
+ date: '2026-06-12T04:54:13Z',
+ pr: 2620,
+ categories: {
+ component_purity: {
+ score: 30,
+ status: 'inferred',
+ note: 'The commit stated every category except Custom CSS was maxed.',
+ },
+ icon_purity: {
+ score: 15,
+ status: 'inferred',
+ note: 'The commit stated every category except Custom CSS was maxed.',
+ },
+ custom_css: {score: 5, status: 'published'},
+ layout_structure: {
+ score: 15,
+ status: 'inferred',
+ note: 'The commit stated every category except Custom CSS was maxed.',
+ },
+ doc_metadata: {
+ score: 10,
+ status: 'inferred',
+ note: 'The commit stated every category except Custom CSS was maxed.',
+ },
+ image_handling: {
+ score: 5,
+ status: 'inferred',
+ note: 'The commit stated every category except Custom CSS was maxed.',
+ },
+ code_quality: {
+ score: 10,
+ status: 'inferred',
+ note: 'The commit stated every category except Custom CSS was maxed.',
+ },
+ },
+ findings: [
+ 'Custom CSS scored 5/15; five declarations were described as multi-pane layout plumbing tracked by #2594 and #2623.',
+ 'An earlier subcommit claimed 97; the final merge message explicitly records 90.',
+ ],
+ }),
+ historicalAudit({
+ id: 'page/form-two-column',
+ score: 92,
+ sha: '4b2088e3963194fa86491d56a46ab3e3ead637aa',
+ date: '2026-06-10T14:07:29-05:00',
+ pr: 2614,
+ categories: {
+ custom_css: {
+ score: 12,
+ status: 'published',
+ note: 'Improved from 8/15.',
+ },
+ layout_structure: {
+ score: 15,
+ status: 'published',
+ note: 'Improved from 8/15.',
+ },
+ },
+ findings: [
+ 'Improved from 81 to 92 through responsive grids, corrected image behavior and alt text, and fewer custom styles.',
+ 'The remaining cap was image markup and fill CSS without a dedicated image component.',
+ ],
+ }),
+ historicalAudit({
+ id: 'page/gallery-hero',
+ score: 85,
+ sha: '8044501e0412cc9ac8901557fc2ca9804e15f3eb',
+ date: '2026-06-10T14:07:41-05:00',
+ pr: 2609,
+ findings: [
+ 'Final review explicitly retained 85, overriding an intermediate 95 claim.',
+ 'The recorded cap was missing image primitives plus image-fill CSS; responsive grid and side padding were fixed.',
+ ],
+ }),
+ historicalAudit({
+ id: 'page/side-gallery',
+ score: 85,
+ sha: '4fb82bf12fe5f376f58963a1d018cd6402d09a0d',
+ date: '2026-06-12T12:41:44-05:00',
+ pr: 2617,
+ findings: [
+ 'Improved from 70 to 85 after responsive Grid replaced a raw CSS-grid div and media query.',
+ 'Image-fill CSS remained because no general image component existed.',
+ ],
+ }),
+ historicalAudit({
+ id: 'page/table-grouped',
+ score: 85,
+ sha: '9aabd5599daded11fc180de2babff47458f5e49a',
+ date: '2026-06-15T15:09:05Z',
+ pr: 2619,
+ categories: {
+ component_purity: {
+ score: 25,
+ status: 'published',
+ note: 'Improved from 15/30.',
+ },
+ },
+ findings: [
+ 'Improved from 72 to 85 after raw table cells, a stray resize-handle line, and dead styles were removed.',
+ 'Raw colgroup/col and group-header CSS remained because Table lacked the required grouping API.',
+ ],
+ }),
+ historicalAudit({
+ id: 'page/login',
+ score: 97,
+ sha: 'dd2ec3ee1390a8cc6ce9d81103d47716519675bf',
+ date: '2026-06-09T19:31:50-05:00',
+ pr: 2585,
+ categories: {
+ custom_css: {score: 12, status: 'published'},
+ },
+ findings: [
+ 'A final body-background declaration changed the recorded total from 100 to 97, overriding the squash subject.',
+ ],
+ }),
+ historicalAudit({
+ id: 'page/login-card',
+ score: 92,
+ sha: '14d9b8cef381f3e09d7333e3775dc13635cd72f2',
+ date: '2026-06-10T02:24:01-05:00',
+ pr: 2587,
+ categories: {
+ custom_css: {score: 12, status: 'published'},
+ icon_purity: {
+ score: null,
+ status: 'unresolved',
+ note: 'An intermediate pass reported 15/15, but the final implementation restored inline SVG logos without publishing final category points.',
+ },
+ },
+ findings: [
+ 'The body background moved an intermediate overall score from 100 to 97; later inline-logo changes produced the final recorded 92.',
+ ],
+ }),
+ historicalAudit({
+ id: 'page/login-split',
+ score: 75,
+ sha: 'c2d0935e20146694b76a549725ea66a756915c71',
+ date: '2026-06-12T17:53:05-05:00',
+ pr: 2597,
+ recordedGrade: 'C',
+ categories: {
+ icon_purity: {
+ score: 15,
+ status: 'published',
+ note: 'Last explicitly published category value.',
+ },
+ custom_css: {
+ score: 5,
+ status: 'intermediate',
+ note: 'Published before later implementation changes.',
+ },
+ layout_structure: {
+ score: 8,
+ status: 'intermediate',
+ note: 'Published before later responsive-layout work.',
+ },
+ },
+ findings: [
+ 'The merge message contains intermediate totals near 83 and 90; the squash subject explicitly records the final 75.',
+ ],
+ }),
+ historicalAudit({
+ id: 'page/login-sso',
+ score: 97,
+ sha: 'b1bc4edd273ec01c016d9add5878f3d82e54c39a',
+ date: '2026-06-10T02:00:36-05:00',
+ pr: 2595,
+ categories: {
+ custom_css: {score: 12, status: 'published'},
+ },
+ findings: [
+ 'Custom CSS fell from seven to three declarations; the remaining full-bleed background image had no component-prop equivalent.',
+ ],
+ }),
+ historicalAudit({
+ id: 'page/mixed-gallery',
+ score: 75,
+ sha: 'e9a6850df979fef3bc47e12960a670a0bb84fb47',
+ date: '2026-06-10T14:04:40-05:00',
+ pr: 2608,
+ recordedGrade: 'C',
+ findings: [
+ 'An intermediate pass claimed 85, but later correctness work lowered the squash-subject score to 75.',
+ 'Responsive masonry required container-query grid behavior that the Grid component could not express.',
+ ],
+ }),
+ historicalAudit({
+ id: 'page/product-detail',
+ score: 82,
+ sha: '3386904fec282fa63d5a45e059fe50dcbc5f8a3a',
+ date: '2026-06-10T14:04:57-05:00',
+ pr: 2612,
+ categories: {
+ layout_structure: {
+ score: 15,
+ status: 'published',
+ note: 'Improved from 8/15.',
+ },
+ },
+ findings: [
+ 'Remaining styles covered image fill/radius, selected-thumbnail outline, and a sticky information column without component-prop equivalents.',
+ ],
+ }),
+ historicalAudit({
+ id: 'page/product-gallery',
+ score: 85,
+ sha: '9abdb9ddb04c8363c4d1649b4ec1fada822705da',
+ date: '2026-06-10T14:02:47-05:00',
+ pr: 2618,
+ findings: [
+ 'The merge message described this as the template ceiling; missing image primitives capped two categories.',
+ ],
+ }),
+ historicalAudit({
+ id: 'page/settings',
+ score: 97,
+ sha: '53d0aae2201b5147559eefca8c917e7f184a3bcc',
+ date: '2026-06-10T14:01:44-05:00',
+ pr: 2621,
+ findings: [
+ 'The only recorded remaining style constrained and centered the outer shell because Layout contentWidth could not cap it.',
+ ],
+ }),
+ historicalAudit({
+ id: 'page/settings-dialog',
+ score: 95,
+ sha: '15bb7c05f3b4c3b5a14c9b60e373b20b07f07618',
+ date: '2026-06-19T04:52:37-07:00',
+ pr: 2629,
+ findings: [
+ 'The remaining prop-less rules were icon box, sticky header, content width, side-nav heading, and dialog height.',
+ ],
+ }),
+ historicalAudit({
+ id: 'page/settings-sidebar',
+ score: 97,
+ sha: '72ba77982e915e5257106cddb0f3c47e77e30894',
+ date: '2026-06-19T04:52:33-07:00',
+ pr: 2628,
+ findings: [
+ 'Remaining styles covered a prop-less icon box and min-height needed in a content-sized host.',
+ ],
+ }),
+ ...[
+ {
+ id: 'block/PowerSearchShowcase',
+ finding:
+ 'Added controlled state and initial filter tokens, plus missing description and componentsUsed metadata.',
+ },
+ {
+ id: 'block/PowerSearchFullFeatured',
+ finding:
+ 'Removed a hardcoded-width overflow wrapper and compacted the configuration under 100 lines.',
+ },
+ {
+ id: 'block/PowerSearchContentSearch',
+ finding: 'The merge message explicitly records 100 after fixes.',
+ },
+ {
+ id: 'block/PowerSearchPresetFilters',
+ finding: 'The merge message explicitly records 100 after fixes.',
+ },
+ {
+ id: 'block/PowerSearchSearchWithTable',
+ finding:
+ 'Replaced a raw layout wrapper and inline style with VStack and added Layout to componentsUsed.',
+ },
+ ].map(({id, finding}) =>
+ historicalAudit({
+ id,
+ score: 100,
+ recordedGrade: 'A+',
+ sha: '07483336979c458581b820e50192cebfd1364969',
+ date: '2026-04-21T18:35:16-07:00',
+ pr: 1625,
+ findings: [finding],
+ }),
+ ),
+];
+
+/**
+ * Bundled ledger seed. Once template-scores.json is published in the wiki, the
+ * sandbox replaces this with the live central collection at runtime.
+ */
+export const templateLedgerSeed: TemplateAuditLedger = {
+ ledgerVersion: 1,
+ rubricVersion: '1',
+ updated: '2026-08-11',
+ about:
+ 'Seed for a central collection of Astryx page and block template audits. Template identity is type/slug, for example page/centered-hero.',
+ caveats: [
+ 'The wiki template-scores.json file is not published yet; this bundled seed is the current source.',
+ 'The initial 25 entries were recovered from merge records and have not been re-run at the current HEAD.',
+ 'Unpublished category detail remains blank rather than being inferred from the total score.',
+ ],
+ templates: audits,
+};
+
+export function templateAuditsById(
+ ledger: TemplateAuditLedger | null,
+): Record<string, TemplateAudit> {
+ return Object.fromEntries(
+ (ledger?.templates ?? []).map(audit => [audit.id, audit]),
+ );
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value != null && !Array.isArray(value);
+}
+
+function isOptionalString(value: unknown): boolean {
+ return value == null || typeof value === 'string';
+}
+
+function isTemplateAuditCategory(value: unknown): boolean {
+ if (!isRecord(value)) {
+ return false;
+ }
+ const score = value.score;
+ return (
+ (score == null || (typeof score === 'number' && Number.isFinite(score))) &&
+ ['published', 'inferred', 'intermediate', 'unresolved'].includes(
+ String(value.status),
+ ) &&
+ isOptionalString(value.note)
+ );
+}
+
+function isTemplateAudit(value: unknown): value is TemplateAudit {
+ if (!isRecord(value) || !isRecord(value.categories)) {
+ return false;
+ }
+
+ const score = value.score;
+ const evidence = value.evidence;
+ return (
+ typeof value.id === 'string' &&
+ /^(page|block)\/[^/]+$/.test(value.id) &&
+ typeof score === 'number' &&
+ Number.isFinite(score) &&
+ score >= 0 &&
+ score <= 100 &&
+ value.grade === templateGrade(score) &&
+ ['A', 'B', 'C', 'D', 'F'].includes(String(value.grade)) &&
+ ['historical', 'current'].includes(String(value.status)) &&
+ typeof value.lastAudited === 'string' &&
+ typeof value.commit === 'string' &&
+ typeof value.rubricVersion === 'string' &&
+ isOptionalString(value.recordedGrade) &&
+ (value.pr == null ||
+ (typeof value.pr === 'number' && Number.isInteger(value.pr))) &&
+ Object.values(value.categories).every(isTemplateAuditCategory) &&
+ Array.isArray(value.findings) &&
+ value.findings.every(finding => typeof finding === 'string') &&
+ Array.isArray(value.topFixes) &&
+ value.topFixes.every(fix => typeof fix === 'string') &&
+ Array.isArray(evidence) &&
+ evidence.every(
+ item =>
+ isRecord(item) &&
+ typeof item.label === 'string' &&
+ isOptionalString(item.href),
+ ) &&
+ typeof value.notes === 'string'
+ );
+}
+
+export function isTemplateAuditLedger(
+ value: unknown,
+): value is TemplateAuditLedger {
+ if (!isRecord(value) || !Array.isArray(value.templates)) {
+ return false;
+ }
+
+ const audits = value.templates;
+ if (!audits.every(isTemplateAudit)) {
+ return false;
+ }
+ const ids = audits.map(audit => audit.id);
+ return (
+ typeof value.ledgerVersion === 'number' &&
+ Number.isInteger(value.ledgerVersion) &&
+ typeof value.rubricVersion === 'string' &&
+ typeof value.updated === 'string' &&
+ isOptionalString(value.about) &&
+ (value.caveats == null ||
+ (Array.isArray(value.caveats) &&
+ value.caveats.every(caveat => typeof caveat === 'string'))) &&
+ new Set(ids).size === ids.length
+ );
+}
+
+export interface TemplateAuditPromptInput {
+ name: string;
+ type: 'Page' | 'Block';
+ codePath: string;
+ docPath: string;
+}
+
+export function templateAuditPrompt({
+ name,
+ type,
+ codePath,
+ docPath,
+}: TemplateAuditPromptInput): string {
+ return `Audit the Astryx ${type.toLowerCase()} template "${name}" against the Template Grading Rubric:
+${TEMPLATE_RUBRIC_URL}
+
+Grade the current template at HEAD, not an earlier commit.
+
+Source: ${codePath}
+Metadata: ${docPath}
+
+Work all seven rubric categories and use the rubric's grading output format. Inspect the rendered template in a real browser, capture the relevant states in light and dark, and include responsive viewport coverage for page templates. Cite exact file locations for every deduction. Do not infer unpublished evidence or award points for anything you did not measure.
+
+Return the complete scorecard, detailed findings, screenshot-test evidence, and the top three fixes. Format the record for the central template-scores.json ledger, using the identity "${type.toLowerCase()}/<slug>".`;
+}