From 2c4e8a3500bc7ae963bfa6d6111126bbd2587c82 Mon Sep 17 00:00:00 2001 From: Kyle MacDonald Date: Mon, 16 Nov 2026 12:33:56 -0500 Subject: [PATCH 1/3] feat(repo): add Mosaic docs site (packages/mosaic-docs) Standalone Next.js app served at /mosaic. Content is generated from swingset's stories and MDX at dev/build time. Ported from clerk/clerk#3840. --- .changeset/mosaic-docs-app.md | 2 + packages/mosaic-docs/.gitignore | 2 + packages/mosaic-docs/AGENTS.md | 9 + packages/mosaic-docs/README.md | 9 + packages/mosaic-docs/next.config.mjs | 8 + packages/mosaic-docs/package.json | 36 ++ packages/mosaic-docs/postcss.config.mjs | 5 + packages/mosaic-docs/scripts/generate.mts | 313 ++++++++++++++++++ .../src/app/[section]/[slug]/page.tsx | 78 +++++ .../mosaic-docs/src/app/[section]/page.tsx | 37 +++ packages/mosaic-docs/src/app/globals.css | 65 ++++ packages/mosaic-docs/src/app/layout.tsx | 83 +++++ packages/mosaic-docs/src/app/page.tsx | 59 ++++ .../mosaic-docs/src/components/BackBanner.tsx | 24 ++ .../mosaic-docs/src/components/BetaNotice.tsx | 46 +++ .../mosaic-docs/src/components/CodeBlock.tsx | 37 +++ .../mosaic-docs/src/components/CopyButton.tsx | 22 ++ packages/mosaic-docs/src/components/Logo.tsx | 34 ++ .../mosaic-docs/src/components/Sidebar.tsx | 99 ++++++ packages/mosaic-docs/src/components/docs.tsx | 104 ++++++ packages/mosaic-docs/src/lib/content.ts | 76 +++++ packages/mosaic-docs/src/lib/mdx.tsx | 28 ++ packages/mosaic-docs/tsconfig.json | 24 ++ packages/mosaic-docs/turbo.json | 16 + pnpm-lock.yaml | 57 +++- 25 files changed, 1269 insertions(+), 4 deletions(-) create mode 100644 .changeset/mosaic-docs-app.md create mode 100644 packages/mosaic-docs/.gitignore create mode 100644 packages/mosaic-docs/AGENTS.md create mode 100644 packages/mosaic-docs/README.md create mode 100644 packages/mosaic-docs/next.config.mjs create mode 100644 packages/mosaic-docs/package.json create mode 100644 packages/mosaic-docs/postcss.config.mjs create mode 100644 packages/mosaic-docs/scripts/generate.mts create mode 100644 packages/mosaic-docs/src/app/[section]/[slug]/page.tsx create mode 100644 packages/mosaic-docs/src/app/[section]/page.tsx create mode 100644 packages/mosaic-docs/src/app/globals.css create mode 100644 packages/mosaic-docs/src/app/layout.tsx create mode 100644 packages/mosaic-docs/src/app/page.tsx create mode 100644 packages/mosaic-docs/src/components/BackBanner.tsx create mode 100644 packages/mosaic-docs/src/components/BetaNotice.tsx create mode 100644 packages/mosaic-docs/src/components/CodeBlock.tsx create mode 100644 packages/mosaic-docs/src/components/CopyButton.tsx create mode 100644 packages/mosaic-docs/src/components/Logo.tsx create mode 100644 packages/mosaic-docs/src/components/Sidebar.tsx create mode 100644 packages/mosaic-docs/src/components/docs.tsx create mode 100644 packages/mosaic-docs/src/lib/content.ts create mode 100644 packages/mosaic-docs/src/lib/mdx.tsx create mode 100644 packages/mosaic-docs/tsconfig.json create mode 100644 packages/mosaic-docs/turbo.json diff --git a/.changeset/mosaic-docs-app.md b/.changeset/mosaic-docs-app.md new file mode 100644 index 00000000000..a845151cc84 --- /dev/null +++ b/.changeset/mosaic-docs-app.md @@ -0,0 +1,2 @@ +--- +--- diff --git a/packages/mosaic-docs/.gitignore b/packages/mosaic-docs/.gitignore new file mode 100644 index 00000000000..10cf32a9a04 --- /dev/null +++ b/packages/mosaic-docs/.gitignore @@ -0,0 +1,2 @@ +# Generated from ../swingset by scripts/generate.mts +.content/ diff --git a/packages/mosaic-docs/AGENTS.md b/packages/mosaic-docs/AGENTS.md new file mode 100644 index 00000000000..af3b7c84114 --- /dev/null +++ b/packages/mosaic-docs/AGENTS.md @@ -0,0 +1,9 @@ + + +## This is NOT the Next.js you know + +This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` (resolved from this file's directory; in monorepos the `next` package may not be visible from the repo root) before writing any code. Heed deprecation notices. + +This block is written and re-added by `next dev` — verify at `node_modules/next/dist/server/lib/generate-agent-files.js`. Removing it from a diff only re-creates the uncommitted change; committing it with your work keeps the tree clean. + + diff --git a/packages/mosaic-docs/README.md b/packages/mosaic-docs/README.md new file mode 100644 index 00000000000..e5f75256c1c --- /dev/null +++ b/packages/mosaic-docs/README.md @@ -0,0 +1,9 @@ +# @clerk/mosaic-docs + +Private Next.js docs site for Mosaic (`@clerk/mosaic`), served at `clerk.com/mosaic` (`basePath: '/mosaic'`). + +```sh +pnpm --filter @clerk/mosaic-docs dev # http://localhost:6021/mosaic +``` + +Content is generated, not written by hand. `scripts/generate.mts` runs before `dev` and `build`. It reads swingset's stories and MDX in `../swingset/src/stories` and writes JSON to the git-ignored `.content/`. Only the Components, Primitives and Hooks groups are included. To change a page, edit its swingset MDX or story. diff --git a/packages/mosaic-docs/next.config.mjs b/packages/mosaic-docs/next.config.mjs new file mode 100644 index 00000000000..39de5ea6588 --- /dev/null +++ b/packages/mosaic-docs/next.config.mjs @@ -0,0 +1,8 @@ +/** @type {import('next').NextConfig} */ +const nextConfig = { + // Served at clerk.com/mosaic. + basePath: '/mosaic', + outputFileTracingIncludes: { '/**': ['./.content/**/*.json'] }, +}; + +export default nextConfig; diff --git a/packages/mosaic-docs/package.json b/packages/mosaic-docs/package.json new file mode 100644 index 00000000000..96405a37521 --- /dev/null +++ b/packages/mosaic-docs/package.json @@ -0,0 +1,36 @@ +{ + "name": "@clerk/mosaic-docs", + "version": "0.0.0", + "private": true, + "type": "module", + "scripts": { + "prebuild": "node scripts/generate.mts", + "build": "next build", + "predev": "node scripts/generate.mts", + "dev": "next dev --port 6021", + "format": "node ../../scripts/format-package.mjs", + "format:check": "node ../../scripts/format-package.mjs --check", + "generate": "node scripts/generate.mts", + "lint": "oxlint -c ../../oxlint.config.mjs src scripts", + "typecheck": "node scripts/generate.mts && next typegen && tsc --noEmit" + }, + "dependencies": { + "@mdx-js/mdx": "^3.1.1", + "clsx": "^2.1.1", + "next": "^16.4.3", + "react": "catalog:react", + "react-dom": "catalog:react", + "remark-gfm": "^4.0.0", + "shiki": "^1.0.0" + }, + "devDependencies": { + "@tailwindcss/postcss": "^4.0.0", + "@tailwindcss/typography": "^0.5.19", + "@types/mdx": "^2.0.13", + "@types/react": "catalog:react", + "@types/react-dom": "catalog:react", + "prettier": "3.8.3", + "tailwindcss": "^4.0.0", + "typescript": "catalog:repo" + } +} diff --git a/packages/mosaic-docs/postcss.config.mjs b/packages/mosaic-docs/postcss.config.mjs new file mode 100644 index 00000000000..a34a3d560dc --- /dev/null +++ b/packages/mosaic-docs/postcss.config.mjs @@ -0,0 +1,5 @@ +export default { + plugins: { + '@tailwindcss/postcss': {}, + }, +}; diff --git a/packages/mosaic-docs/scripts/generate.mts b/packages/mosaic-docs/scripts/generate.mts new file mode 100644 index 00000000000..955d3ce12c8 --- /dev/null +++ b/packages/mosaic-docs/scripts/generate.mts @@ -0,0 +1,313 @@ +/** + * Generates the docs content from swingset (../swingset). Runs before `dev` and `build`. + * + * Usage: node scripts/generate.mts [path/to/packages/swingset] + * + * Reads every `*.stories.tsx` + `*.mdx` pair in swingset's `src/stories`, keeps the groups + * documented here (Components, Primitives, Hooks), and writes one JSON file per item to + * `.content/
/.json` plus a `manifest.json`. `.content/` is git-ignored. + * + * MDX is rewritten into a small vocabulary the site renders itself: + * / → (source of story fn X) + * → (rows stored in JSON) + * … → fenced ```tsx block + */ +import fs from 'node:fs'; +import path from 'node:path'; +import vm from 'node:vm'; + +import { compile } from '@mdx-js/mdx'; +import prettier from 'prettier'; +import remarkGfm from 'remark-gfm'; +import ts from 'typescript'; + +const SECTIONS: Record = { + Components: 'components', + Primitives: 'primitives', + Hooks: 'hooks', +}; + +const swingsetDir = path.resolve(process.argv[2] ?? path.join(import.meta.dirname, '../../swingset')); +const storiesDir = path.join(swingsetDir, 'src/stories'); +const outDir = path.join(import.meta.dirname, '../.content'); + +type Prop = { name: string; type: string; default?: string }; +type Meta = { + group: string; + title: string; + source?: string; + styles?: { _variants?: Record>; _defaultVariants?: Record }; +}; + +function toSlug(s: string) { + return s + .replace(/([a-z0-9])([A-Z])/g, '$1-$2') + .replace(/([A-Z]+)([A-Z][a-z])/g, '$1-$2') + .replace(/[^a-zA-Z0-9]+/g, '-') + .replace(/^-|-$/g, '') + .toLowerCase(); +} + +function evalLiteral(text: string): any { + // Literals come from swingset source in our own monorepo. + return vm.runInNewContext(`(${text})`); +} + +function parseStoryFile(file: string) { + const text = fs.readFileSync(file, 'utf8'); + const sf = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX); + let meta: Meta | undefined; + const fns: Record = {}; + const isExported = (n: ts.Node) => + ts.canHaveModifiers(n) && (ts.getModifiers(n) ?? []).some(m => m.kind === ts.SyntaxKind.ExportKeyword); + + for (const stmt of sf.statements) { + if (!isExported(stmt)) { + continue; + } + if (ts.isVariableStatement(stmt)) { + for (const decl of stmt.declarationList.declarations) { + const name = decl.name.getText(sf); + if (name === 'meta' && decl.initializer) { + let init: ts.Expression = decl.initializer; + while (ts.isSatisfiesExpression(init) || ts.isAsExpression(init)) { + init = init.expression; + } + try { + meta = evalLiteral(init.getText(sf)); + } catch { + // Fall back to the string fields we need. + const pick = (k: string) => init.getText(sf).match(new RegExp(`${k}:\\s*'([^']+)'`))?.[1]; + meta = { + group: pick('group') ?? '', + title: pick('title') ?? '', + source: pick('source'), + }; + } + } else if ( + decl.initializer && + (ts.isArrowFunction(decl.initializer) || ts.isFunctionExpression(decl.initializer)) + ) { + fns[name] = stmt.getText(sf); + } + } + } else if (ts.isFunctionDeclaration(stmt) && stmt.name) { + fns[stmt.name.text] = stmt.getText(sf); + } + } + return { meta, fns }; +} + +/** Light cleanup so story sources read like usage code rather than knob plumbing. */ +function cleanExample(src: string) { + return src + .replace(/^export (default )?/, '') + .replace(/\(\s*props\s*:\s*Record\s*\)/g, '()') + .replace(/\(\s*_props\s*:\s*Record\s*\)/g, '()') + .replace(/^\s*\{\.\.\.(knobsAsProps\(props\)|props|\w+\(props\))\}\n/gm, '') + .replace(/\s\{\.\.\.(knobsAsProps\(props\)|props|\w+\(props\))\}/g, ''); +} + +function variantProps(meta: Meta | undefined): Prop[] { + const variants = meta?.styles?._variants ?? {}; + const defaults = meta?.styles?._defaultVariants ?? {}; + return Object.entries(variants).map(([name, options]) => { + const keys = Object.keys(options); + const isBoolean = keys.every(k => k === 'true' || k === 'false'); + const type = isBoolean ? 'boolean' : keys.map(k => `'${k}'`).join(' | '); + const def = defaults[name]; + return { + name, + type, + default: + def === undefined + ? undefined + : isBoolean + ? JSON.stringify(def) + : `'${typeof def === 'string' ? def : JSON.stringify(def)}'`, + }; + }); +} + +function usageCode(attrs: string, inner: string) { + const component = attrs.match(/component=['"]([^'"]+)['"]/)?.[1] ?? 'Component'; + const importPath = attrs.match(/module=['"]([^'"]+)['"]/)?.[1]; + const propsLit = attrs.match(/props=\{(\{[\s\S]*\})\}/)?.[1]; + const props: Record = propsLit ? evalLiteral(propsLit) : {}; + const attrLines = Object.entries(props) + .map(([k, v]) => (typeof v === 'boolean' ? (v ? k : null) : typeof v === 'number' ? `${k}={${v}}` : `${k}='${v}'`)) + .filter(Boolean); + const body = inner.trim(); + const lines: string[] = []; + if (importPath) { + lines.push(`import { ${component} } from '${importPath}'`, ''); + } + if (attrLines.length === 0) { + lines.push(body ? `<${component}>${body}` : `<${component} />`); + } else { + lines.push(`<${component}`, ...attrLines.map(a => ` ${a}`)); + lines.push(...(body ? ['>', ` ${body}`, ``] : ['/>'])); + } + return '```tsx\n' + lines.join('\n') + '\n```'; +} + +/** Split out fenced code so tag rewrites never touch code samples. */ +function mapOutsideFences(src: string, fn: (chunk: string) => string) { + return src + .split(/(^```[\s\S]*?^```)/m) + .map((chunk, i) => (i % 2 === 1 ? chunk : fn(chunk))) + .join(''); +} + +function transformMdx(mdx: string, moduleFns: Record>, fallbackModule: string) { + const usedExamples: Record = {}; + let props: Prop[] | null = null; + const imports: Record = {}; + for (const m of mdx.matchAll(/^import \* as (\w+) from ['"]\.\/([^'"]+)['"];?$/gm)) { + imports[m[1]] = m[2]; + } + + let body = mdx.replace(/^import .*$/gm, ''); + + // Title + lede. + let title: string | undefined; + body = body.replace(/^# (.+)\n/m, (_, t) => { + title = t.trim(); + return ''; + }); + + body = mapOutsideFences(body, chunk => + chunk + .replace(/<(Story|Preview)\b([\s\S]*?)\/>/g, (_, _tag, attrs: string) => { + const name = attrs.match(/name=['"]([^'"]+)['"]/)?.[1]; + const mod = attrs.match(/storyModule=\{(\w+)\}/)?.[1]; + const file = (mod && imports[mod]) || fallbackModule; + const src = name ? moduleFns[file]?.[name] : undefined; + if (!name || !src) { + return ''; + } + const key = `${file}#${name}`; + usedExamples[key] = cleanExample(src); + return ``; + }) + .replace(//g, (_, attrs: string) => { + const mod = attrs.match(/meta=\{(\w+)\.meta\}/)?.[1]; + const file = (mod && imports[mod]) || fallbackModule; + const extraLit = attrs.match(/extra=\{(\[[\s\S]*\])\}/)?.[1]; + const extra: Prop[] = extraLit ? evalLiteral(extraLit) : []; + props = [...variantProps(metaByFile[file]), ...extra, { name: 'xstyle', type: 'XStyle' }]; + return ''; + }) + .replace(/]*?)(?:\/>|>([\s\S]*?)<\/Usage>)/g, (_, attrs: string, inner = '') => + usageCode(attrs, inner), + ), + ); + + body = body + .replace(/^## Playground$/m, '## Example') + .replace(/\n{3,}/g, '\n\n') + .trim(); + + // Lede = first plain paragraph before any heading. + let description: string | undefined; + const firstBlock = body.split(/\n\n/)[0]; + if (firstBlock && !/^[#<`|-]/.test(firstBlock.trim())) { + description = firstBlock.trim(); + body = body.slice(firstBlock.length).trim(); + } + return { title, description, body, examples: usedExamples, props }; +} + +const metaByFile: Record = {}; + +async function main() { + if (!fs.existsSync(storiesDir)) { + throw new Error(`No swingset stories at ${storiesDir}`); + } + const storyFiles = fs.readdirSync(storiesDir).filter(f => f.endsWith('.stories.tsx') || f.endsWith('.stories.ts')); + const moduleFns: Record> = {}; + for (const f of storyFiles) { + const key = f.replace(/\.tsx?$/, ''); + const { meta, fns } = parseStoryFile(path.join(storiesDir, f)); + moduleFns[key] = fns; + metaByFile[key] = meta; + } + + fs.rmSync(outDir, { recursive: true, force: true }); + const manifest: Record> = {}; + const failures: string[] = []; + + for (const f of storyFiles.sort()) { + const key = f.replace(/\.tsx?$/, ''); + const meta = metaByFile[key]; + if (!meta || !SECTIONS[meta.group]) { + continue; + } + const section = SECTIONS[meta.group]; + const mdxFile = path.join(storiesDir, key.replace(/\.stories$/, '.mdx')); + const mdx = fs.existsSync(mdxFile) ? fs.readFileSync(mdxFile, 'utf8') : `# ${meta.title}\n`; + const t = transformMdx(mdx, moduleFns, key); + const props = t.props ?? (meta.styles ? [...variantProps(meta), { name: 'xstyle', type: 'XStyle' }] : null); + let body = t.body; + if (!t.props && props) { + body += '\n\n## Props\n\n'; + } + + try { + await compile(body, { remarkPlugins: [remarkGfm] }); + } catch (e) { + failures.push(`${key}: ${(e as Error).message}`); + continue; + } + + const slug = toSlug(meta.title); + const item = { + section, + slug, + title: meta.title, + description: t.description, + source: meta.source, + body, + examples: t.examples, + props, + }; + for (const [k, code] of Object.entries(t.examples)) { + try { + t.examples[k] = ( + await prettier.format(code, { + parser: 'typescript', + singleQuote: true, + jsxSingleQuote: true, + semi: false, + printWidth: 80, + }) + ).trim(); + } catch { + // Keep the raw source when it doesn't parse standalone. + } + } + fs.mkdirSync(path.join(outDir, section), { recursive: true }); + fs.writeFileSync(path.join(outDir, section, `${slug}.json`), JSON.stringify(item, null, 2) + '\n'); + (manifest[section] ??= []).push({ slug, title: meta.title, description: t.description }); + } + + for (const list of Object.values(manifest)) { + list.sort((a, b) => a.title.localeCompare(b.title)); + } + fs.writeFileSync(path.join(outDir, 'manifest.json'), JSON.stringify(manifest, null, 2) + '\n'); + + for (const [s, list] of Object.entries(manifest)) { + console.log(`${s}: ${list.length}`); + } + if (failures.length) { + console.error(`\n${failures.length} item(s) skipped (MDX failed to compile):`); + for (const f of failures) { + console.error(` ${f}`); + } + } +} + +main().catch(e => { + console.error(e); + process.exit(1); +}); diff --git a/packages/mosaic-docs/src/app/[section]/[slug]/page.tsx b/packages/mosaic-docs/src/app/[section]/[slug]/page.tsx new file mode 100644 index 00000000000..8d0c643a529 --- /dev/null +++ b/packages/mosaic-docs/src/app/[section]/[slug]/page.tsx @@ -0,0 +1,78 @@ +import type { Metadata } from 'next'; +import { notFound } from 'next/navigation'; + +import { Example, PrevNext, PropsTable } from '@/components/docs'; +import { getItem, getManifest, getOrderedEntries, getSection, SECTIONS, SOURCE_REPO, summarize } from '@/lib/content'; +import { renderMDX } from '@/lib/mdx'; + +type Params = { params: Promise<{ section: string; slug: string }> }; + +export const dynamicParams = false; + +export function generateStaticParams() { + const manifest = getManifest(); + return SECTIONS.flatMap(section => + (manifest[section.slug] ?? []).map(entry => ({ section: section.slug, slug: entry.slug })), + ); +} + +export async function generateMetadata({ params }: Params): Promise { + const { section, slug } = await params; + const item = getItem(section, slug); + if (!item) { + return {}; + } + return { + title: `${item.title} | Mosaic | Clerk`, + description: summarize(item.description), + alternates: { canonical: `/${section}/${slug}` }, + }; +} + +export default async function MosaicItemPage({ params }: Params) { + const { section: sectionSlug, slug } = await params; + const item = getItem(sectionSlug, slug); + const section = getSection(sectionSlug); + if (!item || !section) { + notFound(); + } + + const components = { + Example: ({ id, name }: { id: string; name: string }) => ( + + ), + Props: () => , + }; + const [lede, body] = await Promise.all([ + item.description ? renderMDX(item.description) : null, + renderMDX(item.body, components), + ]); + + const ordered = getOrderedEntries(); + const index = ordered.findIndex(entry => entry.section === sectionSlug && entry.slug === slug); + + return ( + + ); +} diff --git a/packages/mosaic-docs/src/app/[section]/page.tsx b/packages/mosaic-docs/src/app/[section]/page.tsx new file mode 100644 index 00000000000..9b8a923bfa2 --- /dev/null +++ b/packages/mosaic-docs/src/app/[section]/page.tsx @@ -0,0 +1,37 @@ +import type { Metadata } from 'next'; +import { notFound } from 'next/navigation'; + +import { ItemGrid } from '@/components/docs'; +import { getManifest, getSection, SECTIONS } from '@/lib/content'; + +type Params = { params: Promise<{ section: string }> }; + +export const dynamicParams = false; + +export function generateStaticParams() { + return SECTIONS.map(section => ({ section: section.slug })); +} + +export async function generateMetadata({ params }: Params): Promise { + const section = getSection((await params).section); + return section ? { title: `${section.title} | Mosaic | Clerk`, description: section.description } : {}; +} + +export default async function MosaicSectionPage({ params }: Params) { + const section = getSection((await params).section); + if (!section) { + notFound(); + } + const entries = getManifest()[section.slug] ?? []; + + return ( +
+

{section.title}

+

{section.description}

+ +
+ ); +} diff --git a/packages/mosaic-docs/src/app/globals.css b/packages/mosaic-docs/src/app/globals.css new file mode 100644 index 00000000000..871d78485fc --- /dev/null +++ b/packages/mosaic-docs/src/app/globals.css @@ -0,0 +1,65 @@ +@import 'tailwindcss'; +@plugin '@tailwindcss/typography'; + +@custom-variant dark (@media (prefers-color-scheme: dark)); + +@theme { + --font-sans: var(--font-geist), ui-sans-serif, system-ui, sans-serif; + --font-mono: var(--font-geist-mono), ui-monospace, SFMono-Regular, Menlo, monospace; +} + +/* Type roles carried over from clerk.com (Seed). */ +@utility heading-4 { + font-size: 2rem; + line-height: 1.2; + font-weight: 600; + letter-spacing: -0.02em; +} +@utility heading-6 { + font-size: 1.25rem; + line-height: 1.4; + font-weight: 600; + letter-spacing: -0.01em; +} +@utility label-3 { + font-size: 0.8125rem; + line-height: 1.25rem; + font-weight: 500; +} +@utility label-4 { + font-size: 0.6875rem; + line-height: 1.125rem; + font-weight: 500; +} + +/* The description under an item's title. */ +@utility prose-lede { + @apply text-base/7 text-gray-600 dark:text-gray-400; + & p { + margin: 0; + } + & code { + @apply rounded-md bg-gray-950/5 px-1 py-0.5 font-mono text-[0.875em] text-gray-950 dark:bg-white/10 dark:text-white; + } + & strong { + @apply font-semibold text-gray-950 dark:text-white; + } +} + +/* Generated swingset prose on item pages. */ +@utility prose-docs { + @apply prose prose-gray dark:prose-invert prose-headings:font-semibold prose-headings:tracking-tight prose-h2:mt-14 prose-h2:text-2xl prose-h3:text-lg prose-a:text-purple-600 prose-code:rounded-md prose-code:bg-gray-950/5 prose-code:px-1 prose-code:py-0.5 prose-code:font-normal prose-code:before:content-none prose-code:after:content-none dark:prose-code:bg-white/10 max-w-none; +} + +.shiki-frame pre { + padding: 1rem; + background: transparent !important; +} +.shiki-frame span { + color: var(--shiki-light); +} +@media (prefers-color-scheme: dark) { + .shiki-frame span { + color: var(--shiki-dark); + } +} diff --git a/packages/mosaic-docs/src/app/layout.tsx b/packages/mosaic-docs/src/app/layout.tsx new file mode 100644 index 00000000000..a86d5769cf4 --- /dev/null +++ b/packages/mosaic-docs/src/app/layout.tsx @@ -0,0 +1,83 @@ +import './globals.css'; + +import type { Metadata } from 'next'; +import { Geist, Geist_Mono } from 'next/font/google'; +import Link from 'next/link'; + +import { BackBanner } from '@/components/BackBanner'; +import { BetaNotice, GitHubLink } from '@/components/BetaNotice'; +import { Logo } from '@/components/Logo'; +import { MobileNav, Sidebar, type SidebarGroup } from '@/components/Sidebar'; +import { getManifest, itemHref, SECTIONS } from '@/lib/content'; + +const sans = Geist({ subsets: ['latin'], variable: '--font-geist' }); +const mono = Geist_Mono({ subsets: ['latin'], variable: '--font-geist-mono' }); + +export const metadata: Metadata = { + title: 'Mosaic Design System | Clerk', + description: 'Components, primitives, and hooks from Mosaic, the design system behind Clerk’s user interfaces.', + robots: { index: false, follow: false }, +}; + +function getGroups(): Array { + const manifest = getManifest(); + return [ + { title: 'Overview', items: [{ title: 'Introduction', href: '/' }] }, + ...SECTIONS.map(section => ({ + title: section.title, + href: `/${section.slug}`, + items: (manifest[section.slug] ?? []).map(entry => ({ + title: entry.title, + href: itemHref(section.slug, entry.slug), + })), + })), + ]; +} + +export default function RootLayout({ children }: { children: React.ReactNode }) { + const groups = getGroups(); + + return ( + + + +
+
+
+ + + + + + Mosaic + +
+
+ + + +
+
+
+
+ +
+ {children} +
+
+ + + ); +} diff --git a/packages/mosaic-docs/src/app/page.tsx b/packages/mosaic-docs/src/app/page.tsx new file mode 100644 index 00000000000..b35ce13e858 --- /dev/null +++ b/packages/mosaic-docs/src/app/page.tsx @@ -0,0 +1,59 @@ +import Link from 'next/link'; + +import { CodeBlock } from '@/components/CodeBlock'; +import { ItemGrid } from '@/components/docs'; +import { getManifest, SECTIONS } from '@/lib/content'; + +export default function MosaicIndexPage() { + const manifest = getManifest(); + + return ( +
+

Mosaic

+

+ Mosaic is the design system behind Clerk’s next generation of user interface components. It’s the components, + headless primitives, and hooks that Clerk’s sign-in, user profile, and organization screens are built from. +

+

+ Mosaic ships as @clerk/mosaic, + an experimental package: breaking changes can land in minor releases, so pin your version. +

+ +
+ +
+ +
+ {SECTIONS.map(section => ( + + + {section.title} + {manifest[section.slug]?.length ?? 0} + + {section.description} + + ))} +
+ + {SECTIONS.map(section => ( +
+

{section.title}

+ +
+ ))} +
+ ); +} diff --git a/packages/mosaic-docs/src/components/BackBanner.tsx b/packages/mosaic-docs/src/components/BackBanner.tsx new file mode 100644 index 00000000000..2c82c71c7b9 --- /dev/null +++ b/packages/mosaic-docs/src/components/BackBanner.tsx @@ -0,0 +1,24 @@ +/** Slim strip above the sticky header; it scrolls away with the page. */ +export function BackBanner() { + return ( + + ); +} diff --git a/packages/mosaic-docs/src/components/BetaNotice.tsx b/packages/mosaic-docs/src/components/BetaNotice.tsx new file mode 100644 index 00000000000..ec93b4b4bdd --- /dev/null +++ b/packages/mosaic-docs/src/components/BetaNotice.tsx @@ -0,0 +1,46 @@ +// The yellow (#fecf00) matches the Clerk UI beta banner. Narrow screens show only the pill, which still +// links to the changelog. +const CHANGELOG_URL = 'https://github.com/clerk/javascript/blob/main/packages/mosaic/CHANGELOG.md'; + +export function BetaNotice() { + return ( + + + Beta + + Mosaic is still under construction + + Mosaic is still under construction. Not all APIs are stable + + + What’s new + + + ); +} + +export function GitHubLink() { + return ( + + + + + + ); +} diff --git a/packages/mosaic-docs/src/components/CodeBlock.tsx b/packages/mosaic-docs/src/components/CodeBlock.tsx new file mode 100644 index 00000000000..a29df0257c0 --- /dev/null +++ b/packages/mosaic-docs/src/components/CodeBlock.tsx @@ -0,0 +1,37 @@ +import { codeToHtml } from 'shiki'; + +import { CopyButton } from './CopyButton'; + +/** A highlighted code block: a gray frame with an optional title bar around a white code card. */ +export async function CodeBlock({ code, lang = 'tsx', title }: { code: string; lang?: string; title?: string }) { + const html = await codeToHtml(code.trimEnd(), { + lang, + themes: { light: 'github-light', dark: 'github-dark' }, + defaultColor: false, + }).catch(() => + codeToHtml(code.trimEnd(), { + lang: 'text', + themes: { light: 'github-light', dark: 'github-dark' }, + defaultColor: false, + }), + ); + + return ( +
+ {title ? ( +
+ {title} + +
+ ) : ( +
+ +
+ )} +
+
+ ); +} diff --git a/packages/mosaic-docs/src/components/CopyButton.tsx b/packages/mosaic-docs/src/components/CopyButton.tsx new file mode 100644 index 00000000000..0ee46421de0 --- /dev/null +++ b/packages/mosaic-docs/src/components/CopyButton.tsx @@ -0,0 +1,22 @@ +'use client'; + +import { useState } from 'react'; + +export function CopyButton({ code }: { code: string }) { + const [copied, setCopied] = useState(false); + return ( + + ); +} diff --git a/packages/mosaic-docs/src/components/Logo.tsx b/packages/mosaic-docs/src/components/Logo.tsx new file mode 100644 index 00000000000..cfa2c0bb202 --- /dev/null +++ b/packages/mosaic-docs/src/components/Logo.tsx @@ -0,0 +1,34 @@ +/** The Clerk wordmark. */ +export function Logo(props: React.ComponentPropsWithoutRef<'svg'>) { + return ( + + + + + + + ); +} diff --git a/packages/mosaic-docs/src/components/Sidebar.tsx b/packages/mosaic-docs/src/components/Sidebar.tsx new file mode 100644 index 00000000000..18427ea47e3 --- /dev/null +++ b/packages/mosaic-docs/src/components/Sidebar.tsx @@ -0,0 +1,99 @@ +'use client'; + +import { clsx } from 'clsx'; +import Link from 'next/link'; +import { usePathname } from 'next/navigation'; +import { useState } from 'react'; + +export type SidebarGroup = { + title: string; + href?: string; + items: Array<{ title: string; href: string }>; +}; + +function NavLink({ href, children, onNavigate }: { href: string; children: React.ReactNode; onNavigate?: () => void }) { + const pathname = usePathname(); + const active = pathname === href; + return ( + + {children} + + ); +} + +function Nav({ groups, onNavigate }: { groups: Array; onNavigate?: () => void }) { + return ( + + ); +} + +export function Sidebar({ groups }: { groups: Array }) { + return ( + + ); +} + +export function MobileNav({ groups }: { groups: Array }) { + const [open, setOpen] = useState(false); + return ( +
+ + {open && ( +
+
+ )} +
+ ); +} diff --git a/packages/mosaic-docs/src/components/docs.tsx b/packages/mosaic-docs/src/components/docs.tsx new file mode 100644 index 00000000000..2b59f2f43d0 --- /dev/null +++ b/packages/mosaic-docs/src/components/docs.tsx @@ -0,0 +1,104 @@ +import Link from 'next/link'; + +import { CodeBlock } from '@/components/CodeBlock'; +import { itemHref, type Prop } from '@/lib/content'; + +export function Example({ name, code }: { name: string; code?: string }) { + if (!code) { + return null; + } + return ( + + ); +} + +export function PropsTable({ props }: { props: Array | null }) { + if (!props?.length) { + return null; + } + return ( +
+ + + + + + + + + + {props.map(prop => ( + + + + + + ))} + +
PropTypeDefault
+ {prop.name} + {prop.type} + {prop.default ?? '—'} +
+
+ ); +} + +export function PrevNext({ + prev, + next, +}: { + prev?: { title: string; href: string }; + next?: { title: string; href: string }; +}) { + return ( + + ); +} + +export function ItemGrid({ section, entries }: { section: string; entries: Array<{ slug: string; title: string }> }) { + return ( +
    + {entries.map(entry => ( +
  • + + {entry.title} + +
  • + ))} +
+ ); +} diff --git a/packages/mosaic-docs/src/lib/content.ts b/packages/mosaic-docs/src/lib/content.ts new file mode 100644 index 00000000000..879fd1ee858 --- /dev/null +++ b/packages/mosaic-docs/src/lib/content.ts @@ -0,0 +1,76 @@ +import { readFileSync } from 'node:fs'; +import path from 'node:path'; + +// Generated from ../swingset by scripts/generate.mts (runs before dev and build). Don't edit by hand. +const CONTENT_DIR = path.join(process.cwd(), '.content'); + +export const SECTIONS = [ + { slug: 'components', title: 'Components', description: 'Styled building blocks for Clerk interfaces.' }, + { slug: 'primitives', title: 'Primitives', description: 'Headless, unstyled behavior and accessibility parts.' }, + { slug: 'hooks', title: 'Hooks', description: 'State and logic for building with Mosaic.' }, +] as const; + +type SectionSlug = (typeof SECTIONS)[number]['slug']; + +type ManifestEntry = { slug: string; title: string; description?: string }; +export type Manifest = Record>; + +export type Prop = { name: string; type: string; default?: string }; + +export type MosaicItem = { + section: SectionSlug; + slug: string; + title: string; + description?: string; + source?: string; + body: string; + examples: Record; + props: Array | null; +}; + +export function getManifest(): Manifest { + return JSON.parse(readFileSync(path.join(CONTENT_DIR, 'manifest.json'), 'utf8')); +} + +export function getItem(section: string, slug: string): MosaicItem | null { + if (!SECTIONS.some(s => s.slug === section) || !/^[a-z0-9-]+$/.test(slug)) { + return null; + } + try { + return JSON.parse(readFileSync(path.join(CONTENT_DIR, section, `${slug}.json`), 'utf8')); + } catch { + return null; + } +} + +export function getSection(slug: string) { + return SECTIONS.find(s => s.slug === slug) ?? null; +} + +/** The first sentence of a lede, for index cards. */ +export function summarize(description?: string) { + if (!description) { + return undefined; + } + const text = description.replace(/\s+/g, ' ').replace(/\*\*/g, '').trim(); + const match = text.match(/^.+?[.!?](?=\s|$)/); + return (match ? match[0] : text).replace(/`/g, ''); +} + +/** Flat list in sidebar order, for previous/next links. */ +export function getOrderedEntries() { + const manifest = getManifest(); + return SECTIONS.flatMap(section => + (manifest[section.slug] ?? []).map(entry => ({ + ...entry, + section: section.slug, + href: itemHref(section.slug, entry.slug), + })), + ); +} + +export function itemHref(section: string, slug: string) { + return `/${section}/${slug}`; +} + +export const SOURCE_REPO = 'https://github.com/clerk/javascript/blob/main/'; diff --git a/packages/mosaic-docs/src/lib/mdx.tsx b/packages/mosaic-docs/src/lib/mdx.tsx new file mode 100644 index 00000000000..39ca633a134 --- /dev/null +++ b/packages/mosaic-docs/src/lib/mdx.tsx @@ -0,0 +1,28 @@ +import { evaluate } from '@mdx-js/mdx'; +import type { MDXComponents } from 'mdx/types'; +import { isValidElement, type ReactNode } from 'react'; +import * as runtime from 'react/jsx-runtime'; +import remarkGfm from 'remark-gfm'; + +import { CodeBlock } from '@/components/CodeBlock'; + +function Pre({ children }: { children?: ReactNode }) { + if (isValidElement<{ className?: string; children?: unknown }>(children)) { + const { className, children: code } = children.props; + if (typeof code === 'string') { + return ( + + ); + } + } + return
{children}
; +} + +/** Renders an MDX string (generated swingset docs) on the server. */ +export async function renderMDX(source: string, components: MDXComponents = {}) { + const { default: Content } = await evaluate(source, { ...runtime, remarkPlugins: [remarkGfm] }); + return ; +} diff --git a/packages/mosaic-docs/tsconfig.json b/packages/mosaic-docs/tsconfig.json new file mode 100644 index 00000000000..ff0d957b128 --- /dev/null +++ b/packages/mosaic-docs/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "preserve", + "moduleResolution": "bundler", + "jsx": "react-jsx", + "strict": true, + "skipLibCheck": true, + "verbatimModuleSyntax": true, + "moduleDetection": "force", + "lib": ["ES2023", "DOM"], + "types": ["node"], + "paths": { + "@/*": ["./src/*"] + }, + "plugins": [{ "name": "next" }], + "allowJs": true, + "allowImportingTsExtensions": true, + "noEmit": true, + "incremental": true + }, + "include": ["next-env.d.ts", "next.config.mjs", "src", "scripts", ".next/types/**/*.ts", ".next/dev/types/**/*.ts"], + "exclude": ["node_modules"] +} diff --git a/packages/mosaic-docs/turbo.json b/packages/mosaic-docs/turbo.json new file mode 100644 index 00000000000..a5d622f1e43 --- /dev/null +++ b/packages/mosaic-docs/turbo.json @@ -0,0 +1,16 @@ +{ + "extends": ["//"], + "tasks": { + "build": { + "inputs": [ + "package.json", + "next.config.mjs", + "postcss.config.mjs", + "tsconfig.json", + "scripts/**", + "src/**", + "$TURBO_ROOT$/packages/swingset/src/stories/**" + ] + } + } +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 71cc6016976..39af9ee2db6 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1056,6 +1056,55 @@ importers: specifier: ^0.1.0 version: 0.1.0(vitest@5.0.0) + packages/mosaic-docs: + dependencies: + '@mdx-js/mdx': + specifier: ^3.1.1 + version: 3.1.1(supports-color@10.2.2) + clsx: + specifier: ^2.1.1 + version: 2.1.1 + next: + specifier: ^16.4.3 + version: 16.4.5(@babel/core@7.29.7(supports-color@10.2.2))(@opentelemetry/api@1.9.0)(@playwright/test@1.62.1)(@types/node@22.20.1)(babel-plugin-macros@3.1.0)(babel-plugin-react-compiler@1.0.0)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + react: + specifier: 18.3.1 + version: 18.3.1 + react-dom: + specifier: 18.3.1 + version: 18.3.1(react@18.3.1) + remark-gfm: + specifier: ^4.0.0 + version: 4.0.1(supports-color@10.2.2) + shiki: + specifier: ^1.0.0 + version: 1.29.2 + devDependencies: + '@tailwindcss/postcss': + specifier: ^4.0.0 + version: 4.3.0 + '@tailwindcss/typography': + specifier: ^0.5.19 + version: 0.5.20(tailwindcss@4.3.0) + '@types/mdx': + specifier: ^2.0.13 + version: 2.0.14 + '@types/react': + specifier: catalog:react + version: 18.3.28 + '@types/react-dom': + specifier: catalog:react + version: 18.3.7(@types/react@18.3.28) + prettier: + specifier: 3.8.3 + version: 3.8.3 + tailwindcss: + specifier: ^4.0.0 + version: 4.3.0 + typescript: + specifier: catalog:repo + version: 6.0.3 + packages/msw: dependencies: '@clerk/shared': @@ -18220,7 +18269,7 @@ snapshots: dependencies: '@types/istanbul-lib-coverage': 2.0.6 '@types/istanbul-reports': 3.0.4 - '@types/node': 22.20.1 + '@types/node': 24.19.2 '@types/yargs': 15.0.20 chalk: 4.1.2 optional: true @@ -21433,7 +21482,7 @@ snapshots: '@types/ws@7.4.7': dependencies: - '@types/node': 22.20.1 + '@types/node': 12.20.55 '@types/ws@8.18.1': dependencies: @@ -26605,7 +26654,7 @@ snapshots: jest-worker@27.5.1: dependencies: - '@types/node': 22.20.1 + '@types/node': 24.19.2 merge-stream: 2.0.0 supports-color: 8.1.1 optional: true @@ -30194,7 +30243,7 @@ snapshots: rpc-websockets@9.3.8: dependencies: - '@swc/helpers': 0.5.21 + '@swc/helpers': 0.5.23 '@types/uuid': 10.0.0 '@types/ws': 8.18.1 buffer: 6.0.3 From 8d603c3b40437920e66e33adda7984c9b516c8d8 Mon Sep 17 00:00:00 2001 From: Kyle MacDonald Date: Mon, 16 Nov 2026 12:39:14 -0500 Subject: [PATCH 2/3] feat(repo): serve Mosaic docs from the root of mosaic.clerk.com --- packages/mosaic-docs/README.md | 4 ++-- packages/mosaic-docs/next.config.mjs | 3 +-- packages/mosaic-docs/src/app/layout.tsx | 1 + 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/mosaic-docs/README.md b/packages/mosaic-docs/README.md index e5f75256c1c..9f17e7ac32f 100644 --- a/packages/mosaic-docs/README.md +++ b/packages/mosaic-docs/README.md @@ -1,9 +1,9 @@ # @clerk/mosaic-docs -Private Next.js docs site for Mosaic (`@clerk/mosaic`), served at `clerk.com/mosaic` (`basePath: '/mosaic'`). +Private Next.js docs site for Mosaic (`@clerk/mosaic`), served from the root of `mosaic.clerk.com`. ```sh -pnpm --filter @clerk/mosaic-docs dev # http://localhost:6021/mosaic +pnpm --filter @clerk/mosaic-docs dev # http://localhost:6021 ``` Content is generated, not written by hand. `scripts/generate.mts` runs before `dev` and `build`. It reads swingset's stories and MDX in `../swingset/src/stories` and writes JSON to the git-ignored `.content/`. Only the Components, Primitives and Hooks groups are included. To change a page, edit its swingset MDX or story. diff --git a/packages/mosaic-docs/next.config.mjs b/packages/mosaic-docs/next.config.mjs index 39de5ea6588..0a3e5320257 100644 --- a/packages/mosaic-docs/next.config.mjs +++ b/packages/mosaic-docs/next.config.mjs @@ -1,7 +1,6 @@ /** @type {import('next').NextConfig} */ const nextConfig = { - // Served at clerk.com/mosaic. - basePath: '/mosaic', + // Served from the root of mosaic.clerk.com. outputFileTracingIncludes: { '/**': ['./.content/**/*.json'] }, }; diff --git a/packages/mosaic-docs/src/app/layout.tsx b/packages/mosaic-docs/src/app/layout.tsx index a86d5769cf4..89d5135d72a 100644 --- a/packages/mosaic-docs/src/app/layout.tsx +++ b/packages/mosaic-docs/src/app/layout.tsx @@ -14,6 +14,7 @@ const sans = Geist({ subsets: ['latin'], variable: '--font-geist' }); const mono = Geist_Mono({ subsets: ['latin'], variable: '--font-geist-mono' }); export const metadata: Metadata = { + metadataBase: new URL('https://mosaic.clerk.com'), title: 'Mosaic Design System | Clerk', description: 'Components, primitives, and hooks from Mosaic, the design system behind Clerk’s user interfaces.', robots: { index: false, follow: false }, From 47e3f8a459ca9e7615ad5442a6a655bc7a2730ef Mon Sep 17 00:00:00 2001 From: Kyle MacDonald Date: Mon, 16 Nov 2026 12:43:24 -0500 Subject: [PATCH 3/3] chore(repo): dedupe lockfile --- pnpm-lock.yaml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 39af9ee2db6..d58467e6a88 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -18269,7 +18269,7 @@ snapshots: dependencies: '@types/istanbul-lib-coverage': 2.0.6 '@types/istanbul-reports': 3.0.4 - '@types/node': 24.19.2 + '@types/node': 22.20.1 '@types/yargs': 15.0.20 chalk: 4.1.2 optional: true @@ -21482,7 +21482,7 @@ snapshots: '@types/ws@7.4.7': dependencies: - '@types/node': 12.20.55 + '@types/node': 22.20.1 '@types/ws@8.18.1': dependencies: @@ -26654,7 +26654,7 @@ snapshots: jest-worker@27.5.1: dependencies: - '@types/node': 24.19.2 + '@types/node': 22.20.1 merge-stream: 2.0.0 supports-color: 8.1.1 optional: true @@ -30243,7 +30243,7 @@ snapshots: rpc-websockets@9.3.8: dependencies: - '@swc/helpers': 0.5.23 + '@swc/helpers': 0.5.21 '@types/uuid': 10.0.0 '@types/ws': 8.18.1 buffer: 6.0.3