An open source design system that's fully customizable and agent ready
TypeScript
fix(sandbox): surface richtext in the component audit ledger (#5166)
Ernest9e9d82703107
diff --git a/.github/scripts/analyze-pr.js b/.github/scripts/analyze-pr.jsindex 5895f14226..826b458365 100644--- a/.github/scripts/analyze-pr.js+++ b/.github/scripts/analyze-pr.js@@ -30,11 +30,15 @@ const STORYBOOK_STORIES = 'apps/storybook/stories';//// layout:// 'nested' — components live in per-component dirs: src/<Name>/... (core, lab)-// 'flat' — components live as single files: src/<Name>.tsx (charts)+// 'flat' — components live as single files: src/<Name>.tsx (charts,+// richtext). The score-ledger's canonical predicate narrows a flat+// package to its documented component(s) downstream, so listing+// the internal helpers here is harmless — they get filtered out.const PACKAGES = [{ name: '@astryxdesign/core', dir: 'packages/core', layout: 'nested' },{ name: '@astryxdesign/lab', dir: 'packages/lab', layout: 'nested' },{ name: '@astryxdesign/charts', dir: 'packages/charts', layout: 'flat' },+ { name: '@astryxdesign/richtext', dir: 'packages/richtext', layout: 'flat' },];const pkgSrc = (pkg) => `${pkg.dir}/src`;diff --git a/apps/sandbox/scripts/generate-score-ledger.mjs b/apps/sandbox/scripts/generate-score-ledger.mjsindex b59bf929f3..0d973a46ec 100644--- a/apps/sandbox/scripts/generate-score-ledger.mjs+++ b/apps/sandbox/scripts/generate-score-ledger.mjs@@ -3,10 +3,10 @@/*** @file generate-score-ledger.mjs* @description Generates apps/sandbox/src/generated/componentScores.ts — the- * ROSTER of components (read from packages/core/src and packages/lab/src by- * the canonical predicate in scripts/score-ledger.mjs) plus a build-time- * SNAPSHOT of the audit ledger fetched from the wiki.- * @input packages/{core,lab}/src, and the wiki ledger over the network.+ * ROSTER of components (read from the ledger packages — core, lab and+ * richtext — by the canonical predicate in scripts/score-ledger.mjs) plus a+ * build-time SNAPSHOT of the audit ledger fetched from the wiki.+ * @input packages/{core,lab,richtext}/src, and the wiki ledger over the network.* @output src/generated/componentScores.ts* @position Sandbox build step, run by `pnpm generate`.*@@ -175,7 +175,7 @@ const banner = `// Copyright (c) Meta Platforms, Inc. and affiliates.* GENERATED FILE — do not edit.* Regenerate: node apps/sandbox/scripts/generate-score-ledger.mjs*- * \`roster\` is read from packages/{core,lab}/src by the canonical component+ * \`roster\` is read from packages/{core,lab,richtext}/src by the canonical component* predicate. \`snapshot\` is a build-time copy of the wiki ledger, used only* until the page's runtime fetch of LEDGER_URL resolves.*/@@ -273,7 +273,7 @@ export const SECTION_TITLES: Record<string, string> = ${JSON.stringify(SECTION_Texport const SECTION_WEIGHTS: Record<string, number> = ${JSON.stringify(SECTION_WEIGHTS, null, 2)};-/** Every component in packages/{core,lab}/src, by the canonical predicate. */+/** Every component in packages/{core,lab,richtext}/src, by the canonical predicate. */export const roster: RosterEntry[] = ${JSON.stringify(roster, null, 2)};/**diff --git a/apps/sandbox/src/app/(sandbox)/pages/component-scores/page.tsx b/apps/sandbox/src/app/(sandbox)/pages/component-scores/page.tsxindex f7ba0ae7ea..9a7a2711ce 100644--- a/apps/sandbox/src/app/(sandbox)/pages/component-scores/page.tsx+++ b/apps/sandbox/src/app/(sandbox)/pages/component-scores/page.tsx@@ -577,24 +577,27 @@ function AuditDetails({// =============================================================================type AuditFilter = 'audited' | 'tbd';-type PackageFilter = 'core' | 'lab';const AUDIT_FILTER_OPTIONS = [{value: 'audited', label: 'Audited'},{value: 'tbd', label: 'TBD'},];-const PACKAGE_FILTER_OPTIONS = [- {value: 'core', label: 'Core'},- {value: 'lab', label: 'Lab'},-];++// Derived from the roster, not hardcoded, so a package promoted out of lab+// (richtext was) gets a filter option the day it lands rather than showing+// rows that no filter can isolate.+const PACKAGE_FILTER_OPTIONS = [...new Set(roster.map(item => item.package))]+ .sort()+ .map(pkg => ({+ value: pkg,+ label: pkg.charAt(0).toUpperCase() + pkg.slice(1),+ }));export default function ComponentScoresPage() {const [ledger, setLedger] = useState<Ledger | null>(snapshot);const [query, setQuery] = useState('');const [auditFilter, setAuditFilter] = useState<AuditFilter | null>(null);- const [packageFilter, setPackageFilter] = useState<PackageFilter | null>(- null,- );+ const [packageFilter, setPackageFilter] = useState<string | null>(null);const [selectedRowId, setSelectedRowId] = useState<string | null>(null);const [isAuditPanelOpen, setIsAuditPanelOpen] = useState(false);const drawerRef = useRef<HTMLDialogElement>(null);@@ -923,9 +926,7 @@ export default function ComponentScoresPage() {options={PACKAGE_FILTER_OPTIONS}value={packageFilter}onChange={value =>- setPackageFilter(- value ? (value.toLowerCase() as PackageFilter) : null,- )+ setPackageFilter(value ? value.toLowerCase() : null)}hasClearvariant="ghost"diff --git a/scripts/score-ledger.mjs b/scripts/score-ledger.mjsindex 35246fc33f..c133e78777 100644--- a/scripts/score-ledger.mjs+++ b/scripts/score-ledger.mjs@@ -79,7 +79,7 @@ Options--components <a,b,c> --check: components to check.--analysis <file> --check: analysis.json from .github/scripts/analyze-pr.js.--limit <n> --queue: how many rows (default 5).- --package <core|lab> --record: package, if the predicate cannot resolve it.+ --package <name> --record: package, if the predicate cannot resolve it.--from <file|-> --record: scorecard JSON ('-' reads stdin).--allow-regression <why> --record: permit a score drop or a new BLOCK.--push --record/--file-issues: clone the wiki, apply, commit@@ -192,15 +192,41 @@ export const NON_COMPONENT_DIRS = Object.freeze(/** A file that renders: PascalCase `.tsx`, not a test, story, doc or perf file. */const RENDERING_FILE = /^[A-Z][A-Za-z0-9]*\.tsx$/;-/** Packages the ledger covers, with the src dir the predicate sweeps. */+/** A documented component in a flat package: PascalCase `<Name>.doc.mjs`. */+const FLAT_DOC_FILE = /^([A-Z][A-Za-z0-9]*)\.doc\.mjs$/;++/**+ * Packages the ledger covers, with the src dir the predicate sweeps and how+ * that src is laid out.+ *+ * - `nested` (core, lab): one directory per component, `<Name>/<Name>.tsx`.+ * The directory is the unit; `isComponentDirectory` filters out the+ * styles-only and context-only ones.+ * - `flat` (richtext, promoted out of lab so it can be canaried on its own):+ * `<Name>.tsx` files at the src root alongside internal helpers, so there+ * is no directory to key on and the `.doc.mjs` is the component boundary.+ *+ * A component graduating from lab into its own package (richtext did) must be+ * registered here or it silently drops out of the ledger's denominator — the+ * roster reads only these packages, and a score recorded for it in the wiki+ * has no row to attach to.+ */export const LEDGER_PACKAGES = Object.freeze([- {name: 'core', src: 'packages/core/src'},- {name: 'lab', src: 'packages/lab/src'},+ {name: 'core', src: 'packages/core/src', layout: 'nested'},+ {name: 'lab', src: 'packages/lab/src', layout: 'nested'},+ {name: 'richtext', src: 'packages/richtext/src', layout: 'flat'},]);+/** The covered package names, for human-facing CLI messages. */+const LEDGER_PACKAGE_NAMES = LEDGER_PACKAGES.map(p => p.name);+/*** Is `dirName`, directly under `srcDir`, a component directory?*+ * This is the predicate for the `nested` packages (core, lab), where one+ * directory holds one component. Flat packages (richtext) have no such+ * directory — see `flatPackageComponents`.+ ** A component directory:* 1. is not one of the infrastructure directories (hooks/theme/utils/i18n/__tests__);* 2. is PascalCase — infrastructure is lowercase by convention;@@ -231,6 +257,38 @@ export function isComponentDirectory(srcDir, dirName) {return entries.some(e => e.isFile() && RENDERING_FILE.test(e.name));}+/**+ * The component names in a flat package src (richtext), where `<Name>.tsx`+ * files sit at the root alongside internal helpers rather than in a directory+ * each. A `.doc.mjs` is the boundary here: the root also holds sub-parts and+ * plugins (`RichTextEditorToolbar.tsx`, `RichTextEditorAutoLinkPlugin.tsx`)+ * that render but are not audited as components on their own, and the doc file+ * is what distinguishes the public component from them — the same unit the+ * docsite and the wiki ledger already record.+ *+ * @param {string} srcDir absolute path to `packages/<pkg>/src`+ * @returns {string[]} component names, e.g. `['RichTextEditor']`+ */+export function flatPackageComponents(srcDir) {+ let entries;+ try {+ entries = fs.readdirSync(srcDir, {withFileTypes: true});+ } catch {+ return [];+ }+ const names = [];+ for (const entry of entries) {+ if (!entry.isFile()) continue;+ const match = FLAT_DOC_FILE.exec(entry.name);+ if (!match) continue;+ // A doc without the component it documents is a dangling file, not a row.+ if (fs.existsSync(path.join(srcDir, `${match[1]}.tsx`))) {+ names.push(match[1]);+ }+ }+ return names;+}+/*** Every component in the covered packages, sorted by name. This is the ledger's* denominator: it is read from the packages, never from a checked-in list.@@ -241,6 +299,12 @@ export function listComponents(repoRoot = ROOT) {const out = [];for (const pkg of LEDGER_PACKAGES) {const srcDir = path.join(repoRoot, pkg.src);+ if (pkg.layout === 'flat') {+ for (const component of flatPackageComponents(srcDir)) {+ out.push({component, package: pkg.name});+ }+ continue;+ }let entries;try {entries = fs.readdirSync(srcDir, {withFileTypes: true});@@ -1122,7 +1186,7 @@ async function cmdCheck(args) {const components = componentsFromArgs(args);if (components.length === 0) {console.log(- 'score-ledger: this change touches no component in packages/{core,lab}/src — nothing to check.',+ `score-ledger: this change touches no component in packages/{${LEDGER_PACKAGE_NAMES.join(',')}}/src — nothing to check.`,);return 0;}@@ -1283,8 +1347,11 @@ async function cmdStats(args) {` Components: ${stats.total} (${stats.audited} audited, ${stats.unaudited} unaudited — ${stats.percentAudited}%)`,);console.log(- ` core ${stats.byPackage.core.audited}/${stats.byPackage.core.total} · ` +- `lab ${stats.byPackage.lab.audited}/${stats.byPackage.lab.total}`,+ ' ' ++ LEDGER_PACKAGE_NAMES.map(+ name =>+ `${name} ${stats.byPackage[name].audited}/${stats.byPackage[name].total}`,+ ).join(' · '),);console.log(` Grades: A ${g.A} · B ${g.B} · C ${g.C} · D ${g.D} · F ${g.F}`);console.log(` Mean score: ${fmtScore(stats.meanScore)} (audited only)`);@@ -1359,14 +1426,14 @@ async function cmdRecord(args) {const live = matches[0];if (!live) {console.log(- `score-ledger: warning — ${component} is not a component directory in ` +- 'packages/{core,lab}/src under the canonical predicate. Recording anyway.',+ `score-ledger: warning — ${component} is not a component in ` ++ `packages/{${LEDGER_PACKAGE_NAMES.join(',')}}/src under the canonical predicate. Recording anyway.`,);}const pkg = flagValue(args.package) || (live && live.package) || null;if (!pkg) {console.error(- `score-ledger --record: cannot resolve a package for ${component} — pass --package <core|lab>.`,+ `score-ledger --record: cannot resolve a package for ${component} — pass --package <${LEDGER_PACKAGE_NAMES.join('|')}>.`,);return 1;}diff --git a/scripts/score-ledger.test.mjs b/scripts/score-ledger.test.mjsindex eb0bacfe2a..8b646c2e81 100644--- a/scripts/score-ledger.test.mjs+++ b/scripts/score-ledger.test.mjs@@ -32,6 +32,7 @@ import {buildStats,commitMessage,compareEntry,+ flatPackageComponents,gradeFor,isComponentDirectory,issueBody,@@ -321,7 +322,7 @@ describe('the canonical component predicate', () => {expect(isComponentDirectory(coreSrc, 'NotAThing')).toBe(false);});- it('lists both packages, sorted, with no infrastructure', () => {+ it('lists all covered packages, sorted, with no infrastructure', () => {const all = listComponents(REPO_ROOT);const names = all.map(c => c.component);expect(names).toContain('Button');@@ -329,7 +330,38 @@ describe('the canonical component predicate', () => {expect(names).not.toContain('hooks');expect(names).not.toContain('NavItem');expect([...names].sort((a, b) => a.localeCompare(b))).toEqual(names);- expect(new Set(all.map(c => c.package))).toEqual(new Set(['core', 'lab']));+ expect(new Set(all.map(c => c.package))).toEqual(+ new Set(['core', 'lab', 'richtext']),+ );+ });++ it('covers flat packages by their .doc.mjs, not a per-component dir', () => {+ // richtext was promoted out of lab into its own package with a flat src+ // (`RichTextEditor.tsx` at the root, no directory per component). It must+ // still land in the roster or a score recorded for it has no row.+ const all = listComponents(REPO_ROOT);+ const richtext = all.filter(c => c.package === 'richtext');+ expect(richtext).toEqual([{component: 'RichTextEditor', package: 'richtext'}]);+ });+});++describe('the flat-package component predicate', () => {+ const richtextSrc = path.join(REPO_ROOT, 'packages/richtext/src');++ it('keeps the documented component', () => {+ expect(flatPackageComponents(richtextSrc)).toContain('RichTextEditor');+ });++ it('drops undocumented sub-parts and helpers that still render', () => {+ // These render but carry no `.doc.mjs`, so they are not audited rows.+ const names = flatPackageComponents(richtextSrc);+ expect(names).not.toContain('RichTextView');+ expect(names).not.toContain('RichTextEditorToolbar');+ expect(names).not.toContain('RichTextEditorAutoLinkPlugin');+ });++ it('returns nothing for a src dir that does not exist', () => {+ expect(flatPackageComponents(path.join(REPO_ROOT, 'packages/nope/src'))).toEqual([]);});});