Skip to content

Don't create v4 projects for CSS files that don't look like v4 configs #1164

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Feb 5, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 26 additions & 21 deletions packages/tailwindcss-language-server/src/project-locator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import { extractSourceDirectives, resolveCssImports } from './css'
import { normalizeDriveLetter, normalizePath, pathToFileURL } from './utils'
import postcss from 'postcss'
import * as oxide from './oxide'
import { guessTailwindVersion, TailwindVersion } from './version-guesser'

export interface ProjectConfig {
/** The folder that contains the project */
Expand Down Expand Up @@ -130,6 +131,8 @@ export class ProjectLocator {
private async createProject(config: ConfigEntry): Promise<ProjectConfig | null> {
let tailwind = await this.detectTailwindVersion(config)

let possibleVersions = config.entries.flatMap((entry) => entry.versions)

console.log(
JSON.stringify({
tailwind,
Expand Down Expand Up @@ -160,6 +163,15 @@ export class ProjectLocator {
return null
}

// This config doesn't include any v4 features (even ones that were also in v3)
if (!possibleVersions.includes('4')) {
console.warn(
`The config ${config.path} looks like it might be for a different Tailwind CSS version. Skipping.`,
)

return null
}

// v4 does not support .sass, .scss, .less, and .styl files as configs
if (requiresPreprocessor(config.path)) {
console.warn(
Expand Down Expand Up @@ -324,15 +336,19 @@ export class ProjectLocator {
// Read the content of all the CSS files
await Promise.all(css.map((entry) => entry.read()))

// Determine what tailwind versions each file might be using
await Promise.all(css.map((entry) => entry.resolvePossibleVersions()))

// Keep track of files that might import or involve Tailwind in some way
let imports: FileEntry[] = []

for (let file of css) {
// If the CSS file couldn't be read for some reason, skip it
if (!file.content) continue

// Look for `@import`, `@tailwind`, `@theme`, `@config`, etc…
if (!file.isMaybeTailwindRelated()) continue
// This file doesn't appear to use Tailwind CSS nor any imports
// so we can skip it
if (file.versions.length === 0) continue

// Find `@config` directives in CSS files and resolve them to the actual
// config file that they point to. This is only relevant for v3 which
Expand Down Expand Up @@ -642,6 +658,7 @@ class FileEntry {
deps: FileEntry[] = []
realpath: string | null
sources: string[] = []
versions: TailwindVersion[] = []

constructor(
public type: 'js' | 'css',
Expand Down Expand Up @@ -709,6 +726,13 @@ class FileEntry {
}
}

/**
* Determine which Tailwind versions this file might be using
*/
async resolvePossibleVersions() {
this.versions = this.content ? guessTailwindVersion(this.content) : []
}

/**
* Look for `@config` directives in a CSS file and return the path to the config
* file that it points to. This path is (possibly) relative to the CSS file so
Expand All @@ -727,25 +751,6 @@ class FileEntry {

return normalizePath(path.resolve(path.dirname(this.path), match.groups.config.slice(1, -1)))
}

/**
* Look for tailwind-specific directives in a CSS file. This means that it
* participates in the CSS "graph" for the project and we need to traverse
* the graph to find all the CSS files that are considered entrypoints.
*/
isMaybeTailwindRelated(): boolean {
if (!this.content) return false

let HAS_IMPORT = /@import\s*['"]/
let HAS_TAILWIND = /@tailwind\s*[^;]+;/
let HAS_DIRECTIVE = /@(theme|plugin|config|utility|variant|apply)\s*[^;{]+[;{]/

return (
HAS_IMPORT.test(this.content) ||
HAS_TAILWIND.test(this.content) ||
HAS_DIRECTIVE.test(this.content)
)
}
}

function requiresPreprocessor(filepath: string) {
Expand Down
53 changes: 53 additions & 0 deletions packages/tailwindcss-language-server/src/version-guesser.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
export type TailwindVersion = '3' | '4'

/**
* Determine the likely Tailwind version used by the given file
*
* This returns an array of possible versions, as a file could contain
* features that make determining the version ambiguous.
*
* The order *does* matter, as the first item is the most likely version.
*/
export function guessTailwindVersion(content: string): TailwindVersion[] {
// It's likely this is a v4 file if it has a v4 import:
// - `@import "tailwindcss"`
// - `@import "tailwindcss/theme"
// - etc…
let HAS_V4_IMPORT = /@import\s*['"]tailwindcss(?:\/[^'"]+)?['"]/
if (HAS_V4_IMPORT.test(content)) return ['4']

// It's likely this is a v4 file if it has a v4-specific feature:
// - @theme
// - @plugin
// - @utility
// - @variant
// - @custom-variant
let HAS_V4_DIRECTIVE = /@(theme|plugin|utility|custom-variant|variant|reference)\s*[^;{]+[;{]/
if (HAS_V4_DIRECTIVE.test(content)) return ['4']

// It's likely this is a v4 file if it's using v4's custom functions:
// - --alpha(…)
// - --spacing(…)
// - --theme(…)
let HAS_V4_FN = /--(alpha|spacing|theme)\(/
if (HAS_V4_FN.test(content)) return ['4']

// If the file contains older `@tailwind` directives, it's likely a v3 file
let HAS_LEGACY_TAILWIND = /@tailwind\s*(base|preflight|components|variants|screens)+;/
if (HAS_LEGACY_TAILWIND.test(content)) return ['3']

// If the file contains other `@tailwind` directives it might be either
let HAS_TAILWIND = /@tailwind\s*[^;]+;/
if (HAS_TAILWIND.test(content)) return ['4', '3']

// If the file contains other `@apply` or `@config` it might be either
let HAS_COMMON_DIRECTIVE = /@(config|apply)\s*[^;{]+[;{]/
if (HAS_COMMON_DIRECTIVE.test(content)) return ['4', '3']

// If it's got imports at all it could be either
let HAS_IMPORT = /@import\s*['"]/
if (HAS_IMPORT.test(content)) return ['4', '3']

// There's chance this file isn't tailwind-related
return []
}
119 changes: 119 additions & 0 deletions packages/tailwindcss-language-server/tests/env/v4.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -225,3 +225,122 @@ defineTest({
expect(completion.items.length).toBe(12288)
},
})

defineTest({
name: 'v4, uses npm, does not detect v3 config files as possible roots',
fs: {
'package.json': json`
{
"dependencies": {
"tailwindcss": "4.0.1"
}
}
`,
// This file MUST be before the v4 CSS file when sorting alphabetically
'_globals.css': css`
@tailwind base;
@tailwind utilities;
@tailwind components;
`,
'app.css': css`
@import 'tailwindcss';

@theme {
--color-primary: #c0ffee;
}
`,
},
prepare: async ({ root }) => ({ c: await init(root) }),
handle: async ({ c }) => {
let textDocument = await c.openDocument({
lang: 'html',
text: '<div class="bg-primary">',
})

expect(c.project).toMatchObject({
tailwind: {
version: '4.0.1',
isDefaultVersion: false,
},
})

let hover = await c.sendRequest(HoverRequest.type, {
textDocument,

// <div class="bg-primary">
// ^
position: { line: 0, character: 13 },
})

expect(hover).toEqual({
contents: {
language: 'css',
value: dedent`
.bg-primary {
background-color: var(--color-primary) /* #c0ffee */;
}
`,
},
range: {
start: { line: 0, character: 12 },
end: { line: 0, character: 22 },
},
})
},
})

defineTest({
name: 'v4, uses fallback, does not detect v3 config files as possible roots',
fs: {
// This file MUST be before the v4 CSS file when sorting alphabetically
'_globals.css': css`
@tailwind base;
@tailwind utilities;
@tailwind components;
`,
'app.css': css`
@import 'tailwindcss';

@theme {
--color-primary: #c0ffee;
}
`,
},
prepare: async ({ root }) => ({ c: await init(root) }),
handle: async ({ c }) => {
let textDocument = await c.openDocument({
lang: 'html',
text: '<div class="bg-primary">',
})

expect(c.project).toMatchObject({
tailwind: {
version: '4.0.0',
isDefaultVersion: true,
},
})

let hover = await c.sendRequest(HoverRequest.type, {
textDocument,

// <div class="bg-primary">
// ^
position: { line: 0, character: 13 },
})

expect(hover).toEqual({
contents: {
language: 'css',
value: dedent`
.bg-primary {
background-color: var(--color-primary) /* #c0ffee */;
}
`,
},
range: {
start: { line: 0, character: 12 },
end: { line: 0, character: 22 },
},
})
},
})
1 change: 1 addition & 0 deletions packages/vscode-tailwindcss/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
- Allow v4.0 projects not installed with npm to use IntelliSense ([#1157](https://github.com/tailwindlabs/tailwindcss-intellisense/pull/1157))
- Ignore preprocessor files when looking for v4 configs ([#1159](https://github.com/tailwindlabs/tailwindcss-intellisense/pull/1159))
- Allow language service to be used in native ESM environments ([#1122](https://github.com/tailwindlabs/tailwindcss-intellisense/pull/1122))
- Don't create v4 projects for CSS files that don't look like v4 configs [#1164](https://github.com/tailwindlabs/tailwindcss-intellisense/pull/1164)

## 0.14.2

Expand Down