diff --git a/.changeset/backtick-expand-only-in-styled.md b/.changeset/backtick-expand-only-in-styled.md new file mode 100644 index 0000000..365e224 --- /dev/null +++ b/.changeset/backtick-expand-only-in-styled.md @@ -0,0 +1,5 @@ +--- +"vscode-styled-components": patch +--- + +Typing a backtick no longer offers to expand it into a multi-line template everywhere. The "expand template string" suggestion now appears only when the backtick opens a styled template (#386). diff --git a/.changeset/color-picker-output.md b/.changeset/color-picker-output.md new file mode 100644 index 0000000..94bd689 --- /dev/null +++ b/.changeset/color-picker-output.md @@ -0,0 +1,5 @@ +--- +"vscode-styled-components": patch +--- + +The color picker now writes the same values VS Code's picker writes in `.css` files. A semi-transparent hex color always gets a valid two-digit alpha (`#ff00000d` rather than `#ff0000c`), and `hsl()` values use whole numbers. diff --git a/.changeset/enter-after-nested-template.md b/.changeset/enter-after-nested-template.md new file mode 100644 index 0000000..166b8df --- /dev/null +++ b/.changeset/enter-after-nested-template.md @@ -0,0 +1,5 @@ +--- +"vscode-styled-components": patch +--- + +Picking a CSS property from the suggestion list and pressing Enter fills in `: ;` again when the template holds a nested template string inside `${}` (#437). It also works when the styled tag is spread across several lines. diff --git a/.changeset/faster-highlighting.md b/.changeset/faster-highlighting.md new file mode 100644 index 0000000..018a088 --- /dev/null +++ b/.changeset/faster-highlighting.md @@ -0,0 +1,5 @@ +--- +"vscode-styled-components": patch +--- + +Syntax highlighting is about 8% faster on average, measured over about 5,800 lines of styled-components code in JavaScript and TSX, both the first time the editor highlights a file and after. Files with very long single lines gained the most, highlighting about 65% faster on average. diff --git a/.changeset/fix-highlighting-spill.md b/.changeset/fix-highlighting-spill.md new file mode 100644 index 0000000..816efb2 --- /dev/null +++ b/.changeset/fix-highlighting-spill.md @@ -0,0 +1,5 @@ +--- +"vscode-styled-components": patch +--- + +Syntax highlighting no longer breaks for the rest of the file after certain styled components. These now highlight correctly, along with the code below them: a template right after a call whose arrow function returns an object or JSX, like `foo(() => ({ ... }))` or MUI's `styled(({ className, ...props }) => (...))` pattern (#383); `.attrs()` that uses props, even across several lines (#292); a props type written over several lines, like `styled.div<{ color: string }>` broken onto new lines (#358); TypeScript type parameters after `styled.div` (#442); a styled component passed into a function such as `React.memo` (#196); and templates after `Comp.extend`, `keyframes`, and `.withComponent()`. diff --git a/.changeset/keyframe-percent-selectors.md b/.changeset/keyframe-percent-selectors.md new file mode 100644 index 0000000..6c46d9d --- /dev/null +++ b/.changeset/keyframe-percent-selectors.md @@ -0,0 +1,5 @@ +--- +"vscode-styled-components": patch +--- + +Keyframe selectors with decimals, like `33.3%`, now highlight as one selector inside an `@keyframes` block, the same as they already did in a `keyframes` template. diff --git a/.changeset/minimum-vscode-1-74.md b/.changeset/minimum-vscode-1-74.md new file mode 100644 index 0000000..8d6141a --- /dev/null +++ b/.changeset/minimum-vscode-1-74.md @@ -0,0 +1,5 @@ +--- +"vscode-styled-components": patch +--- + +The extension now needs VS Code 1.74 or later, so VS Code starts it for the Enter-key `: ;` command in any JavaScript or TypeScript file, not only after a JSX or TSX file opens. diff --git a/.changeset/modern-css-function-highlighting.md b/.changeset/modern-css-function-highlighting.md new file mode 100644 index 0000000..8cfe546 --- /dev/null +++ b/.changeset/modern-css-function-highlighting.md @@ -0,0 +1,5 @@ +--- +"vscode-styled-components": minor +--- + +Modern CSS functions such as `oklch()`, `color-mix()`, `clamp()`, and `light-dark()` now highlight as functions inside styled templates, and `light-dark()` no longer breaks apart at the hyphen. diff --git a/.changeset/more-styled-tag-shapes.md b/.changeset/more-styled-tag-shapes.md new file mode 100644 index 0000000..5601827 --- /dev/null +++ b/.changeset/more-styled-tag-shapes.md @@ -0,0 +1,5 @@ +--- +"vscode-styled-components": minor +--- + +CSS highlighting now works in more of the ways you write styled components: a tag chain, on one line or split across lines by Prettier (`styled.div` or `Button.extend`, then any number of `.attrs()` and `.withConfig()` calls), a comment between `styled.div` and its backtick, a tag reached through an object (`theme.styled.div`, `$styled.div`, `theme.css`) or through a call or index (`getTheme().styled.div`, `items[0].styled.div`), type arguments that span several lines, including on `theme.keyframes`, and an arrow function whose parameter starts with `$` or has no parentheses, like `styled.div(($props) => ...)` or `styled.div(p => ...)`. diff --git a/.changeset/space-separated-rgb-hsl-swatches.md b/.changeset/space-separated-rgb-hsl-swatches.md new file mode 100644 index 0000000..5f686af --- /dev/null +++ b/.changeset/space-separated-rgb-hsl-swatches.md @@ -0,0 +1,5 @@ +--- +"vscode-styled-components": patch +--- + +Space-separated `rgb()` and `hsl()` colors now show a color swatch and open the color picker, with or without a `/ alpha` value, like `hsl(220 30% 95%)` and `rgb(255 0 153 / 50%)` (#455). diff --git a/.changeset/wide-gamut-color-swatches.md b/.changeset/wide-gamut-color-swatches.md new file mode 100644 index 0000000..2d1bd7e --- /dev/null +++ b/.changeset/wide-gamut-color-swatches.md @@ -0,0 +1,5 @@ +--- +"vscode-styled-components": minor +--- + +`hwb()`, `lab()`, `lch()`, `oklab()`, and `oklch()` colors now show a color swatch, and the color picker can write any color in these five formats. diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 1e7dba6..c2c464d 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -3,6 +3,8 @@ version: 2 updates: - package-ecosystem: github-actions directory: / + commit-message: + prefix: ci cooldown: default-days: 7 schedule: diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 05b1b33..fc2df8c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -37,6 +37,12 @@ jobs: - name: Check formatting run: npm run lint + - name: Typecheck + run: npx tsc --noEmit -p . + + - name: Unit tests + run: npm run test:unit + test: name: Test (${{ matrix.os }}) strategy: diff --git a/.github/workflows/commit-messages.yml b/.github/workflows/commit-messages.yml new file mode 100644 index 0000000..cb8a694 --- /dev/null +++ b/.github/workflows/commit-messages.yml @@ -0,0 +1,42 @@ +name: Commit Messages + +# Separate from ci.yml so editing a PR title reruns only this check, not the OS matrix. +on: + pull_request: + branches: + - main + types: [opened, edited, synchronize, reopened] + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number }} + cancel-in-progress: true + +permissions: + contents: read + +jobs: + commit-messages: + name: Commit messages + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 + persist-credentials: false + + # A squash merge commits the PR title; a rebase merge commits each commit. + - name: Check the PR title and every commit + env: + BASE_SHA: ${{ github.event.pull_request.base.sha }} + HEAD_SHA: ${{ github.event.pull_request.head.sha }} + PR_TITLE: ${{ github.event.pull_request.title }} + run: | + status=0 + sh scripts/check-commit-message.sh -m "$PR_TITLE" || status=1 + for sha in $(git rev-list "$BASE_SHA..$HEAD_SHA"); do + git log -1 --format=%B "$sha" > "$RUNNER_TEMP/message" + sh scripts/check-commit-message.sh "$RUNNER_TEMP/message" || status=1 + done + exit $status diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 1ff3f7e..a0e4083 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -44,11 +44,13 @@ jobs: - run: npm ci - # With pending changesets this opens or updates the "Version Packages" PR; once that PR merges, + # With pending changesets this opens or updates the "chore: version packages" PR; once that PR merges, # `npm run release` publishes to the VS Code Marketplace via trusted publishing (OIDC) and tags vX.Y.Z. # RELEASE_GITHUB_TOKEN (a PAT) lets CI run on the version PR; the job token works but triggers no checks. - name: Version or publish uses: changesets/action@ae32849d5ba541f9ae29e40e22a623bc13562f51 # v2.1.2 with: + commit-message: "chore: version packages" github-token: ${{ secrets.RELEASE_GITHUB_TOKEN || github.token }} + pr-title: "chore: version packages" publish-script: npm run release diff --git a/.gitignore b/.gitignore index 556fd86..45382a3 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,6 @@ +.DS_Store node_modules dist .vscode-test +.integration-test/ +syntaxes/*.json diff --git a/.husky/commit-msg b/.husky/commit-msg new file mode 100644 index 0000000..d216181 --- /dev/null +++ b/.husky/commit-msg @@ -0,0 +1 @@ +sh scripts/check-commit-message.sh --local "$1" diff --git a/.prettierignore b/.prettierignore index 33e61f4..135cf98 100644 --- a/.prettierignore +++ b/.prettierignore @@ -2,5 +2,9 @@ package-lock.json .github node_modules .vscode-test -src/tests +.integration-test/ +src/tests/suite/colorize-fixtures +src/tests/suite/colorize-results dist +.claude/ +syntaxes/src/css.tmLanguage.json diff --git a/.vscode/launch.json b/.vscode/launch.json index 5c79200..a75a1a5 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -8,7 +8,7 @@ "request": "launch", "runtimeExecutable": "${execPath}", "args": [ - "--extensionDevelopmentPath=${workspaceRoot}", + "--extensionDevelopmentPath=${workspaceFolder}", "${workspaceFolder}/src/tests/suite/colorize-fixtures" ], "outFiles": ["${workspaceFolder}/dist/**/*.js"], @@ -24,9 +24,10 @@ "args": [ "--disable-extensions", "--extensionDevelopmentPath=${workspaceFolder}", - "--extensionTestsPath=${workspaceFolder}/src/tests/suite/index.js" + "--extensionTestsPath=${workspaceFolder}/.integration-test/index.js" ], - "internalConsoleOptions": "openOnSessionStart" + "internalConsoleOptions": "openOnSessionStart", + "preLaunchTask": "npm: pretest" } ] } diff --git a/.vscode/tasks.json b/.vscode/tasks.json index 8d8c38f..a084f36 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -19,6 +19,13 @@ }, "label": "npm: watch", "detail": "ESBuild watch mode" + }, + { + "type": "npm", + "script": "pretest", + "problemMatcher": [], + "label": "npm: pretest", + "detail": "Build the extension and bundle the integration tests" } ] } diff --git a/.vscodeignore b/.vscodeignore index e927842..57c2ff0 100644 --- a/.vscodeignore +++ b/.vscodeignore @@ -1,15 +1,19 @@ .changeset/** +.claude/** .editorConfig .github/** .gitignore .husky/** .nvmrc .prettierignore +.integration-test/** .vscode-test/** .vscode/** **/*.map -build.mjs +AGENTS.md +build.mts +scripts/** docs/** src/** -test/ +syntaxes/src/** tsconfig.json diff --git a/AGENTS.md b/AGENTS.md index d5c3db3..48b356f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -6,7 +6,10 @@ This file is the index for agents working in this repo. It holds only one-line r - `npm ci`: install (npm, `package-lock.json`) - `npm test`: build, then run the integration suite in a downloaded VS Code (opens a VS Code window; on headless Linux run `xvfb-run -a npm test`) -- `npx tsc --noEmit -p .`: typecheck (`npm test` bundles with esbuild, which does not typecheck) +- `npm run test:unit`: unit tests (`src/**/*.test.ts` outside the integration suites, and `syntaxes/src/**/*.test.ts`) in Node, no window +- `npm run tokenize -- [--sentinel | --drift] [--grammars ] `: headless tokenizer, no window; modes in the spec, "Test strategy" +- `npm run bench:grammar -- [...]`: grammar speed against the spec's "Performance" bar +- `npx tsc --noEmit -p .`: typecheck every TypeScript file (`npm test` bundles with esbuild, which does not typecheck) - `npm run lint` / `npm run format`: Prettier check / write (the pre-commit hook and CI run the check) - `npm run watch`: rebuild on change; press F5 in VS Code to launch the extension against the colorize fixtures - `npx changeset`: describe a user-facing change @@ -14,15 +17,21 @@ This file is the index for agents working in this repo. It holds only one-line r ## Map +- [docs/spec.md](docs/spec.md): authoritative behavior spec; edit it before the code - `src/extension.ts`: activation; registers the providers below - `src/colorProvider.ts`: color swatches and color picker presentations -- `src/insertColonCommand.ts`, `src/patterns.ts`: the Enter-key `: ;` command; decides "inside CSS" from the injection grammar's begin/end regexes +- `src/insertColonCommand.ts`: the Enter-key `: ;` command - `src/completionItemProvider.ts`: the backtick-expansion snippet -- `syntaxes/styled-components.json`: injection grammar (scope `styled`) into JS/TS/JSX/TSX/Vue/Svelte -- `syntaxes/css.styled.json`: the embedded CSS grammar (scope `source.css.styled`) +- `src/templateScanner.ts`: `isInsideStyledTemplate`, the "inside a styled template" check `insertColonCommand.ts` and `completionItemProvider.ts` use +- `syntaxes/src/styled-components.mts`: injection grammar source (scope `styled`); hosts and tag shapes in the spec +- `syntaxes/src/css.styled.mts`, `syntaxes/src/ownCss.mts`: embedded CSS grammar source (scope `source.css.styled`); copies its CSS rules from `syntaxes/src/css.tmLanguage.json`, VS Code's CSS grammar, vendored +- `syntaxes/src/generate.mts`: writes `syntaxes/*.json` (build output, git-ignored) +- `ThirdPartyNotices.txt`: license notice for the vendored CSS grammar - IntelliSense and diagnostics: the bundled `@styled/typescript-styled-plugin` (separate repo, styled-components/typescript-styled-plugin), registered as a TS server plugin in `package.json` -- `src/tests/runTests.js`: pins the VS Code version tests run against +- `src/tests/vscodeVersion.mts`: pins the VS Code version the tests, the tokenizer, and the grammar benchmark use +- `src/tests/suite/*.test.ts`: integration suites; `scripts/bundle-integration-tests.mts` bundles them into `.integration-test/` in `pretest` - `src/tests/suite/colorize-fixtures/` and `colorize-results/`: grammar snapshot tests +- `scripts/`: the tokenizer, the grammar benchmark, the unit and integration bundlers, and `check-commit-message.sh` (the Conventional Commits check) - `.vscodeignore`: what ships in the published package - `.changeset/`, `.github/workflows/release.yml`: release pipeline - [CONTRIBUTING.md](CONTRIBUTING.md): grammar authoring, plugin debugging, tests, releasing @@ -35,35 +44,37 @@ This file is the index for agents working in this repo. It holds only one-line r ### Prose and communication - American English, no em-dashes. Human-facing text (README, changesets, PR descriptions, issue replies) uses plain words and leads with user impact; agent-facing text uses the most precise term. -- A changeset is one short paragraph per user-noticeable change, leading with the visible effect; no mechanism, no internal-only changes, no unmeasured claims. +- A changeset is one short paragraph per user-noticeable change, leading with the visible effect; a speed claim gives the average percent change and the conditions measured, never absolute timings; no mechanism, no internal-only changes, no unmeasured claims. - No "Generated by" or attribution footers or trailers in commits, PRs, or files. - A user-facing message (`window.show*Message`) states the problem and the fix in plain language, with no internals. ### Correctness and types - `tsconfig.json` is `strict`; types are law. No `as any`, non-null `!`, or `@ts-expect-error`, and no new type-assertion casts; remove existing ones in code you touch. -- Public contract, changed only with a major changeset: grammar scope names (themes and other extensions match them), the language id `source.css.styled`, the command id `extension.insertColonOrSemiColon`, and the extension id. Everything else is internal and may be rewritten freely. +- The public contract (spec, "Public contract") changes only with a major changeset; everything else is internal and may be rewritten freely. - TextMate rules match one line at a time; a rule that needs a newline never matches. Write a rule per line shape (CONTRIBUTING.md, "A line break seems to break the syntax highlighting"). -- Grammar regexes are Oniguruma, not JavaScript. `src/patterns.ts` converts POSIX classes for reuse in JS; a grammar change that adds other Oniguruma-only syntax breaks `insertColonCommand` silently. +- Grammar regexes are Oniguruma, not JavaScript; check one with `npm run tokenize`, never a JavaScript regex engine. +- The grammar and `src/templateScanner.ts` each decide which templates are styled; a tag-shape change updates both, and the scanner's differential test against `colorize-results/` fails on a new disagreement. +- A file Node runs directly (`build.mts`, `scripts/`, the generators, the test runner) is `.mts`, imports with explicit `.mts` or `.ts` extensions, and uses only erasable TypeScript syntax: Node strips its types with no build step. ### Testing and validation -- Every grammar change adds or updates a fixture in `src/tests/suite/colorize-fixtures/` and commits the regenerated `colorize-results/` file. Review every changed token: a first run on a new fixture writes its result and passes without comparing anything, so the committed JSON is the assertion. +- Every grammar change adds or updates a fixture in `src/tests/suite/colorize-fixtures/` and commits the regenerated `colorize-results/` file. Review every changed token: the committed JSON is the assertion (spec, "Test strategy"). - Treat colorize-results drift with suspicion; a token change outside the edited rule is a regression until proven otherwise. -- Bump the pinned VS Code version in `src/tests/runTests.js` deliberately, regenerating and reviewing all results in the same commit. +- Bump the pinned VS Code version in `src/tests/vscodeVersion.mts` deliberately: replace `syntaxes/src/css.tmLanguage.json` with the new build's CSS grammar, then regenerate and review all results in the same commit (CONTRIBUTING.md, "Tests"). - A bug fix starts with a red test (fixture or suite test), then goes green. - Test names read as spec sentences ("activates without an error"). ### Inputs and error handling -- Document text is untrusted (any opened workspace file). Regexes run over it must not backtrack catastrophically (no nested or overlapping quantifiers) and should scan a bounded range, not the whole document, per keystroke. +- Document text is untrusted (any opened workspace file). Regexes run over it must not backtrack catastrophically (no nested or overlapping quantifiers), and a scan that runs per keystroke runs in linear time within the spec's "Performance" budget. - No empty or log-only `catch`; handle the failure or let it surface. ### Organization and naming - One provider or command per file in `src/`; `extension.ts` only wires them. -- Grammar regexes live JSON-escaped in `syntaxes/*.json`; decode before editing, re-encode after (CONTRIBUTING.md, "Syntax"). -- Never reorder grammar `patterns` arrays for tidiness: TextMate tries rules in order, so order is behavior. +- Edit the grammar generators in `syntaxes/src/`, never the generated `syntaxes/*.json` (CONTRIBUTING.md, "Syntax"). +- Never reorder the generators' pattern arrays for tidiness: TextMate tries rules in order, so order is behavior. - Split a file past ~4,000 lines. ### Comments and docs @@ -75,7 +86,7 @@ This file is the index for agents working in this repo. It holds only one-line r ### Security and data - The extension makes no network calls and collects no data; keep it that way. -- Releases publish through Marketplace trusted publishing (OIDC). Never add a long-lived publish token or secret. +- Never add a long-lived publish token or secret (spec, "Packaging and release"). - Workflow hardening is enforced by zizmor in CI: SHA-pinned actions with a version comment, least-privilege `permissions`, `persist-credentials: false`, no dependency cache in the release job. Depth: [docs/github-actions.md](docs/github-actions.md). - Package install scripts stay off (npm's `allowScripts` gate); approve one only on demonstrated breakage, with a one-line reason. @@ -85,13 +96,14 @@ This file is the index for agents working in this repo. It holds only one-line r ### Performance -- The color provider and the grammar run on every edit. Validate a change to either against the previous code with a microbenchmark on a large file; never trade behavior for speed without a measurement. +- The color provider and the grammar run on every edit. Validate a change to either against the previous code (`npm run bench:grammar` for the grammar, the linear-scaling test in `src/colorParsing.test.ts` for the color provider); never trade behavior for speed without a measurement. - Keep measured figures (timings, sizes) out of docs; state the budget and the command that measures it. ### Git and process -- Every PR with a user-facing change adds a changeset (`npx changeset`); CI, docs, and test-only PRs add none. -- Merging to `main` opens or updates the "Version Packages" PR; merging that PR publishes. Never bump `version` or edit `CHANGELOG.md` by hand. +- Commit messages and PR titles follow Conventional Commits (`type(scope): subject`); the commit-msg hook and the "Commit messages" CI job enforce it (CONTRIBUTING.md, "Commit messages"). +- Every PR with a user-facing change adds one changeset per change, written directly as `.changeset/.md` (`npx changeset` is interactive), bumping patch for a fix or speedup, minor for new behavior, major for a public-contract change; template and traps in [docs/changesets.md](docs/changesets.md). CI, docs, and test-only PRs add none. +- Merging to `main` opens or updates the "chore: version packages" PR; merging that PR publishes. Never bump `version` or edit `CHANGELOG.md` by hand. - A dependency change updates `package-lock.json` in the same commit and is verified with `npm test`. - Never `git stash`; use a temporary commit. Never force-push `main`. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 25f29c6..e6c2da9 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,6 +1,6 @@ # Contributing -Start off forking, then cloning the project locally: +Start off forking, then cloning the project locally. The scripts need Node 22.18 or newer (`devEngines` in `package.json`), which runs TypeScript files directly: - `$ npm ci` - Install dependencies - `$ npm test` - Run tests @@ -10,13 +10,19 @@ Start off forking, then cloning the project locally: ## Syntax -The syntax is regex based, tools I've been using have include a mix of [regex101.com](https://regex101.com/) and [regexr.com](https://regexr.com/). Note that VSCode does -not use JavaScript Regex, but [oniguruma](https://github.com/kkos/oniguruma) instead. They are more compatible with the _PCRE_ flavor in these -websites. The Regex in the JSON files are string encoded, so you need to decode/encode them when copying between these websites, you can use a [JSON escape/unescape tool](https://jsonviewertool.com/json-escape). You can test your regex with the node version in a scratch pad to see which groups it matches (these may not always be what you expect) https://github.com/atom/node-oniguruma. +The grammars are TextMate grammars written as TypeScript in `syntaxes/src/`: -It can take some time to get used to the regular expressions. +- `styled-components.mts`: the injection grammar, which finds styled-components tags in JavaScript and TypeScript and starts CSS at the template's backtick +- `css.styled.mts`: the CSS grammar for template content +- `ownCss.mts`: copies the CSS rules `css.styled.mts` uses from `css.tmLanguage.json`, VS Code's CSS grammar (vendored from the pinned VS Code version; its license is in `ThirdPartyNotices.txt`) -To visually test your changes press `F5` while having this project open in VSCode, it will open another window with extension enabled. You can load the `colorize-fixture` folder in that window to see your changes. +`syntaxes/src/generate.mts` writes `syntaxes/styled-components.json` and `syntaxes/css.styled.json`. Every build, `npm run watch`, and `npm run tokenize` (except with `--grammars `) regenerates them; they are git-ignored, so edit the `.mts` sources, never the JSON. + +The regexes are written with `String.raw`, so they need no JSON escaping. VS Code runs them with [Oniguruma](https://github.com/kkos/oniguruma), not JavaScript's regex engine; Oniguruma is closest to the PCRE flavor on [regex101.com](https://regex101.com/). Check a change with `npm run tokenize`, which runs the real grammars. + +The order of the patterns arrays matters: TextMate tries the rules in order, so reordering them changes highlighting. + +To see your changes in the editor, press `F5` with this project open in VS Code. A second window opens with the extension enabled and the colorize fixtures folder loaded. Refer to JS/TS tokens syntax at https://github.com/microsoft/vscode/tree/master/extensions under `/syntaxes/.tmLanguage.json`. @@ -24,15 +30,13 @@ To check how tokens are being matched, select "Developer: Inspect Editor Tokens ### "A line break seems to break the syntax highlighting" -Many of the bugs raised are due to multiline regex not being available. -Textmate grammar can [only match a single line](https://github.com/microsoft/vscode-textmate/issues/32). Unfortunately a lot of the regex we have tries to parse multiple lines at once (which won't work). -This has caused bugs to be raised such as: https://github.com/styled-components/vscode-styled-components/issues/266 and https://github.com/styled-components/vscode-styled-components/issues/277 +A TextMate grammar [matches one line at a time](https://github.com/microsoft/vscode-textmate/issues/32), so a regex that needs to see a newline never matches. Issues [#266](https://github.com/styled-components/vscode-styled-components/issues/266) and [#277](https://github.com/styled-components/vscode-styled-components/issues/277) are examples. -The best fix is to look at the new line and create a new rule in https://github.com/styled-components/vscode-styled-components/blob/master/syntaxes/styled-components.json which will match that line as close as possible whilst still being generic. Regex101 helps with this. +The best fix is to look at the new line and add a rule to `syntaxes/src/styled-components.mts` that matches that line as closely as possible while staying generic. ## Intellisense -Intellisense is handled by https://github.com/microsoft/typescript-styled-plugin. +Intellisense is handled by the bundled `@styled/typescript-styled-plugin` (https://github.com/styled-components/typescript-styled-plugin). For most things `typescript-styled-plugin` is just a [pass-through](https://github.com/microsoft/typescript-styled-plugin/blob/master/src/_language-service.ts#L87-L95) to the CSS/SCSS language services. For example, looking at [getCompletionItems](https://github.com/styled-components/typescript-styled-plugin/blob/master/src/_language-service.ts#L215-L244) you can see it just calls the equivalent on the upstream language services. So if something works natively (CSS file), but not in styled-components its most likely because it's not passing the correct events through. @@ -40,14 +44,14 @@ For most things `typescript-styled-plugin` is just a [pass-through](https://gith ![img](./docs/img/mult-workspace.png) -I use VSCode's multi workspace for this (see above image). I have `typescript-styled-plugin`, `vscode-styled-components`and [`vscode-css-languageserver`](https://github.com/vscode-langservers/vscode-css-languageserver) (optional) folders loaded. +Load `typescript-styled-plugin`, `vscode-styled-components`, and optionally [`vscode-css-languageserver`](https://github.com/vscode-langservers/vscode-css-languageserver) as the folders of one VS Code multi-root workspace (see the image above). You can't run the typescript-styled-plugin directly, instead you need to load a debugger to listen on a port. The below shows you how to set this up so that you can debug both the extension and the plugin at the same time. - Make sure `typescript-styled-plugin` is yarn|npm linked into `vscode-styled-components` (see image above) -- uncomment the plugin section in [tsconfig](https://github.com/styled-components/vscode-styled-components/blob/master/tsconfig.json#L18), make sure the path points to your local checkout of typescript styled plugin +- While debugging, add `"plugins": [{ "name": "../typescript-styled-plugin" }]` under `compilerOptions` in `tsconfig.json`, with the path pointing to your local checkout of the plugin. Don't commit it. - In `vscode-styled-components/.vscode/launch.json`, `"TSS_DEBUG": "9229"` should be set (or `"TSS_REMOTE_DEBUG": "9229"` if using WSL). This allows the debugger to communicate with the typescript-styled-plugin. These may already be set. -- [Debug Tab] Click `Launch extension` +- [Debug Tab] Click `Launch Extension` - Once the new window is up and running go back to the host VSCode instance and on the debug tab Click `Debug Styled Plugin` - This will both build and start the debugger on the typescript-styled-plugin project. You should now be able to use styled-components in the guest window and set breakpoints on the both the plugin and extension in the main window. @@ -74,10 +78,20 @@ This should spawn another instance of VSCode to run the end to end tests in. The syntax tests will generate tokens for [fixtures we have](./src/tests/suite/colorize-fixtures) which are then compared to the results (adjacent folder). If there are changes and the tests fail it will generate a new result (overwriting the previous one). A failing CI run uploads the regenerated results as a `colorize-results-` artifact. -The tests run against the VS Code version pinned in [runTests.js](./src/tests/runTests.js), because built-in themes and grammars change between releases. To move to a newer VS Code, bump the pin, run the tests, review the regenerated results, and commit them together. +The tests run against the VS Code version pinned in [vscodeVersion.mts](./src/tests/vscodeVersion.mts), because built-in themes and grammars change between releases. To move to a newer VS Code, bump the pin, replace `syntaxes/src/css.tmLanguage.json` with that version's `extensions/css/syntaxes/css.tmLanguage.json`, run the tests, review the regenerated results, and commit them together. + +A syntax change updates the test suite. Every fixture except a `.css` fixture ends with `const sentinel = 1;`; a fixture without that last line fails the colorization test, and if highlighting leaks out of a template, a sentinel line loses its plain-code scopes and the test fails. + +To check a grammar change without opening VS Code, run `npm run tokenize -- `. It prints every token's scopes using the pinned VS Code's grammars; add `--sentinel` to check only the sentinel lines (it also fails a fixture without the last sentinel line, and prints `SKIP` for a `.css` file), or `--drift` to compare each fixture with its committed result. A grammar change must not slow highlighting; `npm run bench:grammar` measures it (both tools: [spec, "Test strategy"](docs/spec.md#test-strategy)). + +Logic that needs no editor (parsing, scanning, grammar generation) gets unit tests in `src/**/*.test.ts` or `syntaxes/src/**/*.test.ts`, run with `npm run test:unit`. + +## Commit messages + +Commit messages and PR titles follow [Conventional Commits](https://www.conventionalcommits.org/): `type(scope): subject`, for example `fix(grammar): stop highlighting after an empty template`. The types are feat, fix, perf, refactor, style, test, docs, build, ci, chore, and revert; the scope is optional and holds lowercase letters, digits, and hyphens (`fix(color-picker): ...`), and a `!` after the type or scope marks a breaking change (`feat(grammar)!: ...`). A squash merge uses the PR title as the commit message, so the title follows the same format. -When making syntax changes you should update the test suite. +`scripts/check-commit-message.sh` checks a message. The commit-msg hook runs it on each local commit, and the "Commit messages" CI job (`.github/workflows/commit-messages.yml`) runs it on the PR title and every commit in the PR, again whenever the PR title is edited. The hook also accepts the subjects git writes itself (`fixup! `, `squash! `, `amend! `, and `Revert "..."`); CI does not, so squash or reword those commits before merging. ## Releasing -Every PR with a user-facing change includes a changeset (`npx changeset`, choose patch, minor, or major, and describe the change for users). On merge to `main`, the Release workflow opens or updates a "Version Packages" PR that bumps the version and writes `CHANGELOG.md`. Merging that PR publishes the extension to the VS Code Marketplace through trusted publishing (no stored token), tags `vX.Y.Z`, and creates the GitHub release. +Every PR with a user-facing change includes a changeset (`npx changeset`, choose patch, minor, or major, and describe the change for users). On merge to `main`, the Release workflow opens or updates a "chore: version packages" PR that bumps the version and writes `CHANGELOG.md`. Merging that PR publishes the extension to the VS Code Marketplace through trusted publishing (no stored token), tags `vX.Y.Z`, and creates the GitHub release. diff --git a/README.md b/README.md index 3a86ab4..d4e69a4 100644 --- a/README.md +++ b/README.md @@ -47,7 +47,7 @@ Syntax Highlighting is specifically made to work with `styled` so make sure your See: https://github.com/styled-components/vscode-styled-components/issues/118#issuecomment-833007295 -Secondly make sure your file is set to the right language. It should be `typescriptreact` or `javascriptreact`. Using the correct extensions (jsx, tsx) should help with this. +Highlighting works in files whose language mode is JavaScript, TypeScript, JavaScript React, TypeScript React, Vue, or Svelte (shown in the status bar). Color swatches and the backtick snippet work only in saved files in the two React modes (`javascriptreact` and `typescriptreact`, which the `.jsx` and `.tsx` extensions set). ### Emmet tab completion isn't working diff --git a/ThirdPartyNotices.txt b/ThirdPartyNotices.txt new file mode 100644 index 0000000..f27fc3c --- /dev/null +++ b/ThirdPartyNotices.txt @@ -0,0 +1,71 @@ +THIRD-PARTY SOFTWARE NOTICES AND INFORMATION + +This package includes material from the projects below. Each notice is provided for information only. + +1. microsoft/vscode-css (https://github.com/microsoft/vscode-css), as shipped in Visual Studio Code + + The CSS rules in syntaxes/css.styled.json are copied from Visual Studio Code's CSS grammar (css.tmLanguage.json), which its header describes as converted from https://github.com/microsoft/vscode-css/blob/master/grammars/css.cson (commit de9e6beee756760f31b15efbd782735fc25de3db). + + MIT License + + Copyright (c) Microsoft Corporation. All rights reserved. + + Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +2. atom/language-sass (https://github.com/atom/language-sass), as shipped in Visual Studio Code + + The SCSS-derived rules in syntaxes/css.styled.json (their rule names, scope names, and regular expressions) come from the SCSS grammar of the Atom package language-sass, which Visual Studio Code converts from https://github.com/atom/language-sass/blob/master/grammars/scss.cson (commit f52ab12f7f9346cc2568129d8c4419bd3d506b47). + + MIT License + + Copyright (c) 2014 GitHub Inc. + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + -------------------------------------------------------------------- + + This package was derived from a TextMate bundle located at + https://github.com/alexsancho/Sass.tmbundle and distributed under the following + license, located in `LICENSE.md`: + + Copyright (c) 2012 Alex Sancho, http://alexsancho.name/ + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/build.mjs b/build.mjs deleted file mode 100644 index 6a004c6..0000000 --- a/build.mjs +++ /dev/null @@ -1,41 +0,0 @@ -import esbuild from "esbuild"; - -const production = process.argv[2] === "--production"; -const watch = process.argv[2] === "--watch"; -const context = await esbuild - .context({ - entryPoints: ["./src/extension.ts"], - bundle: true, - outdir: "dist", - external: ["vscode"], - format: "cjs", - sourcemap: !production, - minify: production, - platform: "node", - mainFields: ["module", "main"], - target: "ES2022", - plugins: [ - { - name: "watch", - setup(build) { - build.onEnd(() => { - if (watch) console.log("build finished"); - }); - build.onStart(() => { - if (watch) console.log("building..."); - }); - }, - }, - ], - }) - .catch((e) => { - console.error(e); - process.exit(1); - }); - -if (watch) { - await context.watch(); -} else { - context.rebuild(); - context.dispose(); -} diff --git a/build.mts b/build.mts new file mode 100644 index 0000000..07a1df7 --- /dev/null +++ b/build.mts @@ -0,0 +1,65 @@ +import { spawnSync } from "node:child_process"; +import { watch as watchFiles } from "node:fs"; + +import esbuild from "esbuild"; + +const production = process.argv[2] === "--production"; +const watch = process.argv[2] === "--watch"; + +// A subprocess, not an import: watch mode regenerates, and a module imported once would serve stale grammars. +const generateGrammars = () => + spawnSync(process.execPath, ["./syntaxes/src/generate.mts"], { + stdio: "inherit", + }).status === 0; + +if (!generateGrammars()) process.exit(1); + +const context = await esbuild + .context({ + entryPoints: ["./src/extension.ts"], + bundle: true, + outdir: "dist", + external: ["vscode"], + format: "cjs", + sourcemap: !production, + minify: production, + platform: "node", + mainFields: ["module", "main"], + target: "ES2022", + plugins: watch + ? [ + { + name: "watch", + setup(build) { + build.onEnd(() => console.log("build finished")); + build.onStart(() => console.log("building...")); + }, + }, + ] + : [], + }) + .catch((e) => { + console.error(e); + process.exit(1); + }); + +if (watch) { + let pending: NodeJS.Timeout | undefined; + watchFiles("./syntaxes/src", { recursive: true }, () => { + clearTimeout(pending); + pending = setTimeout(() => { + console.log("building..."); + if (!generateGrammars()) console.error("grammar generation failed"); + console.log("build finished"); + }, 100); + }); + await context.watch(); +} else { + // esbuild has already printed the errors when rebuild rejects. + const built = await context.rebuild().then( + () => true, + () => false, + ); + await context.dispose(); + if (!built) process.exit(1); +} diff --git a/docs/changesets.md b/docs/changesets.md index bad5015..4e0f543 100644 --- a/docs/changesets.md +++ b/docs/changesets.md @@ -4,16 +4,32 @@ Checked 2026-11-18 against @changesets/cli 3.0.3, @changesets/config 4.0.1, chan ## How a release happens -- A PR with a user-facing change adds a changeset (`npx changeset`). On merge to `main`, `release.yml` runs changesets/action: with pending changesets it opens or updates the "Version Packages" PR (version bump and `CHANGELOG.md`). -- Merging the Version Packages PR leaves no pending changesets, so the next run calls `npm run release`. That script skips when the GitHub release `v` already exists, otherwise runs `vsce publish --oidc --skip-duplicate` and then `changeset publish`. +- A PR with a user-facing change adds a changeset (`npx changeset`). On merge to `main`, `release.yml` runs changesets/action: with pending changesets it opens or updates the version PR (version bump and `CHANGELOG.md`). +- Merging the version PR ("chore: version packages", set by the action's `pr-title` and `commit-message` inputs) leaves no pending changesets, so the next run calls `npm run release`. That script skips when the GitHub release `v` already exists, otherwise runs `vsce publish --oidc --skip-duplicate` and then `changeset publish`. - The package is `private: true` (it never goes to npm). `.changeset/config.json` sets `privatePackages: { "version": true, "tag": true }`, so `changeset publish` only creates the `v` tag, and the action creates the GitHub release from it. - A push with nothing to release (CI or docs changes) takes the publish path and stops at the existing-release check. +## Writing a changeset + +One file per user-noticeable change, named `.changeset/.md`: + +```md +--- +"vscode-styled-components": patch +--- + +Highlighting no longer spills out of a styled template when its tag spans several lines. +``` + +- The bump is `patch` for a fix or a speedup, `minor` for new behavior, and `major` for a change to the public contract (docs/spec.md, "Public contract"). +- The body is one short paragraph for users of the extension; its writing rules are in AGENTS.md, "Prose and communication". +- `npx changeset` writes the same file interactively. + ## Rules and traps - CLI and action move together: @changesets/cli 3.x needs changesets/action v2 (it throws at startup on a CLI 2 range), and v2 inputs are kebab-case (`publish-script`, `github-token`). Bumping only one passes PR CI and fails the first release run on `main`. - Pin the config `$schema` to the installed `@changesets/config` major.minor (4.0.x for CLI 3). The 3.1.x schema belongs to CLI 2 and still loads, so a stale pin validates against the wrong schema without complaint. -- Never hand-edit `version` in `package.json` or `CHANGELOG.md`; the Version Packages PR owns both. +- Never hand-edit `version` in `package.json` or `CHANGELOG.md`; the version PR owns both. - A changeset body uses no markdown headings (changesets nests it under its own `### Patch Changes`); use bold labels. - A malformed changeset (no closing `---` fence, or a bump that is not `"vscode-styled-components": patch|minor|major`) passes PR CI, because the changeset is markdown, and then blocks the release on `main`. - `changeset publish` has no `--dry-run`; test the publish path by running the release script with credentials removed, never by hoping it stops in time. diff --git a/docs/github-actions.md b/docs/github-actions.md index ac82d37..1c4bdaf 100644 --- a/docs/github-actions.md +++ b/docs/github-actions.md @@ -16,7 +16,7 @@ Checked 2026-11-18 against actions/checkout v7.0.1, actions/setup-node v7.1.0, a - Publishing uses VS Code Marketplace trusted publishing: `id-token: write` plus `vsce publish --oidc`, no stored token. Never reintroduce a long-lived publish secret. - No dependency cache in the release job (`package-manager-cache: false`, no `cache:` input, no `actions/cache`). A poisoned cache entry would run with the publish identity; the cold install is the accepted cost. - A manual run on a ref other than `main` fails at its first step. That guards against a mistaken dispatch only: a branch can edit the workflow itself, so the Marketplace trusted-publisher binding is the real control. -- Events created with the job's `GITHUB_TOKEN` (the Version Packages PR) start no workflows, so required checks never run on that PR. Setting a `RELEASE_GITHUB_TOKEN` secret (a PAT or GitHub App token) fixes this; `release.yml` already prefers it. +- Events created with the job's `GITHUB_TOKEN` (the version PR) start no workflows, so required checks never run on that PR. Setting a `RELEASE_GITHUB_TOKEN` secret (a PAT or GitHub App token) fixes this; `release.yml` already prefers it. ## Repository settings this baseline assumes diff --git a/docs/spec.md b/docs/spec.md new file mode 100644 index 0000000..3fea758 --- /dev/null +++ b/docs/spec.md @@ -0,0 +1,229 @@ +# Behavior spec + +This spec is the source of truth for what the extension does; the code implements it. A behavior change edits this file first, in the same PR as the code. Intended behavior that the code does not yet meet is listed under [Known deviations](#known-deviations). + +## Scope and hosts + +- Editor: VS Code, from the minimum version in `package.json` `engines.vscode`. Published to the VS Code Marketplace only (Open VSX is requested in #368). +- Activation: opening a `javascriptreact` or `typescriptreact` document, or running the Enter command (VS Code 1.74 and later, the minimum in `engines.vscode`, activates an extension for its own commands). +- The syntax grammar injects into JavaScript, TypeScript, JSX, TSX, Vue, and Svelte documents, everywhere except inside comments and strings. +- The color swatches and the backtick snippet serve documents on disk (`file` scheme) whose language is `javascriptreact` or `typescriptreact`. Untitled documents and plain `.js`/`.ts` files get neither. +- The Enter command's keybinding applies where [Enter command](#enter-command) says. +- IntelliSense and diagnostics run wherever VS Code's TypeScript server runs the bundled plugin (see [IntelliSense and diagnostics](#intellisense-and-diagnostics)). + +## Syntax highlighting + +Highlighting never extends past the end of a recognized template: code after any expression, recognized or not, is highlighted exactly as the host language's own grammar highlights it. + +### Recognized tags + +A template literal is highlighted as CSS when its opening backtick ends one of these tags. The tag head (everything from the tag's root, such as `styled`, to the backtick) may span lines; see [Tag heads across lines](#tag-heads-across-lines). + +- `styled.div`, `styled(Component)`, `styled("div")`, `styled(Namespace.Component)`, `styled(getComponent(props))`, `styled (Component)`, and bare `styled`; the root may also be spelled `Styled` or `$styled` +- roots reached through members, calls, or indexes: `theme.styled.div`, `foo().styled.div`, `items[0].styled.div`, `(await load()).styled.div`, `theme.css`, `theme.keyframes` +- an arrow function returning the template, with a parenthesized or an unparenthesized parameter, on the tag's line too: ``styled.div(({ theme }) => ` ``, ``styled.div(($props) => ` ``, ``styled.div(p => ` ``, ``styled.div.attrs({})(({ theme }) => `color: red;`)`` +- `.attrs(...)` and `.withConfig(...)` chains +- TypeScript generics: `styled.div`, `styled("div")`, `styled("div")`, `.attrs(...)`, and on helpers: `css`, `keyframes`, `createGlobalStyle` +- helpers: `css`, `keyframes`, `createGlobalStyle`, `createGlobalStyles`, `injectGlobal`, `stylesheet` +- `.extend` tags (`Button.extend`, `a().b.extend`) anywhere in an expression, also followed by any number of `.attrs(...)` and `.withConfig(...)` calls (`Button.extend.attrs({}).withConfig({})`), on one line or split across lines +- `.withComponent(...)` tags whose argument is a quoted identifier or a dotted identifier chain (`A.withComponent("a")`, `A.withComponent(Other.Comp)`), also followed by `.extend` +- media helpers: `media.desktop`, `media.breakAt("300px")`; the root may also be spelled `Media` +- the `css` prop: ``css={` `` +- styled-jsx: ``; +const d = ; +const e = ; +const f = styled.div<{ a: boolean }>` + color: ${(p) => (p.a ? "red" : "blue")}; +`; +const sentinel = 1; diff --git a/src/tests/suite/colorize-fixtures/call-prefix-root.js b/src/tests/suite/colorize-fixtures/call-prefix-root.js new file mode 100644 index 0000000..6e62c6e --- /dev/null +++ b/src/tests/suite/colorize-fixtures/call-prefix-root.js @@ -0,0 +1,5 @@ +const i = foo().styled.div`color: red;`; +const j = foo().styled(Button)`color: red;`; +const k = foo().styled.div.attrs({})`color: red;`; +foo().styled.div`color: red;`; +const sentinel = 1; diff --git a/src/tests/suite/colorize-fixtures/closers.js b/src/tests/suite/colorize-fixtures/closers.js new file mode 100644 index 0000000..f3e7a7d --- /dev/null +++ b/src/tests/suite/colorize-fixtures/closers.js @@ -0,0 +1,24 @@ +// A tag after a closer of an earlier line: the tag rule must not consume what the host needs to close its frame +function g() { + return [Comp.extend`color: red;`]; +} + +function f() { + return foo({ a: keyframes`from { color: red; }` }); +} + +const X = cond ? ( + a +) : Comp.extend`color: red;`; + +const anims = [ + 1, 2 ].concat(keyframes`from { color: red; }`); + +const y = cond ? ( + a +) : keyframes`from { color: red; }`; + +const z = cond ? ( + a +) : styled.div`color: red;`; +const sentinel = 1; diff --git a/src/tests/suite/colorize-fixtures/comment.js b/src/tests/suite/colorize-fixtures/comment.js index b36ad28..af14b32 100644 --- a/src/tests/suite/colorize-fixtures/comment.js +++ b/src/tests/suite/colorize-fixtures/comment.js @@ -2,3 +2,4 @@ // height: 20px; // padding: 5px; // ` +const sentinel = 1; diff --git a/src/tests/suite/colorize-fixtures/component.js b/src/tests/suite/colorize-fixtures/component.js index 9bdc2e5..c48ef5a 100644 --- a/src/tests/suite/colorize-fixtures/component.js +++ b/src/tests/suite/colorize-fixtures/component.js @@ -1,3 +1,4 @@ const Component = styled(Component)` color: #ebebeb; `; +const sentinel = 1; diff --git a/src/tests/suite/colorize-fixtures/createGlobalStyle.js b/src/tests/suite/colorize-fixtures/createGlobalStyle.js index 0064b41..4e73343 100644 --- a/src/tests/suite/colorize-fixtures/createGlobalStyle.js +++ b/src/tests/suite/colorize-fixtures/createGlobalStyle.js @@ -3,3 +3,4 @@ const GlobalStyles = createGlobalStyle` color: 'red'; } `; +const sentinel = 1; diff --git a/src/tests/suite/colorize-fixtures/css-prop.js b/src/tests/suite/colorize-fixtures/css-prop.js index 0887aff..c01708f 100644 --- a/src/tests/suite/colorize-fixtures/css-prop.js +++ b/src/tests/suite/colorize-fixtures/css-prop.js @@ -4,3 +4,4 @@ color: ${props => props.theme.colors.text}; `} />; +const sentinel = 1; diff --git a/src/tests/suite/colorize-fixtures/custom-at-rule.js b/src/tests/suite/colorize-fixtures/custom-at-rule.js index 8ea27a3..75ce6b4 100644 --- a/src/tests/suite/colorize-fixtures/custom-at-rule.js +++ b/src/tests/suite/colorize-fixtures/custom-at-rule.js @@ -12,3 +12,4 @@ const customAtRule = styled.div` background-color: red; } ` +const sentinel = 1; diff --git a/src/tests/suite/colorize-fixtures/dot-tag.js b/src/tests/suite/colorize-fixtures/dot-tag.js index 98ffe16..53a905a 100644 --- a/src/tests/suite/colorize-fixtures/dot-tag.js +++ b/src/tests/suite/colorize-fixtures/dot-tag.js @@ -4,3 +4,4 @@ const DotTag = styled.div` font-family: Helvetica; ${mixin}; `; +const sentinel = 1; diff --git a/src/tests/suite/colorize-fixtures/export-default.js b/src/tests/suite/colorize-fixtures/export-default.js index 6ef358f..7723db5 100644 --- a/src/tests/suite/colorize-fixtures/export-default.js +++ b/src/tests/suite/colorize-fixtures/export-default.js @@ -1,3 +1,4 @@ export default styled(ExportComponent)` max-width: 100%; `; +const sentinel = 1; diff --git a/src/tests/suite/colorize-fixtures/extend-chain.js b/src/tests/suite/colorize-fixtures/extend-chain.js new file mode 100644 index 0000000..4cd2707 --- /dev/null +++ b/src/tests/suite/colorize-fixtures/extend-chain.js @@ -0,0 +1,12 @@ +const B = Button.extend.attrs({ a: 1 })`color: red;`; +const C = Button.extend.withConfig({ a: 1 })`color: red;`; +const D = Button.extend.attrs({ + a: 1, +})` + color: red; +`; +const E = Button.extend + .attrs({ a: 1 })` + color: red; +`; +const sentinel = 1; diff --git a/src/tests/suite/colorize-fixtures/extend.js b/src/tests/suite/colorize-fixtures/extend.js index f605b7b..c5adbaa 100644 --- a/src/tests/suite/colorize-fixtures/extend.js +++ b/src/tests/suite/colorize-fixtures/extend.js @@ -15,3 +15,4 @@ const foo = { const Half = getFull().extend` max-width: 100%; ` +const sentinel = 1; diff --git a/src/tests/suite/colorize-fixtures/function-call-space.js b/src/tests/suite/colorize-fixtures/function-call-space.js index 50b8872..7ec3e95 100644 --- a/src/tests/suite/colorize-fixtures/function-call-space.js +++ b/src/tests/suite/colorize-fixtures/function-call-space.js @@ -1,3 +1,4 @@ const Component = styled (Component)` max-width: 100%; `; +const sentinel = 1; diff --git a/src/tests/suite/colorize-fixtures/function-call-with-css-helper.js b/src/tests/suite/colorize-fixtures/function-call-with-css-helper.js index 87d7eb4..85f3318 100644 --- a/src/tests/suite/colorize-fixtures/function-call-with-css-helper.js +++ b/src/tests/suite/colorize-fixtures/function-call-with-css-helper.js @@ -21,3 +21,4 @@ const Component3 = styled.div` width: 100%; `)} `; +const sentinel = 1; diff --git a/src/tests/suite/colorize-fixtures/function-call.js b/src/tests/suite/colorize-fixtures/function-call.js index 492c0ac..fcb7b99 100644 --- a/src/tests/suite/colorize-fixtures/function-call.js +++ b/src/tests/suite/colorize-fixtures/function-call.js @@ -1,3 +1,4 @@ const Component = styled(getComponent(props))` max-width: 100%; `; +const sentinel = 1; diff --git a/src/tests/suite/colorize-fixtures/function-media-queries.js b/src/tests/suite/colorize-fixtures/function-media-queries.js index d55e03b..abc95b1 100644 --- a/src/tests/suite/colorize-fixtures/function-media-queries.js +++ b/src/tests/suite/colorize-fixtures/function-media-queries.js @@ -88,3 +88,4 @@ const Input = styled.input.attrs({ margin: ${props => props.margin}; padding: ${props => props.padding}; `; +const sentinel = 1; diff --git a/src/tests/suite/colorize-fixtures/generics.ts b/src/tests/suite/colorize-fixtures/generics.ts new file mode 100644 index 0000000..24ba889 --- /dev/null +++ b/src/tests/suite/colorize-fixtures/generics.ts @@ -0,0 +1,124 @@ +// #358 and #442: type arguments that span lines +const Container = styled.div<{ + fullWidth?: boolean; + isMyMessage?: boolean | null; +}>` + color: red; +`; + +const B = styled.div< + Props +>` + color: red; +`; +const D = styled.div` + color: red; +`; + +const A = styled(Button)<{ + a: string; +}>` + color: red; +`; +const C = styled("div")<{ + a: string; +}>` + color: red; +`; + +const R = styled.div<{ + a: Record; + b: Array; +}>` + color: red; + ${(p) => p.a && css` + color: red; + `} +`; + +const Pick1 = styled.div & { + b: string +}>` + color: red; +`; + +const X = styled.div<{ a: string; + b: number; +}>` + color: red; +`; +const E = styled.div<{ onClick: () => void; + b: string }>` + color: red; +`; + +// .attrs after and around a generic +const AG = styled.div.attrs((p) => ({ + a: 1, +}))` + color: red; +`; +const ML = styled.div< + Props +>.attrs((p) => ({ + title: `${p.s}`, +}))` + color: red; +`; +const G = styled.div.attrs((p) => ({ + a: 1, +}))<{ b: string }>` + color: red; +`; +const H = styled.div.attrs({ a: 1 })<{ + b: string +}>` + color: red; +`; +const I = styled(Link).attrs<{ $a: boolean }>(({ $a }) => ({ + role: $a ? "x" : "y", +}))` + color: red; +`; +const M6 = styled(Button).attrs({ type: "button" })<{ + a: string +}>` + color: red; +`; +const M7 = styled.div.attrs(p => ({}))` + color: red; +`; + +// helper generics +const GS = createGlobalStyle<{ + dark: boolean; +}>` + body { color: red; } +`; +const c = css<{ + a: string; +}>` + color: red; +`; +const k = keyframes<{ + a: string; +}>` + from { color: red; } +`; + +const T3 = styled(Button)<{ + v: `a-${string}` +}>` + color: red; +`; +const E1 = styled("div")` + color: red; +`; +const E2 = styled.div<{ a: (x: number) => void }>` + color: red; +`; +const E3 = styled.div` + ${(p: Props) => p.a && css`color: red;`} +`; +const sentinel = 1; diff --git a/src/tests/suite/colorize-fixtures/generics.tsx b/src/tests/suite/colorize-fixtures/generics.tsx new file mode 100644 index 0000000..24ba889 --- /dev/null +++ b/src/tests/suite/colorize-fixtures/generics.tsx @@ -0,0 +1,124 @@ +// #358 and #442: type arguments that span lines +const Container = styled.div<{ + fullWidth?: boolean; + isMyMessage?: boolean | null; +}>` + color: red; +`; + +const B = styled.div< + Props +>` + color: red; +`; +const D = styled.div` + color: red; +`; + +const A = styled(Button)<{ + a: string; +}>` + color: red; +`; +const C = styled("div")<{ + a: string; +}>` + color: red; +`; + +const R = styled.div<{ + a: Record; + b: Array; +}>` + color: red; + ${(p) => p.a && css` + color: red; + `} +`; + +const Pick1 = styled.div & { + b: string +}>` + color: red; +`; + +const X = styled.div<{ a: string; + b: number; +}>` + color: red; +`; +const E = styled.div<{ onClick: () => void; + b: string }>` + color: red; +`; + +// .attrs after and around a generic +const AG = styled.div.attrs((p) => ({ + a: 1, +}))` + color: red; +`; +const ML = styled.div< + Props +>.attrs((p) => ({ + title: `${p.s}`, +}))` + color: red; +`; +const G = styled.div.attrs((p) => ({ + a: 1, +}))<{ b: string }>` + color: red; +`; +const H = styled.div.attrs({ a: 1 })<{ + b: string +}>` + color: red; +`; +const I = styled(Link).attrs<{ $a: boolean }>(({ $a }) => ({ + role: $a ? "x" : "y", +}))` + color: red; +`; +const M6 = styled(Button).attrs({ type: "button" })<{ + a: string +}>` + color: red; +`; +const M7 = styled.div.attrs(p => ({}))` + color: red; +`; + +// helper generics +const GS = createGlobalStyle<{ + dark: boolean; +}>` + body { color: red; } +`; +const c = css<{ + a: string; +}>` + color: red; +`; +const k = keyframes<{ + a: string; +}>` + from { color: red; } +`; + +const T3 = styled(Button)<{ + v: `a-${string}` +}>` + color: red; +`; +const E1 = styled("div")` + color: red; +`; +const E2 = styled.div<{ a: (x: number) => void }>` + color: red; +`; +const E3 = styled.div` + ${(p: Props) => p.a && css`color: red;`} +`; +const sentinel = 1; diff --git a/src/tests/suite/colorize-fixtures/head-chain-newline.js b/src/tests/suite/colorize-fixtures/head-chain-newline.js new file mode 100644 index 0000000..325aba2 --- /dev/null +++ b/src/tests/suite/colorize-fixtures/head-chain-newline.js @@ -0,0 +1,14 @@ +const A = styled.div + .attrs({ a: 1 }) + .withConfig({ displayName: "A" })` + color: red; +`; +const B = styled(Button) + .attrs({ b: 2 })` + margin: 0; +`; +const C = styled.div.attrs({ c: 3 }) + .withConfig({ displayName: "C" })` + padding: 0; +`; +const sentinel = 1; diff --git a/src/tests/suite/colorize-fixtures/head-comment.js b/src/tests/suite/colorize-fixtures/head-comment.js new file mode 100644 index 0000000..8646d7d --- /dev/null +++ b/src/tests/suite/colorize-fixtures/head-comment.js @@ -0,0 +1,9 @@ +const A = styled.div // why +` + color: red; +`; +const B = styled.div.attrs({ b: 2 }) /* why */ +` + margin: 0; +`; +const sentinel = 1; diff --git a/src/tests/suite/colorize-fixtures/head-multiline.js b/src/tests/suite/colorize-fixtures/head-multiline.js new file mode 100644 index 0000000..7e7a0c2 --- /dev/null +++ b/src/tests/suite/colorize-fixtures/head-multiline.js @@ -0,0 +1,97 @@ +// #292: .attrs given a props value, and heads that span lines +const M1 = styled.div.attrs(({}))` color: red; `; +const M2 = styled.div.attrs(()=>({}))` color: red; `; +const M3 = styled.div.attrs((someVar))` color: red; `; +const M4 = styled.div.attrs(someFunc())` color: red; `; +const Root = styled.div.attrs(props=>({ + "data-status": `${props.status}` +}))` + color: red; +`; + +const B = styled.div.attrs((p) => ({ + className: `x-${p.a}`, +}))` + color: red; +`; + +const C = styled.div.withConfig({ + shouldForwardProp: (prop) => !["a"].includes(prop), +})` + color: red; +`; + +// #383: a call whose argument is an arrow function returning an object, before a tag's template +const D = styled("div")(({ theme }) => ` + color: red; +`); +const E = styled.div(({ theme }) => ` + color: red; +`); + +const F = styled.div.attrs({ + // a comment with a ) paren + a: 1, /* and ( one */ +})` + color: red; +`; + +const G = styled.div.attrs({ + + a: 1, +})` + color: red; +`; + +const H = styled.div.attrs((p) => ({ + a: 1, +}))` + color: red; + ${(p) => p.a && css` + color: red; + `} +`; +const S = { a: css`color: red;`, b: styled.p`color: red;` }; + +const I = styled( + Button +)` + color: red; +`; +const J = styled + .div` + color: red; +`; + +const K = styled(Button, { + shouldForwardProp: (p) => p.length < 3 && p !== "x", +})` + color: red; +`; + +const L = styled.div.attrs((p) => ({ + a: p?.b ?? 1, + c: [1, 2].map((x) => x < 2), +}))` + color: red; +`; + +const M = styled.div.attrs({ + re: /[(`]/g, +})` + color: red; +`; + +const N = styled.div.attrs({ + s: "(", + t: ")))", +})` + color: red; +`; + +const O = styled.div.attrs({ + title: `a ${b} (`, +})` + color: red; +`; +const sentinel = 1; diff --git a/src/tests/suite/colorize-fixtures/head-multiline.ts b/src/tests/suite/colorize-fixtures/head-multiline.ts new file mode 100644 index 0000000..7e7a0c2 --- /dev/null +++ b/src/tests/suite/colorize-fixtures/head-multiline.ts @@ -0,0 +1,97 @@ +// #292: .attrs given a props value, and heads that span lines +const M1 = styled.div.attrs(({}))` color: red; `; +const M2 = styled.div.attrs(()=>({}))` color: red; `; +const M3 = styled.div.attrs((someVar))` color: red; `; +const M4 = styled.div.attrs(someFunc())` color: red; `; +const Root = styled.div.attrs(props=>({ + "data-status": `${props.status}` +}))` + color: red; +`; + +const B = styled.div.attrs((p) => ({ + className: `x-${p.a}`, +}))` + color: red; +`; + +const C = styled.div.withConfig({ + shouldForwardProp: (prop) => !["a"].includes(prop), +})` + color: red; +`; + +// #383: a call whose argument is an arrow function returning an object, before a tag's template +const D = styled("div")(({ theme }) => ` + color: red; +`); +const E = styled.div(({ theme }) => ` + color: red; +`); + +const F = styled.div.attrs({ + // a comment with a ) paren + a: 1, /* and ( one */ +})` + color: red; +`; + +const G = styled.div.attrs({ + + a: 1, +})` + color: red; +`; + +const H = styled.div.attrs((p) => ({ + a: 1, +}))` + color: red; + ${(p) => p.a && css` + color: red; + `} +`; +const S = { a: css`color: red;`, b: styled.p`color: red;` }; + +const I = styled( + Button +)` + color: red; +`; +const J = styled + .div` + color: red; +`; + +const K = styled(Button, { + shouldForwardProp: (p) => p.length < 3 && p !== "x", +})` + color: red; +`; + +const L = styled.div.attrs((p) => ({ + a: p?.b ?? 1, + c: [1, 2].map((x) => x < 2), +}))` + color: red; +`; + +const M = styled.div.attrs({ + re: /[(`]/g, +})` + color: red; +`; + +const N = styled.div.attrs({ + s: "(", + t: ")))", +})` + color: red; +`; + +const O = styled.div.attrs({ + title: `a ${b} (`, +})` + color: red; +`; +const sentinel = 1; diff --git a/src/tests/suite/colorize-fixtures/injectGlobal.js b/src/tests/suite/colorize-fixtures/injectGlobal.js index 742a254..9dcf4ca 100644 --- a/src/tests/suite/colorize-fixtures/injectGlobal.js +++ b/src/tests/suite/colorize-fixtures/injectGlobal.js @@ -8,3 +8,4 @@ injectGlobal` margin: 0; } `; +const sentinel = 1; diff --git a/src/tests/suite/colorize-fixtures/inside-function.js b/src/tests/suite/colorize-fixtures/inside-function.js index cda42ff..8e9fc76 100644 --- a/src/tests/suite/colorize-fixtures/inside-function.js +++ b/src/tests/suite/colorize-fixtures/inside-function.js @@ -3,3 +3,4 @@ function insideFunction() { height: 15px; `; } +const sentinel = 1; diff --git a/src/tests/suite/colorize-fixtures/inside-method.js b/src/tests/suite/colorize-fixtures/inside-method.js index bed8867..6667e21 100644 --- a/src/tests/suite/colorize-fixtures/inside-method.js +++ b/src/tests/suite/colorize-fixtures/inside-method.js @@ -5,3 +5,4 @@ class InsideMethod extends React.Component { `; } } +const sentinel = 1; diff --git a/src/tests/suite/colorize-fixtures/interpolation-in-function.js b/src/tests/suite/colorize-fixtures/interpolation-in-function.js new file mode 100644 index 0000000..55f25e7 --- /dev/null +++ b/src/tests/suite/colorize-fixtures/interpolation-in-function.js @@ -0,0 +1,10 @@ +const A = styled.div` + background: url(${img}); + background: url(${(p) => p.src}) no-repeat; + background: url("${img}"); + background: url(img-${n}.png); + background: url('${img}'); + font-family: var(--a, "${font}"); + content: attr(data-a "${text}"); +`; +const sentinel = 1; diff --git a/src/tests/suite/colorize-fixtures/jsx-in-head.js b/src/tests/suite/colorize-fixtures/jsx-in-head.js new file mode 100644 index 0000000..3332ba5 --- /dev/null +++ b/src/tests/suite/colorize-fixtures/jsx-in-head.js @@ -0,0 +1,12 @@ +// A Material-UI wrapper: JSX inside the head keeps its JSX scopes +const StyledButton = styled(({ color, ...other }) => ( +