Home

tailwind-ctp-intellisense @614154c0fd1e69a194a5c516946ecf9c592b0550 - refs - log -
-
https://git.jolheiser.com/tailwind-ctp-intellisense.git
Tailwind intellisense + Catppuccin
tailwind-ctp-intellisense / src / lsp / providers / 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
import {
  CodeAction,
  CodeActionParams,
  CodeActionKind,
  TextEdit,
  Range,
} from 'vscode-languageserver'
import { State } from '../../util/state'
import { InvalidApplyDiagnostic } from '../diagnostics/types'
import { getClassNameParts } from '../../util/getClassNameAtPosition'
import { getLanguageBoundaries } from '../../util/getLanguageBoundaries'
import { isCssDoc } from '../../util/css'
import { isWithinRange } from '../../util/isWithinRange'
const dlv = require('dlv')
import type { Root, NodeSource } 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'

export async function provideInvalidApplyCodeActions(
  state: State,
  params: CodeActionParams,
  diagnostic: InvalidApplyDiagnostic
): Promise<CodeAction[]> {
  let document = state.editor.documents.get(params.textDocument.uri)
  let documentText = document.getText()
  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.css.find((range) =>
      isWithinRange(diagnostic.range.start, range)
    )
    if (!cssRange) return []
    cssText = document.getText(cssRange)
  }

  try {
    await postcss([
      postcss.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 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(documentText)

              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
                      )
                    }),
              })

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

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

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

function postcssSourceToRange(source: NodeSource): 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 = dlv(
    state.classNames.classNames,
    classNameParts[classNameParts.length - 1]
  )
  if (!baseClassName) {
    return null
  }
  const info = dlv(state.classNames.classNames, classNameParts)
  let context = info.__context || []
  let pseudo = info.__pseudo || []
  const globalContexts = state.classNames.context
  let screens = dlv(
    state.config,
    'theme.screens',
    dlv(state.config, 'screens', {})
  )
  if (!isObject(screens)) screens = {}
  screens = Object.keys(screens)
  const path = []

  for (let i = 0; i < classNameParts.length - 1; i++) {
    let part = classNameParts[i]
    let common = globalContexts[part]
    if (!common) return null
    if (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), {})
  }
  let rule = {
    // TODO: use proper selector parser
    [selector + pseudo.join('')]: {
      [`@apply ${classNameParts[classNameParts.length - 1]}${
        important ? ' !important' : ''
      }`]: '',
    },
  }
  if (path.length) {
    dset(obj, path, rule)
  } else {
    obj = rule
  }

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