diff --git a/.changeset/gamut-codemods-color-roles.md b/.changeset/gamut-codemods-color-roles.md new file mode 100644 index 0000000000..d9b3557aa5 --- /dev/null +++ b/.changeset/gamut-codemods-color-roles.md @@ -0,0 +1,17 @@ +--- +'@skillsoft/gamut-codemods': minor +--- + +Add a `color-roles` preset that moves Gamut color names onto the generated color system's roles, using design's migration map. + +- Renames and merges are applied. Names that split, were retired or are still pending stay in place, with a `/* color-roles: … */` comment carrying design's rule, and keep failing the type check until someone picks. +- Old palette names (`navy`, `gray-200`) get a `color-roles:` comment and a warning that names where the color is used (a prop, a `theme.colors` lookup, a CSS variable), so the review queue is in the source. Theme lookups are found through `props.theme`, `useTheme()`, a variable holding `theme.colors`, and `colors` or color keys destructured from the theme. Color names built at runtime get a warning. +- Some palette names now get a default role in a color prop, where the codemod knows the use: `red` becomes an error role (`surface-error` for a fill, `text-error` otherwise), `green` a success role, `white` `surface-raised`, `text-inverse` or `border-subtle`, `navy` the nearest role by brightness, `hyper` (the old primary) `action-primary`, and `blue-500` text (links and focus) `action-primary`. Blue fills and borders stay warnings, since they mix interactive and decorative uses. Greys follow their use: `gray-100` and `gray-200` to `surface-default` and `surface-sunken` as fills, `text-subtle` as text for `gray-600` and darker, and `border-subtle` or `border-default` as borders. A theme lookup, `themed()` call or CSS variable takes the same defaults when the CSS property or style key it is the value of says the use (`background-color: ${theme.colors['navy-100']}` becomes `surface-default`). Dark navy fills, colors inside a function like a gradient, and properties other than fills, text and borders stay warnings. The defaults are in `presets/color-roles/decisions.ts`. +- Old `--color-*` CSS variables are renamed to `--color-` in `.css`, `.scss` and `.less` files and inside JS strings and template literals; splits get the same comment. The type check can't see stylesheets, so the leftovers report lists every one left. Indented-syntax `.sass` isn't rewritten. +- Card's `variant` moves onto design's two: `white`, `beige` and `navy` become `default`, `yellow` and `hyper` become `brand`. A `navy` card gets a comment, since it now renders light. +- Old theme names move to the brand themes that replace them: `percipioTheme` → `skillsoftTheme`, `coreTheme` → `originalCodecademyTheme`, and the `PercipioTheme` type → `SkillsoftTheme`. An aliased import (`percipioTheme as theme`) only changes the imported name. A `CoreTheme` type gets a comment pointing at `SkillsoftTheme`, which types every brand. +- Follows design's map: `shadow-primary` and `shadow-secondary` split onto `shadow-key` and `shadow-ambient`. +- Presets can bring their own manifest type, pre-filter and leftovers report. `scope-swap` is unchanged. +- The source run skips build output and caches (`.next`, `.nx`, `coverage`, `tmp`, plus the dirs it already skipped), so a dry run over an app no longer reads its bundles. `tsconfig-dom` warns only where gamut is imported. +- `scope-swap`'s `package-json` migration adds the peers the new packages need at runtime and no longer install: `@vidstack/react` and `react-player` for `@skillsoft/gamut`, at the ranges Gamut declares, only when the app imports `Video` from gamut and doesn't list them yet. It doesn't add `stylis`: `@emotion/cache` brings its own copy, and a second root copy can break emotion's style inserts. +- Themes differ in their spacing scale. In our repo, numeric spacing values (`padding`, `border` and similar) failed the type check under `skillsoftTheme` and passed under `originalCodecademyTheme`. Switching the theme changes that scale, so pick the theme the app was on, not the one the codemod's docs suggest. diff --git a/.changeset/gamut-migration-skill.md b/.changeset/gamut-migration-skill.md new file mode 100644 index 0000000000..1e25d72530 --- /dev/null +++ b/.changeset/gamut-migration-skill.md @@ -0,0 +1,5 @@ +--- +'@skillsoft/gamut-agent-tools': minor +--- + +Add the `gamut-migration` agent skill. It covers every `@skillsoft/gamut-codemods` preset: `scope-swap` for the `@codecademy/gamut*` to `@skillsoft/gamut*` move, and `color-roles` for moving color names onto color roles. For each, it explains the warnings, leftovers and comments the codemod leaves, and what to do about them. It replaces the `gamut-scope-swap` skill. diff --git a/.changeset/gamut-scope-swap-skill.md b/.changeset/gamut-scope-swap-skill.md deleted file mode 100644 index 6b3f020472..0000000000 --- a/.changeset/gamut-scope-swap-skill.md +++ /dev/null @@ -1,6 +0,0 @@ ---- -'@skillsoft/gamut-agent-tools': minor -'@skillsoft/gamut-codemods': patch ---- - -Add the `gamut-scope-swap` agent skill. It helps with the `@codecademy/gamut*` to `@skillsoft/gamut*` move alongside the `scope-swap` codemod: it reads the warnings and leftovers, and fixes what the codemod can't rewrite. The codemod README now points to it. diff --git a/packages/gamut-agent-tools/README.md b/packages/gamut-agent-tools/README.md index 1f6b0d595d..a6ff40fbb6 100644 --- a/packages/gamut-agent-tools/README.md +++ b/packages/gamut-agent-tools/README.md @@ -31,9 +31,16 @@ The first time you run `gamut plugin install` or `update`, it installs `@skillso Before large PRs, or when onboarding an existing codebase, run the `gamut-review` skill to audit for Gamut usage — dependencies, setup, import patterns, `styled()` wrapping that bypasses system props, hardcoded colors, bespoke component duplication, and test conventions. -### Moving from `@codecademy/gamut` +### Migrating with `@skillsoft/gamut-codemods` -If your app still depends on `@codecademy/gamut*`, the `gamut-scope-swap` skill helps with the move to `@skillsoft/gamut*`. It works alongside the [`@skillsoft/gamut-codemods`](../gamut-codemods/README.md) `scope-swap` preset. The codemod does the mechanical rewrite. The skill reads what it reports, including warnings, leftovers, and next steps, and helps with the parts it can't rewrite: deep imports, `Video`, renamed Menu exports, tsconfig `dom`, jest mocks, ESLint plugin keys, Module Federation config, and preview builds. It doesn't run the codemod unless you ask it to. +The `gamut-migration` skill helps with each [`@skillsoft/gamut-codemods`](../gamut-codemods/README.md) preset. The codemod does the mechanical rewrite. The skill reads what it reports (warnings, leftovers, and comments), and helps with the parts it can't rewrite. + +- `scope-swap` moves `@codecademy/gamut*` to `@skillsoft/gamut*`. The skill covers deep imports, `Video`, renamed Menu exports, tsconfig `dom`, jest mocks, ESLint plugin keys, Module Federation config, and preview builds. +- `color-roles` moves Gamut color names onto the roles of the color system. The skill covers the splits, palette colors, and runtime names it marks for a person. + +It doesn't run the codemod unless you ask it to. When a preset ships, the skill gets a section for it. + +If your app still depends on `@codecademy/gamut*`, run `scope-swap` first. Install the plugin after the swap. The `gamut` CLI comes from `@skillsoft/gamut`, so that package has to be in the app first. diff --git a/packages/gamut-agent-tools/skills/gamut-scope-swap/BREAKING_CHANGES.md b/packages/gamut-agent-tools/skills/gamut-migration/BREAKING_CHANGES.md similarity index 100% rename from packages/gamut-agent-tools/skills/gamut-scope-swap/BREAKING_CHANGES.md rename to packages/gamut-agent-tools/skills/gamut-migration/BREAKING_CHANGES.md diff --git a/packages/gamut-agent-tools/skills/gamut-scope-swap/NEXT_EMOTION_INTEROP.md b/packages/gamut-agent-tools/skills/gamut-migration/NEXT_EMOTION_INTEROP.md similarity index 100% rename from packages/gamut-agent-tools/skills/gamut-scope-swap/NEXT_EMOTION_INTEROP.md rename to packages/gamut-agent-tools/skills/gamut-migration/NEXT_EMOTION_INTEROP.md diff --git a/packages/gamut-agent-tools/skills/gamut-migration/SKILL.md b/packages/gamut-agent-tools/skills/gamut-migration/SKILL.md new file mode 100644 index 0000000000..90119f75e1 --- /dev/null +++ b/packages/gamut-agent-tools/skills/gamut-migration/SKILL.md @@ -0,0 +1,211 @@ +--- +name: gamut-migration +description: Use this skill when running a @skillsoft/gamut-codemods preset to migrate code, or triaging what it reports. Covers scope-swap (moving an app from @codecademy/gamut* packages to @skillsoft/gamut*, including deep imports, Video, renamed Menu exports, tsconfig dom, jest mocks, ESLint plugin keys, Module Federation shared config, the removed gamut-kit, and preview builds), color-roles (moving color names onto color roles), and any later preset. Not for day-to-day Gamut usage after a migration (see gamut-review) or for building new UI. +--- + +# Gamut Migration + +Help an app move with a `@skillsoft/gamut-codemods` preset. The codemod does the mechanical rewrite. This skill covers what each preset reports, what it leaves for a person, and how to check the result. Read the section for the preset you're running. The Workflow and What not to do apply to all of them. + +## Presets + +| Preset | Use it for | Run order | +| ------------- | ----------------------------------------------------------- | ------------------ | +| `scope-swap` | Moving from `@codecademy/gamut*` to `@skillsoft/gamut*` | First | +| `color-roles` | Moving Gamut color names onto the roles of the color system | After `scope-swap` | + +For a short overview of every breaking change in the scope move, read [BREAKING_CHANGES.md](BREAKING_CHANGES.md). Load it only when you need the full list. + +Sources of truth, in order: + +1. The codemod's README in `@skillsoft/gamut-codemods`, and `npx @skillsoft/gamut-codemods list` for the presets and the migrations in each. +2. The installed `@skillsoft/gamut` type declarations in `node_modules`. Before you suggest an import, confirm the symbol is actually exported there. Don't invent replacements. +3. The rest of the Gamut skills in this plugin, for choosing a replacement component or style API. + +## Workflow (every preset) + +1. **Check the starting state.** Run `git status`. The codemod refuses to write into uncommitted changes unless it gets `--force`. If the tree is dirty, ask the user to commit or stash first. Don't add `--force` on your own. +2. **Preview.** Run `npx @skillsoft/gamut-codemods . --dry`. It prints every file it would change and its warnings, and writes nothing. Run this before a real run. +3. **Run it,** once the user confirms: `npx @skillsoft/gamut-codemods .`. Run `scope-swap` before `color-roles`. Options: + - `--only=a,b` runs a subset of a preset's migrations, by name. + - `--no-report` skips the leftovers report. + - To undo a run, `git checkout .`. That only restores the original state if the tree was clean before the run. +4. **Triage the output in this order.** Warnings first, because some change runtime behavior. Then leftovers and comments. Then next steps. +5. **Verify.** Reinstall with `yarn`, run the formatter, then type-check, lint, test, and build. If the app uses Module Federation, test the host and its remotes together. + +If the codemod has already run, ask the user to paste the warnings and the leftovers list. If they can't, find the old names yourself (for `scope-swap`). Exclude lockfiles and build output: + +```sh +grep -rn "@codecademy/gamut" --exclude-dir=node_modules --exclude-dir=dist --exclude=yarn.lock . +``` + +## Preset: scope-swap + +Moves `@codecademy/gamut*` to `@skillsoft/gamut*`. Its migrations: `deep-imports`, `moved-exports`, `markdown-video-overrides`, `mf-shared`, `eslint-comments`, `scope-rename`, `package-json`, `eslint-config`, `mdx-imports`, `yarnrc`, `tsconfig-dom`, `next-config`. Run `--only=deep-imports,scope-rename` to run a subset. + +### Warnings + +Each warning starts with `[migration-name] file:line`. The migration name tells you what to check. A skipped migration prints `[migration-name] skipped: ` before the run. `eslint-comments` skips itself when the repo has a flat ESLint config (see Leftovers). + +| Migration | Warning starts with | What to do | +| -------------------------- | ------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `deep-imports` | `unmapped deep import '…'` | The codemod has no mapping for this path. Find the symbol in the installed `@skillsoft/gamut` types. If it's exported from the root, import it from there. If it isn't public, don't deep-import the `dist` path. Ask the Gamut team. | +| `deep-imports` | `… has no public replacement` | `ButtonBase` is deliberately private. Use `FillButton`, `StrokeButton`, `TextButton`, `IconButton`, or `CTAButton`. See the `gamut-buttons` skill for which one. | +| `deep-imports` | `… is only partly public` | Only some names from this path are public. Inline the styles, or use system props or `css()`. See `gamut-style-utilities` and `gamut-system-props`. | +| `deep-imports` | `deep import … in a mock or require() needs a manual rewrite` | Rewrite the mock or `require()` path by hand. | +| `deep-imports` | `rewrote … in a mock or require(). That now covers the whole package` | `jest.mock` of a deep path now mocks the whole package. Check the test still mocks what it needs. If the rename list applies, update renamed names too. | +| `moved-exports` | `namespace import uses …` | `import * as Gamut` can't be rewritten safely. Replace it with named imports. `Video` and `VideoProps` come from `@skillsoft/gamut/Video`. | +| `moved-exports` | `'export *' from … no longer re-exports …` | Add an explicit re-export from `@skillsoft/gamut/Video` if other code depends on it. | +| `moved-exports` | `mock of … stubs Video/VideoProps` | Mock `@skillsoft/gamut/Video` instead of the root package. | +| `markdown-video-overrides` | `skipDefaultOverrides is not an object literal` or `… is not a boolean literal` | The codemod couldn't tell whether this `` opted out of iframes or videos. Pass `iframeOverride={Iframe}` and `videoOverride={MarkdownVideo}` (both from `@skillsoft/gamut/Video`) unless it skipped them. | +| `markdown-video-overrides` | `a different import already uses the name Iframe or MarkdownVideo` | Import the overrides under another local name and pass them by hand. | +| `scope-rename` | `'@codecademy/gamut-kit' has no replacement package` | `gamut-kit` is removed, with no `@skillsoft` replacement. Depend on the individual packages it bundled. | +| `scope-rename` | `renamed N package-name string(s) outside imports. Check the diff.` | Review those lines in the diff. They're usually config or log strings, and a few may not be package names at all. | +| `package-json` | `…: replaced '@codecademy/gamut-kit' with its individual packages` | The individual packages are written at the release range (`^`), not at the kit's old version. They all land in the field `gamut-kit` was in, so `@skillsoft/gamut-tests` may end up in `dependencies`. Move it to `devDependencies` if it belongs there. | +| `package-json` | `… is newer than …, the last release … matches` | The app was on a newer upstream release than `@skillsoft` has synced. Expect type errors where the code uses what that release added. Check the upstream CHANGELOG, and ask the Gamut team before working around it. | +| `mf-shared` | `replaced … in Module Federation shared config` | This is a runtime change. Gamut is now actually shared as a singleton, so host and remotes must agree. Update each remote's shared config to match and deploy them together. | +| `next-config` | `` `experimental.esmExternals: false` makes Next require() … `` | A runtime change. Builds can fail when Next collects page data. See [NEXT_EMOTION_INTEROP.md](NEXT_EMOTION_INTEROP.md), then rebuild every Next app the warning names. Removing the flag is necessary but not always enough: an app can still fail at prerender afterwards (`reading 'push'` on a page, `reading 'slice'` on a dynamic route). Build each app and fix each failing route on its own. | +| `tsconfig-dom` | `"lib" has no "dom"` | The root import used to bring in DOM types through `Video`. Add `"dom"` to that tsconfig's `lib` only if type-checking now fails on `document`, `HTMLElement`, `ResizeObserver`, and similar. The codemod warns only in projects that import `@skillsoft/gamut`, so a worker or script project that never imports Gamut doesn't need it. | + +### Leftovers + +The leftovers list shows every line that still names an old package. The codemod doesn't rewrite these, and the regex can produce false positives. Go through them one by one: + +- **Jest `moduleNameMapper` regexes and tsconfig `paths`.** Update them to the `@skillsoft/*` names. A stale mapper makes tests fail to resolve modules. +- **Flat ESLint configs (`eslint.config.*`) and `.eslintrc.js`.** The codemod doesn't rewrite these. Only the package import changes (`import gamut from '@skillsoft/eslint-plugin-gamut'`). The rule prefix and directive prefix must match the key the plugin is registered under, or ESLint reports rules it can't find: + - Flat config: the prefix is the `plugins` key. With `plugins: { gamut }`, rules and directives stay `gamut/`. When the repo has a flat config, `eslint-comments` leaves directives alone. + - Legacy `.eslintrc` / `.eslintrc.json`: `eslint-config` and `eslint-comments` move everything to `plugin:@skillsoft/gamut/...` and `@skillsoft/gamut/`. + - To rename the flat-config key, rename the key, every rule key, and every directive together. +- **Scripts and CI that read `@codecademy/gamut-kit`.** Version-sync scripts like `sync-gamut-deps` read the kit's `package.json` from `node_modules` and exit when it's missing, which fails CI. Delete them, or make them check that every `@skillsoft` Gamut package uses the same version (they're released together). Update the docs that point to them. The CI job that runs the script fails too: search `.github/workflows` for it (for example `sync-gamut-deps --check`), and change or remove that job in the same change. +- **Storybook config, docs, and comments.** Update them or leave them, but know they still say the old name. +- **Code samples in `.mdx`.** Fenced code blocks are left alone on purpose. Update them by hand if they matter. +- **Files the parser skipped.** Every file is parsed as `tsx`, so Flow-typed JavaScript is skipped. Fix any old names left in those files by hand. + +Don't edit `yarn.lock` by hand. Reinstalling updates it. + +### Runs from an older codemod build + +Migrations match the old `@codecademy` names, so running a newer build over a repo that's already been swapped does nothing for code that has already been renamed. If the first run used an older build (a pkg.pr.new preview, say), check by hand what newer builds handle: + +- **Directives under a flat config.** Older builds rewrote `gamut/` directives to `@skillsoft/gamut/` even when the flat config registers the plugin as `gamut`. Change them back. Lint doesn't always flag this, because a directive that names an unknown rule just stops suppressing anything. Current builds list these in the leftovers, with a note, unless a config registers the plugin as `'@skillsoft/gamut'`. +- **Duplicate imports.** Older `deep-imports` builds added a second `import … from '@skillsoft/gamut'` next to the existing one. `eslint --fix` merges them (`import/no-duplicates`). +- **`` iframes and videos.** Current builds skip `markdown-video-overrides` when the repo is already on upstream 74.0.0 or newer, because those apps already pass the overrides where they want them. On an older upstream release, add them as described under `markdown-video-overrides` above. +- **`esmExternals: false` and newer-than-source versions.** Run `npx @skillsoft/gamut-codemods scope-swap . --dry` with the current build. Report-only migrations like `next-config`, `tsconfig-dom`, and `package-json` still warn. + +### Next steps + +After the migrations finish: + +1. Reinstall with `yarn`. +2. Run the formatter and lint autofix (`prettier --write`, then `eslint --fix`). Split imports from `moved-exports` come out in recast's style, and `@skillsoft` sorts differently from `@codecademy`, so import-order rules like `simple-import-sort` fail until you do. +3. Type-check, run tests, and build. +4. If the app uses Module Federation, run the host and every remote together. +5. If the app depends on preview builds, point every `@skillsoft/*` package at the same preview (including `@skillsoft/eslint-plugin-gamut`) and pin them all with `resolutions`. The codemod README has the exact JSON. Published releases don't need it. + +### Common failures + +| Symptom | Likely cause | Fix | +| ----------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `Module '"@skillsoft/gamut"' has no exported member 'Video'` | `Video` was imported from the root | Import from `@skillsoft/gamut/Video`. | +| `Cannot find name 'document'`, `HTMLElement`, or `ResizeObserver` | The affected tsconfig's `lib` has no `"dom"` | Add `"dom"` to that tsconfig's `compilerOptions.lib`. | +| Components render unstyled, or theme values don't apply | Two copies of `@skillsoft/gamut-styles` or `@skillsoft/variance` are installed | Run `yarn why @skillsoft/gamut-styles`. Make every `@skillsoft/*` package resolve to one version. Pin previews with `resolutions`. After a `resolutions` pin, `yarn why` can list two lock locators for one package. Check `node_modules//package.json` for the copies that are actually installed; one copy is fine. | +| `MenuList`, `MenuListItem`, or `IconOptionComponent` is not exported | Menu's `List*` and SelectDropdown's `IconOption` were renamed on the way to the root | Import the new name. Keep the local alias if the code relies on it, e.g. `import { MenuList as List }`. | +| Jest can't resolve `@skillsoft/...` modules, or a mock doesn't apply | A stale `moduleNameMapper` regex, or a mock still points at the root package | Update the mapper. Mock `@skillsoft/gamut/Video` for `Video`. | +| `Cannot find module '@skillsoft/gamut/Video'`, or `MenuList` is missing, right after install | The installed `@skillsoft/gamut` is older than the codemod. A range like `^0.0.1` can resolve to a release cut before these changes | Check `node_modules/@skillsoft/gamut/package.json` and its `exports`. Point at a build that has them (a newer release, or the matching preview), not at the old deep paths. | +| A preview fix doesn't show up after a push, even after `yarn up` | Yarn treats a `@.tgz` URL as fixed. The lockfile entry and the global cache keep the first build it fetched | Delete the `@skillsoft/*` preview entries from `yarn.lock`, the matching `@skillsoft-*-https-*` zips in the Yarn cache (`yarn config get cacheFolder`), and `node_modules/@skillsoft`, then run `yarn`. Check a file you know changed before you trust the type-check. | +| `import/no-duplicates` on `@skillsoft/gamut`, or hundreds of `simple-import-sort` errors | Rewritten imports weren't merged or re-sorted | Run `eslint --fix`. | +| `Cannot find module '@codecademy/gamut/dist/...'` after the run | The file was skipped by the parser, or the path is in a code sample | Rewrite the import by hand, following the rules above. | +| ESLint: `Definition for rule '…' was not found`, or a disable comment does nothing | The plugin key doesn't match the rewritten directives | Make the plugin key match the directive prefix (see Leftovers). | +| Module not found: `@vidstack/react` or `react-player`, after the scope move | The app uses `Video` without the peers it needs. Gamut no longer installs them | `package-json` adds `@vidstack/react` and `react-player` only when the app imports `Video` from gamut, so an app that doesn't use Video doesn't get them. Check its warnings. To add one by hand, use the range Gamut declares: `yarn add @vidstack/react@~1.12.12 react-player@^3.4.0`. | +| Runtime error `Cannot read properties of undefined (reading 'push')` in stylis, from `@emotion/styled` inserting styles | Suspected: two copies of `stylis` in the tree. `@emotion/cache` ships its own, and a root copy at a different version can be picked up for the rest of Gamut. Not confirmed | Run `yarn why stylis`. Remove any root `stylis` the app added by hand; the codemod doesn't add one. If one copy is still at a different version from `@emotion/cache`'s, pin `stylis` in `resolutions` to the version `@emotion/cache` uses, and reload. | +| Remotes load a second copy of Gamut at runtime | Module Federation `shared` still lists old names on a remote | Update that remote's `shared` config and deploy it with the host. | + +## Preset: color-roles + +`color-roles` moves Gamut color names onto the roles of the generated color system. Run it after `scope-swap`, with the same steps as the Workflow: a `--dry` preview first, then a real run once the user confirms, on a clean tree. + +```sh +npx @skillsoft/gamut-codemods color-roles . --dry +``` + +What it rewrites: renamed and merged color names in the color props (JSX and style objects), `theme.colors.x`, `themed('colors.x')`, and old `--color-*` variables in stylesheets and JS strings. Renames and merges are applied. Anything else is left for a person, marked with a `color-roles:` comment or listed as a warning. + +It skips build output (`node_modules`, `dist`, `build`, `coverage`, `.next`, `.nx`, `tmp`) and generated files (`worker-configuration.d.ts`, `next-env.d.ts`), so don't hand-edit those to make the run pass. + +Warnings start with `[color-roles]`, `[color-roles-themes]` or `[color-roles-stylesheets]`. Work through them with these rules: + +- **`'name' splits into …`, `is retired`, or `is pending`.** The name stays, so it fails the type check. The `color-roles:` comment gives design's rule. Pick the role that rule names for where the color is used, replace the name, then delete the comment. Don't pick by name alone. +- **Palette defaults (`color-roles:palette-default`).** The codemod replaces some old palette names in color props without a comment, because the use is known from the prop. Red becomes an error role: `surface-error` as a fill, `text-error` for text and borders. Green is the same with success (`surface-success`, `text-success`). White becomes `surface-raised` as a fill, `text-inverse` as text, and `border-subtle` as a border. Navy takes the nearest role by brightness: `surface-default` or `surface-sunken` for light fills, `text-subtle` or `text-default` for text, `border-*` for borders. The rules are in `presets/color-roles/decisions.ts`. + Check each one in context. A red button fill should be `action-danger`, not `surface-error`, so that's the one to look at first. A theme lookup or CSS variable gets the same defaults when the CSS property or style key it's the value of says the use (`background-color: ${theme.colors['navy-100']}` becomes `surface-default`); without one, it stays a warning. Navy fills at 400 and darker never get a default. +- **Dark navy fills.** A fill of `navy`, `navy-700` or `navy-800` is a dark area, and no surface is dark on a light page. Make the area dark mode with ``, say why in a comment, and remove the fill. When a `ColorMode mode="dark"` already sits inside the element that paints the fill (a sidebar `aside` with the scope inside it), move the fill onto that `ColorMode` as `bg="surface-default"`. The comment the codemod leaves says this. +- **`is an old palette color with no role of its own`.** No role replaces a palette name, and one name can map to different roles by slot: `navy` is a border in one place and text in another. The `color-roles:` comment says where the name is used (a prop, a `theme.colors` lookup, or a CSS variable). Pick the role for that use from design's component map, `COMPONENTS` in `@skillsoft/gamut-brand`'s `src/migration.ts`, then delete the comment. +- **`hyper` and `yellow` (no default yet).** Both stay warnings. They are the old primary and second brand color, so they don't map to a role by name, and the brand decides where they go. + - `hyper` is the primary. In the light theme it fills primary buttons and marks links and focus. Map it to `action-primary` (with its hover and pressed roles), not to `accent-alt`: `accent-alt` is a second brand color, and it would turn primary buttons into that color. + - `yellow` is the second brand color. It is the warning feedback color (`surface-warning` and `text-warning`), the dark-mode primary (`action-primary` through the brand's override), and decoration: Gantt tracks, badges, card fills, callouts. Split it by use. Warning goes to the warning roles; decoration goes to `surface-brand` or a `viz-*` series. + - `accent` and `accent-alt` are palette slots, not roles. No role is named `accent`. A brand sets them, and `surface-brand` and the dark-mode primary read them. Which brand color yellow becomes is a brand decision: Original Codecademy keeps yellow as its accent, and Skillsoft's accent is a different color. Don't pick the accent color for a brand yourself. +- **`blue-500` and `blue` (partly defaulted).** `blue-500` is admin's light-mode primary (`#1557FF`), and bare `blue` is the same color. The codemod maps their text to `action-primary`, because link and focus text is interactive. Fills and borders stay warnings: they mix interactive uses (selection buttons) with decoration (the Skillsoft family block), and only a person can tell them apart. Map those to `action-primary` when they're interactive, and to `surface-brand` or a `viz-*` series when they're decoration. + Don't map the brand's blue to the Skillsoft primary by hex. Skillsoft's primary is Sapphire, `#1C50BB`, which is close to LX Studio's and Percipio's primary but not the same as admin's blue. +- **`color name built at runtime`.** The codemod can't see the value. Check every name the template can produce, like `${variant}-hover`. +- **Card `variant="navy"` (`color-roles:card-navy`).** `navy` becomes `default`, which renders light. If the card should stay dark, wrap it in `` with a comment saying why, then delete the comment the codemod left. The card's `default` variant is `surface-raised`, which is dark in dark mode. See "Background or ColorMode" below. +- **`percipioTheme`, `coreTheme`, `PercipioTheme`, `CoreTheme`.** Theme names move to their replacements: `skillsoftTheme`, `originalCodecademyTheme`, and `SkillsoftTheme`. A leftover `CoreTheme` type gets a comment. Brand themes share one shape, typed by `SkillsoftTheme`. That is a type, not a theme to switch to: keep the theme the app already uses. +- **`--color-*` in `.css`, `.scss` or `.less`.** The type check can't see stylesheets, so the leftovers report is the only list of what's left. Indented-syntax `.sass` isn't rewritten. Search those by hand for `--color-`. + +**Keep each app's theme.** The codemod doesn't choose a brand theme. An app keeps the one it uses (`originalCodecademyTheme`, `adminTheme`, `platformTheme`, or `skillsoftTheme`). Changing the theme changes the spacing scale: in one repo, numeric `padding` and `border` values failed the type check under `skillsoftTheme` and passed under `originalCodecademyTheme`. Type-check after any theme change. + +Checks before you call it done: + +1. Run the formatter. The `color-roles:` comments make lines long. +2. Type-check. Any old name the codemod left still fails until someone picks its role. +3. The leftovers report lists no `color-roles:` comment. +4. A second `--dry` run over the result reports nothing new to change. + +Don't: + +- Replace a split or palette name with a role you chose by look. Use the rule in the comment, or design's component map. +- Delete a `color-roles:` comment without resolving the name it marks. +- Pass `--force` to get past the clean-tree check. + +The codemod's README (`@skillsoft/gamut-codemods`, "Running color-roles") lists the positions it covers and its limits. + +### Background or ColorMode + +`ColorMode` sets the mode for everything inside it. Use it once, at the top of the app or page, where the mode is decided. Inside that, reach for `Background` for any surface that has its own color. + +- **`ColorMode`** sets the mode you pass: `mode="light"`, `"dark"` or `"system"`. It doesn't look at the color behind it. Put it at the highest level, the app or page root, and leave it there. Add a nested `ColorMode` only when a smaller area has to be a different mode from the page around it, like a sidebar or a navy card that is always dark, and say why in a comment. Give it `bg="surface-default"` when the area paints its own ground. +- **`Background`** paints a `bg` color and picks the mode itself, choosing the one with the most contrast against that color. Its children stay readable whatever mode the page is in. Use it for any surface with a color of its own: a brand gradient, a featured panel, a status fill. It takes no `mode` prop; that's omitted from its props on purpose. + +The test is which one decides: the color or the mode. When the color decides (`surface-brand`, a gradient), use `Background`. When the mode decides (this area is always dark), use `ColorMode`. `Background` can't make an area dark with a role, because it looks its `bg` up in the page's mode, and every surface is light in light mode: `` on a light page paints light and stays light. + +## Working through open color decisions + +Some palette names have no default, because the right role depends on the brand or the screen. When the user asks you to work through them, do it with them, one decision at a time. Don't pick a role for them. + +1. List the open names from the codemod's warnings (`is an old palette color`), grouped by name, with the kind of use (fill, text, border) and a count. +2. For each name, show the uses the way a person can see them: the file, the component, and the prop. Name the candidate roles from the rules in this section, and say which one you'd pick and why. +3. Ask one question per name with the candidate roles as options, and leave room for another role or "keep the warning". Use AskUserQuestion when it's available. +4. Write the answer into `presets/color-roles/decisions.ts` in the codemod, with a comment naming the use it covers. Add a test for it, then run the suite, the type-check and the lint. +5. Record a decision the user made about a brand (which color is the accent, which blue is the primary) in the brand's own file, not in this skill. + +Start with the names that have the most sites. Open today: `yellow` (its role depends on the brand), navy fills at 400 to 600 (translucent, so they look different on every surface), the `blue-500` and `blue` fills and borders, and the palette names the rules above don't cover. + +## Adding a preset + +When a preset ships in `@skillsoft/gamut-codemods`, document it here in the same change: + +1. Add a row to the Presets table, with the name `list` prints. +2. Add a `## Preset: ` section with the command, what it rewrites and skips, the warning prefixes (`[migration-name]`) and what to do about each, and the checks before calling it done. +3. If the preset leaves comments or leftovers for a person, document the marker and how to resolve it, the way `color-roles:` does. +4. Keep the codemod README in step: its preset table and a "Running " section. This skill points there for limits. + +## What not to do + +- Don't re-add `@codecademy/gamut-kit`, and don't create `@skillsoft/gamut-kit`.`@codecademy/gamut-kit` is deprecated and `@skillsoft/gamut-kit` never existed. Depend on the individual packages it bundled. +- Don't fix a warning by deep-importing a `dist` path. Find a public export, or ask the Gamut team. +- Don't silence a warning or leftover by removing the `@skillsoft` entry it points at. +- Don't bump any `@skillsoft/*` package outside the group's shared version. The packages move together. +- Don't run the codemod on a dirty tree, and don't pass `--force` to get past the check. +- Don't hand-edit build output or generated files to get a run to pass. The codemod skips them on purpose. + +## Reporting back + +Say what the codemod changed, which warnings and leftovers are still open, which ones you fixed, and what the user should verify by hand. If you haven't seen the codemod output, ask for it before you start guessing at fixes. diff --git a/packages/gamut-agent-tools/skills/gamut-scope-swap/SKILL.md b/packages/gamut-agent-tools/skills/gamut-scope-swap/SKILL.md deleted file mode 100644 index bbb26f649e..0000000000 --- a/packages/gamut-agent-tools/skills/gamut-scope-swap/SKILL.md +++ /dev/null @@ -1,120 +0,0 @@ ---- -name: gamut-scope-swap -description: Use this skill when moving an app from @codecademy/gamut* packages to @skillsoft/gamut* — running or re-running the scope-swap codemod (@skillsoft/gamut-codemods), triaging its warnings and leftovers, and fixing what it can't rewrite, such as deep imports, Video, renamed Menu exports, tsconfig dom, jest mocks, ESLint plugin keys, Module Federation shared config, the removed gamut-kit, and preview builds. Not for day-to-day Gamut usage after the move (see gamut-review) or for building new UI. ---- - -# Gamut Scope Swap - -Help an app move from `@codecademy/gamut*` to `@skillsoft/gamut*`. The codemod does the mechanical rewrite. This skill covers what the codemod reports, what it leaves for a person, and how to check the result. - -For a short overview of every breaking change, read [BREAKING_CHANGES.md](BREAKING_CHANGES.md). Load it only when you need the full list. The sections below cover triage. - -Sources of truth, in order: - -1. The codemod's README in `@skillsoft/gamut-codemods`, and `npx @skillsoft/gamut-codemods list` for the migrations in each preset. -2. The installed `@skillsoft/gamut` type declarations in `node_modules`. Before you suggest an import, confirm the symbol is actually exported there. Don't invent replacements. -3. The rest of the Gamut skills in this plugin, for choosing a replacement component or style API. - -## Workflow - -1. **Check the starting state.** Run `git status`. The codemod refuses to write into uncommitted changes unless it gets `--force`. If the tree is dirty, ask the user to commit or stash first. Don't add `--force` on your own. -2. **Preview.** Run `npx @skillsoft/gamut-codemods scope-swap . --dry`. It prints every file it would change and its warnings, and writes nothing. Run this before a real run. -3. **Run it,** once the user confirms: `npx @skillsoft/gamut-codemods scope-swap .`. Options: - - `--only=deep-imports,scope-rename` runs a subset of migrations. - - `--no-report` skips the leftovers report. - - To undo a run, `git checkout .`. That only restores the original state if the tree was clean before the run. -4. **Triage the output in this order.** Warnings first, because some change runtime behavior. Then leftovers. Then next steps. -5. **Verify.** Reinstall with `yarn`, run the formatter, then type-check, lint, test, and build. If the app uses Module Federation, test the host and its remotes together. - -If the codemod has already run, ask the user to paste the warnings and the leftovers list. If they can't, find the old names yourself. Exclude lockfiles and build output: - -```sh -grep -rn "@codecademy/gamut" --exclude-dir=node_modules --exclude-dir=dist --exclude=yarn.lock . -``` - -## Warnings - -Each warning starts with `[migration-name] file:line`. The migration name tells you what to check. A skipped migration prints `[migration-name] skipped: ` before the run. `eslint-comments` skips itself when the repo has a flat ESLint config (see Leftovers). - -| Migration | Warning starts with | What to do | -| -------------------------- | ------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `deep-imports` | `unmapped deep import '…'` | The codemod has no mapping for this path. Find the symbol in the installed `@skillsoft/gamut` types. If it's exported from the root, import it from there. If it isn't public, don't deep-import the `dist` path. Ask the Gamut team. | -| `deep-imports` | `… has no public replacement` | `ButtonBase` is deliberately private. Use `FillButton`, `StrokeButton`, `TextButton`, `IconButton`, or `CTAButton`. See the `gamut-buttons` skill for which one. | -| `deep-imports` | `… is only partly public` | Only some names from this path are public. Inline the styles, or use system props or `css()`. See `gamut-style-utilities` and `gamut-system-props`. | -| `deep-imports` | `deep import … in a mock or require() needs a manual rewrite` | Rewrite the mock or `require()` path by hand. | -| `deep-imports` | `rewrote … in a mock or require(). That now covers the whole package` | `jest.mock` of a deep path now mocks the whole package. Check the test still mocks what it needs. If the rename list applies, update renamed names too. | -| `moved-exports` | `namespace import uses …` | `import * as Gamut` can't be rewritten safely. Replace it with named imports. `Video` and `VideoProps` come from `@skillsoft/gamut/Video`. | -| `moved-exports` | `'export *' from … no longer re-exports …` | Add an explicit re-export from `@skillsoft/gamut/Video` if other code depends on it. | -| `moved-exports` | `mock of … stubs Video/VideoProps` | Mock `@skillsoft/gamut/Video` instead of the root package. | -| `markdown-video-overrides` | `skipDefaultOverrides is not an object literal` or `… is not a boolean literal` | The codemod couldn't tell whether this `` opted out of iframes or videos. Pass `iframeOverride={Iframe}` and `videoOverride={MarkdownVideo}` (both from `@skillsoft/gamut/Video`) unless it skipped them. | -| `markdown-video-overrides` | `a different import already uses the name Iframe or MarkdownVideo` | Import the overrides under another local name and pass them by hand. | -| `scope-rename` | `'@codecademy/gamut-kit' has no replacement package` | `gamut-kit` is removed, with no `@skillsoft` replacement. Depend on the individual packages it bundled. | -| `scope-rename` | `renamed N package-name string(s) outside imports. Check the diff.` | Review those lines in the diff. They're usually config or log strings, and a few may not be package names at all. | -| `package-json` | `…: replaced '@codecademy/gamut-kit' with its individual packages` | The individual packages are written at the release range (`^`), not at the kit's old version. They all land in the field `gamut-kit` was in, so `@skillsoft/gamut-tests` may end up in `dependencies`. Move it to `devDependencies` if it belongs there. | -| `package-json` | `… is newer than …, the last release … matches` | The app was on a newer upstream release than `@skillsoft` has synced. Expect type errors where the code uses what that release added. Check the upstream CHANGELOG, and ask the Gamut team before working around it. | -| `mf-shared` | `replaced … in Module Federation shared config` | This is a runtime change. Gamut is now actually shared as a singleton, so host and remotes must agree. Update each remote's shared config to match and deploy them together. | -| `next-config` | `` `experimental.esmExternals: false` makes Next require() … `` | A runtime change. Builds can fail when Next collects page data. See [NEXT_EMOTION_INTEROP.md](NEXT_EMOTION_INTEROP.md), then rebuild every Next app the warning names. | -| `tsconfig-dom` | `"lib" has no "dom"` | The root import used to bring in DOM types through `Video`. Add `"dom"` to that tsconfig's `lib` only if type-checking now fails on `document`, `HTMLElement`, `ResizeObserver`, and similar. | - -## Leftovers - -The leftovers list shows every line that still names an old package. The codemod doesn't rewrite these, and the regex can produce false positives. Go through them one by one: - -- **Jest `moduleNameMapper` regexes and tsconfig `paths`.** Update them to the `@skillsoft/*` names. A stale mapper makes tests fail to resolve modules. -- **Flat ESLint configs (`eslint.config.*`) and `.eslintrc.js`.** The codemod doesn't rewrite these. Only the package import changes (`import gamut from '@skillsoft/eslint-plugin-gamut'`). The rule prefix and directive prefix must match the key the plugin is registered under, or ESLint reports rules it can't find: - - Flat config: the prefix is the `plugins` key. With `plugins: { gamut }`, rules and directives stay `gamut/`. When the repo has a flat config, `eslint-comments` leaves directives alone. - - Legacy `.eslintrc` / `.eslintrc.json`: `eslint-config` and `eslint-comments` move everything to `plugin:@skillsoft/gamut/...` and `@skillsoft/gamut/`. - - To rename the flat-config key, rename the key, every rule key, and every directive together. -- **Scripts and CI that read `@codecademy/gamut-kit`.** Version-sync scripts like `sync-gamut-deps` read the kit's `package.json` from `node_modules` and exit when it's missing, which fails CI. Delete them, or make them check that every `@skillsoft` Gamut package uses the same version (they're released together). Update the docs that point to them. -- **Storybook config, docs, and comments.** Update them or leave them, but know they still say the old name. -- **Code samples in `.mdx`.** Fenced code blocks are left alone on purpose. Update them by hand if they matter. -- **Files the parser skipped.** Every file is parsed as `tsx`, so Flow-typed JavaScript is skipped. Fix any old names left in those files by hand. - -Don't edit `yarn.lock` by hand. Reinstalling updates it. - -## Runs from an older codemod build - -Migrations match the old `@codecademy` names, so running a newer build over a repo that's already been swapped does nothing for code that has already been renamed. If the first run used an older build (a pkg.pr.new preview, say), check by hand what newer builds handle: - -- **Directives under a flat config.** Older builds rewrote `gamut/` directives to `@skillsoft/gamut/` even when the flat config registers the plugin as `gamut`. Change them back. Lint doesn't always flag this, because a directive that names an unknown rule just stops suppressing anything. Current builds list these in the leftovers, with a note, unless a config registers the plugin as `'@skillsoft/gamut'`. -- **Duplicate imports.** Older `deep-imports` builds added a second `import … from '@skillsoft/gamut'` next to the existing one. `eslint --fix` merges them (`import/no-duplicates`). -- **`` iframes and videos.** Current builds skip `markdown-video-overrides` when the repo is already on upstream 74.0.0 or newer, because those apps already pass the overrides where they want them. On an older upstream release, add them as described under `markdown-video-overrides` above. -- **`esmExternals: false` and newer-than-source versions.** Run `npx @skillsoft/gamut-codemods scope-swap . --dry` with the current build. Report-only migrations like `next-config`, `tsconfig-dom`, and `package-json` still warn. - -## Next steps - -After the migrations finish: - -1. Reinstall with `yarn`. -2. Run the formatter and lint autofix (`prettier --write`, then `eslint --fix`). Split imports from `moved-exports` come out in recast's style, and `@skillsoft` sorts differently from `@codecademy`, so import-order rules like `simple-import-sort` fail until you do. -3. Type-check, run tests, and build. -4. If the app uses Module Federation, run the host and every remote together. -5. If the app depends on preview builds, point every `@skillsoft/*` package at the same preview (including `@skillsoft/eslint-plugin-gamut`) and pin them all with `resolutions`. The codemod README has the exact JSON. Published releases don't need it. - -## Common failures - -| Symptom | Likely cause | Fix | -| -------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `Module '"@skillsoft/gamut"' has no exported member 'Video'` | `Video` was imported from the root | Import from `@skillsoft/gamut/Video`. | -| `Cannot find name 'document'`, `HTMLElement`, or `ResizeObserver` | The affected tsconfig's `lib` has no `"dom"` | Add `"dom"` to that tsconfig's `compilerOptions.lib`. | -| Components render unstyled, or theme values don't apply | Two copies of `@skillsoft/gamut-styles` or `@skillsoft/variance` are installed | Run `yarn why @skillsoft/gamut-styles`. Make every `@skillsoft/*` package resolve to one version. Pin previews with `resolutions`. | -| `MenuList`, `MenuListItem`, or `IconOptionComponent` is not exported | Menu's `List*` and SelectDropdown's `IconOption` were renamed on the way to the root | Import the new name. Keep the local alias if the code relies on it, e.g. `import { MenuList as List }`. | -| Jest can't resolve `@skillsoft/...` modules, or a mock doesn't apply | A stale `moduleNameMapper` regex, or a mock still points at the root package | Update the mapper. Mock `@skillsoft/gamut/Video` for `Video`. | -| `Cannot find module '@skillsoft/gamut/Video'`, or `MenuList` is missing, right after install | The installed `@skillsoft/gamut` is older than the codemod. A range like `^0.0.1` can resolve to a release cut before these changes | Check `node_modules/@skillsoft/gamut/package.json` and its `exports`. Point at a build that has them (a newer release, or the matching preview), not at the old deep paths. | -| A preview fix doesn't show up after a push, even after `yarn up` | Yarn treats a `@.tgz` URL as fixed. The lockfile entry and the global cache keep the first build it fetched | Delete the `@skillsoft/*` preview entries from `yarn.lock`, the matching `@skillsoft-*-https-*` zips in the Yarn cache (`yarn config get cacheFolder`), and `node_modules/@skillsoft`, then run `yarn`. Check a file you know changed before you trust the type-check. | -| `import/no-duplicates` on `@skillsoft/gamut`, or hundreds of `simple-import-sort` errors | Rewritten imports weren't merged or re-sorted | Run `eslint --fix`. | -| `Cannot find module '@codecademy/gamut/dist/...'` after the run | The file was skipped by the parser, or the path is in a code sample | Rewrite the import by hand, following the rules above. | -| ESLint: `Definition for rule '…' was not found`, or a disable comment does nothing | The plugin key doesn't match the rewritten directives | Make the plugin key match the directive prefix (see Leftovers). | -| Remotes load a second copy of Gamut at runtime | Module Federation `shared` still lists old names on a remote | Update that remote's `shared` config and deploy it with the host. | - -## What not to do - -- Don't re-add `@codecademy/gamut-kit`, and don't create `@skillsoft/gamut-kit`.`@codecademy/gamut-kit` is deprecated and `@skillsoft/gamut-kit` never existed. Depend on the individual packages it bundled. -- Don't fix a warning by deep-importing a `dist` path. Find a public export, or ask the Gamut team. -- Don't silence a warning or leftover by removing the `@skillsoft` entry it points at. -- Don't bump any `@skillsoft/*` package outside the group's shared version. The packages move together. -- Don't run the codemod on a dirty tree, and don't pass `--force` to get past the check. - -## Reporting back - -Say what the codemod changed, which warnings and leftovers are still open, which ones you fixed, and what the user should verify by hand. If you haven't seen the codemod output, ask for it before you start guessing at fixes. diff --git a/packages/gamut-codemods/README.md b/packages/gamut-codemods/README.md index 15ef0eae56..20ddd02241 100644 --- a/packages/gamut-codemods/README.md +++ b/packages/gamut-codemods/README.md @@ -6,12 +6,15 @@ Codemods for moving a repo onto `@skillsoft/gamut` and between its releases. Each preset is one upgrade. Run them in order if you're more than one behind. -| Preset | What it's for | -| ------------ | ------------------------------------------------------- | -| `scope-swap` | Moving from `@codecademy/gamut*` to `@skillsoft/gamut*` | +| Preset | What it's for | +| ------------- | ---------------------------------------------------------------- | +| `scope-swap` | Moving from `@codecademy/gamut*` to `@skillsoft/gamut*` | +| `color-roles` | Moving Gamut color names onto the generated color system's roles | `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 +65,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. It doesn't add `stylis`: `@emotion/cache` brings its own copy, and a second root copy can break emotion's style inserts. 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. | @@ -73,9 +76,40 @@ Every skillsoft-gamut pull request publishes installable previews through pkg.pr - The codemod doesn't change how Gamut loads at runtime. Next.js apps with `experimental.esmExternals: false` can fail at build or prerender on `@emotion/*` or `react-select` default imports, with errors like `Element type is invalid ... got: object` or `c(...) is not a function`. `next-config` warns about the flag; remove it, along with any `@emotion/*` aliases that were working around it. - Flat ESLint configs (`eslint.config.*`) and `.eslintrc.js` aren't rewritten. In a flat config the rule prefix is whatever key you register the plugin under, so renaming rule keys blindly would break it. They show up in the leftovers. -- Every file is parsed with the `tsx` parser, so Flow-typed JS won't parse. +- Every file is parsed with the `tsx` parser, so Flow-typed JS won't parse. A file the parser rejects is reported as an error and left as is, and the run exits 1. Generated `.d.ts` files can hit this: Babel rejects `export { x as y }` of a `let` inside `declare module`. +- Build output and caches (`node_modules`, `dist`, `build`, `coverage`, `.next`, `.nx`, `tmp`) are never read, so minified bundles don't reach the parser. - The leftovers report uses regex, not an AST, so expect some false positives. +## Running color-roles + +```sh +npx @skillsoft/gamut-codemods color-roles . --dry +npx @skillsoft/gamut-codemods color-roles . +``` + +It maps today's color names (`text`, `primary`, `background-current`, …) onto the roles of the generated color system, using design's migration map (`aliases.ts`, generated from `src/migration.ts` in `@skillsoft/gamut-brand`). + +| Design's kind | What the codemod does | +| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Rename, merge | Replaces the name: `bg="background-primary"` → `bg="surface-default"`, `theme.colors.text` → `theme.colors['text-default']` | +| Split | Leaves the name and puts `/* color-roles: 'background' splits into surface-raised \| surface-default. */` in front of it | +| Retire, pending | The same, with design's rule for what to do instead | +| Old palette color | Takes a default role when its use is known (`decisions.ts`): `bg="red-500"` → `surface-error`, `color: ${theme.colors.hyper}` → `action-primary`. Otherwise marks the site with a `color-roles:` comment and warns, naming the use. Dark navy fills and other names design hasn't mapped always need a person | + +A name left in place is still an old name, so it fails the type check until someone picks its role. The leftovers report lists every `color-roles:` comment still in the code; delete each one once its name is resolved. + +It looks for color names where a color goes: the color props (`color`, `textColor`, `bg`, `borderColor`, `borderColor{X,Y,Left,Right,Top,Bottom}`) in JSX and in style objects, including ternaries, `&&`, and responsive objects and arrays; `theme.colors.x` and `theme.colors['x']`, also through `props.theme`, `useTheme()`, a variable holding `theme.colors`, or `colors` destructured from the theme; keys destructured from `theme.colors`; `themed('colors.x')`; and `var(--color-x)` in strings. `variant="primary"` and other strings that only look like color names are left alone. + +For an old palette color, the use comes from the prop (`bg` is a fill), the style key (`backgroundColor`), or the CSS property in a template (`border: 1px solid ${…}` is a border). A color inside a function (`linear-gradient(…)`, `rgba(…)`) or under a property that isn't a fill, text or border (`box-shadow`, `fill`) has no known use, so it gets a comment. + +Limits: + +- A name held in a variable before it reaches a color prop (`const bg = 'background'`) isn't seen. +- Names built at runtime (`` `${variant}-hover` ``) only warn. +- MDX bodies aren't rewritten. + +On gamut's own source (branch `cass-color-brands`), a run changes 60 files and 273 lines, warns 171 times (about 120 splits, retirements and pending names, 50 old palette colors, 3 runtime names), and takes the type errors from 284 to 145. A second run changes nothing. + ## Contributing ### How it's put together @@ -127,6 +161,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.test.ts b/packages/gamut-codemods/src/cli.test.ts index 2b36e5604d..d586de73ee 100644 --- a/packages/gamut-codemods/src/cli.test.ts +++ b/packages/gamut-codemods/src/cli.test.ts @@ -24,12 +24,20 @@ const mockRun = vi.fn(); const SOURCE_EXT = /\.(m?[jt]sx?|c[jt]s)$/; -const listSources = (target: string): string[] => +/* The runner's ignorePattern is `**\//**`; the fake honors those names. */ +const ignoredDirs = (options: Record) => + new Set( + ((options.ignorePattern as string[] | undefined) ?? []).map((pattern) => + pattern.replace(/^\*\*\//, '').replace(/\/\*\*$/, '') + ) + ); + +const listSources = (target: string, ignored: Set): string[] => fs.statSync(target).isDirectory() ? fs .readdirSync(target) - .filter((name) => name !== 'node_modules') - .flatMap((name) => listSources(path.join(target, name))) + .filter((name) => !ignored.has(name)) + .flatMap((name) => listSources(path.join(target, name), ignored)) : SOURCE_EXT.test(target) ? [target] : []; @@ -44,7 +52,8 @@ const simulateRunner = async ( report: (message: string) => console.log(message), stats: () => {}, }; - for (const file of paths.flatMap(listSources)) { + const ignored = ignoredDirs(options); + for (const file of paths.flatMap((p) => listSources(p, ignored))) { const source = fs.readFileSync(file, 'utf8'); const out = transform( { path: file, source } as FileInfo, @@ -255,6 +264,56 @@ describe('main: full run', () => { expect(output()).toMatch(/\[eslint-comments\] skipped: found flat ESLint/); }); + it('keeps build output and caches out of the source runner', async () => { + const dir = project({ + 'src/Post.tsx': POST, + /* Minified bundles don't parse, so the runner must never be given them. */ + '.next/static/chunks/app.js': "const x = 'gray-900' {{ not js\n", + 'dist/index.js': "const y = 'gray-900' {{ not js\n", + 'coverage/lcov-report/x.js': "const z = 'gray-900' {{ not js\n", + }); + expect(await main(['color-roles', dir, '--force'])).toBe(0); + expect(output()).not.toMatch(/\.next|\/dist\/|coverage/); + + const options = mockRun.mock.calls[0][2]; + expect(options.ignorePattern).toEqual( + expect.arrayContaining([ + '**/.next/**', + '**/.nx/**', + '**/node_modules/**', + '**/dist/**', + ]) + ); + }); + + it('skips generated files, which the runner never reads', async () => { + const dir = project({ + 'src/Post.tsx': POST, + /* wrangler types: Babel rejects this block, and it matches the pre-filter on 'text'. */ + 'worker-configuration.d.ts': + "declare module 'x' {\n let _E: number;\n export { _E as E };\n}\nget(type: 'text'): void;\n", + }); + expect(await main(['color-roles', dir, '--force'])).toBe(0); + expect(output()).not.toMatch(/worker-configuration/); + expect(mockRun.mock.calls[0][2].ignorePattern).toContain( + '**/worker-configuration.d.ts' + ); + }); + + it('warns about tsconfig lib only where gamut is imported', async () => { + const dir = project({ + 'src/Post.tsx': POST, + 'tsconfig.json': JSON.stringify({ compilerOptions: { lib: ['es2020'] } }), + 'worker/src/index.ts': 'export const n = 1;\n', + 'worker/tsconfig.json': JSON.stringify({ + compilerOptions: { lib: ['esnext'] }, + }), + }); + expect(await main(['scope-swap', dir, '--force'])).toBe(0); + expect(output()).toMatch(/\[tsconfig-dom\] .*\/tsconfig\.json "lib"/); + expect(output()).not.toMatch(/\[tsconfig-dom\] .*worker\/tsconfig\.json/); + }); + it('returns 1 when the source runner reports errors', async () => { mockRun.mockResolvedValueOnce({ error: 1 }); const dir = project({ 'src/Post.tsx': POST }); 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/color-roles-manifest.test.ts b/packages/gamut-codemods/src/color-roles-manifest.test.ts new file mode 100644 index 0000000000..ab7c207341 --- /dev/null +++ b/packages/gamut-codemods/src/color-roles-manifest.test.ts @@ -0,0 +1,35 @@ +import { describe, expect, it } from 'vitest'; +import { isAutomatic, manifest } from './presets/color-roles/manifest'; + +/* + The color-roles data is generated from design's map, so these guard the + generator and any hand edit: a row the codemod applies must name exactly one + real role, and no name can be both an alias and an old palette color. +*/ +describe('color-roles manifest', () => { + const rows = Object.entries(manifest.aliases); + const roles = new Set(manifest.roles); + + it('has every alias design maps', () => { + expect(rows).toHaveLength(32); + }); + + it.each(rows.filter(([, a]) => isAutomatic(a)))( + '%s names exactly one role', + (_, alias) => { + expect(alias.to).toHaveLength(1); + } + ); + + it('only targets real roles', () => { + const bad = rows.flatMap(([name, a]) => + a.to.filter((t) => !roles.has(t)).map((t) => `${name} → ${t}`) + ); + expect(bad).toEqual([]); + }); + + it('keeps aliases and old palette names apart', () => { + const both = manifest.oldPalette.filter((n) => n in manifest.aliases); + expect(both).toEqual([]); + }); +}); 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/run-source.ts b/packages/gamut-codemods/src/lib/run-source.ts index 42eb019392..47a2d57595 100644 --- a/packages/gamut-codemods/src/lib/run-source.ts +++ b/packages/gamut-codemods/src/lib/run-source.ts @@ -5,6 +5,7 @@ import type { AstMigration, Edit, Locatable, + Migration, Note, SourceMigration, SpliceMigration, @@ -24,11 +25,11 @@ import type { that embed code, like MDX's ESM blocks. */ -export interface RunSourceOptions { +export interface RunSourceOptions { j: JSCodeshift; source: string; - migrations: SourceMigration[]; - manifest: Manifest; + migrations: SourceMigration[]; + manifest: M; warnFor: (migration: string) => (node: Locatable, message: string) => void; note: Note; } @@ -42,18 +43,18 @@ const applyEdits = (source: string, edits: Edit[]) => source ); -export const runSourceMigrations = ({ +export const runSourceMigrations = ({ j, source: original, migrations, manifest, warnFor, note, -}: RunSourceOptions) => { +}: RunSourceOptions) => { let source = original; const astMigrations = migrations.filter( - (m): m is AstMigration => m.kind === 'ast' + (m): m is AstMigration => m.kind === 'ast' ); if (astMigrations.length > 0) { const root = j(source); @@ -72,7 +73,7 @@ export const runSourceMigrations = ({ } for (const m of migrations.filter( - (x): x is SpliceMigration => x.kind === 'splice' + (x): x is SpliceMigration => x.kind === 'splice' )) { const root = j(source); const edits = m.edits({ @@ -89,7 +90,7 @@ export const runSourceMigrations = ({ return source; }; -/* The pre-filter every caller uses so big repos don't parse every file. */ +/* scope-swap's pre-filter (Preset.mentions): an old package name or rule prefix. */ export const mentionsOldNames = (manifest: Manifest, source: string) => [ ...Object.keys(manifest.packages), @@ -98,8 +99,8 @@ export const mentionsOldNames = (manifest: Manifest, source: string) => ].some((name) => source.includes(name)); /* `only` and `skip` are comma-separated migration names. */ -export const activeSourceMigrations = ( - migrations: { kind: string; name: string }[], +export const activeSourceMigrations = ( + migrations: Migration[], only?: string, skip?: string ) => { @@ -108,5 +109,5 @@ export const activeSourceMigrations = ( return migrations.filter( (m) => m.kind !== 'file' && (!names || names.has(m.name)) && !skipped.has(m.name) - ) as SourceMigration[]; + ) as SourceMigration[]; }; 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/color-roles-stylesheets/__testfixtures__/rerun.input.scss b/packages/gamut-codemods/src/migrations/color-roles-stylesheets/__testfixtures__/rerun.input.scss new file mode 100644 index 0000000000..e28440789c --- /dev/null +++ b/packages/gamut-codemods/src/migrations/color-roles-stylesheets/__testfixtures__/rerun.input.scss @@ -0,0 +1,4 @@ +.panel { + color: /* color-roles: 'navy-800' is an old palette color with no role of its own, used as a CSS variable. Pick the role from design's component map (@skillsoft/gamut-brand src/migration.ts, COMPONENTS). */ var(--color-navy-800); + fill: /* color-roles: 'navy-800' is an old palette color with no role of its own, used as a CSS variable. Pick the role from design's component map (@skillsoft/gamut-brand src/migration.ts, COMPONENTS). */ var(--color-navy-800); +} diff --git a/packages/gamut-codemods/src/migrations/color-roles-stylesheets/__testfixtures__/rerun.output.scss b/packages/gamut-codemods/src/migrations/color-roles-stylesheets/__testfixtures__/rerun.output.scss new file mode 100644 index 0000000000..ec66f79bbd --- /dev/null +++ b/packages/gamut-codemods/src/migrations/color-roles-stylesheets/__testfixtures__/rerun.output.scss @@ -0,0 +1,4 @@ +.panel { + color: var(--color-text-default); + fill: /* color-roles: 'navy-800' is an old palette color with no role of its own, used as a CSS variable. Pick the role from design's component map (@skillsoft/gamut-brand src/migration.ts, COMPONENTS). */ var(--color-navy-800); +} diff --git a/packages/gamut-codemods/src/migrations/color-roles-stylesheets/__testfixtures__/vars.input.scss b/packages/gamut-codemods/src/migrations/color-roles-stylesheets/__testfixtures__/vars.input.scss new file mode 100644 index 0000000000..af5005e2a3 --- /dev/null +++ b/packages/gamut-codemods/src/migrations/color-roles-stylesheets/__testfixtures__/vars.input.scss @@ -0,0 +1,19 @@ +.panel { + color: var(--color-text); + border-color: var(--color-border-secondary); + background: var(--color-background); + box-shadow: 0 1px 4px var(--color-shadow-primary); +} + +.legacy { + fill: var(--color-navy-800); + color: var(--color-navy-800); + background-color: var(--color-navy-100); + border: 1px solid var(--color-navy-300); + outline-color: var(--color-primary, var(--color-text-secondary)); +} + +/* Already on the new names: untouched. */ +.done { + color: var(--color-text-default); +} diff --git a/packages/gamut-codemods/src/migrations/color-roles-stylesheets/__testfixtures__/vars.output.scss b/packages/gamut-codemods/src/migrations/color-roles-stylesheets/__testfixtures__/vars.output.scss new file mode 100644 index 0000000000..74d294d8ff --- /dev/null +++ b/packages/gamut-codemods/src/migrations/color-roles-stylesheets/__testfixtures__/vars.output.scss @@ -0,0 +1,19 @@ +.panel { + color: var(--color-text-default); + border-color: var(--color-border-default); + background: /* color-roles: 'background' splits into surface-raised | surface-default. Anything that sits on the page (card, input, menu, popover, dialog) takes `surface-raised`. Where `background` fills the page itself, it is `surface-default`. */ var(--color-background); + box-shadow: 0 1px 4px /* color-roles: 'shadow-primary' splits into shadow-key | shadow-ambient. Every elevation shadow composes both: `shadow-key` for the tight contact layer, `shadow-ambient` for the soft falloff. The elevation tokens hold only offset, blur and spread; see the elevation system for which depth uses which geometry. */ var(--color-shadow-primary); +} + +.legacy { + fill: /* color-roles: 'navy-800' is an old palette color with no role of its own, used as a CSS variable for `fill`. Pick the role from design's component map (@skillsoft/gamut-brand src/migration.ts, COMPONENTS). */ var(--color-navy-800); + color: var(--color-text-default); + background-color: var(--color-surface-default); + border: 1px solid var(--color-border-subtle); + outline-color: var(--color-action-primary, var(--color-text-subtle)); +} + +/* Already on the new names: untouched. */ +.done { + color: var(--color-text-default); +} diff --git a/packages/gamut-codemods/src/migrations/color-roles-stylesheets/__testfixtures__/vars.warnings.json b/packages/gamut-codemods/src/migrations/color-roles-stylesheets/__testfixtures__/vars.warnings.json new file mode 100644 index 0000000000..9f70360546 --- /dev/null +++ b/packages/gamut-codemods/src/migrations/color-roles-stylesheets/__testfixtures__/vars.warnings.json @@ -0,0 +1,5 @@ +[ + "'background' splits into", + "'shadow-primary' splits into shadow-key | shadow-ambient", + "'--color-navy-800' is an old palette color with no role of its own, used as a CSS variable for `fill`" +] diff --git a/packages/gamut-codemods/src/migrations/color-roles-stylesheets/index.ts b/packages/gamut-codemods/src/migrations/color-roles-stylesheets/index.ts new file mode 100644 index 0000000000..02a9dc7f4c --- /dev/null +++ b/packages/gamut-codemods/src/migrations/color-roles-stylesheets/index.ts @@ -0,0 +1,101 @@ +import type { FileMigration } from '../../lib/types'; +import { + cssPropertyBefore, + paletteDefault, +} from '../../presets/color-roles/decisions'; +import type { ColorRolesManifest } from '../../presets/color-roles/manifest'; +import { + commentText, + describe, + findOldVars, + markedBefore, + mentionsOldVar, + paletteComment, + paletteMessage, + staleMark, +} from '../color-roles/cssVars'; + +/* + Old color variables in stylesheets: `var(--color-text)` in .css, .scss and + .less. The type check can't see these, so this is the only place they're + caught. + + - Renames and merges become `--color-`. + - Splits, retirements and pending names stay, with a + `/* color-roles: … *\/` comment carrying design's rule in front of them. + The preset's leftovers report lists every one by file and line. + - Old palette colors (`--color-navy-800`) take a default from + decisions.ts when the property they're the value of says what they're + for (`color`, `background`, `border-color`). Otherwise they're marked + like the splits. + + Indented-syntax .sass isn't rewritten: its comment rules differ, so a + comment mid-value could break the file. +*/ +export const colorRolesStylesheets: FileMigration = { + name: 'color-roles-stylesheets', + kind: 'file', + description: + 'Rename old `--color-*` variables in stylesheets; mark the ones a person has to pick.', + appliesTo: (file) => /\.(css|scss|less)$/.test(file), + run({ source, manifest, warn, note }) { + if (!mentionsOldVar(source)) return null; + const hits = findOldVars(source, manifest); + if (hits.length === 0) return null; + + let out = ''; + let last = 0; + for (const hit of hits) { + const from = last; + out += source.slice(last, hit.at); + last = hit.at; + /* In front of the `var(` the variable sits in, if there is one. */ + const varAt = source.lastIndexOf('var(', hit.at); + const at = + varAt !== -1 && source.slice(varAt + 4, hit.at).trim() === '' + ? varAt + : hit.at; + const property = hit.palette + ? cssPropertyBefore(source.slice(0, hit.at)) + : undefined; + const where = property + ? `a CSS variable for \`${property}\`` + : 'a CSS variable'; + const role = + hit.role ?? (hit.palette ? paletteDefault(hit.name, where) : null); + if (role) { + /* An earlier run's comment for this name goes with it. */ + const stale = staleMark(source, at, hit.name); + if (stale && stale.start >= from) { + out = + out.slice(0, out.length - (hit.at - stale.start)) + + source.slice(stale.end, hit.at); + } + out += `--color-${role}`; + last = hit.at + `--color-${hit.name}`.length; + if (!hit.role) note('color-roles:palette-default'); + } else if (hit.alias || hit.palette) { + const cssName = `--color-${hit.name}`; + const comment = hit.alias + ? commentText(hit.name, hit.alias) + : paletteComment(hit.name, where); + if (!markedBefore(source, at)) { + out = + out.slice(0, out.length - (hit.at - at)) + + comment + + source.slice(at, hit.at); + } + if (hit.alias) { + warn(describe(hit.name, hit.alias)); + note('color-roles:manual'); + } else { + warn(paletteMessage(cssName, where)); + note('color-roles:palette'); + } + } + } + out += source.slice(last); + note('color-roles:stylesheets'); + return out === source ? null : out; + }, +}; diff --git a/packages/gamut-codemods/src/migrations/color-roles-themes/__testfixtures__/themes.input.tsx b/packages/gamut-codemods/src/migrations/color-roles-themes/__testfixtures__/themes.input.tsx new file mode 100644 index 0000000000..98701af305 --- /dev/null +++ b/packages/gamut-codemods/src/migrations/color-roles-themes/__testfixtures__/themes.input.tsx @@ -0,0 +1,22 @@ +import type { CoreTheme, PercipioTheme } from '@skillsoft/gamut-styles'; +import { + coreTheme, + GamutProvider, + percipioTheme as theme, +} from '@skillsoft/gamut-styles'; + +import { settings } from './settings'; + +export const Percipio = () => ; + +export const Core = () => ; + +export const themes = { coreTheme, dark: { ...coreTheme, mode: 'dark' } }; + +export const label = settings.coreTheme; + +export type Typed = PercipioTheme; + +declare module '@emotion/react' { + export interface Theme extends CoreTheme {} +} diff --git a/packages/gamut-codemods/src/migrations/color-roles-themes/__testfixtures__/themes.output.tsx b/packages/gamut-codemods/src/migrations/color-roles-themes/__testfixtures__/themes.output.tsx new file mode 100644 index 0000000000..4cf7d113d2 --- /dev/null +++ b/packages/gamut-codemods/src/migrations/color-roles-themes/__testfixtures__/themes.output.tsx @@ -0,0 +1,22 @@ +import type { /* color-roles: 'CoreTheme' typed the old core theme, which has no color roles. Brand themes share one shape, typed by 'SkillsoftTheme': use that type, and keep the theme the app already uses. The brand is a per-app choice, and changing it changes the spacing scale. */ CoreTheme, SkillsoftTheme } from '@skillsoft/gamut-styles'; +import { + originalCodecademyTheme, + GamutProvider, + skillsoftTheme as theme, +} from '@skillsoft/gamut-styles'; + +import { settings } from './settings'; + +export const Percipio = () => ; + +export const Core = () => ; + +export const themes = { coreTheme: originalCodecademyTheme, dark: { ...originalCodecademyTheme, mode: 'dark' } }; + +export const label = settings.coreTheme; + +export type Typed = SkillsoftTheme; + +declare module '@emotion/react' { + export interface Theme extends CoreTheme {} +} diff --git a/packages/gamut-codemods/src/migrations/color-roles-themes/__testfixtures__/themes.warnings.json b/packages/gamut-codemods/src/migrations/color-roles-themes/__testfixtures__/themes.warnings.json new file mode 100644 index 0000000000..f1b2c57ce5 --- /dev/null +++ b/packages/gamut-codemods/src/migrations/color-roles-themes/__testfixtures__/themes.warnings.json @@ -0,0 +1 @@ +["'CoreTheme' typed the old core theme"] diff --git a/packages/gamut-codemods/src/migrations/color-roles-themes/index.ts b/packages/gamut-codemods/src/migrations/color-roles-themes/index.ts new file mode 100644 index 0000000000..ec5eb255db --- /dev/null +++ b/packages/gamut-codemods/src/migrations/color-roles-themes/index.ts @@ -0,0 +1,133 @@ +import type { Edit, SpliceMigration } from '../../lib/types'; +import type { ColorRolesManifest } from '../../presets/color-roles/manifest'; +import { MARK, markedBefore } from '../color-roles/cssVars'; + +/* + The old themes' names → the brand themes that replace them, wherever + they're imported from gamut-styles: + + - `percipioTheme` → `skillsoftTheme`, its replacement (`percipioTheme` is + removed), and the `PercipioTheme` type → `SkillsoftTheme`. + - `coreTheme` → `originalCodecademyTheme`, its rebuild. `coreTheme` still + exists but defines no roles, so components lose their colors on it. + + An aliased import (`percipioTheme as theme`) only has its imported name + changed. An unaliased one is renamed everywhere the file uses it. + + The `CoreTheme` type has no same-named successor: brand themes share one + shape, typed by `SkillsoftTheme`. It gets a `color-roles:` comment for a + person, since it's usually a Theme augmentation the app owns. +*/ + +const RENAMES: Record = { + percipioTheme: 'skillsoftTheme', + coreTheme: 'originalCodecademyTheme', + PercipioTheme: 'SkillsoftTheme', + PercipioThemeShape: 'SkillsoftThemeShape', +}; + +const MANUAL: Record = { + CoreTheme: `/* ${MARK} 'CoreTheme' typed the old core theme, which has no color roles. Brand themes share one shape, typed by 'SkillsoftTheme': use that type, and keep the theme the app already uses. The brand is a per-app choice, and changing it changes the spacing scale. */ `, +}; + +const GAMUT_STYLES = /(^|\/)gamut-styles$/; + +interface Node { + type: string; + start: number; + end: number; + [key: string]: any; +} + +export const colorRolesThemes: SpliceMigration = { + name: 'color-roles-themes', + kind: 'splice', + description: + 'Rename percipioTheme and coreTheme to the brand themes that replace them.', + edits({ j, root, source, warn, note }) { + const edits: Edit[] = []; + const seen = new Set(); + const push = (e: Edit) => { + if (seen.has(e.start)) return; + seen.add(e.start); + edits.push(e); + }; + /* Unaliased imports, renamed across the file. */ + const local = new Map(); + + root.find(j.ImportDeclaration).forEach((p) => { + const decl = p.node as unknown as Node; + if (!GAMUT_STYLES.test(decl.source.value)) return; + for (const spec of decl.specifiers ?? []) { + if (spec.type !== 'ImportSpecifier') continue; + const name: string = spec.imported?.name; + const to = RENAMES[name]; + if (to) { + push({ + start: spec.imported.start, + end: spec.imported.end, + text: to, + }); + if (spec.local?.name === name) local.set(name, to); + note('color-roles:themes'); + } else if (MANUAL[name]) { + if (!markedBefore(source, spec.start)) { + push({ start: spec.start, end: spec.start, text: MANUAL[name] }); + } + warn( + spec, + `'${name}' typed the old core theme, which has no color roles. Type brand themes with 'SkillsoftTheme', and keep the theme the app already uses: the brand is a per-app choice.` + ); + note('color-roles:themes'); + } + } + }); + + if (local.size === 0) return edits; + + /* `{ percipioTheme }` keeps its key: `{ percipioTheme: skillsoftTheme }`. */ + root.find(j.Node).forEach((p) => { + const node = p.node as unknown as Node; + if ( + (node.type === 'ObjectProperty' || node.type === 'Property') && + node.shorthand && + node.value?.type === 'Identifier' && + local.has(node.value.name) + ) { + push({ + start: node.start, + end: node.end, + text: `${node.value.name}: ${local.get(node.value.name)}`, + }); + } + }); + + root.find(j.Identifier).forEach((p) => { + const id = p.node as unknown as Node; + const to = local.get(id.name); + if (!to) return; + const parent = p.parent?.node as Node | undefined; + /* `x.percipioTheme` and `{ percipioTheme: … }` name something else. */ + if ( + parent && + (parent.type === 'MemberExpression' || + parent.type === 'OptionalMemberExpression') && + parent.property === p.node && + !parent.computed + ) { + return; + } + if ( + parent && + (parent.type === 'ObjectProperty' || parent.type === 'Property') && + parent.key === p.node && + !parent.computed + ) { + return; + } + push({ start: id.start, end: id.end, text: to }); + }); + + return edits; + }, +}; diff --git a/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/card.input.tsx b/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/card.input.tsx new file mode 100644 index 0000000000..f3ebfe7913 --- /dev/null +++ b/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/card.input.tsx @@ -0,0 +1,13 @@ +import { Card } from '@skillsoft/gamut'; +import { Card as OtherCard } from './OtherCard'; + +export const Cards = ({ featured }: { featured: boolean }) => ( + <> + White + Beige + Navy + Yellow + Hyper + Not gamut's + +); diff --git a/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/card.output.tsx b/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/card.output.tsx new file mode 100644 index 0000000000..5f83a5f7f8 --- /dev/null +++ b/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/card.output.tsx @@ -0,0 +1,13 @@ +import { Card } from '@skillsoft/gamut'; +import { Card as OtherCard } from './OtherCard'; + +export const Cards = ({ featured }: { featured: boolean }) => ( + <> + White + Beige + . */ variant="default">Navy + Yellow + Hyper + Not gamut's + +); diff --git a/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/card.warnings.json b/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/card.warnings.json new file mode 100644 index 0000000000..b03dcb8772 --- /dev/null +++ b/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/card.warnings.json @@ -0,0 +1 @@ +["Card's 'navy' variant becomes 'default'"] diff --git a/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/jsx.input.tsx b/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/jsx.input.tsx new file mode 100644 index 0000000000..c020a037cc --- /dev/null +++ b/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/jsx.input.tsx @@ -0,0 +1,14 @@ +import { Box, Text } from '@skillsoft/gamut'; + +export const Card = ({ active }: { active: boolean }) => ( + + + Title + + Not a variant: secondary is a color here. + + + + + +); diff --git a/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/jsx.output.tsx b/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/jsx.output.tsx new file mode 100644 index 0000000000..9b05d85b4d --- /dev/null +++ b/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/jsx.output.tsx @@ -0,0 +1,14 @@ +import { Box, Text } from '@skillsoft/gamut'; + +export const Card = ({ active }: { active: boolean }) => ( + + + Title + + Not a variant: secondary is a color here. + + + `, say why in a comment, and remove this fill. */ bg="navy" /> + + +); diff --git a/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/jsx.warnings.json b/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/jsx.warnings.json new file mode 100644 index 0000000000..8eca099b43 --- /dev/null +++ b/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/jsx.warnings.json @@ -0,0 +1 @@ +["'navy' is an old palette color with no role of its own"] diff --git a/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/manual.input.tsx b/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/manual.input.tsx new file mode 100644 index 0000000000..e84b7bd1a8 --- /dev/null +++ b/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/manual.input.tsx @@ -0,0 +1,10 @@ +import { Background, Box } from '@skillsoft/gamut'; + +export const Panel = ({ muted }: { muted: boolean }) => ( + + + + + + +); diff --git a/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/manual.output.tsx b/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/manual.output.tsx new file mode 100644 index 0000000000..5d5727b803 --- /dev/null +++ b/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/manual.output.tsx @@ -0,0 +1,10 @@ +import { Background, Box } from '@skillsoft/gamut'; + +export const Panel = ({ muted }: { muted: boolean }) => ( + + + + + + +); diff --git a/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/manual.warnings.json b/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/manual.warnings.json new file mode 100644 index 0000000000..cd766f5bd3 --- /dev/null +++ b/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/manual.warnings.json @@ -0,0 +1,8 @@ +[ + "'background' splits into surface-raised | surface-default", + "'border-primary' splits into border-default | border-subtle", + "'text-disabled' splits into action-disabled | surface-raised | text-subtle", + "'shadow-primary' splits into shadow-key | shadow-ambient", + "'background-contrast' is retired (closest: surface-raised)", + "'border-disabled' splits into border-default | action-disabled" +] diff --git a/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/palette-defaults.input.tsx b/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/palette-defaults.input.tsx new file mode 100644 index 0000000000..e999efa48f --- /dev/null +++ b/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/palette-defaults.input.tsx @@ -0,0 +1,14 @@ +import { Box, Text } from '@skillsoft/gamut'; + +export const Status = () => ( + + Failed + Passed + + + + Heading + + Faint + +); diff --git a/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/palette-defaults.output.tsx b/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/palette-defaults.output.tsx new file mode 100644 index 0000000000..cb457f97ce --- /dev/null +++ b/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/palette-defaults.output.tsx @@ -0,0 +1,14 @@ +import { Box, Text } from '@skillsoft/gamut'; + +export const Status = () => ( + + Failed + Passed + + + `, say why in a comment, and remove this fill. */ bg="navy-800" /> + Heading + + Faint + +); diff --git a/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/palette-defaults.warnings.json b/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/palette-defaults.warnings.json new file mode 100644 index 0000000000..492e99e947 --- /dev/null +++ b/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/palette-defaults.warnings.json @@ -0,0 +1 @@ +["'navy-800' is an old palette color", "'navy-300' is an old palette color"] diff --git a/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/rerun.input.tsx b/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/rerun.input.tsx new file mode 100644 index 0000000000..cd1d7186e7 --- /dev/null +++ b/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/rerun.input.tsx @@ -0,0 +1,24 @@ +import styled from '@emotion/styled'; + +/* + Comments an earlier run left. Where this run picks a role, its comment + goes. Where the name still needs a person, or the comment is for another + name, it stays. +*/ +export const Panel = styled.div` + background: ${({ theme }) => + /* color-roles: 'white' is an old palette color with no role of its own, used as a theme.colors lookup. Pick the role from design's component map (@skillsoft/gamut-brand src/migration.ts, COMPONENTS). */ theme + .colors.white}; + border-color: ${({ theme }) => /* color-roles: 'navy-300' is an old palette color with no role of its own, used as a theme.colors lookup. Pick the role from design's component map (@skillsoft/gamut-brand src/migration.ts, COMPONENTS). */ theme.colors['navy-300']}; + box-shadow: 0 0 0 1px ${({ theme }) => /* color-roles: 'navy-300' is an old palette color with no role of its own, used as a theme.colors lookup. Pick the role from design's component map (@skillsoft/gamut-brand src/migration.ts, COMPONENTS). */ theme.colors['navy-300']}; + color: ${({ theme }) => /* color-roles: 'gray-600' is an old palette color with no role of its own, used as a theme.colors lookup. Pick the role from design's component map (@skillsoft/gamut-brand src/migration.ts, COMPONENTS). */ theme.colors['navy-800']}; +`; + +export const Inked = styled.p/* color-roles: 'red' is an old palette color with no role of its own, used as a CSS variable. Pick the role from design's component map (@skillsoft/gamut-brand src/migration.ts, COMPONENTS). */ ` + color: var(--color-red); +`; + +export const Mixed = styled.p/* color-roles: 'navy-300' is an old palette color with no role of its own, used as a CSS variable. Pick the role from design's component map (@skillsoft/gamut-brand src/migration.ts, COMPONENTS). */ ` + color: var(--color-red); + box-shadow: 0 0 0 1px var(--color-navy-300); +`; diff --git a/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/rerun.output.tsx b/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/rerun.output.tsx new file mode 100644 index 0000000000..a38e308098 --- /dev/null +++ b/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/rerun.output.tsx @@ -0,0 +1,24 @@ +import styled from '@emotion/styled'; + +/* + Comments an earlier run left. Where this run picks a role, its comment + goes. Where the name still needs a person, or the comment is for another + name, it stays. +*/ +export const Panel = styled.div` + background: ${({ theme }) => + theme + .colors['surface-raised']}; + border-color: ${({ theme }) => theme.colors['border-subtle']}; + box-shadow: 0 0 0 1px ${({ theme }) => /* color-roles: 'navy-300' is an old palette color with no role of its own, used as a theme.colors lookup. Pick the role from design's component map (@skillsoft/gamut-brand src/migration.ts, COMPONENTS). */ theme.colors['navy-300']}; + color: ${({ theme }) => /* color-roles: 'gray-600' is an old palette color with no role of its own, used as a theme.colors lookup. Pick the role from design's component map (@skillsoft/gamut-brand src/migration.ts, COMPONENTS). */ theme.colors['text-default']}; +`; + +export const Inked = styled.p` + color: var(--color-text-error); +`; + +export const Mixed = styled.p/* color-roles: 'navy-300' is an old palette color with no role of its own, used as a CSS variable. Pick the role from design's component map (@skillsoft/gamut-brand src/migration.ts, COMPONENTS). */ ` + color: var(--color-text-error); + box-shadow: 0 0 0 1px var(--color-navy-300); +`; diff --git a/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/strings.input.ts b/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/strings.input.ts new file mode 100644 index 0000000000..f4f16d5b75 --- /dev/null +++ b/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/strings.input.ts @@ -0,0 +1,13 @@ +import styled from '@emotion/styled'; + +export const Panel = styled.div` + color: var(--color-text); + border: 1px solid var(--color-border-secondary); +`; + +export const Raised = styled.div` + background: var(--color-background); +`; + +export const fill = 'var(--color-navy-800)'; +export const link = { color: 'var(--color-primary)' }; diff --git a/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/strings.output.ts b/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/strings.output.ts new file mode 100644 index 0000000000..e10d95d4b7 --- /dev/null +++ b/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/strings.output.ts @@ -0,0 +1,13 @@ +import styled from '@emotion/styled'; + +export const Panel = styled.div` + color: var(--color-text-default); + border: 1px solid var(--color-border-default); +`; + +export const Raised = styled.div/* color-roles: 'background' splits into surface-raised | surface-default. Anything that sits on the page (card, input, menu, popover, dialog) takes `surface-raised`. Where `background` fills the page itself, it is `surface-default`. */ ` + background: var(--color-background); +`; + +export const fill = /* color-roles: 'navy-800' is an old palette color with no role of its own, used as a CSS variable. Pick the role from design's component map (@skillsoft/gamut-brand src/migration.ts, COMPONENTS). */ 'var(--color-navy-800)'; +export const link = { color: 'var(--color-action-primary)' }; diff --git a/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/strings.warnings.json b/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/strings.warnings.json new file mode 100644 index 0000000000..c668608f2c --- /dev/null +++ b/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/strings.warnings.json @@ -0,0 +1,4 @@ +[ + "'background' splits into", + "'--color-navy-800' is an old palette color" +] diff --git a/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/styles.input.ts b/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/styles.input.ts new file mode 100644 index 0000000000..e11ae5ce51 --- /dev/null +++ b/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/styles.input.ts @@ -0,0 +1,29 @@ +import styled from '@emotion/styled'; +import { css, states, themed, variant } from '@skillsoft/gamut-styles'; + +export const base = css({ + bg: 'primary', + color: 'background', + '&:hover': { bg: 'primary-hover' }, +}); + +export const variants = variant({ + variants: { + quiet: { textColor: 'text-secondary', borderColor: 'border-tertiary' }, + loud: { bg: 'danger', variant: 'primary' }, + }, +}); + +export const flags = states({ selected: { bg: 'background-selected' } }); + +export const Swatch = styled.div<{ variant: string }>` + color: ${({ theme }) => theme.colors.text}; + background: ${(props) => props.theme.colors['background-hover']}; + border-color: ${({ theme }) => theme.colors.background}; + outline-color: ${themed('colors.primary')}; +`; + +export const runtime = (v: string) => css({ bg: `${v}-hover` }); + +const kind = 'primary'; +export const untouched = { variant: kind, label: 'text' }; diff --git a/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/styles.output.ts b/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/styles.output.ts new file mode 100644 index 0000000000..6b862c558d --- /dev/null +++ b/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/styles.output.ts @@ -0,0 +1,29 @@ +import styled from '@emotion/styled'; +import { css, states, themed, variant } from '@skillsoft/gamut-styles'; + +export const base = css({ + bg: 'action-primary', + /* color-roles: 'background' splits into surface-raised | surface-default. Anything that sits on the page (card, input, menu, popover, dialog) takes `surface-raised`. Where `background` fills the page itself, it is `surface-default`. */ color: 'background', + '&:hover': { bg: 'action-primary-hover' }, +}); + +export const variants = variant({ + variants: { + quiet: { textColor: 'text-subtle', /* color-roles: 'border-tertiary' splits into border-subtle | border-strong. A divider or card hairline is `border-subtle`. Where it marks an active field or a selected row, it is `border-strong`. Gamut’s own two usages, the FeatureShimmer edge and the List scroll shadow, are both `border-subtle`. Core resolves it to a light navy and Percipio to a dark one, so check each app usage for which it meant. */ borderColor: 'border-tertiary' }, + loud: { bg: 'action-danger', variant: 'primary' }, + }, +}); + +export const flags = states({ selected: { bg: 'state-selected' } }); + +export const Swatch = styled.div<{ variant: string }>` + color: ${({ theme }) => theme.colors['text-default']}; + background: ${(props) => /* color-roles: 'background-hover' splits into state-hover | surface-sunken. As a hover, it is the `state-hover` veil. Used as a resting fill (the subtle Alert, a tinted panel), it is `surface-sunken`. */ props.theme.colors['background-hover']}; + border-color: ${({ theme }) => /* color-roles: 'background' splits into surface-raised | surface-default. Anything that sits on the page (card, input, menu, popover, dialog) takes `surface-raised`. Where `background` fills the page itself, it is `surface-default`. */ theme.colors.background}; + outline-color: ${themed('colors.action-primary')}; +`; + +export const runtime = (v: string) => css({ bg: `${v}-hover` }); + +const kind = 'primary'; +export const untouched = { variant: kind, label: 'text' }; diff --git a/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/styles.warnings.json b/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/styles.warnings.json new file mode 100644 index 0000000000..ddd7fac912 --- /dev/null +++ b/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/styles.warnings.json @@ -0,0 +1,6 @@ +[ + "fixture.tsx:6 'background' splits into", + "'border-tertiary' splits into border-subtle | border-strong", + "'background-hover' splits into state-hover | surface-sunken", + "color name built at runtime (`${v}-hover`)" +] diff --git a/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/theme-lookups.input.tsx b/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/theme-lookups.input.tsx new file mode 100644 index 0000000000..e733e3c220 --- /dev/null +++ b/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/theme-lookups.input.tsx @@ -0,0 +1,59 @@ +import styled from '@emotion/styled'; +import { Icon } from '@skillsoft/gamut'; +import { css, themed, useTheme } from '@skillsoft/gamut-styles'; + +import { colors as swatches } from './swatches'; + +/* A dark fill has no default: marked, and the message names the property. */ +export const NavBar = styled.aside` + background-color: ${({ theme }) => theme.colors.navy}; + color: ${({ theme }) => theme.colors.navy}; + border: 1px solid ${(props) => props.theme.colors['navy-300']}; + background: ${({ theme }) => theme.colors['navy-100']}; + border-color: ${themed('colors.red')}; + box-shadow: 0 0 0 1px ${({ theme }) => theme.colors['navy-300']}; +`; + +/* Inside a function the color is one stop of something else: marked. */ +export const Fade = styled.div` + background: linear-gradient(${({ theme }) => theme.colors['navy-100']}, transparent); +`; + +export const Link = styled.a` + color: ${themed('colors.hyper')}; + &:hover { + color: ${({ theme }) => (theme.colors ? theme.colors.text : 'inherit')}; + } +`; + +export const styles = ({ theme }: { theme: any }) => + css({ backgroundColor: theme.colors['gray-100'], color: theme.colors.hyper }); + +export const Aliased = ({ theme }: { theme: any }) => { + const c = theme.colors; + return { color: c.navy, borderColor: c['navy-300'] }; +}; + +export const Destructured = styled.span` + color: ${({ theme: { colors } }) => colors['red-500']}; +`; + +export const Hooked = () => { + const { colors } = useTheme(); + const { text, navy: heading } = useTheme().colors; + return ( + <> + + + + ); +}; + +/* Not the theme: left alone. */ +export const swatch = swatches.navy; + +export const Vars = styled.div` + color: var(--color-red); + box-shadow: 0 0 0 1px var(--color-navy-300); +`; +export const panel = { backgroundColor: 'var(--color-navy-100)' }; diff --git a/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/theme-lookups.output.tsx b/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/theme-lookups.output.tsx new file mode 100644 index 0000000000..07d4c55aa9 --- /dev/null +++ b/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/theme-lookups.output.tsx @@ -0,0 +1,59 @@ +import styled from '@emotion/styled'; +import { Icon } from '@skillsoft/gamut'; +import { css, themed, useTheme } from '@skillsoft/gamut-styles'; + +import { colors as swatches } from './swatches'; + +/* A dark fill has no default: marked, and the message names the property. */ +export const NavBar = styled.aside` + background-color: ${({ theme }) => /* color-roles: 'navy' is an old palette color with no role of its own, used as a theme.colors lookup for `background-color`. A dark navy fill is a dark area: make it dark mode with ``, say why in a comment, and remove this fill. */ theme.colors.navy}; + color: ${({ theme }) => theme.colors['text-default']}; + border: 1px solid ${(props) => props.theme.colors['border-subtle']}; + background: ${({ theme }) => theme.colors['surface-default']}; + border-color: ${themed('colors.text-error')}; + box-shadow: 0 0 0 1px ${({ theme }) => /* color-roles: 'navy-300' is an old palette color with no role of its own, used as a theme.colors lookup for `box-shadow`. Pick the role from design's component map (@skillsoft/gamut-brand src/migration.ts, COMPONENTS). */ theme.colors['navy-300']}; +`; + +/* Inside a function the color is one stop of something else: marked. */ +export const Fade = styled.div` + background: linear-gradient(${({ theme }) => /* color-roles: 'navy-100' is an old palette color with no role of its own, used as a theme.colors lookup. Pick the role from design's component map (@skillsoft/gamut-brand src/migration.ts, COMPONENTS). */ theme.colors['navy-100']}, transparent); +`; + +export const Link = styled.a` + color: ${themed('colors.action-primary')}; + &:hover { + color: ${({ theme }) => (theme.colors ? theme.colors['text-default'] : 'inherit')}; + } +`; + +export const styles = ({ theme }: { theme: any }) => + css({ backgroundColor: theme.colors['surface-default'], color: theme.colors['action-primary'] }); + +export const Aliased = ({ theme }: { theme: any }) => { + const c = theme.colors; + return { color: c['text-default'], borderColor: c['border-subtle'] }; +}; + +export const Destructured = styled.span` + color: ${({ theme: { colors } }) => colors['text-error']}; +`; + +export const Hooked = () => { + const { colors } = useTheme(); + const { 'text-default': text, /* color-roles: 'navy' is an old palette color with no role of its own, used as a key destructured from theme.colors. Pick the role from design's component map (@skillsoft/gamut-brand src/migration.ts, COMPONENTS). */ navy: heading } = useTheme().colors; + return ( + <> + + + + ); +}; + +/* Not the theme: left alone. */ +export const swatch = swatches.navy; + +export const Vars = styled.div/* color-roles: 'navy-300' is an old palette color with no role of its own, used as a CSS variable for `box-shadow`. Pick the role from design's component map (@skillsoft/gamut-brand src/migration.ts, COMPONENTS). */ ` + color: var(--color-text-error); + box-shadow: 0 0 0 1px var(--color-navy-300); +`; +export const panel = { backgroundColor: 'var(--color-surface-default)' }; diff --git a/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/theme-lookups.warnings.json b/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/theme-lookups.warnings.json new file mode 100644 index 0000000000..c876a3a7a0 --- /dev/null +++ b/packages/gamut-codemods/src/migrations/color-roles/__testfixtures__/theme-lookups.warnings.json @@ -0,0 +1,7 @@ +[ + "fixture.tsx:9 'navy' is an old palette color with no role of its own, used as a theme.colors lookup for `background-color`. A dark navy fill is a dark area: make it dark mode with ``", + "'navy-300' is an old palette color with no role of its own, used as a theme.colors lookup for `box-shadow`", + "'navy-100' is an old palette color with no role of its own, used as a theme.colors lookup.", + "'navy' is an old palette color with no role of its own, used as a key destructured from theme.colors", + "'--color-navy-300' is an old palette color with no role of its own, used as a CSS variable for `box-shadow`" +] diff --git a/packages/gamut-codemods/src/migrations/color-roles/cssVars.ts b/packages/gamut-codemods/src/migrations/color-roles/cssVars.ts new file mode 100644 index 0000000000..0040a11a2a --- /dev/null +++ b/packages/gamut-codemods/src/migrations/color-roles/cssVars.ts @@ -0,0 +1,109 @@ +import { paletteAdvice } from '../../presets/color-roles/decisions'; +import type { + ColorAlias, + ColorRolesManifest, +} from '../../presets/color-roles/manifest'; +import { isAutomatic } from '../../presets/color-roles/manifest'; + +export const MARK = 'color-roles:'; + +/* "'background' splits into surface-raised | surface-default. " */ +export const describe = (name: string, { kind, to, rule }: ColorAlias) => { + const roles = to.join(' | '); + const what = + kind === 'split' + ? `splits into ${roles}` + : kind === 'retire' + ? `is retired${roles ? ` (closest: ${roles})` : ''}` + : 'is pending'; + return `'${name}' ${what}. ${rule}`; +}; + +/* The same, safe inside a block comment. */ +export const commentText = (name: string, alias: ColorAlias) => + `/* ${MARK} ${describe(name, alias).replace(/\*\//g, '* /')} */ `; + +/* The color-roles comment right before `at`: where it opens, and its text. */ +const markBefore = (text: string, at: number) => { + const before = text.slice(0, at).trimEnd(); + if (!before.endsWith('*/')) return null; + const open = before.lastIndexOf('/*'); + if (open === -1 || !before.slice(open).includes(MARK)) return null; + return { start: open, text: before.slice(open) }; +}; + +/* Already marked by an earlier run: a color-roles comment right before `at`. */ +export const markedBefore = (text: string, at: number) => + markBefore(text, at) !== null; + +/* + A comment an earlier run left for `name` at `at`, when this run replaces + the name: the range to delete, from the comment up to `at`. A run with a + newer manifest can resolve a name an older one only marked, and the stale + comment would otherwise stay in the leftovers report. +*/ +export const staleMark = (text: string, at: number, name: string) => { + const mark = markBefore(text, at); + return mark?.text.includes(`'${name}'`) + ? { start: mark.start, end: at } + : null; +}; + +/* + An old color variable: `--color-`. The rewritten name is `--color-`, + and no role is also an old name, so a second run leaves it alone. +*/ +const OLD_VAR = /--color-([A-Za-z0-9][\w-]*)/g; + +export const mentionsOldVar = (text: string) => + /--color-[A-Za-z0-9]/.test(text); + +export interface VarHit { + /* Offset of `--color-…` in the text. */ + at: number; + name: string; + /* The role it becomes, for renames and merges. */ + role?: string; + /* Design's row, for splits, retirements and pending names. */ + alias?: ColorAlias; + /* An old palette color (navy-800): no role replaces it by name. */ + palette?: boolean; +} + +/* Every old color variable in `text` the manifest knows about. */ +export const findOldVars = ( + text: string, + manifest: ColorRolesManifest +): VarHit[] => { + const palette = new Set(manifest.oldPalette); + const hits: VarHit[] = []; + for (const m of text.matchAll(OLD_VAR)) { + const name = m[1]; + const alias = manifest.aliases[name]; + if (alias) { + hits.push( + isAutomatic(alias) + ? { at: m.index, name, role: alias.to[0] } + : { at: m.index, name, alias } + ); + } else if (palette.has(name)) { + hits.push({ at: m.index, name, palette: true }); + } + } + return hits; +}; + +/* + `name` is as the person wrote it (`navy`, or `--color-navy` in a stylesheet); + `where` says what the name was used as (`the \`bg\` prop`), since the same + palette name can be a fill in one place and text in another. +*/ +export const paletteMessage = (name: string, where: string) => + `'${name}' is an old palette color with no role of its own, used as ${where}. ${ + paletteAdvice(name.replace(/^--color-/, ''), where) ?? + "Pick the role from design's component map (@skillsoft/gamut-brand src/migration.ts, COMPONENTS)." + }`; + +/* The same, as a comment for a person. Safe inside a block comment. */ +export const paletteComment = (name: string, where: string) => + `/* ${MARK} ${paletteMessage(name, where).replace(/\*\//g, '* /')} */ `; diff --git a/packages/gamut-codemods/src/migrations/color-roles/index.ts b/packages/gamut-codemods/src/migrations/color-roles/index.ts new file mode 100644 index 0000000000..d35707a153 --- /dev/null +++ b/packages/gamut-codemods/src/migrations/color-roles/index.ts @@ -0,0 +1,604 @@ +import type { Edit, SpliceMigration } from '../../lib/types'; +import { + cssPropertyBefore, + paletteDefault, +} from '../../presets/color-roles/decisions'; +import type { ColorRolesManifest } from '../../presets/color-roles/manifest'; +import { isAutomatic } from '../../presets/color-roles/manifest'; +import { + commentText, + describe, + findOldVars, + MARK, + markedBefore, + mentionsOldVar, + paletteComment, + paletteMessage, + staleMark, +} from './cssVars'; + +/* + Today's Gamut color names → roles, wherever a color name sits: + + - a color prop in JSX (`bg="background-primary"`) or in a style object + (`css`, `variant`, `states`, plain objects), including the branches of a + ternary or `&&`, and responsive objects and arrays; + - `theme.colors.text` / `theme.colors['text-disabled']`, also through + `props.theme`, `useTheme()`, a variable holding `theme.colors`, or + `colors` destructured from the theme (`({ theme: { colors } }) =>`); + - keys destructured from `theme.colors` (`const { text } = theme.colors`); + - `themed('colors.primary')`; + - `var(--color-text)` inside a string or template literal, which becomes + `var(--color-text-default)` (stylesheets are the + color-roles-stylesheets migration); + - Card's `variant`, onto design's `default` and `brand`. + + Rename and merge rows are applied. Split, retire and pending rows need a + person: the name stays (so it still fails the type check) and a + `/* color-roles: … *\/` comment with design's rule goes in front of it. + Old palette names (navy, hyper-500) take a default from decisions.ts when + their use is known: the prop, or for a lookup or CSS variable the CSS + property or style key it is the value of. Otherwise they get a comment + like the manual rows. Names built at runtime (`${variant}-hover`) only + warn. Anything outside those positions, like a name in a const that's + passed to `bg` later, isn't seen. +*/ + +/* + Card's variants are design's two: white, beige and navy + become `default`; yellow and hyper become `brand`. +*/ +const CARD_VARIANTS: Record = { + white: 'default', + beige: 'default', + navy: 'default', + yellow: 'brand', + hyper: 'brand', +}; + +const NAVY_CARD = `/* ${MARK} Card's 'navy' variant becomes 'default' (surface-raised), which renders light. If this card should stay dark, wrap it in . */ `; + +const GAMUT = /(^|\/)gamut$/; + +/* Babel AST nodes, loosely: positions plus whatever the type carries. */ +interface Node { + type: string; + start: number; + end: number; + loc?: { start: { line: number } } | null; + [key: string]: any; +} + +const isString = (n: Node | null | undefined): n is Node & { value: string } => + !!n && + (n.type === 'StringLiteral' || + (n.type === 'Literal' && typeof n.value === 'string')); + +const keyName = (prop: Node): string | undefined => { + if (prop.computed) return undefined; + const { key } = prop; + if (key?.type === 'Identifier') return key.name; + if (isString(key)) return key.value; + return undefined; +}; + +const isMember = (n: Node | null | undefined): n is Node => + !!n && + (n.type === 'MemberExpression' || n.type === 'OptionalMemberExpression'); + +/* `theme`, `.theme`, or `useTheme()`. */ +const isTheme = (n: Node | null | undefined) => + !!n && + ((n.type === 'Identifier' && n.name === 'theme') || + (isMember(n) && !n.computed && n.property?.name === 'theme') || + ((n.type === 'CallExpression' || n.type === 'OptionalCallExpression') && + n.callee?.type === 'Identifier' && + n.callee.name === 'useTheme')); + +/* `.colors`. */ +const isThemeColors = (n: Node | null | undefined) => + isMember(n) && + !n.computed && + n.property?.name === 'colors' && + isTheme(n.object); + +/* Path-like: the jscodeshift NodePath fields used here. */ +interface Path { + node: unknown; + parent?: Path | null; + scope?: { lookup(name: string): unknown } | null; +} + +/* + The prop, style key or CSS property a color expression is the value of: + `bg={…}`, `{ backgroundColor: … }`, or `background-color: ${…}` in a + template. It passes through arrow bodies, ternary branches, `&&` / `||` + and type casts; anything else (a call like `rgba(…)`, a nested template) + means the use isn't known. +*/ +const propertyOf = (path: Path): string | undefined => { + let child = path.node; + let { parent } = path; + while (parent) { + const n = parent.node as Node; + switch (n.type) { + case 'ConditionalExpression': + if (child === n.test) return undefined; + break; + case 'ArrowFunctionExpression': + if (child !== n.body) return undefined; + break; + case 'LogicalExpression': + case 'ParenthesizedExpression': + case 'TSAsExpression': + case 'TSSatisfiesExpression': + case 'TSNonNullExpression': + break; + case 'TemplateLiteral': { + const i = n.expressions.indexOf(child); + if (i === -1) return undefined; + return cssPropertyBefore( + n.quasis + .slice(0, i + 1) + .map((q: Node) => q.value.raw) + .join('0') + ); + } + case 'ObjectProperty': + case 'Property': + return child === n.value ? keyName(n) : undefined; + case 'JSXExpressionContainer': { + const attr = parent.parent?.node as Node | undefined; + return attr?.type === 'JSXAttribute' && + attr.name?.type === 'JSXIdentifier' + ? attr.name.name + : undefined; + } + default: + return undefined; + } + child = n; + ({ parent } = parent); + } + return undefined; +}; + +/* "a theme.colors lookup for `color`", or without the tail when unknown. */ +const usedFor = (what: string, property: string | undefined) => + property ? `${what} for \`${property}\`` : what; + +export const colorRoles: SpliceMigration = { + name: 'color-roles', + kind: 'splice', + description: + 'Rename Gamut color names to roles; mark splits, retirements and pending names with design’s rule.', + edits({ j, root, source, manifest, warn, note }) { + const props = new Set(manifest.colorProps); + const palette = new Set(manifest.oldPalette); + const edits: Edit[] = []; + const seen = new Set(); + + const marked = (at: number) => markedBefore(source, at); + + /* Drop an earlier run's comment for `name` at `at`, once. */ + const unmarked = new Set(); + const unmark = (at: number, name: string) => { + const stale = staleMark(source, at, name); + if (!stale || unmarked.has(stale.start)) return; + unmarked.add(stale.start); + edits.push({ ...stale, text: '' }); + }; + + const mark = (at: number, name: string) => { + const alias = manifest.aliases[name]; + if (!marked(at)) { + edits.push({ + start: at, + end: at, + text: commentText(name, alias), + }); + } + }; + + /* + One color name. `replace` swaps it for a role; `markAt` is where a + comment can go (in front of a JSX attribute, not inside it); `where` + says what the name is used as, for the palette message. + */ + const visit = ( + node: Node, + name: string, + replace: (role: string) => Edit, + markAt: number, + where: string + ) => { + if (seen.has(node.start)) return; + seen.add(node.start); + const alias = manifest.aliases[name]; + if (alias) { + if (isAutomatic(alias)) { + edits.push(replace(alias.to[0])); + unmark(markAt, name); + } else { + mark(markAt, name); + warn(node, describe(name, alias)); + note('color-roles:manual'); + } + } else if (palette.has(name)) { + const role = paletteDefault(name, where); + if (role) { + edits.push(replace(role)); + unmark(markAt, name); + note('color-roles:palette-default'); + return; + } + if (!marked(markAt)) { + edits.push({ + start: markAt, + end: markAt, + text: paletteComment(name, where), + }); + } + warn(node, paletteMessage(name, where)); + note('color-roles:palette'); + } + }; + + const visitString = (lit: Node, markAt: number, where: string) => + visit( + lit, + lit.value, + (role) => ({ start: lit.start + 1, end: lit.end - 1, text: role }), + markAt, + where + ); + + /* Every string a color-valued expression can produce. */ + const collect = ( + expr: Node | null | undefined, + where: string, + markAt?: number + ) => { + if (!expr) return; + switch (expr.type) { + case 'StringLiteral': + case 'Literal': + if (isString(expr)) visitString(expr, markAt ?? expr.start, where); + return; + case 'ConditionalExpression': + collect(expr.consequent, where); + collect(expr.alternate, where); + return; + case 'LogicalExpression': + collect(expr.left, where); + collect(expr.right, where); + return; + case 'ObjectExpression': + for (const p of expr.properties) { + if (p.type === 'ObjectProperty' || p.type === 'Property') { + collect(p.value, where); + } + } + return; + case 'ArrayExpression': + expr.elements.forEach((el: Node) => collect(el, where)); + return; + case 'TSAsExpression': + case 'TSSatisfiesExpression': + case 'TSNonNullExpression': + case 'ParenthesizedExpression': + case 'TypeCastExpression': + collect(expr.expression, where, markAt); + return; + case 'TemplateLiteral': + if (expr.expressions.length > 0) { + warn( + expr, + `color name built at runtime (${source.slice( + expr.start, + expr.end + )}). The codemod can't map it; check each value it can take.` + ); + note('color-roles:runtime'); + } + return; + default: + } + }; + + /* + Names bound to the theme's colors, with the scope each is declared in, + so `colors.navy` counts only where `colors` is that binding (and not, + say, an imported `colors`). `const c = theme.colors`, `const { colors } + = theme`, `({ theme: { colors } }) =>`. Patterns that pull color keys + out of `theme.colors` are kept to visit as color names. + */ + const colorsBindings = new Map>(); + const colorPatterns: Node[] = []; + const bind = (path: Path, name: string) => { + const scope = path.scope?.lookup(name); + if (!scope) return; + const scopes = colorsBindings.get(name) ?? new Set(); + scopes.add(scope); + colorsBindings.set(name, scopes); + }; + /* `pattern` destructures a theme: find its `colors`. */ + const fromTheme = (path: Path, pattern: Node) => { + for (const prop of pattern.properties ?? []) { + if (prop.type !== 'ObjectProperty' && prop.type !== 'Property') + continue; + if (keyName(prop) !== 'colors') continue; + const value = + prop.value?.type === 'AssignmentPattern' + ? prop.value.left + : prop.value; + if (value?.type === 'Identifier') bind(path, value.name); + else if (value?.type === 'ObjectPattern') colorPatterns.push(value); + } + }; + root.find(j.VariableDeclarator).forEach((p) => { + const { id, init } = p.node as unknown as Node; + if (id.type === 'Identifier' && isThemeColors(init)) bind(p, id.name); + else if (id.type === 'ObjectPattern') { + if (isTheme(init)) fromTheme(p, id); + else if (isThemeColors(init)) colorPatterns.push(id); + } + }); + root.find(j.ObjectPattern).forEach((p) => { + for (const prop of (p.node as unknown as Node).properties ?? []) { + if ( + (prop.type === 'ObjectProperty' || prop.type === 'Property') && + keyName(prop) === 'theme' && + prop.value?.type === 'ObjectPattern' + ) { + fromTheme(p, prop.value); + } + } + }); + + /* `theme.colors`, or a name bound to it in this scope. */ + const isColors = (n: Node | null | undefined, at: Path) => + isThemeColors(n) || + (n?.type === 'Identifier' && + !!colorsBindings.get(n.name)?.has(at.scope?.lookup(n.name))); + + /* + `const { text, navy: n } = theme.colors`: each key is a color name. + A rename rewrites the key and keeps the local name. + */ + for (const pattern of colorPatterns) { + for (const prop of pattern.properties ?? []) { + if (prop.type !== 'ObjectProperty' && prop.type !== 'Property') + continue; + const name = keyName(prop); + if (!name) continue; + visit( + prop, + name, + (role) => + prop.shorthand + ? { + start: prop.start, + end: prop.end, + text: `'${role}': ${source.slice( + prop.value.start, + prop.value.end + )}`, + } + : { start: prop.key.start, end: prop.key.end, text: `'${role}'` }, + prop.start, + 'a key destructured from theme.colors' + ); + } + } + + root.find(j.JSXAttribute).forEach((p) => { + const attr = p.node as unknown as Node; + if (attr.name?.type !== 'JSXIdentifier' || !props.has(attr.name.name)) { + return; + } + const { value } = attr; + const where = `the \`${attr.name.name}\` prop`; + if (isString(value)) collect(value, where, attr.start); + else if (value?.type === 'JSXExpressionContainer') { + collect(value.expression, where); + } + }); + + root.find(j.Node).forEach((p) => { + const node = p.node as unknown as Node; + if (node.type === 'ObjectProperty' || node.type === 'Property') { + const key = keyName(node); + if (key && props.has(key)) { + collect( + node.value, + `the \`${key}\` value`, + isString(node.value) ? node.start : undefined + ); + } + return; + } + + if (isMember(node) && isColors(node.object, p)) { + const { property } = node; + const name = node.computed + ? isString(property) + ? property.value + : undefined + : property?.name; + if (!name) return; + visit( + node, + name, + (role) => + node.computed + ? { start: property.start + 1, end: property.end - 1, text: role } + : { + /* `.text` → `['text-default']`, keeping a `?.` */ + start: node.object.end, + end: property.end, + text: `${ + source.slice(node.object.end, property.start).includes('?.') + ? '?.' + : '' + }['${role}']`, + }, + node.start, + usedFor('a theme.colors lookup', propertyOf(p)) + ); + return; + } + + if ( + node.type === 'CallExpression' && + node.callee?.type === 'Identifier' && + node.callee.name === 'themed' && + isString(node.arguments?.[0]) && + node.arguments[0].value.startsWith('colors.') + ) { + const arg = node.arguments[0]; + const name = arg.value.slice('colors.'.length); + visit( + arg, + name, + (role) => ({ + start: arg.start + 1, + end: arg.end - 1, + text: `colors.${role}`, + }), + node.start, + usedFor("a themed('colors.…') lookup", propertyOf(p)) + ); + } + }); + + /* + `var(--color-…)` in a string or template literal. A rename is applied + in place; a name for a person gets its comment in front of the + literal, outside the string. + */ + root.find(j.Node).forEach((p) => { + const node = p.node as unknown as Node; + const literal = isString(node) || node.type === 'TemplateLiteral'; + if (!literal) return; + const raw = source.slice(node.start, node.end); + if (!mentionsOldVar(raw)) return; + /* Names this literal still needs a person for, and names it replaced. */ + let open = false; + const replaced: string[] = []; + for (const hit of findOldVars(raw, manifest)) { + const at = node.start + hit.at; + /* + The property is in the literal (`color: var(--color-red)`), or the + literal is only the `var(` and its key says (`{ color: 'var(…)' }`). + */ + const where = usedFor( + 'a CSS variable', + hit.palette + ? /^\s*var\(\s*$/.test(raw.slice(1, hit.at)) + ? propertyOf(p) + : cssPropertyBefore(raw.slice(0, hit.at)) + : undefined + ); + const role = + hit.role ?? (hit.palette ? paletteDefault(hit.name, where) : null); + if (role) { + edits.push({ + start: at, + end: at + `--color-${hit.name}`.length, + text: `--color-${role}`, + }); + replaced.push(hit.name); + if (!hit.role) note('color-roles:palette-default'); + continue; + } + open = true; + if (hit.alias) { + if (!marked(node.start) && !seen.has(node.start)) { + seen.add(node.start); + edits.push({ + start: node.start, + end: node.start, + text: commentText(hit.name, hit.alias), + }); + } + warn(node, describe(hit.name, hit.alias)); + note('color-roles:manual'); + } else if (hit.palette) { + const cssName = `--color-${hit.name}`; + if (!marked(node.start) && !seen.has(node.start)) { + seen.add(node.start); + edits.push({ + start: node.start, + end: node.start, + text: paletteComment(hit.name, where), + }); + } + warn(node, paletteMessage(cssName, where)); + note('color-roles:palette'); + } + } + /* The comment sits in front of the literal, so it goes only when nothing in it is left. */ + if (!open) replaced.forEach((name) => unmark(node.start, name)); + }); + + /* Card's variant, when Card comes from gamut. */ + const cardNames = new Set(); + root.find(j.ImportDeclaration).forEach((p) => { + const decl = p.node as unknown as Node; + if (!GAMUT.test(decl.source.value)) return; + for (const spec of decl.specifiers ?? []) { + if (spec.type === 'ImportSpecifier' && spec.imported?.name === 'Card') { + cardNames.add(spec.local?.name ?? 'Card'); + } + } + }); + if (cardNames.size > 0) { + root.find(j.JSXOpeningElement).forEach((p) => { + const el = p.node as unknown as Node; + if (el.name?.type !== 'JSXIdentifier' || !cardNames.has(el.name.name)) { + return; + } + for (const attr of el.attributes ?? []) { + if (attr.type !== 'JSXAttribute' || attr.name?.name !== 'variant') { + continue; + } + const lits: Node[] = []; + const gather = (e: Node | null | undefined) => { + if (!e) return; + if (isString(e)) lits.push(e); + else if (e.type === 'ConditionalExpression') { + gather(e.consequent); + gather(e.alternate); + } else if (e.type === 'LogicalExpression') gather(e.right); + }; + if (isString(attr.value)) gather(attr.value); + else if (attr.value?.type === 'JSXExpressionContainer') { + gather(attr.value.expression); + } + for (const lit of lits) { + const to = CARD_VARIANTS[lit.value]; + if (!to) continue; + edits.push({ start: lit.start + 1, end: lit.end - 1, text: to }); + if (lit.value === 'navy') { + if (!marked(attr.start)) { + edits.push({ + start: attr.start, + end: attr.start, + text: NAVY_CARD, + }); + } + warn( + lit, + "Card's 'navy' variant becomes 'default', which renders light. Wrap the card in if it should stay dark." + ); + note('color-roles:card-navy'); + } + } + } + }); + } + + return edits; + }, +}; diff --git a/packages/gamut-codemods/src/migrations/markdown-video-overrides/index.ts b/packages/gamut-codemods/src/migrations/markdown-video-overrides/index.ts index ec39e76ad3..ddf200ff26 100644 --- a/packages/gamut-codemods/src/migrations/markdown-video-overrides/index.ts +++ b/packages/gamut-codemods/src/migrations/markdown-video-overrides/index.ts @@ -65,7 +65,7 @@ const readSkips = ( ) => { const skips = new Map(); const unreadable = new Set(); - const value = skipAttr.value; + const { value } = skipAttr; if ( value?.type !== 'JSXExpressionContainer' || @@ -188,7 +188,7 @@ export const markdownVideoOverrides: AstMigration = { ({ skips, unreadable } = read); if (read.removed) changed = true; - const value = skipAttr.value; + const { value } = skipAttr; if ( value?.type === 'JSXExpressionContainer' && value.expression.type === 'ObjectExpression' && @@ -219,7 +219,7 @@ export const markdownVideoOverrides: AstMigration = { const local = new Map(); const missing: string[] = []; for (const name of names) { - if (bound.has(name)) local.set(name, bound.get(name) as string); + if (bound.has(name)) local.set(name, bound.get(name)!); else { local.set(name, name); missing.push(name); @@ -257,7 +257,7 @@ export const markdownVideoOverrides: AstMigration = { j.property( 'init', j.identifier('component'), - j.identifier(local.get(component) as string) + j.identifier(local.get(component)!) ), ]); path.node.attributes = [ 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/palette-defaults.test.ts b/packages/gamut-codemods/src/palette-defaults.test.ts new file mode 100644 index 0000000000..c5433d1556 --- /dev/null +++ b/packages/gamut-codemods/src/palette-defaults.test.ts @@ -0,0 +1,121 @@ +import { describe, expect, it } from 'vitest'; +import { + cssPropertyBefore, + DEFAULT_ROLES, + paletteAdvice, + paletteDefault, +} from './presets/color-roles/decisions'; +import { manifest } from './presets/color-roles/manifest'; + +describe('palette defaults', () => { + it('only name roles the generated system has', () => { + for (const role of DEFAULT_ROLES) { + expect(manifest.roles).toContain(role); + } + }); + + it('leave a color alone when its use is not known', () => { + expect(paletteDefault('red-500', 'a theme.colors lookup')).toBeNull(); + expect(paletteDefault('red-500', 'a CSS variable')).toBeNull(); + }); + + it('read the use of a lookup or CSS variable from the property it is for', () => { + expect( + paletteDefault('navy-100', 'a theme.colors lookup for `background-color`') + ).toBe('surface-default'); + expect(paletteDefault('red', 'a CSS variable for `color`')).toBe( + 'text-error' + ); + expect( + paletteDefault('navy-300', 'a CSS variable for `border-left-color`') + ).toBe('border-subtle'); + expect( + paletteDefault('navy-300', 'a theme.colors lookup for `box-shadow`') + ).toBeNull(); + expect( + paletteDefault('navy-300', 'a theme.colors lookup for `border-radius`') + ).toBeNull(); + /* A dark navy fill has no default, wherever it sits. */ + expect( + paletteDefault('navy', 'a theme.colors lookup for `background-color`') + ).toBeNull(); + }); + + it('send dark navy fills to a dark-mode scope', () => { + for (const name of ['navy', 'navy-700', 'navy-800']) { + expect( + paletteAdvice(name, 'a theme.colors lookup for `background-color`') + ).toContain(''); + } + expect(paletteAdvice('navy-500', 'the `bg` prop')).toBeNull(); + expect(paletteAdvice('navy', 'the `color` prop')).toBeNull(); + expect(paletteAdvice('navy', 'a theme.colors lookup')).toBeNull(); + }); + + it('find the CSS property a value is being written for', () => { + expect(cssPropertyBefore('width: 2px;\n background-color: ')).toBe( + 'background-color' + ); + expect(cssPropertyBefore('border: 1px solid ')).toBe('border'); + expect(cssPropertyBefore('&:hover {\n color: ')).toBe('color'); + expect(cssPropertyBefore('color: var(')).toBe('color'); + expect(cssPropertyBefore('Color: var( ')).toBe('color'); + expect(cssPropertyBefore('background: linear-gradient(')).toBeUndefined(); + expect(cssPropertyBefore('color: rgba(0, 0, 0, 0.5) ')).toBeUndefined(); + expect(cssPropertyBefore('$accent: ')).toBeUndefined(); + expect(cssPropertyBefore('1px solid ')).toBeUndefined(); + expect(cssPropertyBefore('.panel { ')).toBeUndefined(); + expect( + cssPropertyBefore("color: /* color-roles: 'navy' (see: map) */ var(") + ).toBe('color'); + }); + + it('map hyper, the old primary, to action-primary', () => { + expect(paletteDefault('hyper', 'the `bg` prop')).toBe('action-primary'); + expect(paletteDefault('hyper-500', 'the `color` prop')).toBe( + 'action-primary' + ); + expect(paletteDefault('hyper-400', 'the `bg` prop')).toBeNull(); + expect(paletteDefault('yellow', 'the `bg` prop')).toBeNull(); + }); + + it('map the warning family, yellow-0 fills and yellow ink, and leave the accent to a person', () => { + expect(paletteDefault('yellow-0', 'the `bg` prop')).toBe('surface-warning'); + expect(paletteDefault('yellow', 'the `color` prop')).toBe('text-warning'); + expect(paletteDefault('yellow-900', 'the `textColor` prop')).toBe( + 'text-warning' + ); + expect(paletteDefault('yellow', 'the `bg` prop')).toBeNull(); + expect(paletteDefault('yellow-500', 'the `bg` prop')).toBeNull(); + expect(paletteDefault('yellow-400', 'the `color` prop')).toBeNull(); + }); + + it('map blue-500 text to action-primary, and leave blue fills to a person', () => { + expect(paletteDefault('blue-500', 'the `color` prop')).toBe( + 'action-primary' + ); + expect(paletteDefault('blue', 'the `textColor` prop')).toBe( + 'action-primary' + ); + expect(paletteDefault('blue-500', 'the `bg` prop')).toBeNull(); + expect(paletteDefault('blue-500', 'the `borderColor` prop')).toBeNull(); + expect(paletteDefault('blue-300', 'the `color` prop')).toBeNull(); + }); + + it('follow the use for greys, and keep light grey text for a person', () => { + expect(paletteDefault('gray-100', 'the `bg` prop')).toBe('surface-default'); + expect(paletteDefault('gray-300', 'the `bg` prop')).toBe('surface-sunken'); + expect(paletteDefault('gray-800', 'the `color` prop')).toBe('text-subtle'); + expect(paletteDefault('gray-300', 'the `borderColor` prop')).toBe( + 'border-subtle' + ); + expect(paletteDefault('gray-900', 'the `borderColor` prop')).toBe( + 'border-default' + ); + expect(paletteDefault('gray-100', 'the `color` prop')).toBeNull(); + }); + + it('keep dark navy fills for design', () => { + expect(paletteDefault('navy-600', 'the `bg` prop')).toBeNull(); + }); +}); diff --git a/packages/gamut-codemods/src/presets/color-roles/aliases.ts b/packages/gamut-codemods/src/presets/color-roles/aliases.ts new file mode 100644 index 0000000000..6df7deac3c --- /dev/null +++ b/packages/gamut-codemods/src/presets/color-roles/aliases.ts @@ -0,0 +1,331 @@ +import type { ColorAlias, ColorRolesManifest } from './manifest'; + +/* + Generated from design's migration map: @skillsoft/gamut-brand + src/migration.ts (TOKEN_MAP). Regenerate when design's map changes + (~/z_team/everest/color-tokens/codemod/gen-manifest.ts); don't edit rows by + hand. +*/ +export const aliases: Record = { + text: { + kind: 'rename', + to: ['text-default'], + rule: 'Body copy and headings.', + }, + 'text-accent': { + kind: 'merge', + to: ['text-default'], + rule: 'Headings take `text-default` too. Emphasis comes from weight and size, not from a second ink.', + }, + 'text-secondary': { + kind: 'rename', + to: ['text-subtle'], + rule: 'Descriptions, metadata, helper copy. An opaque color in every theme, so it no longer depends on what sits underneath it.', + }, + 'text-disabled': { + kind: 'split', + to: ['action-disabled', 'surface-raised', 'text-subtle'], + rule: 'A disabled label or icon drawn straight on a surface (text button, link, menu item, form label) is `action-disabled`, the same color as a disabled fill. On a disabled fill the label is a knockout: it takes the surface the control sits on, usually `surface-raised`. The value inside a disabled input is `action-disabled` too, since a disabled field no longer carries a disabled fill for it to sit on. The proposal describes `action-disabled` as a fill only; its use as the disabled ink is an addition for the proposal’s next revision.', + }, + 'feedback-error': { + kind: 'rename', + to: ['text-error'], + rule: 'Error text and icons, including inline validation and the border of a field in error. Destructive buttons are `action-danger`, not this.', + }, + 'feedback-success': { + kind: 'rename', + to: ['text-success'], + rule: 'Success text and icons. Always with an icon.', + }, + 'feedback-warning': { + kind: 'rename', + to: ['text-warning'], + rule: 'Warning text and icons. Dark enough to be read as text, so it can carry a message on its own rather than only an icon.', + }, + background: { + kind: 'split', + to: ['surface-raised', 'surface-default'], + rule: 'Anything that sits on the page (card, input, menu, popover, dialog) takes `surface-raised`. Where `background` fills the page itself, it is `surface-default`.', + }, + 'background-primary': { + kind: 'rename', + to: ['surface-default'], + rule: 'The page background, the base every other surface is placed on.', + }, + 'background-current': { + kind: 'split', + to: ['surface-default', 'surface-raised', 'surface-sunken'], + rule: 'Whatever surface the element sits on. Becomes a `surface-current` alias that every surface container (the page, raised, sunken, `Background`) sets to its own role, so it always resolves to one of these three. Masks and backdrops that must match their parent read it: sticky List headers, scroll and truncation fades, Drawer, DataList empty rows, the transparent Disclosure. Nothing sets it by hand.', + }, + 'background-contrast': { + kind: 'retire', + to: ['surface-raised'], + rule: 'Use `surface-raised`. Maximum contrast against the page is what raised already provides in dark mode, and light mode has no surface lighter than it. In Gamut it backs ToolTip and InfoTip, block Tabs and the video player’s tooltip and slider value, all remapped; none needs it to be black.', + }, + 'background-selected': { + kind: 'rename', + to: ['state-selected'], + rule: 'A veil composited over the element’s own fill, not an opaque fill that replaces it. The element keeps its surface underneath.', + }, + 'background-hover': { + kind: 'split', + to: ['state-hover', 'surface-sunken'], + rule: 'As a hover, it is the `state-hover` veil. Used as a resting fill (the subtle Alert, a tinted panel), it is `surface-sunken`.', + }, + 'background-disabled': { + kind: 'rename', + to: ['action-disabled'], + rule: 'The disabled fill for every action variant. One token, whatever was disabled.', + }, + 'background-success': { + kind: 'rename', + to: ['surface-success'], + rule: 'The success tint behind an alert or inline confirmation.', + }, + 'background-warning': { + kind: 'rename', + to: ['surface-warning'], + rule: 'The warning tint behind an alert or inline caution.', + }, + 'background-error': { + kind: 'rename', + to: ['surface-error'], + rule: 'The error tint behind an alert or inline validation message.', + }, + 'shadow-primary': { + kind: 'split', + to: ['shadow-key', 'shadow-ambient'], + rule: 'Every elevation shadow composes both: `shadow-key` for the tight contact layer, `shadow-ambient` for the soft falloff. The elevation tokens hold only offset, blur and spread; see the elevation system for which depth uses which geometry.', + }, + 'shadow-secondary': { + kind: 'split', + to: ['shadow-key', 'shadow-ambient'], + rule: 'Same as `shadow-primary`. Depth comes from geometry, not from a second color, so both legacy tokens land on the same pair.', + }, + primary: { + kind: 'rename', + to: ['action-primary'], + rule: 'Primary fills, strokes, links and focus rings. Pressed is new: `action-primary-pressed`.', + }, + 'primary-hover': { + kind: 'rename', + to: ['action-primary-hover'], + rule: 'Hover for the primary action.', + }, + 'primary-inverse': { + kind: 'retire', + to: ['action-primary'], + rule: 'A primary action on an inverted ground is `action-primary` inside a dark-mode scope. The mode does the inverting.', + }, + secondary: { + kind: 'rename', + to: ['action-neutral'], + rule: 'The secondary button and secondary icon/text buttons. Labels on it are `text-inverse`.', + }, + 'secondary-hover': { + kind: 'rename', + to: ['action-neutral-hover'], + rule: 'Hover for the secondary action.', + }, + danger: { + kind: 'rename', + to: ['action-danger'], + rule: 'Destructive actions: delete, remove, revoke. Error messaging is `text-error`.', + }, + 'danger-hover': { + kind: 'rename', + to: ['action-danger-hover'], + rule: 'Hover for the destructive action.', + }, + interface: { + kind: 'merge', + to: ['action-primary'], + rule: 'Checkboxes, radios, toggles, focus rings and inline links share the one interactive blue.', + }, + 'interface-hover': { + kind: 'merge', + to: ['action-primary-hover'], + rule: 'Hover for the same controls.', + }, + 'border-primary': { + kind: 'split', + to: ['border-default', 'border-subtle'], + rule: 'A border that carries meaning (field outline, control stroke, a container that needs an edge to be seen) is `border-default`. A border that only decorates or backs up a shadow (card hairline, table rule, the edge of a menu, popover, toast or dialog) is `border-subtle`.', + }, + 'border-secondary': { + kind: 'merge', + to: ['border-default'], + rule: 'Same as `border-primary`. One meaningful border weight.', + }, + 'border-tertiary': { + kind: 'split', + to: ['border-subtle', 'border-strong'], + rule: 'A divider or card hairline is `border-subtle`. Where it marks an active field or a selected row, it is `border-strong`. Gamut’s own two usages, the FeatureShimmer edge and the List scroll shadow, are both `border-subtle`. Core resolves it to a light navy and Percipio to a dark one, so check each app usage for which it meant.', + }, + 'border-disabled': { + kind: 'split', + to: ['border-default', 'action-disabled'], + rule: 'A disabled control with an `action-disabled` fill (button, tag) keeps its outline at `border-default`. A disabled field has no such fill, so its outline is `action-disabled`, the same color as its label and value.', + }, +}; + +/* Every role the generated system has (gamut-brand src/roles.ts), so the manifest test can check targets. */ +export const roles: ColorRolesManifest['roles'] = [ + 'surface-sunken', + 'surface-default', + 'surface-raised', + 'surface-success', + 'surface-warning', + 'surface-error', + 'surface-brand', + 'surface-brand-subtle', + 'text-default', + 'text-subtle', + 'text-inverse', + 'text-success', + 'text-warning', + 'text-error', + 'border-strong', + 'border-default', + 'border-subtle', + 'action-primary', + 'action-primary-hover', + 'action-primary-pressed', + 'action-danger', + 'action-danger-hover', + 'action-danger-pressed', + 'action-neutral', + 'action-neutral-hover', + 'action-neutral-pressed', + 'action-disabled', + 'state-hover', + 'state-pressed', + 'state-selected', + 'viz-1', + 'viz-2', + 'viz-3', + 'viz-4', + 'viz-5', + 'viz-6', + 'viz-7', + 'viz-8', + 'viz-seq-1', + 'viz-seq-2', + 'viz-seq-3', + 'viz-seq-4', + 'shadow-key', + 'shadow-ambient', + 'shadow-scrim', +]; + +/* + Every palette name the old themes define (core, admin, platform, percipio, + lxStudio) that isn't an alias, from main's built themes. No role replaces + them by name; design maps them per component. +*/ +export const oldPalette: ColorRolesManifest['oldPalette'] = [ + 'beige', + 'beige-0', + 'beige-100', + 'blue', + 'blue-0', + 'blue-100', + 'blue-300', + 'blue-400', + 'blue-500', + 'blue-800', + 'comment-dark', + 'comment-light', + 'gold', + 'gold-800', + 'gray-100', + 'gray-200', + 'gray-300', + 'gray-600', + 'gray-800', + 'gray-900', + 'green', + 'green-0', + 'green-100', + 'green-400', + 'green-700', + 'green-900', + 'hyper', + 'hyper-400', + 'hyper-500', + 'indent-active-dark', + 'indent-active-light', + 'indent-inactive-dark', + 'indent-inactive-light', + 'lightBeige', + 'lightBlue', + 'lightGreen', + 'line-number-active-dark', + 'line-number-active-light', + 'line-number-inactive-dark', + 'line-number-inactive-light', + 'lxStudioBgPrimary', + 'lxStudioSuccess', + 'navy', + 'navy-100', + 'navy-200', + 'navy-300', + 'navy-400', + 'navy-500', + 'navy-600', + 'navy-700', + 'navy-800', + 'navy-900', + 'orange', + 'orange-100', + 'orange-500', + 'orange-800', + 'paleBlue', + 'paleGreen', + 'palePink', + 'paleRed', + 'paleYellow', + 'percipioActionDangerHover', + 'percipioActionPrimaryHover', + 'percipioActionSecondary', + 'percipioActionSecondaryHover', + 'percipioBgError', + 'percipioBgPrimary', + 'percipioBgSuccess', + 'percipioBgWarning', + 'percipioDanger', + 'percipioFeedbackSuccess', + 'percipioFeedbackWarning', + 'percipioTextAccent', + 'percipioTextDisabled', + 'percipioTextPrimary', + 'percipioTextSecondary', + 'pink', + 'pink-0', + 'pink-400', + 'pink-800', + 'purple', + 'purple-300', + 'red', + 'red-0', + 'red-300', + 'red-400', + 'red-500', + 'red-600', + 'red-900', + 'sapphire', + 'teal', + 'teal-500', + 'white-100', + 'white-200', + 'white-300', + 'white-400', + 'white-500', + 'white-600', + 'white-700', + 'yellow', + 'yellow-0', + 'yellow-400', + 'yellow-500', + 'yellow-900', +]; diff --git a/packages/gamut-codemods/src/presets/color-roles/decisions.ts b/packages/gamut-codemods/src/presets/color-roles/decisions.ts new file mode 100644 index 0000000000..90aa458e1c --- /dev/null +++ b/packages/gamut-codemods/src/presets/color-roles/decisions.ts @@ -0,0 +1,219 @@ +/* + Hand-written decisions for old palette names, which have no role of their + own. aliases.ts is generated from design's map, so the choices that map + doesn't make live here. + + The codemod replaces a palette name only when it knows what the color is + for: a background, a text color, or a border. A prop says so by its name. + A theme lookup or a CSS variable says so by the CSS property or style key + it is the value of (`background-color: ${theme.colors['navy-100']}`, + `{ color: 'var(--color-red)' }`). When nothing says, or the color sits + inside a function like a gradient or `rgba()`, it stays a warning. + + - red: an error. A fill is the error tint (the Alert's surface); text and + borders take the error ink, which is how design's map pairs feedback-error. + A destructive button should be `action-danger` instead, so a red fill on + a button needs a look. + - green: the same for success. + - white: the surface on a light page (fill), the light ink on a dark one + (text), and a hairline (border). White is a translucent tint in the old + palette, so its brightness depends on what sits behind it; these three + are what it means in practice. + - navy: picked by brightness. Each step is composited over the light page + and matched to the nearest role in its family. Dark navy fills (400 and + up) have no dark background role in the light palette, so they stay + warnings for design to decide. +*/ + +export type UseKind = 'fill' | 'text' | 'border'; + +/* Props, style keys and CSS properties, in camel or kebab case. */ +const PROP_KINDS: [RegExp, UseKind][] = [ + [/^(bg|background|background-?color)$/i, 'fill'], + [/^(color|textColor)$/, 'text'], + [/^border(?!.*(radius|width|style|collapse|spacing|image))/i, 'border'], +]; + +/* + What a palette site is used as, from the `where` the visitor records: the + name in backticks at its end (`the \`bg\` prop`, `a theme.colors lookup + for \`background-color\``). +*/ +export const kindOfUse = (where: string): UseKind | null => { + const match = /`([^`]+)`(?: (?:prop|value))?$/.exec(where); + if (!match) return null; + return PROP_KINDS.find(([re]) => re.test(match[1]))?.[1] ?? null; +}; + +/* + The CSS property a value is being written for, when `text` ends partway + into that value: `border: 1px solid ` gives `border`. A value that has + opened a function (`linear-gradient(`, `rgba(`) gives nothing, since the + color is then one stop of something else. An open `var(` is allowed, so + `color: var(` gives `color`. Comments are skipped, so one an earlier run + left in the value (`color: /* color-roles: … *\/ var(`) doesn't count. +*/ +export const cssPropertyBefore = (text: string): string | undefined => { + const match = /(? = { + fill: 'surface-error', + text: 'text-error', + border: 'text-error', +}; + +const SUCCESS: Record = { + fill: 'surface-success', + text: 'text-success', + border: 'text-success', +}; + +const WHITE: Record = { + fill: 'surface-raised', + text: 'text-inverse', + border: 'border-subtle', +}; + +/* + The warning family. yellow-0 is the warning tint and bare yellow or + yellow-900 is the warning ink, as the old core theme uses them. yellow-400 + and yellow-500 are the accent, so they stay warnings for a person. +*/ +const YELLOW_FILL_WARNING = 'surface-warning'; +const YELLOW_TEXT_WARNING = 'text-warning'; + +/* + hyper is the old primary: primary fills, links and focus. Only hyper and + hyper-500 map, since the other steps are hover and pressed tints. +*/ +const HYPER: Record = { + fill: 'action-primary', + text: 'action-primary', + border: 'action-primary', +}; + +/* + blue-500 is admin's light-mode primary. Its text is interactive (links, + focus), so it takes action-primary. Its fills and borders mix interactive + uses (selection buttons) with decoration (the Skillsoft family block), and + the codemod can't tell them apart, so they stay warnings. Bare `blue` is + the same color. +*/ +const BLUE_TEXT = 'action-primary'; + +/* + The greys are neutral (no hue), and a brightness match would make the + mid greys text-inverse, which is light ink on a light page. So they follow + what the use is: fills by lightness, every grey text as text-subtle, and + borders by weight. Gray-100 to 300 text stays a warning, since it would be + close to invisible on a light page. +*/ +const GRAY_FILL: Record = { + '100': 'surface-default', + '200': 'surface-sunken', + '300': 'surface-sunken', +}; +const GRAY_TEXT: Record = { + '600': 'text-subtle', + '800': 'text-subtle', + '900': 'text-subtle', +}; +const GRAY_BORDER: Record = { + '300': 'border-subtle', + '600': 'border-default', + '800': 'border-default', + '900': 'border-default', +}; + +const NAVY: Record> = { + fill: { + '100': 'surface-default', + '200': 'surface-sunken', + '300': 'surface-sunken', + }, + text: { + '400': 'text-subtle', + '500': 'text-subtle', + '600': 'text-subtle', + '700': 'text-subtle', + '800': 'text-default', + }, + border: { + '100': 'border-subtle', + '200': 'border-subtle', + '300': 'border-subtle', + '400': 'border-default', + '500': 'border-default', + '600': 'border-default', + '700': 'border-strong', + '800': 'border-strong', + }, +}; + +/* + The role a palette name takes in this use, or null to leave it for a + person. A bare `navy` is navy-800, and a bare `white` is the full white. +*/ +export const paletteDefault = (name: string, where: string): string | null => { + const kind = kindOfUse(where); + if (!kind) return null; + const family = name.replace(/-\d+$/, ''); + const shade = /-(\d+)$/.exec(name)?.[1]; + switch (family) { + case 'red': + return ERROR[kind]; + case 'green': + return SUCCESS[kind]; + case 'white': + return WHITE[kind]; + case 'gray': { + const table = { fill: GRAY_FILL, text: GRAY_TEXT, border: GRAY_BORDER }[ + kind + ]; + return table[shade ?? ''] ?? null; + } + case 'blue': + return (shade === undefined || shade === '500') && kind === 'text' + ? BLUE_TEXT + : null; + case 'yellow': + if (kind === 'fill' && shade === '0') return YELLOW_FILL_WARNING; + if (kind === 'text' && (shade === undefined || shade === '900')) + return YELLOW_TEXT_WARNING; + return null; + case 'hyper': + return shade === undefined || shade === '500' ? HYPER[kind] : null; + case 'navy': + return NAVY[kind][shade ?? '800'] ?? null; + default: + return null; + } +}; + +/* + Design's rule for a palette name that has no default, when there is one. + A dark navy fill is a dark area, not a surface: no surface is dark on a + light page, so the area becomes dark mode and takes that mode's page + surface. The translucent mid steps (400 to 600) have no rule yet. +*/ +export const paletteAdvice = (name: string, where: string): string | null => + kindOfUse(where) === 'fill' && /^navy(-(700|800))?$/.test(name) + ? 'A dark navy fill is a dark area: make it dark mode with ``, say why in a comment, and remove this fill.' + : null; + +/* Every role a default can name. manifest.test.ts checks these exist. */ +export const DEFAULT_ROLES = [ + ...Object.values(ERROR), + ...Object.values(SUCCESS), + ...Object.values(WHITE), + YELLOW_FILL_WARNING, + YELLOW_TEXT_WARNING, + ...Object.values(NAVY).flatMap((steps) => Object.values(steps)), +]; diff --git a/packages/gamut-codemods/src/presets/color-roles/index.ts b/packages/gamut-codemods/src/presets/color-roles/index.ts new file mode 100644 index 0000000000..2150c834b4 --- /dev/null +++ b/packages/gamut-codemods/src/presets/color-roles/index.ts @@ -0,0 +1,75 @@ +import fs from 'node:fs'; + +import type { Leftover } from '../../lib/leftovers'; +import { walk } from '../../lib/leftovers'; +import type { Preset } from '../../lib/types'; +import { colorRoles } from '../../migrations/color-roles'; +import { colorRolesStylesheets } from '../../migrations/color-roles-stylesheets'; +import { colorRolesThemes } from '../../migrations/color-roles-themes'; +import type { ColorRolesManifest } from './manifest'; +import { manifest } from './manifest'; + +const escape = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + +/* + A quoted old name, one read off `theme.colors`, an old `--color-*` + variable, a Card (whose variants are renamed), or an old theme name. +*/ +const OLD_NAMES = new RegExp( + `['"\`](?:${[...Object.keys(manifest.aliases), ...manifest.oldPalette] + .map(escape) + .join( + '|' + )})['"\`]|colors\\.[A-Za-z]|--color-[A-Za-z0-9]| = { + name: 'color-roles', + description: + 'Move Gamut color names onto the roles of the generated color system.', + manifest, + mentions: (source) => OLD_NAMES.test(source), + /* Every name the run marked for a person and nobody has resolved yet. */ + leftovers(roots) { + const hits: Leftover[] = []; + for (const root of roots) { + const files = fs.statSync(root).isDirectory() ? walk(root) : [root]; + for (const file of files) { + if (!SOURCE.test(file)) continue; + fs.readFileSync(file, 'utf8') + .split('\n') + .forEach((text, i) => { + if (text.includes('color-roles:')) { + hits.push({ file, line: i + 1, text: text.trim() }); + } + }); + } + } + return hits; + }, + migrations: [colorRoles, colorRolesThemes, colorRolesStylesheets], + checklist: [ + 'Run your formatter (prettier --write). The `color-roles:` comments can make lines long.', + 'Type-check. Every name the codemod left in place is still an old name, so it fails until someone picks its role.', + 'Work through the leftovers: each `color-roles:` comment carries design’s rule for choosing. Replace the name, then delete the comment.', + ], + conditionalChecklist: { + 'color-roles:manual': + 'Some names are splits, retirements or pending (see the warnings). Splits need the role for where the color is used; retired names have a rule instead of a role; pending names wait for a system that doesn’t exist yet. Shadows split onto `shadow-key` and `shadow-ambient`, the two layers every elevation shadow draws.', + 'color-roles:stylesheets': + 'Stylesheets used old `--color-*` variables. Renames are done; the type check can’t see stylesheets, so the leftovers report below is the only list of what’s left. Indented-syntax .sass files aren’t rewritten: search them for `--color-` by hand.', + 'color-roles:themes': + 'Old theme names moved: `percipioTheme` → `skillsoftTheme` (its replacement) and `coreTheme` → `originalCodecademyTheme` (its rebuild). A `CoreTheme` type, usually in a Theme augmentation, is left with a comment: brand themes share one shape, typed by `SkillsoftTheme`.', + 'color-roles:card-navy': + 'Some Cards used the `navy` variant. It becomes `default`, which renders light; wrap a card in `` where it should stay dark, then delete the comment.', + 'color-roles:palette-default': + 'Some old palette colors were replaced by the defaults in presets/color-roles/decisions.ts: red becomes an error role, green a success role, white a surface or ink, and navy the nearest one by brightness. Check each one in context. A red button fill should be `action-danger`, not `surface-error`.', + 'color-roles:palette': + 'Some code uses old palette colors (navy, hyper-500, …) directly. No role replaces them by name. Pick each one from design’s component map, in @skillsoft/gamut-brand src/migration.ts (COMPONENTS).', + 'color-roles:runtime': + 'Some color names are built at runtime, like `${variant}-hover`. The codemod can’t see their values; check each name the template can produce.', + }, +}; diff --git a/packages/gamut-codemods/src/presets/color-roles/manifest.ts b/packages/gamut-codemods/src/presets/color-roles/manifest.ts new file mode 100644 index 0000000000..97b75da5b4 --- /dev/null +++ b/packages/gamut-codemods/src/presets/color-roles/manifest.ts @@ -0,0 +1,57 @@ +import { aliases, oldPalette, roles } from './aliases'; + +/* + color-roles: today's Gamut color names → the roles of the generated color + system. The rows are design's (aliases.ts, generated); this file holds the + shape and the props a color can appear in. +*/ + +/* + - rename / merge: one role replaces the name. Applied. + - split: one of several roles, depending on where it's used. + - retire: no role replaces it; `rule` says what to do instead. + - pending: decided, but its role arrives with a system that doesn't exist + yet. No row is pending today; shadows became a split. + The last three need a person; the codemod leaves the name and a comment. +*/ +export type ColorKind = 'rename' | 'merge' | 'split' | 'retire' | 'pending'; + +export interface ColorAlias { + kind: ColorKind; + /* Roles, most common first. Empty for some retire and pending rows. */ + to: string[]; + rule: string; +} + +export interface ColorRolesManifest { + aliases: Record; + /* Every role of the generated system; alias targets must be among them. */ + roles: string[]; + /* Old palette names (navy, hyper-500, …). No role replaces them by name. */ + oldPalette: string[]; + /* Props whose values are color names: gamut-styles variance/config.ts `color`. */ + colorProps: string[]; +} + +export const manifest: ColorRolesManifest = { + aliases, + roles, + /* Bare `white` is a Gamut color name, but design's list only has the steps. */ + oldPalette: [...oldPalette, 'white'], + colorProps: [ + 'color', + 'textColor', + 'bg', + 'borderColor', + 'borderColorX', + 'borderColorY', + 'borderColorLeft', + 'borderColorRight', + 'borderColorTop', + 'borderColorBottom', + ], +}; + +/* Applied by the codemod, vs. left for a person. */ +export const isAutomatic = (alias: ColorAlias) => + alias.kind === 'rename' || alias.kind === 'merge'; diff --git a/packages/gamut-codemods/src/presets/index.ts b/packages/gamut-codemods/src/presets/index.ts index 2ff0c9294a..76c153c249 100644 --- a/packages/gamut-codemods/src/presets/index.ts +++ b/packages/gamut-codemods/src/presets/index.ts @@ -1,4 +1,5 @@ import type { Preset } from '../lib/types'; +import { colorRolesPreset } from './color-roles'; import { scopeSwap } from './scope-swap'; /* @@ -7,8 +8,10 @@ import { scopeSwap } from './scope-swap'; Later presets are named for the release they target and can reuse migrations from src/migrations with a different manifest. */ -export const presets: Record = { +/* Each preset has its own manifest type; callers only pass it through. */ +export const presets: Record> = { [scopeSwap.name]: scopeSwap, + [colorRolesPreset.name]: colorRolesPreset, }; /* @@ -17,7 +20,7 @@ export const presets: Record = { switch, so presets have to list every `ast` migration before any `splice` one. */ -export const validatePreset = (preset: Preset) => { +export const validatePreset = (preset: Preset) => { const source = preset.migrations.filter((m) => m.kind !== 'file'); const firstSplice = source.findIndex((m) => m.kind === 'splice'); const lateAst = diff --git a/packages/gamut-codemods/src/presets/manifest.test.ts b/packages/gamut-codemods/src/presets/manifest.test.ts index 98c3790a1c..018d4b7f23 100644 --- a/packages/gamut-codemods/src/presets/manifest.test.ts +++ b/packages/gamut-codemods/src/presets/manifest.test.ts @@ -1,17 +1,25 @@ +import { describe, expect, it } from 'vitest'; import fs from 'node:fs'; import path from 'node:path'; import ts from 'typescript'; -import { describe, expect, it } from 'vitest'; -import { type DeepImport, renameSpecifier } from '../lib/manifest'; +import { + type DeepImport, + type Manifest, + renameSpecifier, +} from '../lib/manifest'; import { presets } from '.'; import { manifest } from './scope-swap/manifest'; +/* Manifests that promise exports: scope-swap's shape. Other presets have none. */ +const movesExports = (m: unknown): m is Manifest => + typeof m === 'object' && m !== null && 'movedExports' in m; + /* Guards against a manifest that promises something the packages don't - deliver. Runs against the built dist, so the packages have to be built - first (the `test` target's `^build` wires that up). + deliver. Runs against the built dist, so `^build` has to run first + (project.json wires that up). */ const REPO = path.join(__dirname, '../../../..'); @@ -32,8 +40,9 @@ const importsToCheck = () => { names.forEach((name) => set.add(name)); byModule.set(spec, set); }; - for (const preset of Object.values(presets)) { - const m = preset.manifest; + for (const m of Object.values(presets) + .map((preset) => preset.manifest) + .filter(movesExports)) { for (const rule of m.movedExports) { add(renameSpecifier(m, rule.to), rule.names); } @@ -110,7 +119,7 @@ const exportsOf = (specifiers: string[]) => { }); }; -describe('manifests', { timeout: 15_000 }, () => { +describe('manifests', { timeout: 60_000 }, () => { /* A deep-import row sends every name imported from `from` to `to`, so everything `from` exports has to be available there: directly, via @@ -201,6 +210,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/transform.ts b/packages/gamut-codemods/src/transform.ts index e1e60939f0..be7cf254b4 100644 --- a/packages/gamut-codemods/src/transform.ts +++ b/packages/gamut-codemods/src/transform.ts @@ -3,11 +3,7 @@ import path from 'node:path'; import type { API, FileInfo } from 'jscodeshift'; -import { - activeSourceMigrations, - mentionsOldNames, - runSourceMigrations, -} from './lib/run-source'; +import { activeSourceMigrations, runSourceMigrations } from './lib/run-source'; import type { Locatable } from './lib/types'; import { getPreset } from './presets'; @@ -41,7 +37,7 @@ export default function transform( ) { const preset = getPreset(options.preset ?? 'scope-swap'); const { manifest } = preset; - if (!mentionsOldNames(manifest, file.source)) return undefined; + if (!preset.mentions(file.source)) return undefined; const note = (key: string) => { if (options.notesDir) { 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'); + }); +});