Home

tailwind-ctp-intellisense @983cfe5ac77e845fd93b07b7823b9553f5de40eb - refs - log -
-
https://git.jolheiser.com/tailwind-ctp-intellisense.git
Tailwind intellisense + Catppuccin
tailwind-ctp-intellisense / src / lsp / providers / codeActionProvider / index.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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
import {
  CodeAction,
  CodeActionParams,
  CodeActionKind,
  Range,
  TextEdit,
} from 'vscode-languageserver'
import { State } from '../../util/state'
import { findLast } from '../../util/find'
import { isWithinRange } from '../../util/isWithinRange'
import { getClassNameParts } from '../../util/getClassNameAtPosition'
const dlv = require('dlv')
import dset from 'dset'
import { removeRangesFromString } from '../../util/removeRangesFromString'
import detectIndent from 'detect-indent'
import { cssObjToAst } from '../../util/cssObjToAst'
import isObject from '../../../util/isObject'
import { getDiagnostics } from '../diagnostics/diagnosticsProvider'
import { rangesEqual } from '../../util/rangesEqual'
import {
  DiagnosticKind,
  isInvalidApplyDiagnostic,
  AugmentedDiagnostic,
  InvalidApplyDiagnostic,
  isUtilityConflictsDiagnostic,
  UtilityConflictsDiagnostic,
  isInvalidConfigPathDiagnostic,
  isInvalidTailwindDirectiveDiagnostic,
  isInvalidScreenDiagnostic,
  isInvalidVariantDiagnostic,
} from '../diagnostics/types'
import { flatten, dedupeBy } from '../../../util/array'
import { joinWithAnd } from '../../util/joinWithAnd'

async function getDiagnosticsFromCodeActionParams(
  state: State,
  params: CodeActionParams,
  only?: DiagnosticKind[]
): Promise<AugmentedDiagnostic[]> {
  let document = state.editor.documents.get(params.textDocument.uri)
  let diagnostics = await getDiagnostics(state, document, only)

  return params.context.diagnostics
    .map((diagnostic) => {
      return diagnostics.find((d) => {
        return (
          d.code === diagnostic.code &&
          d.message === diagnostic.message &&
          rangesEqual(d.range, diagnostic.range)
        )
      })
    })
    .filter(Boolean)
}

export async function provideCodeActions(
  state: State,
  params: CodeActionParams
): Promise<CodeAction[]> {
  let codes = params.context.diagnostics
    .map((diagnostic) => diagnostic.code)
    .filter(Boolean) as DiagnosticKind[]

  let diagnostics = await getDiagnosticsFromCodeActionParams(
    state,
    params,
    codes
  )

  let actions = diagnostics.map((diagnostic) => {
    if (isInvalidApplyDiagnostic(diagnostic)) {
      return provideInvalidApplyCodeActions(state, params, diagnostic)
    }

    if (isUtilityConflictsDiagnostic(diagnostic)) {
      return provideUtilityConflictsCodeActions(state, params, diagnostic)
    }

    if (
      isInvalidConfigPathDiagnostic(diagnostic) ||
      isInvalidTailwindDirectiveDiagnostic(diagnostic) ||
      isInvalidScreenDiagnostic(diagnostic) ||
      isInvalidVariantDiagnostic(diagnostic)
    ) {
      return diagnostic.suggestions.map((suggestion) => ({
        title: `Replace with '${suggestion}'`,
        kind: CodeActionKind.QuickFix,
        diagnostics: [diagnostic],
        edit: {
          changes: {
            [params.textDocument.uri]: [
              {
                range: diagnostic.range,
                newText: suggestion,
              },
            ],
          },
        },
      }))
    }

    return []
  })

  return Promise.all(actions)
    .then(flatten)
    .then((x) => dedupeBy(x, (item) => JSON.stringify(item.edit)))
}

function classNameToAst(
  state: State,
  className: string,
  selector: string = `.${className}`,
  important: boolean = false
) {
  const parts = getClassNameParts(state, className)
  if (!parts) {
    return null
  }
  const baseClassName = dlv(
    state.classNames.classNames,
    parts[parts.length - 1]
  )
  if (!baseClassName) {
    return null
  }
  const info = dlv(state.classNames.classNames, parts)
  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 < parts.length - 1; i++) {
    let part = parts[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 ${parts[parts.length - 1]}${
        important ? ' !important' : ''
      }`]: '',
    },
  }
  if (path.length) {
    dset(obj, path, rule)
  } else {
    obj = rule
  }

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

async function provideUtilityConflictsCodeActions(
  state: State,
  params: CodeActionParams,
  diagnostic: UtilityConflictsDiagnostic
): Promise<CodeAction[]> {
  return [
    {
      title: `Delete ${joinWithAnd(
        diagnostic.otherClassNames.map(
          (otherClassName) => `'${otherClassName.className}'`
        )
      )}`,
      kind: CodeActionKind.QuickFix,
      diagnostics: [diagnostic],
      edit: {
        changes: {
          [params.textDocument.uri]: [
            {
              range: diagnostic.className.classList.range,
              newText: removeRangesFromString(
                diagnostic.className.classList.classList,
                diagnostic.otherClassNames.map(
                  (otherClassName) => otherClassName.relativeRange
                )
              ),
            },
          ],
        },
      },
    },
  ]
}

async function provideInvalidApplyCodeActions(
  state: State,
  params: CodeActionParams,
  diagnostic: InvalidApplyDiagnostic
): Promise<CodeAction[]> {
  let document = state.editor.documents.get(params.textDocument.uri)
  let documentText = document.getText()
  const { postcss } = state.modules
  let change: TextEdit

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

  await postcss([
    postcss.plugin('', (_options = {}) => {
      return (root) => {
        root.walkRules((rule) => {
          if (change) return false

          rule.walkAtRules('apply', (atRule) => {
            let { start, end } = atRule.source
            let range: Range = {
              start: {
                line: start.line - 1,
                character: start.column - 1,
              },
              end: {
                line: end.line - 1,
                character: end.column - 1,
              },
            }

            if (!isWithinRange(diagnostic.range.start, range)) {
              // keep looking
              return true
            }

            let className = document.getText(diagnostic.range)
            let ast = classNameToAst(
              state,
              className,
              rule.selector,
              diagnostic.className.classList.important
            )

            if (!ast) {
              return false
            }

            rule.after(ast.nodes)
            let insertedRule = rule.next()

            if (totalClassNamesInClassList === 1) {
              atRule.remove()
            }

            let outputIndent: string
            let documentIndent = detectIndent(documentText)

            change = {
              range: {
                start: {
                  line: rule.source.start.line - 1,
                  character: rule.source.start.column - 1,
                },
                end: {
                  line: rule.source.end.line - 1,
                  character: rule.source.end.column,
                },
              },
              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(documentText, { from: undefined })

  if (!change) {
    return []
  }

  return [
    {
      title: 'Extract to new rule',
      kind: CodeActionKind.QuickFix,
      diagnostics: [diagnostic],
      edit: {
        changes: {
          [params.textDocument.uri]: [
            ...(totalClassNamesInClassList > 1
              ? [
                  {
                    range: diagnostic.className.classList.range,
                    newText: removeRangesFromString(
                      diagnostic.className.classList.classList,
                      diagnostic.className.relativeRange
                    ),
                  },
                ]
              : []),
            change,
          ],
        },
      },
    },
  ]
}