diff --git a/package.json b/package.json index e69b854..50cccd4 100644 --- a/package.json +++ b/package.json @@ -17,6 +17,7 @@ "lint": "oxlint", "deploy": "pnpm build && wrangler deploy", "seo": "vite-node scripts/seo.ts", + "tw:fix": "vite-node scripts/tw-fix.ts", "core:build": "pnpm --filter @fadeltd/devtools-core build" }, "dependencies": { @@ -36,6 +37,7 @@ "react-router": "8.4.0" }, "devDependencies": { + "@tailwindcss/node": "4.3.3", "@tailwindcss/vite": "4.3.3", "@types/node": "24.9.2", "@types/react": "19.3.0", diff --git a/packages/core/src/id-gen/ulid.test.ts b/packages/core/src/id-gen/ulid.test.ts index 1c0cd34..fb04a77 100644 --- a/packages/core/src/id-gen/ulid.test.ts +++ b/packages/core/src/id-gen/ulid.test.ts @@ -154,8 +154,10 @@ describe('monotonic ULID', () => { describe('ULID through generateIds', () => { it('is canonical uppercase by default, lowercase on request', () => { - const [upper] = generateIds(opts({ count: 1 }), mulberry32(1)).ids - const [lower] = generateIds(opts({ count: 1, letterCase: 'lower' }), mulberry32(1)).ids + // Both calls need the same clock: with the real one, a millisecond tick + // between them changes the time prefix and the comparison fails. + const [upper] = generateIds(opts({ count: 1 }), mulberry32(1), fixed(T)).ids + const [lower] = generateIds(opts({ count: 1, letterCase: 'lower' }), mulberry32(1), fixed(T)).ids expect(upper).toMatch(ULID) expect(lower).toBe(upper!.toLowerCase()) }) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 80210dc..8e9143e 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -51,6 +51,9 @@ importers: specifier: 8.4.0 version: 8.4.0(react-dom@19.3.0(react@19.3.0))(react@19.3.0) devDependencies: + '@tailwindcss/node': + specifier: 4.3.3 + version: 4.3.3 '@tailwindcss/vite': specifier: 4.3.3 version: 4.3.3(vite@8.3.0(@types/node@24.9.2)(esbuild@0.28.1)(jiti@2.7.0)) diff --git a/scripts/tailwind.test.ts b/scripts/tailwind.test.ts new file mode 100644 index 0000000..3f3c821 --- /dev/null +++ b/scripts/tailwind.test.ts @@ -0,0 +1,40 @@ +import { describe, expect, it } from 'vitest' +import { applyFindings, findInSource, findNonCanonical } from './tailwind' + +// A stand-in canonicalizer, so the extraction tests don't depend on Tailwind. +const fake = (token: string) => ({ 'w-[220px]': 'w-55', 'rounded-[2px]': 'rounded-xs' })[token] ?? token + +describe('findInSource', () => { + it('finds classes in className strings, cn() arguments and template literals', () => { + const src = [ + `const a =
`, + `const b = cn('p-2', on && 'rounded-[2px]')`, + 'const c = `gap-2 ${x} w-[220px]`', + ].join('\n') + const found = findInSource('x.tsx', src, fake) + expect(found.map((f) => [f.line, f.from, f.to])).toEqual([ + [1, 'w-[220px]', 'w-55'], + [2, 'rounded-[2px]', 'rounded-xs'], + [3, 'w-[220px]', 'w-55'], + ]) + }) + + it('ignores JSX text, so an apostrophe cannot open a fake string', () => { + const src = `const a =

Don't w-[220px] it's fine

` + expect(findInSource('x.tsx', src, fake)).toEqual([]) + }) + + it('reports offsets that applyFindings can rewrite exactly', () => { + const src = `` + const out = applyFindings(src, findInSource('x.tsx', src, fake)) + expect(out).toBe(``) + }) +}) + +describe('src/', () => { + // The guard: new code must use the canonical spelling. Run `pnpm tw:fix --write`. + it('has no non-canonical Tailwind classes', { timeout: 60_000 }, async () => { + const findings = await findNonCanonical() + expect(findings.map((f) => `${f.file}:${f.line} ${f.from} → ${f.to}`)).toEqual([]) + }) +}) diff --git a/scripts/tailwind.ts b/scripts/tailwind.ts new file mode 100644 index 0000000..01be5d3 --- /dev/null +++ b/scripts/tailwind.ts @@ -0,0 +1,123 @@ +/** + * Find Tailwind classes that have a canonical spelling, using Tailwind's own + * canonicalizer -- the engine behind the editor's "can be written as" hints. + * + * Only string and template literals are inspected (parsed with oxc via Vite), + * never JSX text, so an apostrophe in "Don't" cannot open a fake string. + * Each token is canonicalized on its own: collapsing `mt-2 mb-2` into `my-2` + * would change which classes a conditional `cn()` branch toggles. + */ +import { readFileSync, readdirSync, statSync } from 'node:fs' +import { join, relative } from 'node:path' +import { __unstable__loadDesignSystem } from '@tailwindcss/node' +import { parseAst } from 'vite' + +export interface Finding { + file: string + line: number + column: number + /** Absolute offset of the token in the file. */ + offset: number + from: string + to: string +} + +type DesignSystem = Awaited> + +const ROOT = join(import.meta.dirname, '..') +const CSS_ENTRY = join(ROOT, 'src/styles/global.css') + +export async function loadDesignSystem(): Promise { + return __unstable__loadDesignSystem(readFileSync(CSS_ENTRY, 'utf8'), { + base: join(ROOT, 'src/styles'), + }) +} + +export function sourceFiles(dir = join(ROOT, 'src')): string[] { + const out: string[] = [] + for (const name of readdirSync(dir)) { + const path = join(dir, name) + if (statSync(path).isDirectory()) out.push(...sourceFiles(path)) + else if (name.endsWith('.tsx')) out.push(path) + } + return out +} + +interface Segment { + start: number + text: string +} + +/** Raw text of every string literal and template chunk, with its offset. */ +function stringSegments(source: string): Segment[] { + const segments: Segment[] = [] + const visit = (node: unknown): void => { + if (Array.isArray(node)) { + for (const child of node) visit(child) + return + } + if (node === null || typeof node !== 'object') return + const n = node as { type?: string; start: number; end: number; value?: unknown } + if (n.type === 'Literal' && typeof n.value === 'string') { + // start/end include the quotes. + segments.push({ start: n.start + 1, text: source.slice(n.start + 1, n.end - 1) }) + } else if (n.type === 'TemplateElement') { + // oxc's span includes the opening delimiter (` or }) and the closing one + // (` or ${), so the raw text starts one character in. + const { raw } = n.value as { raw: string } + segments.push({ start: n.start + 1, text: raw }) + } + for (const key in n) { + if (key !== 'type' && key !== 'start' && key !== 'end') visit((n as Record)[key]) + } + } + visit(parseAst(source, { lang: 'tsx' })) + return segments +} + +export function findInSource( + file: string, + source: string, + canonical: (token: string) => string, +): Finding[] { + const findings: Finding[] = [] + for (const segment of stringSegments(source)) { + for (const match of segment.text.matchAll(/\S+/g)) { + const from = match[0] + const to = canonical(from) + if (to === from) continue + const offset = segment.start + match.index + const before = source.slice(0, offset) + const line = before.split('\n').length + findings.push({ file, line, column: offset - before.lastIndexOf('\n'), offset, from, to }) + } + } + return findings +} + +export function canonicalizer(ds: DesignSystem): (token: string) => string { + const cache = new Map() + return (token) => { + let hit = cache.get(token) + if (hit === undefined) { + // rem: 16 is what turns `w-[220px]` into `w-55`, as the editor suggests. + hit = ds.canonicalizeCandidates([token], { rem: 16 })[0] ?? token + cache.set(token, hit) + } + return hit + } +} + +export async function findNonCanonical(files = sourceFiles()): Promise { + const canonical = canonicalizer(await loadDesignSystem()) + return files.flatMap((file) => findInSource(relative(ROOT, file), readFileSync(file, 'utf8'), canonical)) +} + +/** Apply findings for one file, last offset first so earlier offsets stay valid. */ +export function applyFindings(source: string, findings: Finding[]): string { + let out = source + for (const f of findings.toSorted((a, b) => b.offset - a.offset)) { + out = out.slice(0, f.offset) + f.to + out.slice(f.offset + f.from.length) + } + return out +} diff --git a/scripts/tw-fix.ts b/scripts/tw-fix.ts new file mode 100644 index 0000000..f98ac51 --- /dev/null +++ b/scripts/tw-fix.ts @@ -0,0 +1,25 @@ +/** + * List Tailwind classes in src/ that have a canonical spelling, and rewrite + * them with --write. The test in tailwind.test.ts fails CI on any that remain. + * + * pnpm tw:fix # report + * pnpm tw:fix --write # rewrite in place + */ +import { readFileSync, writeFileSync } from 'node:fs' +import { join } from 'node:path' +import { applyFindings, findNonCanonical } from './tailwind' + +const findings = await findNonCanonical() +for (const f of findings) console.log(`${f.file}:${f.line}:${f.column} ${f.from} → ${f.to}`) + +if (process.argv.includes('--write')) { + const byFile = new Map() + for (const f of findings) byFile.set(f.file, [...(byFile.get(f.file) ?? []), f]) + for (const [file, list] of byFile) { + const path = join(import.meta.dirname, '..', file) + writeFileSync(path, applyFindings(readFileSync(path, 'utf8'), list)) + } + console.log(`tw:fix: rewrote ${findings.length} classes in ${byFile.size} files`) +} else { + console.log(`tw:fix: ${findings.length} non-canonical classes${findings.length > 0 ? ' (run with --write)' : ''}`) +} diff --git a/src/components/CommandPalette.tsx b/src/components/CommandPalette.tsx index b2b18f8..2b1fc65 100644 --- a/src/components/CommandPalette.tsx +++ b/src/components/CommandPalette.tsx @@ -49,7 +49,7 @@ export function CommandPalette({ open, onOpenChange }: Props) { shouldFilter={false} loop label="Search tools" - className="panel relative z-10 flex max-h-[400px] w-full max-w-[640px] flex-col overflow-hidden bg-surface-2" + className="panel relative z-10 flex max-h-100 w-full max-w-160 flex-col overflow-hidden bg-surface-2" onKeyDown={(e) => { if (e.key === 'Escape') { e.preventDefault() @@ -73,7 +73,7 @@ export function CommandPalette({ open, onOpenChange }: Props) { {recent.length > 0 && ( {recent.map((tool) => ( {rest.map((tool) => ( {/* Pinning is an action you go looking for, so it only appears once you have typed something. */} @@ -181,7 +181,7 @@ function ToolRow({ {tool.title} {pinIndex >= 0 && ( - + {renderCombo(`mod+${pinIndex + 1}`)} )} diff --git a/src/components/ShortcutCheatsheet.tsx b/src/components/ShortcutCheatsheet.tsx index 0ec23d1..478669a 100644 --- a/src/components/ShortcutCheatsheet.tsx +++ b/src/components/ShortcutCheatsheet.tsx @@ -21,7 +21,7 @@ export function ShortcutCheatsheet({ open, onClose }: { open: boolean; onClose: return (