diff --git a/packages/gamut-codemods/README.md b/packages/gamut-codemods/README.md index 15ef0eae56..f29910eff8 100644 --- a/packages/gamut-codemods/README.md +++ b/packages/gamut-codemods/README.md @@ -12,6 +12,8 @@ Each preset is one upgrade. Run them in order if you're more than one behind. `npx @skillsoft/gamut-codemods list` shows every preset and the migrations inside it. +The `gamut-migration` agent skill in [`@skillsoft/gamut-agent-tools`](../gamut-agent-tools/README.md) covers every preset: what each one reports, what it leaves for a person, and how to check the result. Read it alongside the preset's section here. + ## Running scope-swap Start from a clean working tree. The codemod won't write into uncommitted changes (pass `--force` to override), so `git checkout .` always undoes a run. @@ -62,7 +64,7 @@ Every skillsoft-gamut pull request publishes installable previews through pkg.pr | `mf-shared` | Replaces `@codecademy/gamut-kit` in Module Federation `shared` config with the packages it bundled. Gamut becomes a real singleton, so test the host and remotes together. | | `eslint-comments` | `// eslint-disable-next-line gamut/x` → `@skillsoft/gamut/x`. | | `scope-rename` | Every `@codecademy/gamut*` module string becomes `@skillsoft/gamut*`: imports, exports, `require`, `import()`, `jest.mock`/`vi.mock`, `declare module`, and `import('x').T`. Also exact package-name strings elsewhere, like `transpilePackages`, with one warning per file, and package names in comments (`/dist` paths and removed packages are left for the leftovers). | -| `package-json` | Renames dependencies and sets their versions. A new package that's already listed keeps its value (a preview URL, say), and a `*` peer range stays `*`. Replaces `@codecademy/gamut-kit` with the individual packages. | +| `package-json` | Renames dependencies and sets their versions. A new package that's already listed keeps its value (a preview URL, say), and a `*` peer range stays `*`. It also adds the peers the new packages need and don't install: `@vidstack/react` and `react-player`, only when the app imports `Video` from gamut and doesn't list the peer. Replaces `@codecademy/gamut-kit` with the individual packages. | | `eslint-config` | `.eslintrc` / `.eslintrc.json`: plugin name, `plugin:` extends, and rule keys. | | `mdx-imports` | Runs the migrations above over `import`/`export` statements in `.mdx` files. Fenced code blocks are left alone. | | `yarnrc` | `.yarnrc.yml` list items, like `npmPreapprovedPackages`: renames old package names, or drops them if a glob like `'@skillsoft/*'` already covers the new one. | @@ -127,6 +129,8 @@ Two rules hold it together: Create `src/presets//` with a manifest and an `index.ts`, register it in `src/presets/index.ts`, and reuse migrations from `src/migrations`. +Then document it in the `gamut-migration` skill (`packages/gamut-agent-tools/skills/gamut-migration/SKILL.md`): a row in its Presets table and a `## Preset: ` section. Add the same preset to the table at the top of this README. The skill's "Adding a preset" section lists what to cover. + ### recast gotchas already hit - Rebuild specifiers instead of mutating them. Changing `imported` on `import { List }` drops the alias, because `imported` and `local` share one source range. diff --git a/packages/gamut-codemods/src/cli.ts b/packages/gamut-codemods/src/cli.ts index 7315dd62a3..cbcf95dbf6 100644 --- a/packages/gamut-codemods/src/cli.ts +++ b/packages/gamut-codemods/src/cli.ts @@ -5,14 +5,10 @@ import path from 'node:path'; import jscodeshift from 'jscodeshift'; -import { findFlatEslintConfig } from './lib/eslint'; +import { gamutUsage, videoUsage } from './lib/gamut-imports'; import { dirtyTreeReason } from './lib/git'; -import { findLeftovers, walk } from './lib/leftovers'; -import { - activeSourceMigrations, - mentionsOldNames, - runSourceMigrations, -} from './lib/run-source'; +import { GENERATED_FILES, SKIP_DIRS, walk } from './lib/leftovers'; +import { activeSourceMigrations, runSourceMigrations } from './lib/run-source'; import type { FileMigration, Preset } from './lib/types'; import { getPreset, presets } from './presets'; @@ -72,17 +68,19 @@ export const parseArgs = (argv: string[]): Options | 'help' | 'list' => { const heading = (text: string) => console.log(`\n— ${text} —`); const runFileMigrations = ( - preset: Preset, + preset: Preset, opts: Options, note: (key: string) => void ) => { const only = opts.only ? new Set(opts.only.split(',')) : null; const skip = new Set(opts.skip ? opts.skip.split(',') : []); const active = preset.migrations.filter( - (m): m is FileMigration => + (m): m is FileMigration => m.kind === 'file' && (!only || only.has(m.name)) && !skip.has(m.name) ); let changed = 0; + const usesGamut = gamutUsage(); + const usesVideo = videoUsage(); for (const root of opts.paths) { const files = fs.statSync(root).isDirectory() ? walk(root) : [root]; @@ -93,7 +91,7 @@ const runFileMigrations = ( const warn = (msg: string) => console.log(`[${migration.name}] ${file} ${msg}`); const transformSource = (code: string) => - mentionsOldNames(preset.manifest, code) + preset.mentions(code) ? runSourceMigrations({ j: jscodeshift.withParser('tsx'), source: code, @@ -113,6 +111,8 @@ const runFileMigrations = ( manifest: preset.manifest, warn, note, + usesGamut: () => usesGamut(file), + usesVideo: () => usesVideo(file), transformSource, }); if (next === null) continue; @@ -125,7 +125,7 @@ const runFileMigrations = ( return changed; }; -const printChecklist = (preset: Preset, notes: Set) => { +const printChecklist = (preset: Preset, notes: Set) => { heading('next steps'); const items = [ ...Object.entries(preset.conditionalChecklist) @@ -194,7 +194,12 @@ export const main = async (argv: string[]) => { dry: opts.dry, extensions: 'ts,tsx,js,jsx,mjs,cjs,mts,cts', /* .d.ts stays in: Emotion theme augmentations import gamut-styles. */ - ignorePattern: ['**/node_modules/**', '**/dist/**', '**/build/**'], + /* Same list as the leftovers walk: build output and caches, which hold + minified bundles that aren't source and won't parse. */ + ignorePattern: [ + ...[...SKIP_DIRS].map((dir) => `**/${dir}/**`), + ...[...GENERATED_FILES].map((file) => `**/${file}`), + ], parser: 'tsx', babel: false, verbose: 0, @@ -213,10 +218,8 @@ export const main = async (argv: string[]) => { heading( 'leftovers skipped in --dry (nothing was written, so everything would show up)' ); - } else if (opts.report) { - const hits = findLeftovers(opts.paths, preset.manifest, { - eslintRuleKeys: !findFlatEslintConfig(opts.paths), - }); + } else if (opts.report && preset.leftovers) { + const hits = preset.leftovers(opts.paths); heading(`leftovers (${hits.length})`); hits.forEach((hit) => console.log( diff --git a/packages/gamut-codemods/src/lib/gamut-imports.ts b/packages/gamut-codemods/src/lib/gamut-imports.ts new file mode 100644 index 0000000000..8202580ede --- /dev/null +++ b/packages/gamut-codemods/src/lib/gamut-imports.ts @@ -0,0 +1,58 @@ +import fs from 'node:fs'; +import path from 'node:path'; + +import { walk } from './leftovers'; + +/* + Whether the source under a directory imports gamut, under either scope or + any of its subpaths. A worker in a repo that also has a gamut app never + imports it, and warnings about gamut's behaviour don't apply there. +*/ +const SOURCE = /\.(m?[jt]sx?|c[jt]s|mdx?)$/; +const GAMUT_SPECIFIER = /['"`](?:@codecademy|@skillsoft)\/gamut[\w./-]*['"`]/; + +const GAMUT_VIDEO_PATH = + /['"`](?:@codecademy|@skillsoft)\/gamut\/Video[\w/-]*['"`]/; +const IMPORT = + /import\s[^;]*?from\s*['"`]((?:@codecademy|@skillsoft)\/gamut[\w./-]*)['"`]/g; +const VIDEO_NAME = /\b(?:Video|VideoProps|MarkdownVideo)\b/; + +/* True when the file imports a Video name from gamut, or reaches the Video subpath. */ +const usesVideoIn = (source: string) => { + if (GAMUT_VIDEO_PATH.test(source)) return true; + for (const match of source.matchAll(IMPORT)) { + const clause = match[0].slice(0, match[0].lastIndexOf('from')); + if (VIDEO_NAME.test(clause)) return true; + } + return false; +}; + +const containsGamut = (dir: string, test: (source: string) => boolean) => { + for (const file of walk(dir)) { + if (!SOURCE.test(file)) continue; + if (test(fs.readFileSync(file, 'utf8'))) return true; + } + return false; +}; + +const memoizedPer = (test: (source: string) => boolean) => { + const seen = new Map(); + return (file: string) => { + const dir = path.dirname(file); + let known = seen.get(dir); + if (known === undefined) { + known = containsGamut(dir, test); + seen.set(dir, known); + } + return known; + }; +}; + +export const videoUsage = () => memoizedPer(usesVideoIn); + +/* + One check per run: each directory is walked once, however many files in + it ask. The CLI makes one of these and hands each file a closure over it. +*/ +export const gamutUsage = () => + memoizedPer((source) => GAMUT_SPECIFIER.test(source)); diff --git a/packages/gamut-codemods/src/lib/leftovers.ts b/packages/gamut-codemods/src/lib/leftovers.ts index 45220b8a60..b2ae64bc0d 100644 --- a/packages/gamut-codemods/src/lib/leftovers.ts +++ b/packages/gamut-codemods/src/lib/leftovers.ts @@ -19,6 +19,15 @@ export const SKIP_DIRS = new Set([ '.nx', 'tmp', ]); +/* + Generated by a tool and rebuilt on demand, so nobody edits them by hand. + worker-configuration.d.ts is `wrangler types`: a Babel bug rejects its + `declare module` block, and it has no color names to rewrite anyway. +*/ +export const GENERATED_FILES = new Set([ + 'worker-configuration.d.ts', + 'next-env.d.ts', +]); const SKIP_FILES = /(^|\/)(yarn\.lock|package-lock\.json|pnpm-lock\.yaml|CHANGELOG\.md)$/; /* .mdc is Cursor rules; .code-snippets is VS Code snippets (JSONC). */ @@ -72,7 +81,7 @@ export function* walk(dir: string): Generator { for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { if (entry.isDirectory()) { if (!SKIP_DIRS.has(entry.name)) yield* walk(path.join(dir, entry.name)); - } else { + } else if (!GENERATED_FILES.has(entry.name)) { yield path.join(dir, entry.name); } } diff --git a/packages/gamut-codemods/src/lib/manifest.ts b/packages/gamut-codemods/src/lib/manifest.ts index 1e667af00e..3de1032a21 100644 --- a/packages/gamut-codemods/src/lib/manifest.ts +++ b/packages/gamut-codemods/src/lib/manifest.ts @@ -61,6 +61,21 @@ export interface Manifest { the new package doesn't have yet; package-json warns. */ sourceVersions: Record; + /* + Peers the packages in `when` declare and need at runtime. The new + packages don't install them, so package-json adds them to an app that + depends on one of those packages. `when` uses OLD names, like the rest + of the manifest; manifest.test.ts checks `range` against the source. + */ + requiredPeers: Record< + string, + { + range: string; + when: string[]; + /* Only when the app imports Video, which is the one thing that loads these. */ + video?: boolean; + } + >; movedExports: MovedExport[]; deepImports: DeepImport[]; /* ESLint plugin prefix, for rule keys, `plugin:` extends, and comments. */ diff --git a/packages/gamut-codemods/src/lib/types.ts b/packages/gamut-codemods/src/lib/types.ts index ee3e0690fb..f99feeb811 100644 --- a/packages/gamut-codemods/src/lib/types.ts +++ b/packages/gamut-codemods/src/lib/types.ts @@ -1,5 +1,6 @@ import type { Collection, JSCodeshift } from 'jscodeshift'; +import type { Leftover } from './leftovers'; import type { Manifest } from './manifest'; /* Anything with a source location, so warnings can point at a line. */ @@ -16,11 +17,15 @@ export type Warn = (node: Locatable, message: string) => void; */ export type Note = (checklistKey: string) => void; -export interface SourceContext { +/* + `M` is the preset's manifest type. It defaults to scope-swap's Manifest, so + migrations written for that preset don't name it. +*/ +export interface SourceContext { j: JSCodeshift; root: Collection; source: string; - manifest: Manifest; + manifest: M; warn: Warn; note: Note; } @@ -31,7 +36,7 @@ export interface Edit { text: string; } -interface MigrationBase { +interface MigrationBase { name: string; description: string; /* @@ -39,7 +44,7 @@ interface MigrationBase { skip this migration for the whole run (the CLI prints it and notes `skipped:`), or null to run it. */ - skipReason?(roots: string[], manifest: Manifest): string | null; + skipReason?(roots: string[], manifest: M): string | null; } /* @@ -47,24 +52,24 @@ interface MigrationBase { whatever it thinks changed, and in semicolon-less files that has spread to neighbouring statements. Return true if anything changed. */ -export interface AstMigration extends MigrationBase { +export interface AstMigration extends MigrationBase { kind: 'ast'; - run(ctx: SourceContext): boolean; + run(ctx: SourceContext): boolean; /* Formatting fixes on the printed output that the AST can't express. */ - postPrint?(source: string, ctx: { manifest: Manifest }): string; + postPrint?(source: string, ctx: { manifest: M }): string; } /* Uses the AST to find ranges, then edits the original text by offset. The default for anything that swaps one string for another. */ -export interface SpliceMigration extends MigrationBase { +export interface SpliceMigration extends MigrationBase { kind: 'splice'; - edits(ctx: SourceContext): Edit[]; + edits(ctx: SourceContext): Edit[]; } /* Gets raw text for non-source files (package.json, .eslintrc, .mdx). */ -export interface FileMigration extends MigrationBase { +export interface FileMigration extends MigrationBase { kind: 'file'; /* Not `match`: CodeQL reads `migration.match(file)` as @@ -73,9 +78,16 @@ export interface FileMigration extends MigrationBase { appliesTo(path: string): boolean; run(ctx: { source: string; - manifest: Manifest; + manifest: M; warn: (message: string) => void; note: Note; + /* + Whether the source under this file's directory imports gamut. For + warnings that only matter where gamut is used, like a worker's tsconfig. + */ + usesGamut: () => boolean; + /* Whether the source under this file's directory imports Video from gamut. */ + usesVideo: () => boolean; /* Runs the preset's source migrations (respecting --only) over a snippet of JS/TS, for files that embed code, like MDX's ESM blocks. @@ -84,15 +96,24 @@ export interface FileMigration extends MigrationBase { }): string | null; } -export type SourceMigration = AstMigration | SpliceMigration; -export type Migration = SourceMigration | FileMigration; +export type SourceMigration = + | AstMigration + | SpliceMigration; +export type Migration = SourceMigration | FileMigration; -export interface Preset { +export interface Preset { name: string; description: string; - manifest: Manifest; + manifest: M; + /* + The cheap pre-filter every caller uses, so big repos don't parse every + file: false means no migration in this preset could change `source`. + */ + mentions(source: string): boolean; + /* After a write run, what's left for a person. Omit for no report. */ + leftovers?(roots: string[]): Leftover[]; /* Run in order. All `ast` migrations must come before any `splice` one. */ - migrations: Migration[]; + migrations: Migration[]; /* Printed at the end of every run. */ checklist: string[]; /* Printed only when a migration calls note(key). */ diff --git a/packages/gamut-codemods/src/migrations/package-json/__testfixtures__/already-renamed.output.json b/packages/gamut-codemods/src/migrations/package-json/__testfixtures__/already-renamed.output.json index e51edd4454..892e231504 100644 --- a/packages/gamut-codemods/src/migrations/package-json/__testfixtures__/already-renamed.output.json +++ b/packages/gamut-codemods/src/migrations/package-json/__testfixtures__/already-renamed.output.json @@ -7,6 +7,8 @@ "@skillsoft/gamut-patterns": "^{{version}}", "@skillsoft/gamut-styles": "^{{version}}", "@skillsoft/gamut-tests": "^{{version}}", - "@skillsoft/variance": "^{{version}}" + "@skillsoft/variance": "^{{version}}", + "@vidstack/react": "~1.12.12", + "react-player": "^3.4.0" } } diff --git a/packages/gamut-codemods/src/migrations/package-json/__testfixtures__/kit.output.json b/packages/gamut-codemods/src/migrations/package-json/__testfixtures__/kit.output.json index 779450d73c..1f2cf5fdf5 100644 --- a/packages/gamut-codemods/src/migrations/package-json/__testfixtures__/kit.output.json +++ b/packages/gamut-codemods/src/migrations/package-json/__testfixtures__/kit.output.json @@ -8,7 +8,9 @@ "@skillsoft/gamut-styles": "^{{version}}", "@skillsoft/gamut-tests": "^{{version}}", "@skillsoft/variance": "^{{version}}", - "react": "^19.0.0" + "@vidstack/react": "~1.12.12", + "react": "^19.0.0", + "react-player": "^3.4.0" }, "devDependencies": { "@skillsoft/eslint-plugin-gamut": "^0.0.1" diff --git a/packages/gamut-codemods/src/migrations/package-json/__testfixtures__/newer-than-source.output.json b/packages/gamut-codemods/src/migrations/package-json/__testfixtures__/newer-than-source.output.json index 780d3a617b..cb4bdf03fb 100644 --- a/packages/gamut-codemods/src/migrations/package-json/__testfixtures__/newer-than-source.output.json +++ b/packages/gamut-codemods/src/migrations/package-json/__testfixtures__/newer-than-source.output.json @@ -2,6 +2,8 @@ "name": "app", "dependencies": { "@skillsoft/gamut": "^{{version}}", - "@skillsoft/gamut-styles": "^{{version}}" + "@skillsoft/gamut-styles": "^{{version}}", + "@vidstack/react": "~1.12.12", + "react-player": "^3.4.0" } } diff --git a/packages/gamut-codemods/src/migrations/package-json/__testfixtures__/peers.output.json b/packages/gamut-codemods/src/migrations/package-json/__testfixtures__/peers.output.json index e4ecfdfaf1..b1144cafa9 100644 --- a/packages/gamut-codemods/src/migrations/package-json/__testfixtures__/peers.output.json +++ b/packages/gamut-codemods/src/migrations/package-json/__testfixtures__/peers.output.json @@ -2,6 +2,8 @@ "name": "lib", "peerDependencies": { "@skillsoft/gamut": "*", - "@skillsoft/gamut-styles": "^{{version}}" + "@skillsoft/gamut-styles": "^{{version}}", + "@vidstack/react": "~1.12.12", + "react-player": "^3.4.0" } } diff --git a/packages/gamut-codemods/src/migrations/package-json/__testfixtures__/required-peers.input.json b/packages/gamut-codemods/src/migrations/package-json/__testfixtures__/required-peers.input.json new file mode 100644 index 0000000000..5add39af17 --- /dev/null +++ b/packages/gamut-codemods/src/migrations/package-json/__testfixtures__/required-peers.input.json @@ -0,0 +1,7 @@ +{ + "name": "app", + "dependencies": { + "@codecademy/gamut": "^73.0.0", + "react": "^18.3.0" + } +} diff --git a/packages/gamut-codemods/src/migrations/package-json/__testfixtures__/required-peers.output.json b/packages/gamut-codemods/src/migrations/package-json/__testfixtures__/required-peers.output.json new file mode 100644 index 0000000000..d1970a370a --- /dev/null +++ b/packages/gamut-codemods/src/migrations/package-json/__testfixtures__/required-peers.output.json @@ -0,0 +1,9 @@ +{ + "name": "app", + "dependencies": { + "@skillsoft/gamut": "^{{version}}", + "@vidstack/react": "~1.12.12", + "react": "^18.3.0", + "react-player": "^3.4.0" + } +} diff --git a/packages/gamut-codemods/src/migrations/package-json/index.ts b/packages/gamut-codemods/src/migrations/package-json/index.ts index de42ad63cf..8750bba087 100644 --- a/packages/gamut-codemods/src/migrations/package-json/index.ts +++ b/packages/gamut-codemods/src/migrations/package-json/index.ts @@ -15,6 +15,9 @@ import type { FileMigration } from '../../lib/types'; A range newer than manifest.sourceVersions gets a warning: the code may already use APIs that only exist upstream, which no rename can fix. + + An app that depends on a package in manifest.requiredPeers also gets that + peer, at the range the package declares, when it doesn't list one. */ const FIELDS = [ @@ -37,7 +40,7 @@ export const packageJson: FileMigration = { kind: 'file', description: 'Rename dependencies in package.json.', appliesTo: (file) => /(^|\/)package\.json$/.test(file), - run({ source, manifest, warn, note }) { + run({ source, manifest, warn, note, usesVideo }) { const pkg = JSON.parse(source) as Record; let changed = false; @@ -87,6 +90,34 @@ export const packageJson: FileMigration = { } } + /* + Peers the new packages need at runtime but no longer install. Each is + added once, to the first field that lists a package that needs it. + */ + const listed = (name: string) => + FIELDS.some((field) => name in ((pkg[field] ?? {}) as object)); + const dependsOn = (deps: Record, old: string) => + old in deps || (manifest.packages[old]?.to ?? old) in deps; + for (const [name, { range, when, video }] of Object.entries( + manifest.requiredPeers + )) { + if (listed(name)) continue; + if (video && !usesVideo()) continue; + const owner = ( + ['dependencies', 'peerDependencies', 'devDependencies'] as const + ).find((field) => { + const deps = pkg[field] as Record | undefined; + return deps !== undefined && when.some((old) => dependsOn(deps, old)); + }); + if (!owner) continue; + pkg[owner] = sortKeys({ + ...(pkg[owner] as Record), + [name]: range, + }); + note('required-peers'); + changed = true; + } + if (!changed) return null; const trailing = source.endsWith('\n') ? '\n' : ''; return JSON.stringify(pkg, null, detectIndent(source)) + trailing; diff --git a/packages/gamut-codemods/src/migrations/tsconfig-dom/index.ts b/packages/gamut-codemods/src/migrations/tsconfig-dom/index.ts index 5221702476..18ce0325ee 100644 --- a/packages/gamut-codemods/src/migrations/tsconfig-dom/index.ts +++ b/packages/gamut-codemods/src/migrations/tsconfig-dom/index.ts @@ -7,6 +7,9 @@ import type { FileMigration } from '../../lib/types'; anyway. Once Video moves to its subpath they're gone, and `document`, `HTMLInputElement`, `ResizeObserver` and friends stop type-checking. Adding "dom" is the owner's call, so this warns rather than rewriting. + + Only tsconfigs whose directory imports gamut get the warning. A worker in + the same repo never got DOM types from it, so it has nothing to lose. */ const LIB = /"lib"\s*:\s*\[([^\]]*)\]/; @@ -17,9 +20,9 @@ export const tsconfigDom: FileMigration = { description: 'Warn about tsconfig `lib` settings without "dom", which Video used to supply.', appliesTo: (file) => /(^|\/)tsconfig[\w.-]*\.json$/.test(file), - run({ source, warn, note }) { + run({ source, warn, note, usesGamut }) { const lib = LIB.exec(source); - if (lib && !/["']dom["']/i.test(lib[1])) { + if (lib && !/["']dom["']/i.test(lib[1]) && usesGamut()) { warn( `"lib" has no "dom". Gamut's root import used to bring DOM types in through Video; add "dom" if type-checking now fails on document, HTMLElement, and so on.` ); diff --git a/packages/gamut-codemods/src/presets/manifest.test.ts b/packages/gamut-codemods/src/presets/manifest.test.ts index 98c3790a1c..88292182e4 100644 --- a/packages/gamut-codemods/src/presets/manifest.test.ts +++ b/packages/gamut-codemods/src/presets/manifest.test.ts @@ -201,6 +201,35 @@ describe('manifests', { timeout: 15_000 }, () => { } }); + it('require peers at the ranges the packages declare', () => { + /* + Each required peer must match what every package in `when` declares + in its own peerDependencies, or the migration would add a range that + doesn't install alongside the package that needs it. + */ + const packages = fs + .readdirSync(path.join(REPO, 'packages')) + .filter((dir) => + fs.existsSync(path.join(REPO, 'packages', dir, 'package.json')) + ) + .map( + (dir) => + readJson(`packages/${dir}/package.json`) as { + name: string; + peerDependencies?: Record; + } + ); + for (const [peer, { range, when }] of Object.entries( + manifest.requiredPeers + )) { + for (const old of when) { + const name = manifest.packages[old]?.to ?? old; + const pkg = packages.find((p) => p.name === name); + expect(pkg?.peerDependencies?.[peer]).toBe(range); + } + } + }); + it('keep source versions in step with each package changelog', () => { /* The top CHANGELOG heading is the upstream release the fork was synced diff --git a/packages/gamut-codemods/src/presets/scope-swap/index.ts b/packages/gamut-codemods/src/presets/scope-swap/index.ts index c08b1b14e7..0532416d50 100644 --- a/packages/gamut-codemods/src/presets/scope-swap/index.ts +++ b/packages/gamut-codemods/src/presets/scope-swap/index.ts @@ -1,3 +1,6 @@ +import { findFlatEslintConfig } from '../../lib/eslint'; +import { findLeftovers } from '../../lib/leftovers'; +import { mentionsOldNames } from '../../lib/run-source'; import type { Preset } from '../../lib/types'; import { deepImports } from '../../migrations/deep-imports'; import { eslintComments } from '../../migrations/eslint-comments'; @@ -17,6 +20,11 @@ export const scopeSwap: Preset = { name: 'scope-swap', description: 'Move from @codecademy/gamut* to @skillsoft/gamut*.', manifest, + mentions: (source) => mentionsOldNames(manifest, source), + leftovers: (roots) => + findLeftovers(roots, manifest, { + eslintRuleKeys: !findFlatEslintConfig(roots), + }), migrations: [ deepImports, movedExports, @@ -39,7 +47,9 @@ export const scopeSwap: Preset = { ], conditionalChecklist: { 'removed:@codecademy/gamut-kit': - "gamut-kit is gone. Delete anything that reads it for versions, such as a sync-gamut-deps script. @skillsoft/gamut-styles has @emotion/cache and stylis peer dependencies, so add them if yarn warns that they aren't provided.", + "gamut-kit is gone. Delete anything that reads it for versions, such as a sync-gamut-deps script. @skillsoft/gamut-styles needs @emotion/cache, so add it if yarn warns that it isn't provided. Don't add stylis by hand: @emotion/cache brings its own copy, and a second root copy can break style inserts.", + 'required-peers': + 'package.json gained peer dependencies that the @skillsoft packages need at runtime and no longer install for you (the package-json warnings list them). Run `yarn install`. If yarn still reports a peer as missing, the app is pinned to another version of it: move it to the range the migration wrote.', 'video-peers': 'Video needs two peer dependencies that Gamut no longer installs for you: `@vidstack/react` and `react-player`. Gamut supports @vidstack/react 1.12.x only (its npm `latest` tag is 0.6.x). Install them: `yarn add @vidstack/react@~1.12.12 react-player@^3.4.0`.', 'tsconfig-no-dom': diff --git a/packages/gamut-codemods/src/presets/scope-swap/manifest.ts b/packages/gamut-codemods/src/presets/scope-swap/manifest.ts index e7e782310c..00af0f9e6e 100644 --- a/packages/gamut-codemods/src/presets/scope-swap/manifest.ts +++ b/packages/gamut-codemods/src/presets/scope-swap/manifest.ts @@ -89,6 +89,24 @@ export const manifest: Manifest = { 'eslint-plugin-gamut': '3.1.0', }, + requiredPeers: { + '@vidstack/react': { + range: '~1.12.12', + when: ['@codecademy/gamut'], + video: true, + }, + 'react-player': { + range: '^3.4.0', + when: ['@codecademy/gamut'], + video: true, + }, + /* + stylis is not listed. @emotion/cache brings its own copy, and a root + copy at a different version from that one breaks emotion's inserts + (suspected: Cannot read properties of undefined (reading 'push')). + */ + }, + movedExports: [ { from: '@codecademy/gamut', diff --git a/packages/gamut-codemods/src/transform.test.ts b/packages/gamut-codemods/src/transform.test.ts index 9972b4993b..ea8d960141 100644 --- a/packages/gamut-codemods/src/transform.test.ts +++ b/packages/gamut-codemods/src/transform.test.ts @@ -82,10 +82,25 @@ describe.each(Object.values(presets))('preset $name', (preset) => { manifest: preset.manifest, warn: (w) => warnings.push(w), note: () => {}, + /* Fixtures test the text; the project check is the CLI's. */ + usesGamut: () => true, + usesVideo: () => true, transformSource: (code) => runSource(preset.name, code).out, }); expect((out ?? c.input).trim()).toBe(c.output.trim()); expectWarnings(warnings, c.warnings); + + /* Idempotent: a second run over the output changes nothing. */ + const again = migration.run({ + source: c.output, + manifest: preset.manifest, + warn: () => {}, + note: () => {}, + usesGamut: () => true, + usesVideo: () => true, + transformSource: (code) => runSource(preset.name, code).out, + }); + expect((again ?? c.output).trim()).toBe(c.output.trim()); return; } @@ -105,7 +120,14 @@ describe.each(Object.values(presets))('preset $name', (preset) => { }); } - const endToEnd = readCases(path.join(__dirname, '__testfixtures__')); + /* scope-swap's end-to-end cases sit at the top; other presets' in a folder named for them. */ + const endToEnd = readCases( + path.join( + __dirname, + '__testfixtures__', + preset.name === 'scope-swap' ? '' : preset.name + ) + ); if (endToEnd.length > 0) { it.each(endToEnd)('every migration: $name', (c) => { expect(runSource(preset.name, c.input).out.trim()).toBe(c.output.trim()); diff --git a/packages/gamut-codemods/src/video-peers.test.ts b/packages/gamut-codemods/src/video-peers.test.ts new file mode 100644 index 0000000000..741e41ae16 --- /dev/null +++ b/packages/gamut-codemods/src/video-peers.test.ts @@ -0,0 +1,86 @@ +import { describe, expect, it } from 'vitest'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; + +import { videoUsage } from './lib/gamut-imports'; +import { packageJson } from './migrations/package-json'; +import { manifest } from './presets/scope-swap/manifest'; + +const dirWith = (files: Record) => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'video-peers-')); + for (const [name, text] of Object.entries(files)) { + fs.writeFileSync(path.join(dir, name), text); + } + return dir; +}; + +const uses = (files: Record) => { + const dir = dirWith(files); + return videoUsage()(path.join(dir, 'package.json')); +}; + +describe('video usage', () => { + it('counts an import of Video from the Video subpath', () => { + expect( + uses({ 'a.tsx': "import { Video } from '@skillsoft/gamut/Video';" }) + ).toBe(true); + }); + + it('counts a Video name imported from the root of either scope', () => { + expect( + uses({ 'a.tsx': "import { Box, Video } from '@skillsoft/gamut';" }) + ).toBe(true); + expect( + uses({ + 'a.tsx': + "import {\n Video,\n VideoProps,\n} from '@codecademy/gamut';", + }) + ).toBe(true); + }); + + it('does not count gamut imports without Video', () => { + expect( + uses({ 'a.tsx': "import { Box, Text } from '@skillsoft/gamut';" }) + ).toBe(false); + expect( + uses({ 'a.tsx': "import { Markdown } from '@skillsoft/gamut';" }) + ).toBe(false); + }); + + it('does not count Video from other packages', () => { + expect(uses({ 'a.tsx': "import { Video } from 'some-other-lib';" })).toBe( + false + ); + }); +}); + +describe('vidstack and react-player', () => { + const pkg = JSON.stringify({ + name: 'app', + dependencies: { '@codecademy/gamut': '^73.0.0' }, + }); + const run = (usesVideo: boolean) => + JSON.parse( + (packageJson.run as any)({ + source: pkg, + manifest, + warn: () => {}, + note: () => {}, + usesVideo: () => usesVideo, + }) ?? pkg + ).dependencies as Record; + + it('are left out when the app does not use Video', () => { + const deps = run(false); + expect(deps).not.toHaveProperty('@vidstack/react'); + expect(deps).not.toHaveProperty('react-player'); + expect(deps).toHaveProperty('@skillsoft/gamut'); + }); + + it('are added when the app uses Video', () => { + const deps = run(true); + expect(deps['@vidstack/react']).toBe('~1.12.12'); + expect(deps['react-player']).toBe('^3.4.0'); + }); +}); diff --git a/packages/gamut-docs/astro.config.mjs b/packages/gamut-docs/astro.config.mjs index b686a8fe40..5eebad4df0 100644 --- a/packages/gamut-docs/astro.config.mjs +++ b/packages/gamut-docs/astro.config.mjs @@ -94,7 +94,17 @@ export default defineConfig({ baseUrl: 'https://github.com/Codecademy/skillsoft-gamut/edit/main/packages/gamut-docs/', }, - customCss: ['./src/styles/gamut-core-theme.css'], + // OPEN QUESTION (resolve before the site is published): gamut-theme.css + // loads the Skillsoft Text, Skillsoft Sans, Roboto and Roboto Mono web + // fonts from https://www.codecademy.com/gamut/, the same files + // gamut-styles serves to consumers. Confirm the font license allows + // these to be served from a public docs site. If it doesn't, remove the + // @font-face block and the --sl-font variables in gamut-theme.css to + // fall back to Starlight's font stack. + customCss: [ + '@skillsoft/gamut-styles/tokens.css', + './src/styles/gamut-theme.css', + ], plugins: [ starlightSidebarTopics( [ diff --git a/packages/gamut-docs/src/content/docs/components/actions/Buttons/cta-button.mdx b/packages/gamut-docs/src/content/docs/components/actions/Buttons/cta-button.mdx index ebbf83aabe..f9ce99ca81 100644 --- a/packages/gamut-docs/src/content/docs/components/actions/Buttons/cta-button.mdx +++ b/packages/gamut-docs/src/content/docs/components/actions/Buttons/cta-button.mdx @@ -30,7 +30,7 @@ Use this for a single, high-visibility marketing action — the offset shadow an - **Anything other than the single most important action on the page** — use [FillButton](/components/actions/buttons/fill-button/) instead. - **An icon alongside the label** — `CTAButton` doesn't support the `icon`/`iconPosition` props the other buttons do; use [FillButton](/components/actions/buttons/fill-button/) if an inline icon is required. - **Icon-only actions** — use [IconButton](/components/actions/buttons/icon-button/) instead; it requires an accessible name via its `tip` prop. -- **Outside its color-mode context** — don't place a light-mode button on a navy background; wrap the surface in `Background` instead of styling around it. +- **Outside its color-mode context** — don't place a light-mode button on a dark background; wrap the surface in `Background` instead of styling around it. ### Anatomy diff --git a/packages/gamut-docs/src/content/docs/components/actions/Buttons/fill-button.mdx b/packages/gamut-docs/src/content/docs/components/actions/Buttons/fill-button.mdx index 8ff9ed6fef..211bc417ec 100644 --- a/packages/gamut-docs/src/content/docs/components/actions/Buttons/fill-button.mdx +++ b/packages/gamut-docs/src/content/docs/components/actions/Buttons/fill-button.mdx @@ -33,7 +33,7 @@ Use this for primary actions. Include a leading or trailing icon from our mini i - **Low-emphasis, inline actions** — use [TextButton](/components/actions/buttons/text-button/) instead. - **Icon-only actions** — use [IconButton](/components/actions/buttons/icon-button/) instead; it requires an accessible name via its `tip` prop. - **Marketing / high-visibility CTAs** — use [CTAButton](/components/actions/buttons/cta-button/) instead. -- **Outside its color-mode context** — don't place a light-mode button on a navy background; wrap the surface in `Background` instead of styling around it. +- **Outside its color-mode context** — don't place a light-mode button on a dark background; wrap the surface in `Background` instead of styling around it. ### Anatomy diff --git a/packages/gamut-docs/src/content/docs/components/actions/Buttons/icon-button.mdx b/packages/gamut-docs/src/content/docs/components/actions/Buttons/icon-button.mdx index 11dc87a327..7c00899037 100644 --- a/packages/gamut-docs/src/content/docs/components/actions/Buttons/icon-button.mdx +++ b/packages/gamut-docs/src/content/docs/components/actions/Buttons/icon-button.mdx @@ -30,7 +30,7 @@ Use this for secondary or space-constrained actions with a recognizable icon and - **A visible label fits** — use [TextButton](/components/actions/buttons/text-button/), [StrokeButton](/components/actions/buttons/stroke-button/), or [FillButton](/components/actions/buttons/fill-button/) instead; don't reach for an icon-only button just to save space if a label would fit. - **Marketing / high-visibility CTAs** — use [CTAButton](/components/actions/buttons/cta-button/) instead. -- **Outside its color-mode context** — don't place a light-mode button on a navy background; wrap the surface in `Background` instead of styling around it. +- **Outside its color-mode context** — don't place a light-mode button on a dark background; wrap the surface in `Background` instead of styling around it. ### Anatomy diff --git a/packages/gamut-docs/src/content/docs/components/actions/Buttons/stroke-button.mdx b/packages/gamut-docs/src/content/docs/components/actions/Buttons/stroke-button.mdx index acedbc1ef8..21df320012 100644 --- a/packages/gamut-docs/src/content/docs/components/actions/Buttons/stroke-button.mdx +++ b/packages/gamut-docs/src/content/docs/components/actions/Buttons/stroke-button.mdx @@ -31,7 +31,7 @@ Use this for secondary actions. Include a leading or trailing icon from our mini - **Low-emphasis, inline actions** — use [TextButton](/components/actions/buttons/text-button/) instead. - **Icon-only actions** — use [IconButton](/components/actions/buttons/icon-button/) instead; it requires an accessible name via its `tip` prop. - **Marketing / high-visibility CTAs** — use [CTAButton](/components/actions/buttons/cta-button/) instead. -- **Outside its color-mode context** — don't place a light-mode button on a navy background; wrap the surface in `Background` instead of styling around it. +- **Outside its color-mode context** — don't place a light-mode button on a dark background; wrap the surface in `Background` instead of styling around it. ### Anatomy diff --git a/packages/gamut-docs/src/content/docs/components/actions/Buttons/text-button.mdx b/packages/gamut-docs/src/content/docs/components/actions/Buttons/text-button.mdx index 2978300e1b..145c7911b7 100644 --- a/packages/gamut-docs/src/content/docs/components/actions/Buttons/text-button.mdx +++ b/packages/gamut-docs/src/content/docs/components/actions/Buttons/text-button.mdx @@ -32,7 +32,7 @@ Use this for tertiary actions. Include a leading or trailing icon from our mini - **Secondary / outlined actions** — use [StrokeButton](/components/actions/buttons/stroke-button/) instead. - **Icon-only actions** — use [IconButton](/components/actions/buttons/icon-button/) instead; it requires an accessible name via its `tip` prop. - **Marketing / high-visibility CTAs** — use [CTAButton](/components/actions/buttons/cta-button/) instead. -- **Outside its color-mode context** — don't place a light-mode button on a navy background; wrap the surface in `Background` instead of styling around it. +- **Outside its color-mode context** — don't place a light-mode button on a dark background; wrap the surface in `Background` instead of styling around it. ### Anatomy diff --git a/packages/gamut-docs/src/content/docs/components/containers/card.mdx b/packages/gamut-docs/src/content/docs/components/containers/card.mdx index 09c710b9e6..a99cbce47d 100644 --- a/packages/gamut-docs/src/content/docs/components/containers/card.mdx +++ b/packages/gamut-docs/src/content/docs/components/containers/card.mdx @@ -1,6 +1,6 @@ --- title: Card -description: A contained surface with background color variants, optional shadow/pattern treatments, and hover behavior. +description: A contained surface with two variants, optional shadow/pattern treatments, and hover behavior. --- import FigmaEmbed from '~/components/FigmaEmbed.astro'; @@ -14,8 +14,8 @@ Use `Card` to present a piece of information as a distinct, contained surface, w **Best practices:** -- Use `variant="default"` (the default) for a background that follows the current color mode automatically; use `white`/`yellow`/`beige` inside a light-mode surface, or `navy`/`hyper` inside a dark-mode surface, when a static color is what's needed. -- Add `isInteractive` when wrapping `Card` in an `Anchor` — it applies a `'md'` border radius and a hover shadow effect, and a card with a pattern loses its pattern on hover. +- Use `variant="default"` (the default) for a card on `surface-raised`, which follows the color mode. Use `variant="brand"` for a featured card on the brand gradient. Every card has a `border-subtle` hairline. The old color variants (`white`, `beige`, `navy`, `yellow`, `hyper`) are gone; for a dark card, wrap it in ``. +- Add `isInteractive` when wrapping `Card` in an `Anchor`. It applies an `'md'` border radius and the theme's raised shadow, and on hover a `state-hover` layer and a deeper shadow; a card with a pattern loses its pattern on hover. A card that isn't interactive has no shadow. - `borderRadius` defaults to `'none'` (non-interactive) or `'md'` (`isInteractive`), and can be overridden — the outline/pattern shadow automatically matches whatever `borderRadius` is set. **When NOT to use:** @@ -34,25 +34,23 @@ The shadow/pattern treatment (`shadow`) always renders along the bottom edge plu Wrap `Card` in an `Anchor` and add `isInteractive` to get the hover shadow and `'md'` border radius: - + ## Prop Reference ### Variant - - - + + ### Shadow - - - - + + + ### Border radius `borderRadius` defaults to `'none'`, or `'md'` when `isInteractive` is set, and can be overridden independently of both: - + diff --git a/packages/gamut-docs/src/content/docs/components/data-display/bar-chart.mdx b/packages/gamut-docs/src/content/docs/components/data-display/bar-chart.mdx index e984aeddfd..7fc89eeb87 100644 --- a/packages/gamut-docs/src/content/docs/components/data-display/bar-chart.mdx +++ b/packages/gamut-docs/src/content/docs/components/data-display/bar-chart.mdx @@ -33,7 +33,7 @@ Use `BarChart` to visualize comparative data across categories, as a horizontal 4. **Scale/value axis** — the minimum is always 0; dividers and the maximum are adjustable via `scaleInterval`/`maxScaleValue`. 5. **Series one value** 6. **Series two value** (optional, via `seriesTwoValue`) — creates the stacked effect. -7. **Series one bar** — defaults to the text color; gains an automatic white/navy border for contrast when needed. +7. **Series one bar** — defaults to the text color; gains an automatic light or dark border for contrast when needed. 8. **Series two bar** — defaults to the primary color; same automatic border rule. ## Usage examples diff --git a/packages/gamut-docs/src/content/docs/concepts/best-practices.md b/packages/gamut-docs/src/content/docs/concepts/best-practices.md index 470334b8e5..d480fab140 100644 --- a/packages/gamut-docs/src/content/docs/concepts/best-practices.md +++ b/packages/gamut-docs/src/content/docs/concepts/best-practices.md @@ -7,7 +7,7 @@ For best practices specific to one component — like alerts, errors, or confirm ## Prefer semantic tokens over raw values -Access colors through Gamut's semantic aliases (`text`, `background`, `primary`, `secondary`) rather than raw color values — see [Color modes](/concepts/color-modes/) for why. Aliases guarantee you get the right color for the right theme and color mode, with the right types and states. +Access colors through Gamut's color roles (`text-default`, `surface-raised`, `action-primary` and the rest) rather than raw values or palette colors; see [Color modes](/concepts/color-modes/) for why. Roles give you the right color for the theme and color mode, with the right types and states. [Color system](/concepts/color-system/#pick-a-role-by-its-job) lists which role fits which job. ```tsx import { css } from '@skillsoft/gamut-styles'; @@ -17,7 +17,7 @@ import styled from '@emotion/styled'; const Box = styled.div(css({ p: 4 })); // A semantic color, not a raw one -const OtherCoolThing = styled.div(css({ color: 'primary', p: 4 })); +const OtherCoolThing = styled.div(css({ color: 'action-primary', p: 4 })); ``` `variant` and `states` extend the same idea to whole sets of styles — see [Compose and variants](/foundations/system-props/compose-and-variants/) for the full API. diff --git a/packages/gamut-docs/src/content/docs/concepts/color-modes.md b/packages/gamut-docs/src/content/docs/concepts/color-modes.md index 47fa30082d..f9b9617f6c 100644 --- a/packages/gamut-docs/src/content/docs/concepts/color-modes.md +++ b/packages/gamut-docs/src/content/docs/concepts/color-modes.md @@ -1,22 +1,31 @@ --- title: Color modes -description: How light/dark color mode works conceptually, distinct from theming. +description: How light and dark mode work, and how they combine with a brand. --- -Gamut components are built on semantic color aliases, not raw color values. Each alias names what a color is _used for_, not what it looks like: +Gamut components use color roles, not color values. Each role names a job, not a look: -- `text` — the standard color for all type. -- `background` — the base background color. -- `primary` — the color for interactive elements with a primary action. -- `secondary` — the color for interactive elements with a secondary action. +- `text-default`, for body text and headings. +- `surface-default`, for the page. +- `surface-raised`, for cards, menus, dialogs and fields. +- `action-primary`, for the main interactive fill, links and focus rings. -Building components against these aliases, instead of specific values, guarantees: +Every role points at a palette color once for light mode and once for dark mode. A color mode is the choice between those two. Switching the mode switches every role at once, so a component built on roles works in both modes with no extra code. The full list of roles is on the [Color system](/concepts/color-system/#roles) page. -- Components work correctly in any context, without extra configuration. -- Color usage stays consistent and accessible between contexts. -- Code reads more meaningfully, since each alias hints at its own purpose. -- Configuration stays simple — swapping a color mode swaps every aliased value at once. +## Modes are HTML attributes -A color mode is the layer that resolves each alias to an actual value, for a light or dark context. For the exact values each alias resolves to, see [Themes](/foundations/themes/). For how to actually apply a color mode or build a component that adapts to it, see [Supporting dark mode](/guides/supporting-dark-mode/). +The `data-color-mode` attribute sets a mode, and the roles under it resolve in plain CSS. `ColorMode` sets the attribute for you: -This is distinct from [theming](/guides/theming-your-app/): a theme swaps which _palette_ Gamut draws from (Core, Admin, LX Studio); a color mode swaps _which half_ of that palette — light or dark — an alias resolves against. The two compose: the same alias resolves differently depending on both which theme and which color mode are active. +```tsx +import { ColorMode } from '@skillsoft/gamut-styles'; + +const Panel = ({ children }) => {children}; +``` + +Modes nest: a light section can hold a dark panel, which can hold a light card. Each mode block also sets the CSS `color-scheme`, so scrollbars and native form controls follow the mode. A page starts in its brand's initial mode, which is light for every brand but Platform, with nothing set on ``. + +## Modes and brands + +A brand decides which palette the roles draw from: Skillsoft's, Original Codecademy's, and so on. A mode decides which of that brand's two mappings is active. The two combine: `action-primary` is a different color in each brand and each mode, but it always means the main action. + +Each theme carries one brand, and a page carries one brand's colors. See [Themes](/foundations/themes/) for the brands Gamut ships, and [Supporting dark mode](/guides/supporting-dark-mode/) for how to apply a mode or build a component that adapts to it. diff --git a/packages/gamut-docs/src/content/docs/concepts/color-system.md b/packages/gamut-docs/src/content/docs/concepts/color-system.md new file mode 100644 index 0000000000..4ed83c1494 --- /dev/null +++ b/packages/gamut-docs/src/content/docs/concepts/color-system.md @@ -0,0 +1,343 @@ +--- +title: Color system +description: How Gamut generates its colors from a few brand hues, checks them, and ships them as roles for light and dark mode. +--- + +Gamut's colors come from a generator in `@skillsoft/gamut-brand`. A brand supplies a few hues. The generator turns them into a palette, maps the palette onto named roles for light and dark mode, checks every pairing for contrast, and writes the result as CSS, JSON and TypeScript. Components and app code use the role names. `@skillsoft/gamut-styles` ships the result for Gamut's own brands, so an app on one of them never runs the generator. A team that wants its own colors runs it at build time; see [Build your own brand](#build-your-own-brand). + +## How it works + +Each step feeds the next one: + +1. A brand names a hue for each slot. +2. The generator builds a palette of 11 grades per slot. +3. Roles point at palette colors, once per mode. +4. The build checks contrast and stops if anything fails. +5. The build writes each brand's `tokens.css`, DTCG JSON and TypeScript constants. +6. `GamutProvider` puts the theme's brand's `tokens.css` on the page. +7. HTML attributes switch the mode inside the page. + +The generator lives in `packages/gamut-brand/src/`, and the output for Gamut's brands is checked in at `packages/gamut-styles/src/tokens/generated//`. + +### Brand inputs + +A brand is a `BrandInput` object with a name and a hue for each of eight slots. A new brand needs only this object, with no hand-written theme or alias table. The slots are: + +- `neutral-light` and `neutral-dark`, for surfaces, text and borders +- `primary`, for actions, links and focus rings +- `accent` and `accent-alt`, for brand gradients and charts +- `danger`, `warning` and `success`, for status + +Only `primary` is required. A brand that leaves out its neutrals gets neutrals derived from the primary hue. A brand that leaves out a status or accent slot gets Gamut's default hue for it, so red still means error. + +The generator keeps only the hue of each input. `#3A10E5` means "this blue-violet hue", and the generator decides how light and how colorful each step is. + +A brand can also set `initialMode`, `'light'` or `'dark'`, the mode a page starts in. It defaults to `'light'`. + +```ts +export const originalCodecademyBrand: BrandInput = { + name: 'originalCodecademy', + hues: { + 'neutral-light': '#FFF0E5', + 'neutral-dark': '#10162F', + primary: '#3A10E5', + accent: '#FFD300', + // ... + }, +}; +``` + +When a brand has to keep an exact color the generator wouldn't produce, it can add overrides. An override pins a palette step to a hex value, points a role at a different palette color in one mode, or moves a gradient's colors to another slot. Original Codecademy uses overrides to keep its exact yellow and to make dark mode's primary action yellow. Its navy and beige aren't pinned: exact, they carry far more chroma than the generated surfaces next to them, so the generated steps at their hues are used instead. Overrides go through the same checks as everything else. + +Five brands ship today: + +- `skillsoft`, the default, which replaces Percipio. Its theme is `skillsoftTheme`: Percipio's fonts, font weights and resting shadow, with colors generated from the Skillsoft brand's hues. +- `originalCodecademy`, the old Core theme rebuilt as a brand. Its theme is `originalCodecademyTheme`. +- `admin`, `platform` and `lxStudio`, the other old themes rebuilt the same way. Their themes keep their old names: `adminTheme`, `platformTheme` and `lxStudioTheme`. `percipioTheme` is removed; use `skillsoftTheme` instead. + +Each rebuilt brand takes its colors from what its old theme showed in each job, and keeps that theme's fonts and weights. Shadows are drawn in the shadow roles: Original Codecademy keeps old Core's hard offset, and every other brand uses a soft shadow. The `platform` brand starts in dark mode, and `platformTheme` keeps its `editor-*` code editor colors, which aren't part of the generated system. + +### Palette + +Each slot becomes a ramp of 11 grades, from `100` (lightest) to `1100` (darkest). The generator works in [OKLCH](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value/oklch), a way of writing a color as lightness, chroma (how colorful it is) and hue. OKLCH lightness matches how bright people see a color, so two colors with the same lightness look equally light whatever their hue. + +Every grade has a fixed lightness, and that lightness is the same in every slot and every brand. Chroma is a share of the most color a screen can show at that lightness and hue. Because lightness is fixed, the contrast between two grades barely changes from brand to brand: `primary-800` on `neutral-light-100` has close to the same contrast whatever the primary hue is. That is what lets every brand share one role mapping. + +Palette colors are [CSS custom properties](https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties) named `--color-palette--`, for example `--color-palette-primary-800`. A few steps also come in translucent versions, such as `--color-palette-primary-600-a6` at 6% opacity. `--color-white` and `--color-black` sit outside the ramps. Palette colors exist for the system to build roles from. Components don't use them. + +### Roles + +A role names a job and points at a palette color in each mode. There are 45 roles: + +| Family | Roles | Used for | +| ----------- | ------------------------------------------------------------------------------------- | ---------------------------------------------------------------- | +| `surface-*` | `default`, `raised`, `sunken`, `success`, `warning`, `error`, `brand`, `brand-subtle` | Anything with a background: the page, cards, wells, status tints | +| `text-*` | `default`, `subtle`, `inverse`, `success`, `warning`, `error` | Text and icons | +| `border-*` | `strong`, `default`, `subtle` | Borders and dividers | +| `action-*` | `primary`, `danger` and `neutral`, each with `-hover` and `-pressed`; `disabled` | Interactive fills and inks: buttons, links, toggles | +| `state-*` | `hover`, `pressed`, `selected` | Translucent layers over elements that have no fill of their own | +| `viz-*` | `1` to `8` (categorical), `seq-1` to `seq-4` (sequential) | Charts | +| `shadow-*` | `key`, `ambient`, `scrim` | Shadow colors and the dimmed layer behind a modal | + +Each role has one job. `surface-raised` is the lighter surface step: cards, menus, dialogs and form fields, and flat sections with a border. How high something sits comes from its shadow, not its fill. The mapping is the same for every brand: `text-subtle` is `neutral-dark-800` in light mode and `neutral-light-400` in dark mode on every brand. Only the palette under it changes. + +Roles are custom properties named `--color-`, for example `--color-action-primary`. The two brand surfaces also have a gradient. `--color-surface-brand` is the flat fallback color, and `--gradient-surface-brand` is the gradient to paint over it. The same goes for `surface-brand-subtle`. + +The shadow roles hold only color. Every elevation shadow has two layers, `shadow-key` for the tight edge and `shadow-ambient` for the soft falloff, and the elevation supplies the offset and blur. Raised and hover differ in geometry, not color. `shadow-scrim` is the dimmed layer behind a modal. The shadow alphas are design's current values and may still be tuned. + +### Checks + +The generator refuses to write a brand's files if a check fails, in either mode. It checks that: + +- every text role reaches a 4.5:1 [contrast ratio](https://www.w3.org/WAI/WCAG22/Understanding/contrast-minimum.html) on the surfaces it's meant for; +- every border, action and chart role that carries meaning reaches 3:1, the [non-text contrast](https://www.w3.org/WAI/WCAG22/Understanding/non-text-contrast.html) minimum; +- the translucent `state-*` roles still meet those minimums once they're laid over each surface; +- `state-pressed` looks visibly different from `state-hover` on every surface; +- 204 text and icon pairings inside 25 real components, such as an `Alert` icon on its tint, meet their minimum. + +`border-subtle`, `action-disabled` and the `shadow-*` roles are exempt from contrast: the first is decorative, the second marks an inactive control, and a shadow isn't something to read. Separation of the three status colors for people with color-vision deficiencies is measured and reported, but doesn't fail the build. + +The generator runs every check a second time on the values read back out of the brand's own `tokens.css`, so what ships is what was checked. To see the full report for Gamut's brands, run: + +```sh +yarn workspace @skillsoft/gamut-styles validate:tokens +``` + +### Outputs + +Each brand gets its own set of three outputs. No file holds more than one brand: + +| Output | Import | For | +| ------------ | ------------------------------------------------------------------------- | --------------------------------------------------------------- | +| `tokens.css` | `@skillsoft/gamut-styles/tokens/.css` | The brand's colors as custom properties | +| DTCG JSON | `@skillsoft/gamut-styles/tokens//{palette,light,dark}.tokens.json` | Tools outside JavaScript, such as Figma plugins and native apps | +| TS constants | `@skillsoft/gamut-styles/tokens` | Code that needs the values or the role table itself | + +`@skillsoft/gamut-styles/tokens.css` is the default brand's file, `skillsoft`. + +The JSON follows the [Design Tokens Community Group](https://www.designtokens.org/) (DTCG) format, a shared JSON format for design tokens. There is one file each for the palette, light roles and dark roles, and each color is OKLCH with its hex value alongside. The TypeScript entry exports the default brand's `palette`, `roles`, `gradients`, `contentModes` and `tokensCss`, plus every brand under `brands`, such as `brands.originalCodecademy.palette`. It doesn't depend on React or Emotion. + +A brand's `tokens.css` puts every value inside a [cascade layer](https://developer.mozilla.org/en-US/docs/Web/CSS/@layer) called `tokens`, with the brand's palette and its initial mode on `:root`: + +```css +@layer reset, base, tokens, recipes, utilities; + +@layer tokens { + :root, + [data-brand='originalCodecademy'] { + --color-palette-primary-800: oklch(0.4115 0.2344 274.1); + /* ... */ + } + :root, + [data-color-mode='light'] { + --color-text-default: var(--color-palette-neutral-dark-1000); + /* ... */ + } + [data-color-mode='dark'] { + --color-action-primary: var(--color-palette-accent-300); + /* ... */ + } +} +``` + +A brand's overrides sit in its mode blocks, like Original Codecademy's yellow `action-primary` in dark mode in the previous example. + +Styles inside a layer lose to styles outside any layer, whatever the selector. Emotion's styles and your own unlayered CSS override a token value without needing a more specific selector. + +### How the colors reach the page + +A theme built on the color system carries its brand's `tokens.css` as a string, and `GamutProvider` injects it as an Emotion global style, the same way it injects its reset and typography styles. A React app gets its brand's colors without loading a file, starts in the brand's initial mode with no attributes on ``, and the colors are in the server-rendered HTML too. + +The theme's own colors are `var()` names like `var(--color-surface-raised)`, so `css()`, `variant()`, `states()` and system props keep working as they did before. + +If your app loads the brand's `tokens.css` itself, pass `useTokens={false}` to `GamutProvider` to skip the injected copy. Loading both does no harm, because the rules are identical. Pages without React or Emotion, such as plain HTML or email, can link the brand's `tokens.css` directly. + +### Modes and brands at runtime + +A mode switch is an HTML attribute. The `ColorMode` component sets two attributes on its element, `data-color-mode` and `data-brand`, and every role inside it points at its color for that mode, through plain CSS. It nests as deep as you need. Each mode block also sets [`color-scheme`](https://developer.mozilla.org/en-US/docs/Web/CSS/color-scheme), so scrollbars and native form controls follow the mode. + +`data-brand` names the palette. A page carries one brand's CSS, the theme's, so every `ColorMode` inside it is in that brand, overrides included. Use `ColorMode`, or `Background` for a colored section; if you set the attributes by hand, set both on the same element. + +The `Background` component decides its content mode at build time. For each of the 90 opaque palette colors (the 88 ramp steps, white and black), the generator records whether light-mode or dark-mode content reads better on it. `Background` looks the answer up in that table instead of measuring contrast in the browser on every render. + +## Intended use + +### Pick a role by its job + +| Job | Role | +| ------------------------------------------- | ------------------------------------------------ | +| The page, a nav or a header | `surface-default` | +| A card, popover, menu, modal panel or field | `surface-raised` | +| An inset well, code block or disabled field | `surface-sunken` | +| Body text and headings | `text-default` | +| Descriptions, metadata and helper text | `text-subtle` | +| Anything clickable | `action-*` | +| A disabled label, value or field outline | `action-disabled` | +| Hover and press on something with no fill | `state-hover`, `state-pressed`, `state-selected` | +| A border that carries meaning, like a field | `border-default` | +| A divider, or the edge of a floating panel | `border-subtle` | +| A shadow's two layers | `shadow-key`, `shadow-ambient` | +| The dimmed layer behind a modal | `shadow-scrim` | + +```tsx +import { Box, Text } from '@skillsoft/gamut'; + +const Card = () => ( + + Course progress + Updated 2 hours ago + +); +``` + +### Give raised surfaces a hairline + +In light mode `surface-raised` is too close to the page to see on its own, so anything on it takes a `border-subtle` hairline. Floating surfaces, such as menus, popovers, tooltips and toasts, add a shadow that separates them from whatever is underneath. Field outlines and control strokes carry meaning, so they stay `border-default`. + +`Card` has two variants: `default` on `surface-raised`, and `brand`, the featured card on the brand gradient. Every card has the hairline. An interactive card adds the raised shadow at rest and, on hover, the `state-hover` layer and a deeper shadow; its border doesn't change. + +### Use `text-inverse` on filled controls + +A label on a filled action, such as `action-primary`, uses `text-inverse` in either mode. `text-inverse` is only checked against `action-primary`, `action-neutral` and `action-danger`. + +```tsx + + Start lesson + +``` + +### Pair a status tint with a status ink + +A status message is a tint behind and an ink on top. An error box uses `surface-error` for the background and `text-error` for the icon and the message; each status ink clears text contrast on its own tint. A floating `Alert` takes the same ink on its border. Show warnings with an icon, not color alone. + +### Put colored sections inside `Background` + +`Background` paints a color and switches the mode inside it to whichever one reads better on that color. Inside, every role resolves in the new mode, so `text-default` stays readable without picking a mode by hand. + +```tsx +import { Background } from '@skillsoft/gamut-styles'; + +const PromoBand = ({ children }) => ( + + {children} + +); +``` + +### Use `viz-*` for charts + +Use `viz-1` to `viz-8` for categorical series and `viz-seq-1` to `viz-seq-4` for ordered steps from low to high. Don't rely on color alone to tell series apart; add labels, patterns or markers ([WCAG use of color](https://www.w3.org/WAI/WCAG22/Understanding/use-of-color.html)). For the same reason, links keep their underline. + +### Use roles, never palette colors + +Write `bg="surface-raised"`, not `bg="palette-neutral-light-100"`. A palette color is the same in every mode, so it doesn't change when the mode does, and it breaks dark mode. + +### Set up an app + +A React app gets the colors from `GamutProvider`. Pass the theme for your brand: + +```tsx +import { + GamutProvider, + originalCodecademyTheme, +} from '@skillsoft/gamut-styles'; + +export const App = ({ children }) => ( + {children} +); +``` + +The page starts in that brand and its initial mode, `` included, with nothing to set on ``. + +Pages without React load the brand's file, such as `@skillsoft/gamut-styles/tokens/originalCodecademy.css`. + +## Build your own brand + +A team that needs its own colors builds a brand with `@skillsoft/gamut-brand`, the same tool that builds Gamut's. It runs at build time only, so install it as a dev dependency: + +```sh +yarn add -D @skillsoft/gamut-brand +``` + +Write the brand. Only `name` and `hues.primary` are required: + +```ts +// src/theme/acme.brand.ts +import { defineBrand } from '@skillsoft/gamut-brand'; + +export default defineBrand({ + name: 'acme', + hues: { primary: '#0A5CFF', accent: '#FFB000' }, +}); +``` + +Generate it, and check in the `src/theme/acme/` folder it writes: + +```sh +gamut-brand build src/theme/acme.brand.ts +``` + +Build the theme from the generated values, and pass it to `GamutProvider` like any other theme: + +```ts +import { + createBrandTheme, + fontWeightMediumTitle, + percipioFontFamily, + softElevation, +} from '@skillsoft/gamut-styles'; + +import * as values from './acme/values'; + +export const acmeTheme = createBrandTheme(values, { + name: 'acme', + fontFamily: percipioFontFamily, + fontWeight: fontWeightMediumTitle, + elevation: softElevation, +}); +``` + +Every brand has the same palette keys and the same 45 roles, so `acmeTheme` has the same type as Gamut's themes. System props, `css()`, `variant()` and `states()` stay typed, and `bg="surface-raisd"` fails to compile. `defineBrand` is typed too, so a misspelled slot or role fails. + +A brand that fails a check isn't written, and the error names the check, its worst value and where. Pick another hue, or pin the color with an override, and run the build again. + +To keep the files current, run `gamut-brand build src/theme/acme.brand.ts --watch` next to your dev server, and the same command with `--check` in CI. `--check` writes nothing and fails when the files are out of date, including after an upgrade of `@skillsoft/gamut-brand`. Keep `@skillsoft/gamut-brand` on the same version as `@skillsoft/gamut-styles`. + +## Compared with the old color system + +### What stays the same + +- Themes are still variance themes, and components still style with `css()`, `variant()`, `states()` and system props. Only the color names change. +- Components still use names, not values. The old themes already handed components `var()` names, and the new ones do the same. +- Color modes still work through CSS custom properties and still nest. An attribute drives them now instead of an injected class. +- `GamutProvider`, `ColorMode` and `Background` keep the same props, and `GamutProvider` still delivers the colors. +- The old look comes back as brands. Original Codecademy is old Core rebuilt from its navy, beige, hyper and yellow, with the same fonts and old Core's hard offset shadow. Admin, Platform and LX Studio are rebuilt the same way, under their old theme names. + +### What improves + +| | Old | New | +| ----------------- | ------------------------------------------------------- | ------------------------------------------------------------------- | +| Where values live | Emotion theme objects, written onto the page at runtime | One generated stylesheet per brand, injected once | +| Mode switch | Every alias for the mode written into a new class | One attribute | +| `Background` | Contrast math on every render | A table decided at build time | +| Accessibility | Colors picked by hand and never checked | Every role pairing and 204 component pairings checked at build time | +| Names | Ambiguous: `background` is both the page and a card | One job each: `surface-default`, `surface-raised` | +| New brand | A hand-written theme and alias table | A few hues and `gamut-brand build`, checked automatically | +| Who can read it | JavaScript only | CSS, DTCG JSON and TypeScript from one source | +| Color space | Hex, tuned by hand per step | OKLCH with fixed lightness per grade, hex alongside in the JSON | + +### What costs more + +- Every color name changes. `text` becomes `text-default` and `primary` becomes `action-primary`. Some old names split into several roles depending on where they're used: `background` becomes `surface-raised` on a card and `surface-default` on the page, so a person has to choose each time. The type check fails on every old name until it's moved. +- Rebuilt themes aren't pixel-identical. Roles use the same grades on every brand, so some colors move noticeably even when the brand hues match the old theme. Overrides cover colors that have to stay exact. +- Colors that only one old theme had are gone, such as LX Studio's `lxStudioBgPrimary`. Use the role for the job instead. +- The browser floor goes up. `tokens.css` uses `oklch()`, [`color-mix()`](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value/color-mix), `@layer` and [container query units](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_containment/Container_queries#container_query_length_units) with no hex fallback. Browsers older than about Chrome and Edge 111, Safari 16.2 or Firefox 113 get no color. Check [oklch support](https://caniuse.com/mdn-css_types_color_oklch) and [color-mix support](https://caniuse.com/mdn-css_types_color_color-mix) against your app's browser list. +- Any unlayered CSS overrides a token. That's on purpose, but a stray global rule can now change a color. +- Some pieces are missing. Shadow geometry lives in each brand's theme for now, and floating surfaces borrow the raised shadow until there's an overlay depth. The chart colors use the order solved for Skillsoft's hues, so another brand gets that order without it being re-solved for its own hues. +- The Emotion theme carries sRGB copies of each color, because the [polished](https://polished.js.org/) library can't read OKLCH. Code that reads a color from the theme in JavaScript gets a very slightly different value from what's on screen. diff --git a/packages/gamut-docs/src/content/docs/concepts/index.md b/packages/gamut-docs/src/content/docs/concepts/index.md index 916c956a0a..b76756f11f 100644 --- a/packages/gamut-docs/src/content/docs/concepts/index.md +++ b/packages/gamut-docs/src/content/docs/concepts/index.md @@ -8,6 +8,7 @@ Explanation: how and why the system is built the way it is, for when you want to - [Best practices](/concepts/best-practices/) - [Brand](/concepts/brand/) - [Color modes](/concepts/color-modes/) +- [Color system](/concepts/color-system/) - [FAQs](/concepts/faqs/) - [Naming conventions rationale](/concepts/naming-conventions-rationale/) - [Voice & tone](/concepts/voice-and-tone/) diff --git a/packages/gamut-docs/src/content/docs/foundations/design-tokens/colors.mdx b/packages/gamut-docs/src/content/docs/foundations/design-tokens/colors.mdx index c8a8694892..2ba7978c31 100644 --- a/packages/gamut-docs/src/content/docs/foundations/design-tokens/colors.mdx +++ b/packages/gamut-docs/src/content/docs/foundations/design-tokens/colors.mdx @@ -11,6 +11,15 @@ import DesignTokenTable from '~/components/DesignTokenTable.astro'; Every visual identity color is available on the `colors` key of the theme object, including the named standard colors and their swatches. +Colors come from the [color system](/concepts/color-system/), in two layers: + +- **Roles**, such as `surface-raised`, `text-default` and `action-primary`. Each names a job and resolves to a different color in light and dark mode. Components and app code use roles. +- **Palette colors**, named `palette--`, such as `palette-primary-800`, plus `white` and `black`. A palette color is the same in every mode. Roles point at these; components shouldn't. + +Each color is also a CSS custom property with a `--color-` prefix, such as `var(--color-surface-raised)`, for stylesheets and pages without React. + +See [Color modes](/concepts/color-modes/) for how roles follow the mode. + ## Standard colors The color atoms Codecademy designs should draw from. Check accessibility contrast requirements when pairing them. diff --git a/packages/gamut-docs/src/content/docs/foundations/design-tokens/elevation.mdx b/packages/gamut-docs/src/content/docs/foundations/design-tokens/elevation.mdx index c5cc2ecdac..e40042816b 100644 --- a/packages/gamut-docs/src/content/docs/foundations/design-tokens/elevation.mdx +++ b/packages/gamut-docs/src/content/docs/foundations/design-tokens/elevation.mdx @@ -11,6 +11,6 @@ import DesignTokenTable from '~/components/DesignTokenTable.astro'; Elevation describes how a surface like `Card` renders shadow and lift. The scale has three states — `rest`, `hover`, and `hoverMirrored` — each with a `shadow` and a `transform` token, accessed with a dash-case key, `elevation['-']`. `hoverMirrored` is for a surface that casts its shadow to the right instead of the left, such as `Card`'s `patternRight` shadow. -Shadow colors reference the `shadow-primary` color mode alias, so they follow light and dark mode automatically. A theme can supply its own scale with `addScale('elevation', ...)` — Skillsoft, for example, replaces the hard offset shadow with a soft, blurred one and no lift. +Every shadow is drawn in two roles, `shadow-key` (the tight contact layer) and `shadow-ambient` (the soft falloff), so shadows follow color mode automatically. Each theme supplies its own geometry: Original Codecademy keeps a hard offset, and the other themes use a soft shadow with no lift. diff --git a/packages/gamut-docs/src/content/docs/foundations/design-tokens/index.md b/packages/gamut-docs/src/content/docs/foundations/design-tokens/index.md index 77444f4fd8..5c518bc2dd 100644 --- a/packages/gamut-docs/src/content/docs/foundations/design-tokens/index.md +++ b/packages/gamut-docs/src/content/docs/foundations/design-tokens/index.md @@ -22,7 +22,7 @@ Reach for a token directly only when a [system prop](/foundations/system-props/) ```tsx // on the theme prop of any styled component const styles = styled.div` - color: ${({ theme }) => theme.colors.blue}; + color: ${({ theme }) => theme.colors['text-subtle']}; `; // or imported directly diff --git a/packages/gamut-docs/src/content/docs/foundations/eslint-rules.md b/packages/gamut-docs/src/content/docs/foundations/eslint-rules.md index 27716af235..536da66442 100644 --- a/packages/gamut-docs/src/content/docs/foundations/eslint-rules.md +++ b/packages/gamut-docs/src/content/docs/foundations/eslint-rules.md @@ -55,11 +55,11 @@ Suggests the `themed()` utility over reaching directly into `theme` inside a sty ```tsx // Instead of: const StyledDiv = styled.div` - color: ${({ theme }) => theme.colors.primary}; + color: ${({ theme }) => theme.colors['action-primary']}; `; // Prefer: -const StyledBox = styled(Box)(css({ color: themed('colors.primary') })); +const StyledBox = styled(Box)(css({ color: themed('colors.action-primary') })); ``` ## Configuration diff --git a/packages/gamut-docs/src/content/docs/foundations/system-props/compose-and-variants.md b/packages/gamut-docs/src/content/docs/foundations/system-props/compose-and-variants.md index a73d4fb01c..dbb7f4b59f 100644 --- a/packages/gamut-docs/src/content/docs/foundations/system-props/compose-and-variants.md +++ b/packages/gamut-docs/src/content/docs/foundations/system-props/compose-and-variants.md @@ -66,7 +66,7 @@ const Anchor = styled.a( variant({ variants: { interface: { - color: 'navy', + color: 'text-default', '&:hover': { textDecoration: 'none', border: '2px solid currentColor' }, }, }, diff --git a/packages/gamut-docs/src/content/docs/foundations/system-props/prop-groups/color.mdx b/packages/gamut-docs/src/content/docs/foundations/system-props/prop-groups/color.mdx index 8b4720e01d..f111722bc2 100644 --- a/packages/gamut-docs/src/content/docs/foundations/system-props/prop-groups/color.mdx +++ b/packages/gamut-docs/src/content/docs/foundations/system-props/prop-groups/color.mdx @@ -7,12 +7,16 @@ sidebar: import SystemPropTable from '~/components/SystemPropTable.astro'; -Color props control foreground, background, and border colors, restricted to the theme's color palette. `bg` is a shorthand for background color. +Color props control foreground, background, and border colors, restricted to the theme's colors. Use [color roles](/concepts/color-system/#pick-a-role-by-its-job), which follow the color mode. `bg` is a shorthand for background color. ```tsx const ColorExample = styled.div(system.color); -; +; ``` These props support both physical and logical CSS properties, resolved by `useLogicalProperties` on `GamutProvider` — see [Migrating to logical properties](/guides/migrating-to-logical-properties/). diff --git a/packages/gamut-docs/src/content/docs/foundations/themes.md b/packages/gamut-docs/src/content/docs/foundations/themes.md index f6349c9cd3..a946ebec03 100644 --- a/packages/gamut-docs/src/content/docs/foundations/themes.md +++ b/packages/gamut-docs/src/content/docs/foundations/themes.md @@ -1,20 +1,31 @@ --- title: Themes -description: The theme palettes available (Core, Admin, LX Studio and Platform) and their values. +description: The themes Gamut ships (Skillsoft, Original Codecademy, Admin, Platform and LX Studio) and how they relate to brands. --- -Every Emotion component in Gamut has typed access to the current theme's tokens, without any extra imports — most commonly through [system props](/foundations/system-props/) or the `theme` prop. +Every Emotion component in Gamut has typed access to the current theme's tokens, without any extra imports, most commonly through [system props](/foundations/system-props/) or the `theme` prop. ## Available themes -- **Core** — Codecademy's own public-facing theme. -- **Admin** — the internal admin/back-office theme. -- **LX Studio** — the theme for LX Studio. -- **Platform** — the shared learning-platform theme. +Each theme is one brand of the [color system](/concepts/color-system/), plus that brand's fonts, font weights and shadows: + +| Theme | Brand | For | +| ------------------------- | -------------------- | --------------------------------------------------------------- | +| `skillsoftTheme` | `skillsoft` | The default. Replaces `percipioTheme` | +| `originalCodecademyTheme` | `originalCodecademy` | Codecademy's public-facing product, rebuilt from the Core theme | +| `adminTheme` | `admin` | Internal admin and back-office tools | +| `platformTheme` | `platform` | The learning environment. Starts in dark mode | +| `lxStudioTheme` | `lxStudio` | LX Studio | + +`GamutProvider` uses `skillsoftTheme` when you don't pass one. Every theme has the same palette keys and the same roles, so they all share one type, `SkillsoftTheme`, and a component that type-checks against one works on all of them. + +`coreTheme` is still exported, on the old color names, until the move to roles is finished. Use `originalCodecademyTheme` for new work. + +A team that needs its own colors can build its own brand and theme; see [Creating a custom theme](/guides/creating-a-custom-theme/). ## Comparing themes live -Use Storybook's Theme Switcher (paintbrush icon in the toolbar) to preview any component across every theme, paired with the Color Mode selector to check both light and dark variants of each. This is the fastest way to see a token's actual resolved value — exact hex codes and scale values are theme-specific and aren't reproduced statically here. +Use Storybook's Theme Switcher (paintbrush icon in the toolbar) to preview any component in every theme, and the Color Mode selector to check light and dark for each. Exact color values are theme-specific and aren't reproduced here. ## Choosing a theme diff --git a/packages/gamut-docs/src/content/docs/getting-started/build-your-first-page.md b/packages/gamut-docs/src/content/docs/getting-started/build-your-first-page.md index f7c3eacdb9..50220b831f 100644 --- a/packages/gamut-docs/src/content/docs/getting-started/build-your-first-page.md +++ b/packages/gamut-docs/src/content/docs/getting-started/build-your-first-page.md @@ -11,19 +11,19 @@ It assumes you've completed [Installation](/getting-started/installation/) and h ## 1. Lay down a colored surface -`Background` paints a semantic color behind its children and keeps text inside it readable in both color modes. Start your page component with one: +`Background` paints a color role behind its children and keeps text inside it readable in both color modes. Start your page component with one: ```tsx title="WelcomePage.tsx" import { Background } from '@skillsoft/gamut-styles'; export const WelcomePage = () => ( - + {/* content goes here */} ); ``` -Run your app. You should see a full-width beige panel with 32px of padding and nothing in it yet. +Run your app. You should see a full-width panel, a step darker than the page, with 32px of padding and nothing in it yet. ## 2. Add a heading @@ -34,7 +34,7 @@ import { Background } from '@skillsoft/gamut-styles'; import { Text } from '@skillsoft/gamut'; export const WelcomePage = () => ( - + Welcome to Gamut @@ -42,7 +42,7 @@ export const WelcomePage = () => ( ); ``` -Refresh — you now have a styled heading sitting in the beige panel. +Refresh — you now have a styled heading sitting in the panel. ## 3. Arrange content in a grid @@ -54,7 +54,7 @@ import { Text } from '@skillsoft/gamut'; import { GridBox } from '@skillsoft/gamut'; export const WelcomePage = () => ( - + Welcome to Gamut @@ -87,7 +87,7 @@ import { GridBox } from '@skillsoft/gamut'; import { Text } from '@skillsoft/gamut'; export const WelcomePage = () => ( - + Welcome to Gamut @@ -120,7 +120,7 @@ export const WelcomePage = () => ( You should now have a page with: -- A beige background panel with consistent padding. +- A `surface-sunken` panel with consistent padding. - A page heading and supporting copy. - A responsive two-column layout that collapses to one column on narrow screens. - A card containing a secondary heading, copy, and a primary button that links to the component reference. diff --git a/packages/gamut-docs/src/content/docs/getting-started/installation.md b/packages/gamut-docs/src/content/docs/getting-started/installation.md index 7c66f61063..cc806c919a 100644 --- a/packages/gamut-docs/src/content/docs/getting-started/installation.md +++ b/packages/gamut-docs/src/content/docs/getting-started/installation.md @@ -48,10 +48,10 @@ render( `GamutProvider` does four things every Gamut app needs: -1. Wraps your app in the theme context. +1. Wraps your app in the theme context. Without a `theme` prop, it uses `skillsoftTheme`; see [Theming your app](/guides/theming-your-app/) to pick another. 2. Creates an Emotion cache with Gamut's plugins. -3. Injects global styles and CSS variables. -4. Sets the current color mode context and variables. +3. Injects global styles and the theme's brand colors as CSS variables. +4. Starts the page in the brand's initial color mode. For Next.js, do this in `_app.tsx`. For Gatsby, do it in both `gatsby-ssr.js` and `gatsby-browser.js` via `wrapRootElement`. @@ -70,11 +70,11 @@ Gamut components read their allowed props from your Emotion theme shape, so decl ```tsx title="theme.d.ts" import '@emotion/react'; -// Use whichever theme shape matches your app: `CoreTheme` or `PlatformTheme`. -import { CoreTheme } from '@skillsoft/gamut-styles'; +// Every Gamut theme shares this type, whichever one your app uses. +import type { SkillsoftTheme } from '@skillsoft/gamut-styles'; declare module '@emotion/react' { - export interface Theme extends CoreTheme {} + export interface Theme extends SkillsoftTheme {} } ``` @@ -87,7 +87,7 @@ import { Background } from '@skillsoft/gamut-styles'; import { Text } from '@skillsoft/gamut'; export const App = () => ( - + Hello World! ); diff --git a/packages/gamut-docs/src/content/docs/guides/creating-a-custom-theme.md b/packages/gamut-docs/src/content/docs/guides/creating-a-custom-theme.md index 008acad46e..6196cad583 100644 --- a/packages/gamut-docs/src/content/docs/guides/creating-a-custom-theme.md +++ b/packages/gamut-docs/src/content/docs/guides/creating-a-custom-theme.md @@ -1,163 +1,195 @@ --- title: Creating a custom theme -description: Build a custom theme with gamut-styles' createTheme builder. +description: Build your own brand with @skillsoft/gamut-brand and turn it into a theme with createBrandTheme. --- ## When to reach for this -Most apps should [choose an existing theme](/guides/theming-your-app/) rather than build a new one — reach for a custom theme only for a genuinely new product surface that doesn't fit Core, Admin, LX Studio or Platform. +Most apps should [choose an existing theme](/guides/theming-your-app/). Build your own only when a product needs its own colors, for example to white-label Gamut for a customer. -## The `createTheme` builder +A custom theme has two parts: -Themes are built with `createTheme` from `@skillsoft/variance`, giving you type-safe autocomplete, automatic CSS variable generation, built-in light/dark color mode support, and full compatibility with existing Gamut components: +- **A brand**: a few hues, which `@skillsoft/gamut-brand` turns into a palette, light and dark roles, and the CSS for them, all checked for contrast. +- **A theme**: the brand's generated values plus fonts, font weights and shadows, put together by `createBrandTheme` from `@skillsoft/gamut-styles`. -```tsx -import { createTheme } from '@skillsoft/variance'; - -const myTheme = createTheme({ - ...baseTheme, - fontFamily: customFontFamily, -}) - .addColors(colorPalette) - .addColorModes('light', colorModeConfig) - .addScale('customProperty', scaleFunction) // only for new scales - .addName('my-theme') - .build(); +The result has the same type as Gamut's own themes, so every component, system prop and `css()` call works and stays type-checked. See [Color system](/concepts/color-system/) for how the generator works. + +## 1. Install the generator + +`@skillsoft/gamut-brand` runs at build time only, so install it as a dev dependency, on the same version as `@skillsoft/gamut-styles`: + +```sh +yarn add -D @skillsoft/gamut-brand ``` -## 1. Start from `coreTheme` +## 2. Write the brand -Extend `coreTheme` unless you're certain you have a full replacement for every token — see [Themes](/foundations/themes/) for what Core already provides: +Only `name` and `hues.primary` are required: -```tsx -import { createTheme } from '@skillsoft/variance'; -import { coreTheme } from '@skillsoft/gamut-styles'; +```ts +// src/theme/acme.brand.ts +import { defineBrand } from '@skillsoft/gamut-brand'; -const myCustomTheme = createTheme({ - ...coreTheme, - // your overrides here +export default defineBrand({ + name: 'acme', + hues: { primary: '#0A5CFF', accent: '#FFB000' }, }); ``` -## 2. Define a color palette +`name` becomes the brand's `data-brand` attribute and its output folder: letters, digits and `_`, starting with a letter. -Build an object of your brand's raw colors — usually a `brand` object, plus a numbered `50`–`900` scale per hue: +`hues` takes a hue in degrees, or a color to take the hue from, for each of eight slots: `primary`, `neutral-light`, `neutral-dark`, `accent`, `accent-alt`, `danger`, `warning` and `success`. Slots you leave out are filled in: neutrals from the primary's hue, and status and accent slots from Gamut's defaults, so red still means error. -```tsx -const myColorPalette = { - brand: { - primary: '#004C54', - secondary: '#000000', - black: '#000000', - white: '#FFFFFF', - }, - kelly: { - 50: '#E6FFF7', - 500: '#00B388', - 900: '#004D3D', - // ...the rest of the scale - }, - success: '#10B981', - warning: '#F59E0B', - error: '#DC2626', -}; - -const myTheme = createTheme({ ...coreTheme }).addColors(myColorPalette); +Only a color's hue is kept. `#0A5CFF` means "this blue's hue", and the generator sets how light and how colorful each grade is, which is what keeps contrast the same for every brand. To start from one of Gamut's brands, spread it: + +```ts +import { defineBrand, skillsoftBrand } from '@skillsoft/gamut-brand'; + +export default defineBrand({ + ...skillsoftBrand, + name: 'acme', + hues: { ...skillsoftBrand.hues, primary: '#0A5CFF' }, +}); ``` -## 3. Map colors to semantic tokens per color mode +### Optional settings -`.addColorModes` maps your palette onto the same semantic aliases Gamut components already read from — `text`, `background`, `primary`, `secondary`, `border`, and the rest — once per color mode. See [Color modes](/concepts/color-modes/) for what each alias means: +- `initialMode: 'dark'` starts pages in dark mode. The default is `'light'`. +- `overrides` keeps colors the generator wouldn't produce. Use them sparingly; each one still goes through every check. -```tsx -const myTheme = createTheme({ ...coreTheme }) - .addColors(myColorPalette) - .addColorModes('light', { - light: { - text: { _: 'brand-black', secondary: 'silver-700' }, - background: { _: 'brand-white', primary: 'kelly-50' }, - primary: { _: 'brand-primary', hover: 'kelly-700' }, - border: { primary: 'kelly-500', secondary: 'kelly-200' }, - // ... - }, - dark: { - text: { _: 'brand-white', secondary: 'silver-400' }, - background: { _: 'brand-black', primary: 'midnight-800' }, - primary: { _: 'brand-accent', hover: 'silver-400' }, - border: { primary: 'midnight-600', secondary: 'midnight-700' }, - // ... - }, - }); +```ts +overrides: { + // An exact color for one palette step. Pick the grade nearest its lightness. + palette: { 'accent-300': '#FFB000' }, + // A role pointed at another palette color in one mode. + roles: { dark: { 'action-primary': { slot: 'accent', grade: 300 } } }, + // A gradient's circles moved to another slot. + gradients: { 'surface-brand': { accent: 'accent-alt' } }, +}, ``` -## 4. Override or add scales +`defineBrand` is typed, so a misspelled slot, role or palette step fails to compile. -Override an existing scale — `spacing`, `fontFamily`, `fontWeight`, and the rest — directly in the initial `createTheme()` object. Reach for `.addScale()` only for a genuinely new scale that doesn't already exist on `coreTheme`: +## 3. Generate the files -```tsx -const myTheme = createTheme({ - ...coreTheme, - fontFamily: { ...coreTheme.fontFamily, base: '"Roboto", sans-serif' }, - spacing: { ...coreTheme.spacing, xs: 4, sm: 8, md: 16 }, -}) - .addColors(myColorPalette) - .addColorModes('light', colorModeConfig) - .addScale('shadows', ({ colors }) => ({ - sm: `0 1px 2px ${colors['shadow-primary']}`, - md: `0 4px 6px ${colors['shadow-secondary']}`, - })); +```sh +gamut-brand build src/theme/acme.brand.ts +``` + +This writes `src/theme/acme/`: + +| File | What it is | +| -------------------------------------------------------------- | --------------------------------------------------------------------------------- | +| `values.ts` | The palette, roles and the brand's CSS as typed constants, for `createBrandTheme` | +| `tokens.css` | The brand's `--color-*` and `--gradient-*` custom properties, and nothing else | +| `palette.tokens.json`, `light.tokens.json`, `dark.tokens.json` | DTCG JSON for Figma and other design tools | + +Check the folder in, like any generated source. + +A brand that fails a contrast check isn't written. The error names the check, its worst value and where: + +``` +refusing to generate "acme"; failed checks: + text-inverse ≥ 4.5:1: 1.04 at light: action-primary + action-primary ≥ 3:1: 1.04 at light: surface-sunken ``` -## 5. Convert scales to CSS variables +Pick another hue, or change the override that caused it, and build again. -`.createScaleVariables` turns a scale into real CSS custom properties, for better runtime performance: +## 4. Keep the files current + +Add the build to your scripts: + +```json title="package.json" +{ + "scripts": { + "brand": "gamut-brand build src/theme/acme.brand.ts", + "brand:watch": "gamut-brand build src/theme/acme.brand.ts --watch", + "brand:check": "gamut-brand build src/theme/acme.brand.ts --check" + } +} +``` + +Run `--watch` next to your dev server. It regenerates when the brand file, or a file next to it, changes, and only rewrites files whose contents changed. Run `--check` in CI: it writes nothing, and fails when the files are out of date, including after an upgrade of `@skillsoft/gamut-brand`. `--out ` writes somewhere other than a folder named after the brand. + +## 5. Build the theme + +`createBrandTheme` takes the generated values and everything about the brand that isn't color: + +```ts +// src/theme/index.ts +import { + createBrandTheme, + fontWeightMediumTitle, + percipioFontFamily, + softElevation, +} from '@skillsoft/gamut-styles'; + +import * as values from './acme/values'; + +export const acmeTheme = createBrandTheme(values, { + name: 'acme', + fontFamily: percipioFontFamily, + fontWeight: fontWeightMediumTitle, + elevation: softElevation, +}); +``` + +| Option | What it sets | +| ------------- | ----------------------------------------------------------------------------------------------------------------- | +| `name` | The theme's name | +| `fontFamily` | Every font family key Gamut uses. `percipioFontFamily` is Skillsoft's | +| `fontWeight` | Every font weight key, including `title`. `fontWeightMediumTitle` sets titles to 500 | +| `elevation` | How shadows are drawn. `softElevation` is the soft shadow; `offsetElevation` is Original Codecademy's hard offset | +| `borderRadii` | Optional. Defaults to Gamut's radii | + +Shadow colors come from the brand's `shadow-key` and `shadow-ambient` roles, so an elevation works with any brand. + +## 6. Use it + +Pass the theme to `GamutProvider`. It puts the brand's CSS on the page, so the app loads nothing else: ```tsx -const myTheme = createTheme({ ...coreTheme }) - .addColors(myColorPalette) - .addColorModes('light', colorModeConfig) - .addScale('shadows', shadowConfig) - .createScaleVariables('shadows') // creates --shadow-sm, --shadow-md, ... - .addName('my-custom-theme') - .build(); + + + +``` + +Declare the Emotion theme type once, as for any Gamut app. Every brand theme shares the `SkillsoftTheme` type: + +```ts title="emotion.d.ts" +import '@emotion/react'; +import type { SkillsoftTheme } from '@skillsoft/gamut-styles'; + +declare module '@emotion/react' { + export interface Theme extends SkillsoftTheme {} +} ``` -## Using your theme +`` then compiles, and `` doesn't. + +A page without React loads the generated `acme/tokens.css` instead. -Follow [Installation](/getting-started/installation/) to wire up `GamutProvider` with your new theme, the same way you would with any existing one. +## Previewing in Gamut's Storybook -To preview it against real components in Storybook before shipping, register it in the theme switcher: +To preview a brand against real components in Gamut's own Storybook, add its theme to the theme switcher: ```tsx // packages/.storybook/theming/GamutThemeProvider.tsx const themeMap = { - core: coreTheme, - admin: adminTheme, - lxStudio: lxStudioTheme, - 'your-theme-here': yourCustomTheme, + // ...Gamut's themes + acme: acmeTheme, } as const; ``` -```tsx -// packages/.storybook/preview.ts -theme: { - name: 'Theme', - defaultValue: 'core', - toolbar: { - icon: 'paintbrush', - items: [ - { value: 'core', title: 'Core' }, - { value: 'your-theme-here', title: 'Custom Theme' }, - ], - }, -}, +```ts +// packages/.storybook/preview.ts, under globalTypes.theme.toolbar.items +{ value: 'acme', title: 'Acme' }, ``` ## Best practices -- Replace every token, or extend from `coreTheme` — a partial theme breaks compatibility with existing components. -- Override an existing scale in `createTheme()`'s initial object; reach for `.addScale()` only for scales that don't already exist. -- Map your palette to semantic color names (`primary`, `secondary`, and the rest), not just raw brand colors. -- Provide both light and dark color modes. -- Convert frequently-used scales to CSS variables for performance. -- Test the theme against real Gamut components before shipping it. +- Supply as few hues as you need. Every hue you supply is one more you have to keep in step with your brand. +- Prefer a hue over an override. Overrides are for a color that has to be exact, such as a logo color. +- Use roles in your own code too, never palette colors. A palette color doesn't change with the mode. +- Check both modes in Storybook before shipping. diff --git a/packages/gamut-docs/src/content/docs/guides/supporting-dark-mode.md b/packages/gamut-docs/src/content/docs/guides/supporting-dark-mode.md index 3a2333aaf1..3e4a187022 100644 --- a/packages/gamut-docs/src/content/docs/guides/supporting-dark-mode.md +++ b/packages/gamut-docs/src/content/docs/guides/supporting-dark-mode.md @@ -3,7 +3,7 @@ title: Supporting dark mode description: Make a page or component work correctly in both color modes. --- -Gamut components are built on semantic color aliases (`text`, `background`, `primary`, `secondary`, and more — see [Color modes](/concepts/color-modes/) for why), so most components support both color modes automatically, with no extra work. This guide covers the parts that need you to actually do something. +Gamut components are built on color roles (`text-default`, `surface-raised`, `action-primary` and the rest; see [Color modes](/concepts/color-modes/) for why), so most components support both color modes with no extra work. This guide covers the parts that need you to do something. ## Setting a color mode @@ -22,26 +22,30 @@ const Page = ({ children }) => {children}; ## Setting a background without guessing the mode -Use `` instead of picking a color mode by hand for a section's background — it checks the contrast between the background color you give it and the current mode's text color, and switches to an accessible mode automatically if the combination wouldn't pass: +Use `` instead of picking a color mode by hand for a section's background. It paints the color you give it and switches the mode inside to whichever one's text reads better on that color: ```tsx import { Background } from '@skillsoft/gamut-styles'; -const Page = ({ children }) => {children}; +const Page = ({ children }) => ( + {children} +); ``` -`` establishes a new color context for everything inside it, so you can safely nest one background inside another — a dark section can contain its own lighter card, for example, and each still resolves its own aliases correctly. +The choice is made at build time: for every opaque palette color, the color system records whether light-mode or dark-mode content reads better on it, and `Background` looks the answer up. -The color a `` resolves to is exposed as the `background-current` theme variable — reach for it when a descendant needs to reference its ancestor's background directly, for example to simulate transparency against it. +`` establishes a new color context for everything inside it, so you can safely nest one background inside another. A dark section can contain its own lighter card, and each still resolves its own roles correctly. + +The color a `` paints is exposed as the `background-current` theme variable (`--color-background-current` in CSS). Reach for it when a descendant needs to reference its ancestor's background directly, for example to simulate transparency against it. ## Reading the current mode in JS -Reach for these only when you need the mode value itself, not just correctly-themed styles: +Reach for these only when you need the mode value itself, not just correctly themed styles: -- `useColorModes()` — returns `[mode, modeColors, modes, getColorValue]`, for when you need every mode's values, not just the active one. -- `useCurrentMode(mode?)` — returns just the active mode key, or lets you override it. -- `usePrefersDarkMode()` — returns a boolean from the reader's OS-level `prefers-color-scheme: dark` media query, independent of whatever `` is actually active. +- `useColorModes()` returns `[mode, modeColors, modes, getColorValue]`, for when you need every mode's values, not just the active one. +- `useCurrentMode(mode?)` returns just the active mode key, or lets you override it. +- `usePrefersDarkMode()` returns a boolean from the reader's OS-level `prefers-color-scheme: dark` media query, independent of whatever `` is active. ## Checking your work -Toggle color mode with Storybook's Color Mode selector while reviewing a component or page — a component built entirely from semantic aliases and system props should need no other changes to read correctly in both modes. If something looks wrong in one mode only, that's usually a raw color value that should have been a semantic alias instead. +Toggle color mode with Storybook's Color Mode selector while reviewing a component or page. A component built entirely from roles and system props should need no other changes to read correctly in both modes. If something looks wrong in one mode only, it's usually a palette color or a raw value that should have been a role. A palette color, such as `palette-neutral-light-100`, is the same in every mode, so it doesn't change when the mode does. diff --git a/packages/gamut-docs/src/content/docs/guides/theming-your-app.md b/packages/gamut-docs/src/content/docs/guides/theming-your-app.md index 7bb853d736..20338449fa 100644 --- a/packages/gamut-docs/src/content/docs/guides/theming-your-app.md +++ b/packages/gamut-docs/src/content/docs/guides/theming-your-app.md @@ -3,25 +3,36 @@ title: Theming your app description: Choose and wire up a Gamut theme for your application. --- -Every Emotion component in Gamut has typed access to the current theme's tokens, without any extra imports — most directly through the `theme` prop every styled component receives, or through the `theme` object imported straight from `@skillsoft/gamut-styles`. +Every Emotion component in Gamut has typed access to the current theme's tokens, without any extra imports: through the `theme` prop every styled component receives, or through the `theme` object imported from `@skillsoft/gamut-styles`. ## 1. Choose a theme -See [Themes](/foundations/themes/) for the available palettes (Core, Admin, LX Studio, Platform) and what each one is for. Use Storybook's Theme Switcher (paintbrush icon in the toolbar) to preview your components across every theme before committing to one, paired with the Color Mode selector to check both light and dark variants. +See [Themes](/foundations/themes/) for the themes Gamut ships (Skillsoft, Original Codecademy, Admin, Platform, LX Studio) and what each one is for. Use Storybook's Theme Switcher (paintbrush icon in the toolbar) to preview your components in each theme before committing to one, and the Color Mode selector to check light and dark. ## 2. Wire up the theme -`GamutProvider` (covered in [Installation](/getting-started/installation/)) already puts the right theme's values on Emotion's context for you. From there, reach a token: +Pass the theme to `GamutProvider` (covered in [Installation](/getting-started/installation/)). It puts the theme's values on Emotion's context and its brand's colors on the page: + +```tsx +import { + GamutProvider, + originalCodecademyTheme, +} from '@skillsoft/gamut-styles'; + +export const App = ({ children }) => ( + {children} +); +``` + +Without a `theme`, `GamutProvider` uses `skillsoftTheme`. From there, reach a token: ```tsx import { css } from '@skillsoft/gamut-styles'; import styled from '@emotion/styled'; -// Preferred: through a system prop -const Box = styled.div(css({ bg: 'navy-400', p: 4 })); - -// Preferred: through a ColorMode semantic alias -const OtherCoolThing = styled.div(css({ color: 'primary', p: 4 })); +// Preferred: through a system prop, with a color role +const Panel = styled.div(css({ bg: 'surface-raised', p: 4 })); +const Callout = styled.div(css({ color: 'action-primary', p: 4 })); ``` ```tsx @@ -29,14 +40,14 @@ const OtherCoolThing = styled.div(css({ color: 'primary', p: 4 })); import styled from '@emotion/styled'; const styles = styled.div` - color: ${({ theme }) => theme.colors.blue}; + color: ${({ theme }) => theme.colors['text-subtle']}; `; ``` -Prefer the first form — a [system prop](/foundations/system-props/) — whenever one exists for what you're styling; it's type-checked against the active theme's scales, so a typo or an out-of-range value is a compile error instead of a silent fallback. +Prefer the first form, a [system prop](/foundations/system-props/), whenever one exists for what you're styling. It's type-checked against the theme's scales, so a typo or an out-of-range value is a compile error instead of a silent fallback. ## 3. Check your work across themes -Re-open the Theme Switcher and step through every theme your app might run under, in both color modes. A component built entirely from semantic aliases and system props should need no extra work to look right everywhere; if something looks off in one theme, that's usually a sign a raw value snuck in somewhere it should have been a token. +Re-open the Theme Switcher and step through every theme your app might run under, in both color modes. A component built entirely from roles and system props should need no extra work to look right everywhere. If something looks off in one theme, a raw value or a palette color usually snuck in where a role belonged. -See [Design tokens](/foundations/design-tokens/) for the full list of token categories, and [Color modes](/concepts/color-modes/) for how color mode composes with theme choice. +See [Design tokens](/foundations/design-tokens/) for the token categories, [Color modes](/concepts/color-modes/) for how color mode combines with a brand, and [Color system](/concepts/color-system/#pick-a-role-by-its-job) for which role fits which job. diff --git a/packages/gamut-docs/src/styles/gamut-core-theme.css b/packages/gamut-docs/src/styles/gamut-core-theme.css deleted file mode 100644 index 50cc69e2ca..0000000000 --- a/packages/gamut-docs/src/styles/gamut-core-theme.css +++ /dev/null @@ -1,84 +0,0 @@ -/** - * Custom Starlight color theme derived from Gamut's `coreTheme` - * (packages/gamut-styles/src/themes/core.ts). - * - * Starlight themes are just overrides of its CSS custom properties (see - * https://starlight.astro.build/guides/css-and-tailwind/#theming). Each - * variable below is paired with the coreTheme color-mode token it stands in - * for, so this file can be re-derived if coreTheme's palette changes. - * - * Only colors are wired up here — coreTheme's typography (fontFamily) relies - * on licensed, non-self-hosted fonts (Apercu/Suisse) that this site doesn't - * load, so Starlight's default font stack is left in place. - */ - -:root[data-theme="light"] { - /* gray-1..7: coreTheme's light-mode navy scale, most-to-least intense */ - --sl-color-gray-1: #0a0d1c; /* navy-900 — text.accent */ - --sl-color-gray-2: #10162f; /* navy-800 — text._ (body text) */ - --sl-color-gray-3: rgba(16, 22, 47, 0.86); /* navy-700 */ - --sl-color-gray-4: rgba(16, 22, 47, 0.75); /* navy-600 — border.secondary */ - --sl-color-gray-5: rgba( - 16, - 22, - 47, - 0.28 - ); /* navy-300 — border.tertiary (hairline) */ - --sl-color-gray-6: rgba( - 16, - 22, - 47, - 0.12 - ); /* navy-200 — subtle bg tint (inline code) */ - --sl-color-gray-7: rgba( - 16, - 22, - 47, - 0.04 - ); /* navy-100 — background.selected */ - - /* white/black are Starlight's text/bg endpoints, inverted per mode */ - --sl-color-white: #0a0d1c; /* navy-900 — heading text */ - --sl-color-black: #ffffff; /* background._ — page background */ - - /* accent: primary._ / primary.hover (hyper) */ - --sl-color-accent-low: color-mix(in srgb, #3a10e5 10%, white); - --sl-color-accent: #3a10e5; /* hyper-500 */ - --sl-color-accent-high: color-mix(in srgb, #3a10e5 65%, black); - - /* background.primary — a warm chrome tone behind the top nav, distinct - from the white content canvas (background._) */ - --sl-color-bg-nav: #fff0e5; /* beige */ -} - -:root[data-theme="dark"] { - /* gray-1..6: coreTheme's dark-mode white scale, most-to-least intense */ - --sl-color-gray-1: #ffffff; /* white — text._ */ - --sl-color-gray-2: rgba(255, 255, 255, 0.8); /* white-700 */ - --sl-color-gray-3: rgba(255, 255, 255, 0.65); /* white-600 — text.secondary */ - --sl-color-gray-4: rgba(255, 255, 255, 0.5); /* white-500 — border.disabled */ - --sl-color-gray-5: rgba( - 255, - 255, - 255, - 0.2 - ); /* white-300 — border.tertiary (hairline) */ - --sl-color-gray-6: rgba( - 255, - 255, - 255, - 0.09 - ); /* white-200 — subtle bg tint (inline code) */ - - --sl-color-white: #ffffff; /* text._ — heading text */ - --sl-color-black: #10162f; /* navy-800 — background._ (page background) */ - - /* accent: primary._ / primary.hover (yellow) */ - --sl-color-accent-low: color-mix(in srgb, #ffd300 20%, black); - --sl-color-accent: #ffd300; /* yellow-500 */ - --sl-color-accent-high: color-mix(in srgb, #ffd300 85%, white); - - /* background.primary — a deeper chrome tone behind the top nav, distinct - from the navy-800 content canvas (background._) */ - --sl-color-bg-nav: #0a0d1c; /* navy-900 */ -} diff --git a/packages/gamut-docs/src/styles/gamut-theme.css b/packages/gamut-docs/src/styles/gamut-theme.css new file mode 100644 index 0000000000..7775670aa8 --- /dev/null +++ b/packages/gamut-docs/src/styles/gamut-theme.css @@ -0,0 +1,241 @@ +/* + * Starlight's colors, taken from the Skillsoft brand of Gamut's color system. + * + * `@skillsoft/gamut-styles/tokens.css`, loaded before this file, puts the + * brand's palette on `:root`. Starlight switches modes with `data-theme`, not + * Gamut's `data-color-mode`, so the roles' mode blocks don't apply here. + * Instead each Starlight variable points at the palette color its Gamut role + * uses in that mode, named in the comment beside it. If a role's mapping + * changes, update the line here. + * + * Starlight themes are overrides of its CSS custom properties + * (https://starlight.astro.build/guides/css-and-tailwind/#theming). + * + * Fonts match the skillsoft theme's percipioFontFamily: Skillsoft Text for + * body, Skillsoft Sans for accents, Roboto for system, Roboto Mono for code. + * The files are the ones gamut-styles loads from its CDN (remoteAssets/fonts.ts). + * Open question: whether the docs site may serve them publicly. See the note + * in astro.config.mjs. + */ + +/* Skillsoft Text (base) */ +@font-face { + font-display: swap; + font-family: 'Skillsoft Text'; + font-style: normal; + font-weight: 400; + src: url('https://www.codecademy.com/gamut/SkillsoftText-Regular.woff2') format('woff2'), url('https://www.codecademy.com/gamut/SkillsoftText-Regular.woff') format('woff'); +} +@font-face { + font-display: swap; + font-family: 'Skillsoft Text'; + font-style: italic; + font-weight: 400; + src: url('https://www.codecademy.com/gamut/SkillsoftText-RegularItalic.woff2') format('woff2'), url('https://www.codecademy.com/gamut/SkillsoftText-RegularItalic.woff') format('woff'); +} +@font-face { + font-display: swap; + font-family: 'Skillsoft Text'; + font-style: normal; + font-weight: 500; + src: url('https://www.codecademy.com/gamut/SkillsoftText-Medium.woff2') format('woff2'), url('https://www.codecademy.com/gamut/SkillsoftText-Medium.woff') format('woff'); +} +@font-face { + font-display: swap; + font-family: 'Skillsoft Text'; + font-style: italic; + font-weight: 500; + src: url('https://www.codecademy.com/gamut/SkillsoftText-MediumItalic.woff2') format('woff2'), url('https://www.codecademy.com/gamut/SkillsoftText-MediumItalic.woff') format('woff'); +} +@font-face { + font-display: swap; + font-family: 'Skillsoft Text'; + font-style: normal; + font-weight: 700; + src: url('https://www.codecademy.com/gamut/SkillsoftText-Bold.woff2') format('woff2'), url('https://www.codecademy.com/gamut/SkillsoftText-Bold.woff') format('woff'); +} +@font-face { + font-display: swap; + font-family: 'Skillsoft Text'; + font-style: italic; + font-weight: 700; + src: url('https://www.codecademy.com/gamut/SkillsoftText-BoldItalic.woff2') format('woff2'), url('https://www.codecademy.com/gamut/SkillsoftText-BoldItalic.woff') format('woff'); +} + +/* Skillsoft Sans (accent) */ +@font-face { + font-display: swap; + font-family: 'Skillsoft Sans'; + font-style: normal; + font-weight: 400; + src: url('https://www.codecademy.com/gamut/SkillsoftSans-Regular.woff2') format('woff2'), url('https://www.codecademy.com/gamut/SkillsoftSans-Regular.woff') format('woff'); +} +@font-face { + font-display: swap; + font-family: 'Skillsoft Sans'; + font-style: italic; + font-weight: 400; + src: url('https://www.codecademy.com/gamut/SkillsoftSans-RegularItalic.woff2') format('woff2'), url('https://www.codecademy.com/gamut/SkillsoftSans-RegularItalic.woff') format('woff'); +} +@font-face { + font-display: swap; + font-family: 'Skillsoft Sans'; + font-style: normal; + font-weight: 500; + src: url('https://www.codecademy.com/gamut/SkillsoftSans-Medium.woff2') format('woff2'), url('https://www.codecademy.com/gamut/SkillsoftSans-Medium.woff') format('woff'); +} +@font-face { + font-display: swap; + font-family: 'Skillsoft Sans'; + font-style: italic; + font-weight: 500; + src: url('https://www.codecademy.com/gamut/SkillsoftSans-MediumItalic.woff2') format('woff2'), url('https://www.codecademy.com/gamut/SkillsoftSans-MediumItalic.woff') format('woff'); +} +@font-face { + font-display: swap; + font-family: 'Skillsoft Sans'; + font-style: normal; + font-weight: 700; + src: url('https://www.codecademy.com/gamut/SkillsoftSans-Bold.woff2') format('woff2'), url('https://www.codecademy.com/gamut/SkillsoftSans-Bold.woff') format('woff'); +} +@font-face { + font-display: swap; + font-family: 'Skillsoft Sans'; + font-style: italic; + font-weight: 700; + src: url('https://www.codecademy.com/gamut/SkillsoftSans-BoldItalic.woff2') format('woff2'), url('https://www.codecademy.com/gamut/SkillsoftSans-BoldItalic.woff') format('woff'); +} + +/* Roboto (system) */ +@font-face { + font-display: swap; + font-family: 'Roboto'; + font-style: normal; + font-weight: 400; + src: url('https://www.codecademy.com/gamut/roboto-regular.woff2') format('woff2'), url('https://www.codecademy.com/gamut/roboto-regular.woff') format('woff'); +} +@font-face { + font-display: swap; + font-family: 'Roboto'; + font-style: italic; + font-weight: 400; + src: url('https://www.codecademy.com/gamut/roboto-italic.woff2') format('woff2'), url('https://www.codecademy.com/gamut/roboto-italic.woff') format('woff'); +} +@font-face { + font-display: swap; + font-family: 'Roboto'; + font-style: normal; + font-weight: 500; + src: url('https://www.codecademy.com/gamut/roboto-bold.woff2') format('woff2'), url('https://www.codecademy.com/gamut/roboto-bold.woff') format('woff'); +} +@font-face { + font-display: swap; + font-family: 'Roboto'; + font-style: italic; + font-weight: 500; + src: url('https://www.codecademy.com/gamut/roboto-bold-italic.woff2') format('woff2'), url('https://www.codecademy.com/gamut/roboto-bold-italic.woff') format('woff'); +} +@font-face { + font-display: swap; + font-family: 'Roboto'; + font-style: normal; + font-weight: 700; + src: url('https://www.codecademy.com/gamut/roboto-bold.woff2') format('woff2'), url('https://www.codecademy.com/gamut/roboto-bold.woff') format('woff'); +} +@font-face { + font-display: swap; + font-family: 'Roboto'; + font-style: italic; + font-weight: 700; + src: url('https://www.codecademy.com/gamut/roboto-bold-italic.woff2') format('woff2'), url('https://www.codecademy.com/gamut/roboto-bold-italic.woff') format('woff'); +} + +/* Roboto Mono (code) */ +@font-face { + font-display: swap; + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 400; + src: url('https://www.codecademy.com/gamut/roboto-mono-regular.woff2') format('woff2'), url('https://www.codecademy.com/gamut/roboto-mono-regular.woff') format('woff'); +} +@font-face { + font-display: swap; + font-family: 'Roboto Mono'; + font-style: normal; + font-weight: 700; + src: url('https://www.codecademy.com/gamut/roboto-mono-bold.woff2') format('woff2'), url('https://www.codecademy.com/gamut/roboto-mono-bold.woff') format('woff'); +} + +:root { + /* Starlight's font variables, set to the skillsoft theme's families */ + --sl-font: 'Skillsoft Text', -apple-system, BlinkMacSystemFont, 'Segoe UI', + Roboto, sans-serif; + --sl-font-mono: 'Roboto Mono', monospace; +} + +:root[data-theme="light"] { + /* gray-1..7, most to least intense */ + /* border-strong */ + --sl-color-gray-1: var(--color-palette-neutral-dark-1100); + /* text-default */ + --sl-color-gray-2: var(--color-palette-neutral-dark-1000); + /* text-subtle */ + --sl-color-gray-3: var(--color-palette-neutral-dark-800); + /* border-default */ + --sl-color-gray-4: var(--color-palette-neutral-dark-600); + /* border-subtle */ + --sl-color-gray-5: var(--color-palette-neutral-dark-300); + /* surface-sunken */ + --sl-color-gray-6: var(--color-palette-neutral-light-200); + /* surface-default */ + --sl-color-gray-7: var(--color-palette-neutral-light-100); + + /* Starlight's text and background endpoints */ + /* text-default */ + --sl-color-white: var(--color-palette-neutral-dark-1000); + /* surface-default */ + --sl-color-black: var(--color-palette-neutral-light-100); + + --sl-color-accent-low: var(--color-palette-primary-100); + /* action-primary */ + --sl-color-accent: var(--color-palette-primary-800); + /* action-primary-pressed */ + --sl-color-accent-high: var(--color-palette-primary-1000); + + /* surface-raised */ + + --sl-color-bg-nav: var(--color-white); +} + +:root[data-theme="dark"] { + /* border-strong */ + --sl-color-gray-1: var(--color-palette-neutral-light-100); + /* text-default */ + --sl-color-gray-2: var(--color-palette-neutral-light-200); + /* text-subtle */ + --sl-color-gray-3: var(--color-palette-neutral-light-400); + /* border-default */ + --sl-color-gray-4: var(--color-palette-neutral-light-600); + /* border-subtle */ + --sl-color-gray-5: var(--color-palette-neutral-light-900); + /* surface-raised */ + --sl-color-gray-6: var(--color-palette-neutral-dark-1000); + /* surface-default */ + --sl-color-gray-7: var(--color-palette-neutral-dark-1100); + + /* border-strong */ + + --sl-color-white: var(--color-palette-neutral-light-100); + /* surface-default */ + --sl-color-black: var(--color-palette-neutral-dark-1100); + + --sl-color-accent-low: var(--color-palette-primary-1100); + /* action-primary */ + --sl-color-accent: var(--color-palette-primary-400); + /* action-primary-pressed */ + --sl-color-accent-high: var(--color-palette-primary-200); + + /* surface-sunken */ + + --sl-color-bg-nav: var(--color-black); +} diff --git a/packages/gamut/src/Badge/Badge.stories.tsx b/packages/gamut/src/Badge/Badge.stories.tsx index 276515d680..3da0342c1e 100644 --- a/packages/gamut/src/Badge/Badge.stories.tsx +++ b/packages/gamut/src/Badge/Badge.stories.tsx @@ -66,7 +66,7 @@ export const Custom: Story = { render: (args) => (