Home

tailwind-ctp-intellisense @19a550d0de1f3bfbc2a49297e9f7e0c53cfc1ca6 - refs - log -
-
https://git.jolheiser.com/tailwind-ctp-intellisense.git
Tailwind intellisense + Catppuccin
tailwind-ctp-intellisense / packages / tailwindcss-language-service / src / codeActions / provideInvalidApplyCodeActions.ts
- raw
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
import type { CodeAction, CodeActionParams, TextEdit, Range } from 'vscode-languageserver'
import { State } from '../util/state'
import { InvalidApplyDiagnostic } from '../diagnostics/types'
import { isCssDoc } from '../util/css'
import { getLanguageBoundaries } from '../util/getLanguageBoundaries'
import { getClassNameMeta } from '../util/getClassNameMeta'
import { getClassNameParts } from '../util/getClassNameAtPosition'
import { validateApply } from '../util/validateApply'
import { isWithinRange } from '../util/isWithinRange'
import dlv from 'dlv'
import type { Root, Source } from 'postcss'
import { absoluteRange } from '../util/absoluteRange'
import { removeRangesFromString } from '../util/removeRangesFromString'
import detectIndent from 'detect-indent'
import isObject from '../util/isObject'
import { cssObjToAst } from '../util/cssObjToAst'
import { dset } from 'dset'
import selectorParser from 'postcss-selector-parser'
import { flatten } from '../util/array'
import { getTextWithoutComments } from '../util/doc'

export async function provideInvalidApplyCodeActions(
  state: State,
  params: CodeActionParams,
  diagnostic: InvalidApplyDiagnostic
): Promise<CodeAction[]> {
  let document = state.editor.documents.get(params.textDocument.uri)
  if (!document) return []
  let documentText = getTextWithoutComments(document, 'css')
  let cssRange: Range
  let cssText = documentText
  const { postcss } = state.modules
  let changes: TextEdit[] = []

  let totalClassNamesInClassList = diagnostic.className.classList.classList.split(/\s+/).length

  let className = diagnostic.className.className
  let classNameParts = getClassNameParts(state, className)
  let classNameInfo = dlv(state.classNames.classNames, classNameParts)

  if (Array.isArray(classNameInfo)) {
    return []
  }

  if (!isCssDoc(state, document)) {
    let languageBoundaries = getLanguageBoundaries(state, document)
    if (!languageBoundaries) return []
    cssRange = languageBoundaries
      .filter((b) => b.type === 'css')
      .find(({ range }) => isWithinRange(diagnostic.range.start, range))?.range
    if (!cssRange) return []
    cssText = getTextWithoutComments(document, 'css', cssRange)
  }

  try {
    await postcss
      .module([
        // TODO: use plain function?
        // @ts-ignore
        postcss.module.plugin('', (_options = {}) => {
          return (root: Root) => {
            root.walkRules((rule) => {
              if (changes.length) return false

              rule.walkAtRules('apply', (atRule) => {
                let atRuleRange = postcssSourceToRange(atRule.source)
                if (cssRange) {
                  atRuleRange = absoluteRange(atRuleRange, cssRange)
                }

                if (!isWithinRange(diagnostic.range.start, atRuleRange)) return undefined // true

                let ast = classNameToAst(
                  state,
                  classNameParts,
                  rule.selector,
                  diagnostic.className.classList.important
                )

                if (!ast) return false

                rule.after(ast.nodes)
                let insertedRule = rule.next()
                if (!insertedRule) return false

                if (totalClassNamesInClassList === 1) {
                  atRule.remove()
                } else {
                  changes.push({
                    range: diagnostic.className.classList.range,
                    newText: removeRangesFromString(
                      diagnostic.className.classList.classList,
                      diagnostic.className.relativeRange
                    ),
                  })
                }

                let ruleRange = postcssSourceToRange(rule.source)
                if (cssRange) {
                  ruleRange = absoluteRange(ruleRange, cssRange)
                }

                let outputIndent: string
                let documentIndent = detectIndent(cssText)

                changes.push({
                  range: ruleRange,
                  newText:
                    rule.toString() +
                    (insertedRule.raws.before || '\n\n') +
                    insertedRule
                      .toString()
                      .replace(/\n\s*\n/g, '\n')
                      .replace(/(@apply [^;\n]+)$/gm, '$1;')
                      .replace(/([^\s^]){$/gm, '$1 {')
                      .replace(/^\s+/gm, (m: string) => {
                        if (typeof outputIndent === 'undefined') outputIndent = m
                        return m.replace(new RegExp(outputIndent, 'g'), documentIndent.indent)
                      })
                      .replace(/^(\s+)(.*?[^{}]\n)([^\s}])/gm, '$1$2$1$3'),
                })

                return false
              })

              return undefined // true
            })
          }
        }),
      ])
      .process(cssText, { from: undefined })
  } catch (_) {
    return []
  }

  if (!changes.length) {
    return []
  }

  return [
    {
      title: 'Extract to new rule',
      kind: 'quickfix', // CodeActionKind.QuickFix,
      diagnostics: [diagnostic],
      edit: {
        changes: {
          [params.textDocument.uri]: changes,
        },
      },
    },
  ]
}

function postcssSourceToRange(source: Source): Range {
  return {
    start: {
      line: source.start.line - 1,
      character: source.start.column - 1,
    },
    end: {
      line: source.end.line - 1,
      character: source.end.column,
    },
  }
}

function classNameToAst(
  state: State,
  classNameParts: string[],
  selector: string,
  important: boolean = false
) {
  const baseClassName = classNameParts[classNameParts.length - 1]
  const validatedBaseClassName = validateApply(state, [baseClassName])
  if (validatedBaseClassName === null || validatedBaseClassName.isApplyable === false) {
    return null
  }
  const meta = getClassNameMeta(state, classNameParts)
  if (Array.isArray(meta)) return null
  let context = meta.context
  let pseudo = meta.pseudo
  const globalContexts = state.classNames.context
  const path = []

  for (let i = 0; i < classNameParts.length - 1; i++) {
    let part = classNameParts[i]
    let common = globalContexts[part]
    if (!common) return null
    if (state.screens.includes(part)) {
      path.push(`@screen ${part}`)
      context = context.filter((con) => !common.includes(con))
    }
  }

  path.push(...context)

  let obj = {}
  for (let i = 1; i <= path.length; i++) {
    dset(obj, path.slice(0, i), {})
  }

  selector = appendPseudosToSelector(selector, pseudo)
  if (selector === null) return null

  let rule = {
    [selector]: {
      [`@apply ${baseClassName}${important ? ' !important' : ''}`]: '',
    },
  }
  if (path.length) {
    dset(obj, path, rule)
  } else {
    obj = rule
  }

  return cssObjToAst(obj, state.modules.postcss)
}

function appendPseudosToSelector(selector: string, pseudos: string[]): string | null {
  if (pseudos.length === 0) return selector

  let canTransform = true

  let transformedSelector = selectorParser((selectors) => {
    flatten(selectors.split((_) => true)).forEach((sel) => {
      // @ts-ignore
      for (let i = sel.nodes.length - 1; i >= 0; i--) {
        // @ts-ignore
        if (sel.nodes[i].type !== 'pseudo') {
          break
          // @ts-ignore
        } else if (pseudos.includes(sel.nodes[i].value)) {
          canTransform = false
          break
        }
      }
      if (canTransform) {
        pseudos.forEach((p) => {
          // @ts-ignore
          sel.append(selectorParser.pseudo({ value: p }))
        })
      }
    })
  }).processSync(selector)

  if (!canTransform) return null

  return transformedSelector
}