Skip to content

WIP: Add custom css class from config files to completion #1425

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

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
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

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"name": "custom-classes-test",
"version": "1.0.0",
"dependencies": {
"tailwindcss": "3.4.17"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
@tailwind base;
@tailwind components;
@tailwind utilities;

.custom-button {
background-color: #1a9dd9;
color: white;
padding: 0.5rem 1rem;
border-radius: 0.25rem;
font-weight: 600;
}

.typography-h3 {
font-family: Montserrat;
font-size: 48px;
font-style: normal;
font-weight: 700;
line-height: 116.7%;
}

.card {
background-color: white;
border: 1px solid #e5e7eb;
border-radius: 0.5rem;
padding: 1.5rem;
box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
module.exports = {
content: ['./**/*.{html,js,ts,jsx,tsx}'],
theme: {
extend: {},
},
plugins: [],
}
88 changes: 62 additions & 26 deletions packages/tailwindcss-language-service/src/completionProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,12 @@ import removeMeta from './util/removeMeta'
import { formatColor, getColor, getColorFromValue } from './util/color'
import { isHtmlContext, isHtmlDoc } from './util/html'
import { isCssContext } from './util/css'
import { findLast, matchClassAttributes, matchClassFunctions } from './util/find'
import {
findClassNamesInRange,
findLast,
matchClassAttributes,
matchClassFunctions,
} from './util/find'
import { stringifyConfigValue, stringifyCss } from './util/stringify'
import { stringifyScreen, Screen } from './util/screens'
import isObject from './util/isObject'
Expand Down Expand Up @@ -282,36 +287,44 @@ export function completionsFromClassList(
}
}

return withDefaults(
{
isIncomplete: false,
items: items.concat(
state.classList.reduce<CompletionItem[]>((items, [className, { color }], index) => {
if (state.blocklist?.includes([...existingVariants, className].join(state.separator))) {
return items
}
// Add custom CSS classes to completions
let allItems = items.concat(
state.classList.reduce<CompletionItem[]>((items, [className, { color }], index) => {
if (state.blocklist?.includes([...existingVariants, className].join(state.separator))) {
return items
}

let kind = color ? CompletionItemKind.Color : CompletionItemKind.Constant
let documentation: string | undefined
let kind = color ? CompletionItemKind.Color : CompletionItemKind.Constant
let documentation: string | undefined

if (color && typeof color !== 'string') {
documentation = formatColor(color)
}
if (color && typeof color !== 'string') {
documentation = formatColor(color)
}

if (prefix.length > 0 && existingVariants.length === 0) {
className = `${prefix}:${className}`
}
if (prefix.length > 0 && existingVariants.length === 0) {
className = `${prefix}:${className}`
}

items.push({
label: className,
kind,
...(documentation ? { documentation } : {}),
sortText: naturalExpand(index, state.classList.length),
})

return items
}, [] as CompletionItem[]),
)

items.push({
label: className,
kind,
...(documentation ? { documentation } : {}),
sortText: naturalExpand(index, state.classList.length),
})
// Add custom CSS classes if they exist
if (state.customCssClasses && state.customCssClasses.length > 0) {
allItems = allItems.concat(state.customCssClasses)
}

return items
}, [] as CompletionItem[]),
),
return withDefaults(
{
isIncomplete: false,
items: allItems,
},
{
data: {
Expand Down Expand Up @@ -2231,6 +2244,13 @@ export async function doComplete(
): Promise<CompletionList | null> {
if (state === null) return { items: [], isIncomplete: false }

const customClassNames = await provideCustomClassNameCompletions(
state,
document,
position,
context,
)

const result =
(await provideClassNameCompletions(state, document, position, context)) ||
(await provideThemeDirectiveCompletions(state, document, position)) ||
Expand Down Expand Up @@ -2264,6 +2284,22 @@ export async function resolveCompletionItem(
return item
}

// Handle custom CSS classes
if (item.data?._type === 'custom-css-class') {
const declarations = item.data.declarations as Record<string, string>
if (declarations) {
const cssRules = Object.entries(declarations)
.map(([prop, value]) => ` ${prop}: ${value};`)
.join('\n')

item.documentation = {
kind: 'markdown' as typeof MarkupKind.Markdown,
value: `\`\`\`css\n.${item.label} {\n${cssRules}\n}\n\`\`\``,
}
}
return item
}

if (item.data?._type === 'screen') {
let screens = dlv(state.config, ['theme', 'screens'], dlv(state.config, ['screens'], {}))
if (!isObject(screens)) screens = {}
Expand Down
21 changes: 21 additions & 0 deletions packages/tailwindcss-language-service/src/hoverProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,27 @@ async function provideClassNameHover(
let className = await findClassNameAtPosition(state, document, position)
if (className === null) return null

// Check if this is a custom CSS class
if (state.customCssClasses && state.customCssClasses.length > 0) {
const customClass = state.customCssClasses.find((cls) => cls.label === className.className)
if (customClass) {
const declarations = customClass.data?.declarations as Record<string, string>
if (declarations) {
const cssRules = Object.entries(declarations)
.map(([prop, value]) => ` ${prop}: ${value};`)
.join('\n')

return {
contents: {
language: 'css',
value: `.${className.className} {\n${cssRules}\n}`,
},
range: className.range,
}
}
}
}

if (state.v4) {
let root = state.designSystem.compile([className.className])[0]

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import { expect, test } from 'vitest'
import { extractCustomClassesFromCss } from './css-class-scanner'

test('extract custom CSS classes from CSS content', async ({ expect }) => {
const css = `
.typography-h3 {
font-family: Montserrat;
font-size: 48px;
font-style: normal;
font-weight: 700;
line-height: 116.7%;
}

.custom-button {
background-color: #1a9dd9;
color: white;
padding: 0.5rem 1rem;
border-radius: 0.25rem;
}

/* This should be ignored as it's a Tailwind utility */
.text-blue-500 {
color: #3b82f6;
}

/* This should be ignored as it has pseudo-selectors */
.hover\:bg-blue-500:hover {
background-color: #3b82f6;
}
`

const classes = extractCustomClassesFromCss(css, 'test.css')

expect(classes).toHaveLength(2)
expect(classes[0]).toEqual({
className: 'typography-h3',
source: 'test.css',
declarations: {
'font-family': 'Montserrat',
'font-size': '48px',
'font-style': 'normal',
'font-weight': '700',
'line-height': '116.7%',
},
})
expect(classes[1]).toEqual({
className: 'custom-button',
source: 'test.css',
declarations: {
'background-color': '#1a9dd9',
color: 'white',
padding: '0.5rem 1rem',
'border-radius': '0.25rem',
},
})
})

test('ignore Tailwind utility classes', async ({ expect }) => {
const css = `
.text-blue-500 {
color: #3b82f6;
}

.bg-red-500 {
background-color: #ef4444;
}

.p-4 {
padding: 1rem;
}
`

const classes = extractCustomClassesFromCss(css, 'test.css')

expect(classes).toHaveLength(0)
})

test('ignore complex selectors', async ({ expect }) => {
const css = `
.button:hover {
background-color: #1a9dd9;
}

.input[type="text"] {
border: 1px solid #ccc;
}

.nav > li {
display: inline-block;
}
`

const classes = extractCustomClassesFromCss(css, 'test.css')

expect(classes).toHaveLength(0)
})
Loading