Skip to content

Compute correct document selectors when a project is initialized #1335

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

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
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
148 changes: 86 additions & 62 deletions packages/tailwindcss-language-server/src/project-locator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -206,62 +206,7 @@ export class ProjectLocator {
// Look for the package root for the config
config.packageRoot = await getPackageRoot(path.dirname(config.path), this.base)

let selectors: DocumentSelector[] = []

// selectors:
// - CSS files
for (let entry of config.entries) {
if (entry.type !== 'css') continue
selectors.push({
pattern: entry.path,
priority: DocumentSelectorPriority.CSS_FILE,
})
}

// - Config File
selectors.push({
pattern: config.path,
priority: DocumentSelectorPriority.CONFIG_FILE,
})

// - Content patterns from config
for await (let selector of contentSelectorsFromConfig(
config,
tailwind.features,
this.resolver,
)) {
selectors.push(selector)
}

// - Directories containing the CSS files
for (let entry of config.entries) {
if (entry.type !== 'css') continue
selectors.push({
pattern: normalizePath(path.join(path.dirname(entry.path), '**')),
priority: DocumentSelectorPriority.CSS_DIRECTORY,
})
}

// - Directory containing the config
selectors.push({
pattern: normalizePath(path.join(path.dirname(config.path), '**')),
priority: DocumentSelectorPriority.CONFIG_DIRECTORY,
})

// - Root of package that contains the config
selectors.push({
pattern: normalizePath(path.join(config.packageRoot, '**')),
priority: DocumentSelectorPriority.PACKAGE_DIRECTORY,
})

// Reorder selectors from most specific to least specific
selectors.sort((a, z) => a.priority - z.priority)

// Eliminate duplicate selector patterns
selectors = selectors.filter(
({ pattern }, index, documentSelectors) =>
documentSelectors.findIndex(({ pattern: p }) => p === pattern) === index,
)
let selectors = await calculateDocumentSelectors(config, tailwind.features, this.resolver)

return {
config,
Expand Down Expand Up @@ -545,13 +490,14 @@ function contentSelectorsFromConfig(
entry: ConfigEntry,
features: Feature[],
resolver: Resolver,
actualConfig?: any,
): AsyncIterable<DocumentSelector> {
if (entry.type === 'css') {
return contentSelectorsFromCssConfig(entry, resolver)
}

if (entry.type === 'js') {
return contentSelectorsFromJsConfig(entry, features)
return contentSelectorsFromJsConfig(entry, features, actualConfig)
}
}

Expand Down Expand Up @@ -586,11 +532,18 @@ async function* contentSelectorsFromJsConfig(
if (typeof item !== 'string') continue

let filepath = item.startsWith('!')
? `!${path.resolve(contentBase, item.slice(1))}`
? path.resolve(contentBase, item.slice(1))
: path.resolve(contentBase, item)

filepath = normalizePath(filepath)
filepath = normalizeDriveLetter(filepath)

if (item.startsWith('!')) {
filepath = `!${filepath}`
}

yield {
pattern: normalizePath(filepath),
pattern: filepath,
priority: DocumentSelectorPriority.CONTENT_FILE,
}
}
Expand All @@ -603,8 +556,11 @@ async function* contentSelectorsFromCssConfig(
let auto = false
for (let item of entry.content) {
if (item.kind === 'file') {
let filepath = item.file
filepath = normalizePath(filepath)
filepath = normalizeDriveLetter(filepath)
yield {
pattern: normalizePath(item.file),
pattern: filepath,
priority: DocumentSelectorPriority.CONTENT_FILE,
}
} else if (item.kind === 'auto' && !auto) {
Expand Down Expand Up @@ -657,12 +613,16 @@ async function* detectContentFiles(
if (!result) return

for (let file of result.files) {
yield normalizePath(file)
file = normalizePath(file)
file = normalizeDriveLetter(file)
yield file
}

for (let { base, pattern } of result.globs) {
// Do not normalize the glob itself as it may contain escape sequences
yield normalizePath(base) + '/' + pattern
base = normalizePath(base)
base = normalizeDriveLetter(base)
yield `${base}/${pattern}`
}
} catch {
//
Expand Down Expand Up @@ -793,3 +753,67 @@ function requiresPreprocessor(filepath: string) {

return ext === '.scss' || ext === '.sass' || ext === '.less' || ext === '.styl' || ext === '.pcss'
}

export async function calculateDocumentSelectors(
config: ConfigEntry,
features: Feature[],
resolver: Resolver,
actualConfig?: any,
) {
let selectors: DocumentSelector[] = []

// selectors:
// - CSS files
for (let entry of config.entries) {
if (entry.type !== 'css') continue

selectors.push({
pattern: normalizeDriveLetter(normalizePath(entry.path)),
priority: DocumentSelectorPriority.CSS_FILE,
})
}

// - Config File
selectors.push({
pattern: normalizeDriveLetter(normalizePath(config.path)),
priority: DocumentSelectorPriority.CONFIG_FILE,
})

// - Content patterns from config
for await (let selector of contentSelectorsFromConfig(config, features, resolver, actualConfig)) {
selectors.push(selector)
}

// - Directories containing the CSS files
for (let entry of config.entries) {
if (entry.type !== 'css') continue

selectors.push({
pattern: normalizeDriveLetter(normalizePath(path.join(path.dirname(entry.path), '**'))),
priority: DocumentSelectorPriority.CSS_DIRECTORY,
})
}

// - Directory containing the config
selectors.push({
pattern: normalizeDriveLetter(normalizePath(path.join(path.dirname(config.path), '**'))),
priority: DocumentSelectorPriority.CONFIG_DIRECTORY,
})

// - Root of package that contains the config
selectors.push({
pattern: normalizeDriveLetter(normalizePath(path.join(config.packageRoot, '**'))),
priority: DocumentSelectorPriority.PACKAGE_DIRECTORY,
})

// Reorder selectors from most specific to least specific
selectors.sort((a, z) => a.priority - z.priority)

// Eliminate duplicate selector patterns
selectors = selectors.filter(
({ pattern }, index, documentSelectors) =>
documentSelectors.findIndex(({ pattern: p }) => p === pattern) === index,
)

return selectors
}
38 changes: 15 additions & 23 deletions packages/tailwindcss-language-server/src/projects.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ import {
normalizeDriveLetter,
} from './utils'
import type { DocumentService } from './documents'
import type { ProjectConfig } from './project-locator'
import { calculateDocumentSelectors, type ProjectConfig } from './project-locator'
import { supportedFeatures } from '@tailwindcss/language-service/src/features'
import { loadDesignSystem } from './util/v4'
import { readCssFile } from './util/css'
Expand Down Expand Up @@ -286,7 +286,9 @@ export async function createProjectService(
)
}

function onFileEvents(changes: Array<{ file: string; type: FileChangeType }>): void {
async function onFileEvents(
changes: Array<{ file: string; type: FileChangeType }>,
): Promise<void> {
let needsInit = false
let needsRebuild = false

Expand All @@ -307,16 +309,11 @@ export async function createProjectService(
projectConfig.configPath &&
(isConfigFile || isDependency)
) {
documentSelector = [
...documentSelector.filter(
({ priority }) => priority !== DocumentSelectorPriority.CONTENT_FILE,
),
...getContentDocumentSelectorFromConfigFile(
projectConfig.configPath,
initialTailwindVersion,
projectConfig.folder,
),
]
documentSelector = await calculateDocumentSelectors(
projectConfig.config,
state.features,
resolver,
)

checkOpenDocuments()
}
Expand Down Expand Up @@ -963,17 +960,12 @@ export async function createProjectService(

/////////////////////
if (!projectConfig.isUserConfigured) {
documentSelector = [
...documentSelector.filter(
({ priority }) => priority !== DocumentSelectorPriority.CONTENT_FILE,
),
...getContentDocumentSelectorFromConfigFile(
state.configPath,
tailwindcss.version,
projectConfig.folder,
originalConfig,
),
]
documentSelector = await calculateDocumentSelectors(
projectConfig.config,
state.features,
resolver,
originalConfig,
)
}
//////////////////////

Expand Down
Original file line number Diff line number Diff line change
@@ -1,38 +1,85 @@
import { test } from 'vitest'
import { withFixture } from '../common'
import { expect } from 'vitest'
import { css, defineTest, html, js, json, symlinkTo } from '../../src/testing'
import dedent from 'dedent'
import { createClient } from '../utils/client'

withFixture('multi-config-content', (c) => {
test.concurrent('multi-config with content config - 1', async ({ expect }) => {
let textDocument = await c.openDocument({ text: '<div class="bg-foo">', dir: 'one' })
let res = await c.sendRequest('textDocument/hover', {
textDocument,
position: { line: 0, character: 13 },
defineTest({
name: 'multi-config with content config',
fs: {
'tailwind.config.one.js': js`
module.exports = {
content: ['./one/**/*'],
theme: {
extend: {
colors: {
foo: 'red',
},
},
},
}
`,
'tailwind.config.two.js': js`
module.exports = {
content: ['./two/**/*'],
theme: {
extend: {
colors: {
foo: 'blue',
},
},
},
}
`,
},
prepare: async ({ root }) => ({ client: await createClient({ root }) }),
handle: async ({ client }) => {
let one = await client.open({
lang: 'html',
name: 'one/index.html',
text: '<div class="bg-foo">',
})

expect(res).toEqual({
let two = await client.open({
lang: 'html',
name: 'two/index.html',
text: '<div class="bg-foo">',
})

// <div class="bg-foo">
// ^
let hoverOne = await one.hover({ line: 0, character: 13 })
let hoverTwo = await two.hover({ line: 0, character: 13 })

expect(hoverOne).toEqual({
contents: {
language: 'css',
value:
'.bg-foo {\n --tw-bg-opacity: 1;\n background-color: rgb(255 0 0 / var(--tw-bg-opacity, 1)) /* #ff0000 */;\n}',
value: dedent`
.bg-foo {
--tw-bg-opacity: 1;
background-color: rgb(255 0 0 / var(--tw-bg-opacity, 1)) /* #ff0000 */;
}
`,
},
range: {
start: { line: 0, character: 12 },
end: { line: 0, character: 18 },
},
range: { start: { line: 0, character: 12 }, end: { line: 0, character: 18 } },
})
})

test.concurrent('multi-config with content config - 2', async ({ expect }) => {
let textDocument = await c.openDocument({ text: '<div class="bg-foo">', dir: 'two' })
let res = await c.sendRequest('textDocument/hover', {
textDocument,
position: { line: 0, character: 13 },
})

expect(res).toEqual({
expect(hoverTwo).toEqual({
contents: {
language: 'css',
value:
'.bg-foo {\n --tw-bg-opacity: 1;\n background-color: rgb(0 0 255 / var(--tw-bg-opacity, 1)) /* #0000ff */;\n}',
value: dedent`
.bg-foo {
--tw-bg-opacity: 1;
background-color: rgb(0 0 255 / var(--tw-bg-opacity, 1)) /* #0000ff */;
}
`,
},
range: {
start: { line: 0, character: 12 },
end: { line: 0, character: 18 },
},
range: { start: { line: 0, character: 12 }, end: { line: 0, character: 18 } },
})
})
},
})
2 changes: 2 additions & 0 deletions packages/vscode-tailwindcss/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
- Ignore Python virtual env directories by default ([#1336](https://github.com/tailwindlabs/tailwindcss-intellisense/pull/1336))
- Ignore Yarn v2+ metadata & cache directories by default ([#1336](https://github.com/tailwindlabs/tailwindcss-intellisense/pull/1336))
- Ignore some build caches by default ([#1336](https://github.com/tailwindlabs/tailwindcss-intellisense/pull/1336))
- Compute correct document selectors when a project is initialized ([#1335](https://github.com/tailwindlabs/tailwindcss-intellisense/pull/1335))
- Fix matching of some content file paths on Windows ([#1335](https://github.com/tailwindlabs/tailwindcss-intellisense/pull/1335))

# 0.14.16

Expand Down