Skip to content

Add support for v3-alpha #424

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 7 commits into from
Oct 1, 2021
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
564 changes: 305 additions & 259 deletions package-lock.json

Large diffs are not rendered by default.

3 changes: 2 additions & 1 deletion packages/tailwindcss-language-server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,15 @@
"access": "public"
},
"devDependencies": {
"@ctrl/tinycolor": "3.1.4",
"@parcel/watcher": "2.0.0-alpha.10",
"@types/debounce": "1.2.0",
"@types/node": "14.14.34",
"@types/vscode": "1.52.0",
"@vercel/ncc": "0.28.4",
"builtin-modules": "3.2.0",
"chokidar": "3.5.1",
"color-name": "1.1.4",
"culori": "0.20.1",
"debounce": "1.2.0",
"detective": "5.2.0",
"dlv": "1.1.3",
Expand Down
147 changes: 104 additions & 43 deletions packages/tailwindcss-language-server/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,12 +69,15 @@ import {
} from './lsp/diagnosticsProvider'
import { doCodeActions } from 'tailwindcss-language-service/src/codeActions/codeActionProvider'
import { getDocumentColors } from 'tailwindcss-language-service/src/documentColorProvider'
import { fromRatio, names as namedColors } from '@ctrl/tinycolor'
import { debounce } from 'debounce'
import { getModuleDependencies } from './util/getModuleDependencies'
import assert from 'assert'
// import postcssLoadConfig from 'postcss-load-config'
import * as parcel from './watcher/index.js'
import { generateRules } from 'tailwindcss-language-service/src/util/jit'
import { getColor } from 'tailwindcss-language-service/src/util/color'
import * as culori from 'culori'
import namedColors from 'color-name'

const CONFIG_FILE_GLOB = '{tailwind,tailwind.config}.{js,cjs}'
const TRIGGER_CHARACTERS = [
Expand All @@ -101,7 +104,7 @@ declare var __non_webpack_require__: typeof require
const connection =
process.argv.length <= 2 ? createConnection(process.stdin, process.stdout) : createConnection()

console.log = connection.console.log.bind(connection.console)
// console.log = connection.console.log.bind(connection.console)
console.error = connection.console.error.bind(connection.console)

process.on('unhandledRejection', (e: any) => {
Expand Down Expand Up @@ -150,6 +153,15 @@ function first<T>(...options: Array<() => T>): T {
}
}

function firstOptional<T>(...options: Array<() => T>): T | undefined {
for (let i = 0; i < options.length; i++) {
let option = options[i]
try {
return option()
} catch (_) {}
}
}

interface ProjectService {
state: State
tryInit: () => Promise<void>
Expand Down Expand Up @@ -528,8 +540,8 @@ async function createProjectService(
}

if (semver.gte(tailwindcssVersion, '1.99.0')) {
applyComplexClasses = __non_webpack_require__(
resolveFrom(tailwindDir, './lib/lib/substituteClassApplyAtRules')
applyComplexClasses = firstOptional(() =>
__non_webpack_require__(resolveFrom(tailwindDir, './lib/lib/substituteClassApplyAtRules'))
)
} else if (semver.gte(tailwindcssVersion, '1.7.0')) {
applyComplexClasses = __non_webpack_require__(
Expand All @@ -551,6 +563,13 @@ async function createProjectService(

try {
let createContext = first(
() => {
let createContextFn = __non_webpack_require__(
resolveFrom(configDir, 'tailwindcss/lib/lib/setupContextUtils')
).createContext
assert.strictEqual(typeof createContextFn, 'function')
return (state) => createContextFn(state.config)
},
() => {
let createContextFn = __non_webpack_require__(
resolveFrom(configDir, 'tailwindcss/lib/jit/lib/setupContextUtils')
Expand Down Expand Up @@ -582,17 +601,30 @@ async function createProjectService(

jitModules = {
generateRules: {
module: __non_webpack_require__(
resolveFrom(configDir, 'tailwindcss/lib/jit/lib/generateRules')
).generateRules,
module: first(
() =>
__non_webpack_require__(resolveFrom(configDir, 'tailwindcss/lib/lib/generateRules'))
.generateRules,
() =>
__non_webpack_require__(
resolveFrom(configDir, 'tailwindcss/lib/jit/lib/generateRules')
).generateRules
),
},
createContext: {
module: createContext,
},
expandApplyAtRules: {
module: __non_webpack_require__(
resolveFrom(configDir, 'tailwindcss/lib/jit/lib/expandApplyAtRules')
).default,
module: first(
() =>
__non_webpack_require__(
resolveFrom(configDir, 'tailwindcss/lib/lib/expandApplyAtRules')
).default,
() =>
__non_webpack_require__(
resolveFrom(configDir, 'tailwindcss/lib/jit/lib/expandApplyAtRules')
).default
),
},
}
} catch (_) {
Expand Down Expand Up @@ -728,6 +760,8 @@ async function createProjectService(
let presetVariants: any[] = []
let originalConfig: any

let isV3 = semver.gte(tailwindcss.version, '2.99.0')

let hook = new Hook(fs.realpathSync(state.configPath), (exports) => {
originalConfig = klona(exports)

Expand All @@ -736,7 +770,7 @@ async function createProjectService(
separator = ':'
}
dset(exports, sepLocation, `__TWSEP__${separator}__TWSEP__`)
exports.purge = []
exports[isV3 ? 'content' : 'purge'] = []

let mode: any
if (Array.isArray(exports.presets)) {
Expand All @@ -753,7 +787,9 @@ async function createProjectService(
}
delete exports.mode

if (state.modules.jit && mode === 'jit') {
let isJit = isV3 || (state.modules.jit && mode === 'jit')

if (isJit) {
state.jit = true
exports.variants = []

Expand Down Expand Up @@ -828,32 +864,42 @@ async function createProjectService(
if (state.jit) {
state.jitContext = state.modules.jit.createContext.module(state)
state.jitContext.tailwindConfig.separator = state.config.separator
if (state.jitContext.getClassList) {
state.classList = state.jitContext.getClassList().map((className) => {
return [className, { color: getColor(state, className) }]
})
}
}

let postcssResult: Result
try {
postcssResult = await postcss
.module([
// ...state.postcssPlugins.before.map((x) => x()),
tailwindcss.module(state.configPath),
// ...state.postcssPlugins.after.map((x) => x()),
])
.process(
[
semver.gte(tailwindcss.version, '0.99.0') ? 'base' : 'preflight',
'components',
'utilities',
]
.map((x) => `/*__tw_intellisense_layer_${x}__*/\n@tailwind ${x};`)
.join('\n'),
{
from: undefined,
}
)
} catch (error) {
throw error
} finally {

if (state.classList) {
hook.unhook()
} else {
try {
postcssResult = await postcss
.module([
// ...state.postcssPlugins.before.map((x) => x()),
tailwindcss.module(state.configPath),
// ...state.postcssPlugins.after.map((x) => x()),
])
.process(
[
semver.gte(tailwindcss.version, '0.99.0') ? 'base' : 'preflight',
'components',
'utilities',
]
.map((x) => `/*__tw_intellisense_layer_${x}__*/\n@tailwind ${x};`)
.join('\n'),
{
from: undefined,
}
)
} catch (error) {
throw error
} finally {
hook.unhook()
}
}

if (state.dependencies) {
Expand All @@ -865,7 +911,9 @@ async function createProjectService(
state.configId = getConfigId(state.configPath, state.dependencies)

state.plugins = await getPlugins(originalConfig)
state.classNames = (await extractClassNames(postcssResult.root)) as ClassNames
if (postcssResult) {
state.classNames = (await extractClassNames(postcssResult.root)) as ClassNames
}
state.variants = getVariants(state)

let screens = dlv(state.config, 'theme.screens', dlv(state.config, 'screens', {}))
Expand Down Expand Up @@ -939,16 +987,25 @@ async function createProjectService(
let currentColor = match[1]

let isNamedColor = colorNames.includes(currentColor)
let color = fromRatio({

let color: culori.RgbColor = {
mode: 'rgb',
r: params.color.red,
g: params.color.green,
b: params.color.blue,
a: params.color.alpha,
})
alpha: params.color.alpha,
}

let hexValue = culori.formatHex8(color)

if (!isNamedColor && (currentColor.length === 4 || currentColor.length === 5)) {
let [, ...chars] =
hexValue.match(/^#([a-f\d])\1([a-f\d])\2([a-f\d])\3(?:([a-f\d])\4)?$/i) ?? []
if (chars.length) {
hexValue = `#${chars.filter(Boolean).join('')}`
}
}

let hexValue = color.toHex8String(
!isNamedColor && (currentColor.length === 4 || currentColor.length === 5)
)
if (hexValue.length === 5) {
hexValue = hexValue.replace(/f$/, '')
} else if (hexValue.length === 9) {
Expand All @@ -959,8 +1016,12 @@ async function createProjectService(

return [
hexValue,
color.toRgbString().replace(/ /g, ''),
color.toHslString().replace(/ /g, ''),
culori.formatRgb(color).replace(/ /g, ''),
culori
.formatHsl(color)
.replace(/ /g, '')
// round numbers
.replace(/\d+\.\d+(%?)/g, (value, suffix) => `${Math.round(parseFloat(value))}${suffix}`),
].map((value) => ({ label: `${prefix}-[${value}]` }))
},
}
Expand Down
2 changes: 1 addition & 1 deletion packages/tailwindcss-language-server/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,5 @@
"tailwindcss-language-service/*": ["../packages/tailwindcss-language-service/*"]
}
},
"include": ["src", "../packages/tailwindcss-language-service"]
"include": ["src", "../packages/tailwindcss-language-service", "../../types"]
}
Loading