Home

tailwind-ctp-intellisense @dce390d98ca75bc6a0cf19d29e16ca6422faa924 - refs - log -
-
https://git.jolheiser.com/tailwind-ctp-intellisense.git
Tailwind intellisense + Catppuccin
tailwind-ctp-intellisense / packages / tailwindcss-language-service / src / completionProvider.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
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
import { State } from './util/state'
import type {
  CompletionItem,
  CompletionItemKind,
  Range,
  MarkupKind,
  CompletionList,
  TextDocument,
  Position,
  CompletionContext,
} from 'vscode-languageserver'
const dlv = require('dlv')
import removeMeta from './util/removeMeta'
import { getColor, getColorFromValue } from './util/color'
import { isHtmlContext } from './util/html'
import { isCssContext } from './util/css'
import { findLast } from './util/find'
import { stringifyConfigValue, stringifyCss } from './util/stringify'
import { stringifyScreen, Screen } from './util/screens'
import isObject from './util/isObject'
import * as emmetHelper from 'vscode-emmet-helper-bundled'
import { isValidLocationForEmmetAbbreviation } from './util/isValidLocationForEmmetAbbreviation'
import { isJsContext } from './util/js'
import { naturalExpand } from './util/naturalExpand'
import semver from 'semver'
import { docsUrl } from './util/docsUrl'
import { ensureArray } from './util/array'
import { getClassAttributeLexer, getComputedClassAttributeLexer } from './util/lexers'
import { validateApply } from './util/validateApply'
import { flagEnabled } from './util/flagEnabled'
import { remToPx } from './util/remToPx'
import { createMultiRegexp } from './util/createMultiRegexp'
import * as jit from './util/jit'
import { TinyColor } from '@ctrl/tinycolor'
import { getVariantsFromClassName } from './util/getVariantsFromClassName'

let isUtil = (className) =>
  Array.isArray(className.__info)
    ? className.__info.some((x) => x.__source === 'utilities')
    : className.__info.__source === 'utilities'

export function completionsFromClassList(
  state: State,
  classList: string,
  classListRange: Range,
  filter?: (item: CompletionItem) => boolean,
  document?: TextDocument,
  context?: CompletionContext
): CompletionList {
  let classNames = classList.split(/[\s+]/)
  const partialClassName = classNames[classNames.length - 1]
  let sep = state.separator
  let parts = partialClassName.split(sep)
  let subset: any
  let subsetKey: string[] = []
  let isSubset: boolean = false

  let replacementRange = {
    ...classListRange,
    start: {
      ...classListRange.start,
      character: classListRange.end.character - partialClassName.length,
    },
  }

  if (state.jit) {
    if (
      context &&
      (context.triggerKind === 1 ||
        (context.triggerKind === 2 && context.triggerCharacter === '/')) &&
      partialClassName.includes('/')
    ) {
      // opacity modifiers
      let beforeSlash = partialClassName.split('/').slice(0, -1).join('/')
      let testClass = beforeSlash + '/[0]'
      let { rules } = jit.generateRules(state, [testClass])
      if (rules.length > 0) {
        let opacities = dlv(state.config, 'theme.opacity', {})
        if (!isObject(opacities)) {
          opacities = {}
        }
        return {
          isIncomplete: false,
          items: Object.keys(opacities).map((opacity, index) => {
            let className = `${beforeSlash}/${opacity}`
            let kind: CompletionItemKind = 21
            let documentation: string = null

            const color = getColor(state, className)
            if (color !== null) {
              kind = 16
              if (typeof color !== 'string') {
                documentation = color.toRgbString().replace(/(^rgba\([^)]+) 0\)$/, '$1 0.001)')
              }
            }

            return {
              label: className,
              documentation,
              kind,
              sortText: naturalExpand(index),
              data: [className],
              textEdit: {
                newText: className,
                range: replacementRange,
              },
            }
          }),
        }
      }
    }

    let allVariants = Object.keys(state.variants)
    let { variants: existingVariants, offset } = getVariantsFromClassName(state, partialClassName)

    replacementRange.start.character += offset

    let important = partialClassName.substr(offset).startsWith('!')
    if (important) {
      replacementRange.start.character += 1
    }

    let items: CompletionItem[] = []

    if (!important) {
      items.push(
        ...Object.entries(state.variants)
          .filter(([variant]) => !existingVariants.includes(variant))
          .map(([variant, definition], index) => {
            let resultingVariants = [...existingVariants, variant].sort(
              (a, b) => allVariants.indexOf(b) - allVariants.indexOf(a)
            )

            return {
              label: variant + sep,
              kind: 9,
              detail: definition,
              data: 'variant',
              command: {
                title: '',
                command: 'editor.action.triggerSuggest',
              },
              sortText: '-' + naturalExpand(index),
              textEdit: {
                newText: resultingVariants[resultingVariants.length - 1] + sep,
                range: replacementRange,
              },
              additionalTextEdits:
                resultingVariants.length > 1
                  ? [
                      {
                        newText:
                          resultingVariants.slice(0, resultingVariants.length - 1).join(sep) + sep,
                        range: {
                          start: {
                            ...classListRange.start,
                            character: classListRange.end.character - partialClassName.length,
                          },
                          end: {
                            ...replacementRange.start,
                            character: replacementRange.start.character,
                          },
                        },
                      },
                    ]
                  : [],
            } as CompletionItem
          })
      )
    }

    return {
      isIncomplete: false,
      items: items
        .concat(
          Object.keys(state.classNames.classNames)
            .filter((className) => {
              let item = state.classNames.classNames[className]
              if (existingVariants.length === 0) {
                return item.__info
              }
              return item.__info && isUtil(item)
            })
            .map((className, index) => {
              let kind: CompletionItemKind = 21
              let documentation: string = null

              const color = getColor(state, className)
              if (color !== null) {
                kind = 16
                if (typeof color !== 'string' && color.a !== 0) {
                  documentation = color.toRgbString()
                }
              }

              return {
                label: className,
                kind,
                documentation,
                sortText: naturalExpand(index),
                data: [...existingVariants, important ? `!${className}` : className],
                textEdit: {
                  newText: className,
                  range: replacementRange,
                },
              } as CompletionItem
            })
        )
        .filter((item) => {
          if (item === null) {
            return false
          }
          if (filter && !filter(item)) {
            return false
          }
          return true
        }),
    }
  }

  for (let i = parts.length - 1; i > 0; i--) {
    let keys = parts.slice(0, i).filter(Boolean)
    subset = dlv(state.classNames.classNames, keys)
    if (typeof subset !== 'undefined' && typeof dlv(subset, ['__info', '__rule']) === 'undefined') {
      isSubset = true
      subsetKey = keys
      replacementRange = {
        ...replacementRange,
        start: {
          ...replacementRange.start,
          character: replacementRange.start.character + keys.join(sep).length + sep.length,
        },
      }
      break
    }
  }

  return {
    isIncomplete: false,
    items: Object.keys(isSubset ? subset : state.classNames.classNames)
      .filter((k) => k !== '__info')
      .filter((className) => isContextItem(state, [...subsetKey, className]))
      .map((className, index): CompletionItem => {
        return {
          label: className + sep,
          kind: 9,
          documentation: null,
          command: {
            title: '',
            command: 'editor.action.triggerSuggest',
          },
          sortText: '-' + naturalExpand(index),
          data: [...subsetKey, className],
          textEdit: {
            newText: className + sep,
            range: replacementRange,
          },
        }
      })
      .concat(
        Object.keys(isSubset ? subset : state.classNames.classNames)
          .filter((className) =>
            dlv(state.classNames.classNames, [...subsetKey, className, '__info'])
          )
          .map((className, index) => {
            let kind: CompletionItemKind = 21
            let documentation: string = null

            const color = getColor(state, className)
            if (color !== null) {
              kind = 16
              if (typeof color !== 'string' && color.a !== 0) {
                documentation = color.toRgbString()
              }
            }

            return {
              label: className,
              kind,
              documentation,
              sortText: naturalExpand(index),
              data: [...subsetKey, className],
              textEdit: {
                newText: className,
                range: replacementRange,
              },
            }
          })
      )
      .filter((item) => {
        if (item === null) {
          return false
        }
        if (filter && !filter(item)) {
          return false
        }
        return true
      }),
  }
}

function provideClassAttributeCompletions(
  state: State,
  document: TextDocument,
  position: Position,
  context?: CompletionContext
): CompletionList {
  let str = document.getText({
    start: document.positionAt(Math.max(0, document.offsetAt(position) - 500)),
    end: position,
  })

  const match = findLast(/(?:\s|:|\()(?:class(?:Name)?|\[ngClass\])=['"`{]/gi, str)

  if (match === null) {
    return null
  }

  const lexer =
    match[0][0] === ':' || match[0].trim().startsWith('[ngClass]')
      ? getComputedClassAttributeLexer()
      : getClassAttributeLexer()
  lexer.reset(str.substr(match.index + match[0].length - 1))

  try {
    let tokens = Array.from(lexer)
    let last = tokens[tokens.length - 1]
    if (last.type.startsWith('start') || last.type === 'classlist') {
      let classList = ''
      for (let i = tokens.length - 1; i >= 0; i--) {
        if (tokens[i].type === 'classlist') {
          classList = tokens[i].value + classList
        } else {
          break
        }
      }

      return completionsFromClassList(
        state,
        classList,
        {
          start: {
            line: position.line,
            character: position.character - classList.length,
          },
          end: position,
        },
        undefined,
        document,
        context
      )
    }
  } catch (_) {}

  return null
}

async function provideCustomClassNameCompletions(
  state: State,
  document: TextDocument,
  position: Position
): Promise<CompletionList> {
  const settings = await state.editor.getConfiguration(document.uri)
  const regexes = dlv(settings, 'tailwindCSS.experimental.classRegex', [])
  if (regexes.length === 0) return null

  const positionOffset = document.offsetAt(position)

  const searchRange: Range = {
    start: document.positionAt(Math.max(0, positionOffset - 500)),
    end: document.positionAt(positionOffset + 500),
  }

  let str = document.getText(searchRange)

  for (let i = 0; i < regexes.length; i++) {
    try {
      let [containerRegex, classRegex] = Array.isArray(regexes[i]) ? regexes[i] : [regexes[i]]

      containerRegex = createMultiRegexp(containerRegex)
      let containerMatch

      while ((containerMatch = containerRegex.exec(str)) !== null) {
        const searchStart = document.offsetAt(searchRange.start)
        const matchStart = searchStart + containerMatch.start
        const matchEnd = searchStart + containerMatch.end
        const cursor = document.offsetAt(position)
        if (cursor >= matchStart && cursor <= matchEnd) {
          let classList

          if (classRegex) {
            classRegex = createMultiRegexp(classRegex)
            let classMatch

            while ((classMatch = classRegex.exec(containerMatch.match)) !== null) {
              const classMatchStart = matchStart + classMatch.start
              const classMatchEnd = matchStart + classMatch.end
              if (cursor >= classMatchStart && cursor <= classMatchEnd) {
                classList = classMatch.match.substr(0, cursor - classMatchStart)
              }
            }

            if (typeof classList === 'undefined') {
              throw Error()
            }
          } else {
            classList = containerMatch.match.substr(0, cursor - matchStart)
          }

          return completionsFromClassList(state, classList, {
            start: {
              line: position.line,
              character: position.character - classList.length,
            },
            end: position,
          })
        }
      }
    } catch (_) {}
  }

  return null
}

function provideAtApplyCompletions(
  state: State,
  document: TextDocument,
  position: Position
): CompletionList {
  let str = document.getText({
    start: { line: Math.max(position.line - 30, 0), character: 0 },
    end: position,
  })

  const match = findLast(/@apply\s+(?<classList>[^;}]*)$/gi, str)

  if (match === null) {
    return null
  }

  const classList = match.groups.classList

  return completionsFromClassList(
    state,
    classList,
    {
      start: {
        line: position.line,
        character: position.character - classList.length,
      },
      end: position,
    },
    (item) => {
      if (item.kind === 9) {
        return (
          semver.gte(state.version, '2.0.0-alpha.1') || flagEnabled(state, 'applyComplexClasses')
        )
      }
      let validated = validateApply(state, item.data)
      return validated !== null && validated.isApplyable === true
    }
  )
}

function provideClassNameCompletions(
  state: State,
  document: TextDocument,
  position: Position,
  context?: CompletionContext
): CompletionList {
  if (isCssContext(state, document, position)) {
    return provideAtApplyCompletions(state, document, position)
  }

  if (isHtmlContext(state, document, position) || isJsContext(state, document, position)) {
    return provideClassAttributeCompletions(state, document, position, context)
  }

  return null
}

function provideCssHelperCompletions(
  state: State,
  document: TextDocument,
  position: Position
): CompletionList {
  if (!isCssContext(state, document, position)) {
    return null
  }

  let text = document.getText({
    start: { line: position.line, character: 0 },
    // read one extra character so we can see if it's a ] later
    end: { line: position.line, character: position.character + 1 },
  })

  const match = text
    .substr(0, text.length - 1) // don't include that extra character from earlier
    .match(/\b(?<helper>config|theme)\(['"](?<keys>[^'"]*)$/)

  if (match === null) {
    return null
  }

  let base = match.groups.helper === 'config' ? state.config : dlv(state.config, 'theme', {})
  let parts = match.groups.keys.split(/([\[\].]+)/)
  let keys = parts.filter((_, i) => i % 2 === 0)
  let separators = parts.filter((_, i) => i % 2 !== 0)
  // let obj =
  //   keys.length === 1 ? base : dlv(base, keys.slice(0, keys.length - 1), {})

  // if (!isObject(obj)) return null

  function totalLength(arr: string[]): number {
    return arr.reduce((acc, cur) => acc + cur.length, 0)
  }

  let obj: any
  let offset: number = 0
  let separator: string = separators.length ? separators[separators.length - 1] : null

  if (keys.length === 1) {
    obj = base
  } else {
    for (let i = keys.length - 1; i > 0; i--) {
      let o = dlv(base, keys.slice(0, i))
      if (isObject(o)) {
        obj = o
        offset = totalLength(parts.slice(i * 2))
        separator = separators[i - 1]
        break
      }
    }
  }

  if (!obj) return null

  return {
    isIncomplete: false,
    items: Object.keys(obj).map((item, index) => {
      let color = getColorFromValue(obj[item])
      const replaceDot: boolean = item.indexOf('.') !== -1 && separator && separator.endsWith('.')
      const insertClosingBrace: boolean =
        text.charAt(text.length - 1) !== ']' &&
        (replaceDot || (separator && separator.endsWith('[')))
      const detail = stringifyConfigValue(obj[item])

      return {
        label: item,
        filterText: `${replaceDot ? '.' : ''}${item}`,
        sortText: naturalExpand(index),
        kind: color ? 16 : isObject(obj[item]) ? 9 : 10,
        // VS Code bug causes some values to not display in some cases
        detail: detail === '0' || detail === 'transparent' ? `${detail} ` : detail,
        documentation: color instanceof TinyColor && color.a !== 0 ? color.toRgbString() : null,
        textEdit: {
          newText: `${replaceDot ? '[' : ''}${item}${insertClosingBrace ? ']' : ''}`,
          range: {
            start: {
              line: position.line,
              character:
                position.character - keys[keys.length - 1].length - (replaceDot ? 1 : 0) - offset,
            },
            end: position,
          },
        },
        data: 'helper',
      }
    }),
  }
}

function provideTailwindDirectiveCompletions(
  state: State,
  document: TextDocument,
  position: Position
): CompletionList {
  if (!isCssContext(state, document, position)) {
    return null
  }

  let text = document.getText({
    start: { line: position.line, character: 0 },
    end: position,
  })

  const match = text.match(/^\s*@tailwind\s+(?<partial>[^\s]*)$/i)

  if (match === null) return null

  return {
    isIncomplete: false,
    items: [
      semver.gte(state.version, '1.0.0-beta.1')
        ? {
            label: 'base',
            documentation: {
              kind: 'markdown' as typeof MarkupKind.Markdown,
              value: `This injects Tailwind’s base styles and any base styles registered by plugins.\n\n[Tailwind CSS Documentation](${docsUrl(
                state.version,
                'functions-and-directives/#tailwind'
              )})`,
            },
          }
        : {
            label: 'preflight',
            documentation: {
              kind: 'markdown' as typeof MarkupKind.Markdown,
              value: `This injects Tailwind’s base styles, which is a combination of Normalize.css and some additional base styles.\n\n[Tailwind CSS Documentation](${docsUrl(
                state.version,
                'functions-and-directives/#tailwind'
              )})`,
            },
          },
      {
        label: 'components',
        documentation: {
          kind: 'markdown' as typeof MarkupKind.Markdown,
          value: `This injects Tailwind’s component classes and any component classes registered by plugins.\n\n[Tailwind CSS Documentation](${docsUrl(
            state.version,
            'functions-and-directives/#tailwind'
          )})`,
        },
      },
      {
        label: 'utilities',
        documentation: {
          kind: 'markdown' as typeof MarkupKind.Markdown,
          value: `This injects Tailwind’s utility classes and any utility classes registered by plugins.\n\n[Tailwind CSS Documentation](${docsUrl(
            state.version,
            'functions-and-directives/#tailwind'
          )})`,
        },
      },
      state.jit && semver.gte(state.version, '2.1.99')
        ? {
            label: 'variants',
            documentation: {
              kind: 'markdown' as typeof MarkupKind.Markdown,
              value: `Use this directive to control where Tailwind injects the utility variants.\n\nThis directive is considered an advanced escape hatch and it is recommended to omit it whenever possible. If omitted, Tailwind will append these classes to the very end of your stylesheet by default.\n\n[Tailwind CSS Documentation](${docsUrl(
                state.version,
                'just-in-time-mode#variants-are-inserted-at-tailwind-variants'
              )})`,
            },
          }
        : {
            label: 'screens',
            documentation: {
              kind: 'markdown' as typeof MarkupKind.Markdown,
              value: `Use this directive to control where Tailwind injects the responsive variations of each utility.\n\nIf omitted, Tailwind will append these classes to the very end of your stylesheet by default.\n\n[Tailwind CSS Documentation](${docsUrl(
                state.version,
                'functions-and-directives/#tailwind'
              )})`,
            },
          },
    ].map((item) => ({
      ...item,
      kind: 21,
      data: '@tailwind',
      textEdit: {
        newText: item.label,
        range: {
          start: {
            line: position.line,
            character: position.character - match.groups.partial.length,
          },
          end: position,
        },
      },
    })),
  }
}

function provideVariantsDirectiveCompletions(
  state: State,
  document: TextDocument,
  position: Position
): CompletionList {
  if (!isCssContext(state, document, position)) {
    return null
  }

  let text = document.getText({
    start: { line: position.line, character: 0 },
    end: position,
  })

  const match = text.match(/^\s*@variants\s+(?<partial>[^}]*)$/i)

  if (match === null) return null

  const parts = match.groups.partial.split(/\s*,\s*/)

  if (/\s+/.test(parts[parts.length - 1])) return null

  let possibleVariants = Object.keys(state.variants)
  const existingVariants = parts.slice(0, parts.length - 1)

  if (state.jit) {
    possibleVariants.unshift('responsive')
    possibleVariants = possibleVariants.filter((v) => !state.screens.includes(v))
  }

  return {
    isIncomplete: false,
    items: possibleVariants
      .filter((v) => existingVariants.indexOf(v) === -1)
      .map((variant, index) => ({
        // TODO: detail
        label: variant,
        detail: state.variants[variant],
        kind: 21,
        data: 'variant',
        sortText: naturalExpand(index),
        textEdit: {
          newText: variant,
          range: {
            start: {
              line: position.line,
              character: position.character - parts[parts.length - 1].length,
            },
            end: position,
          },
        },
      })),
  }
}

function provideLayerDirectiveCompletions(
  state: State,
  document: TextDocument,
  position: Position
): CompletionList {
  if (!isCssContext(state, document, position)) {
    return null
  }

  let text = document.getText({
    start: { line: position.line, character: 0 },
    end: position,
  })

  const match = text.match(/^\s*@layer\s+(?<partial>[^\s]*)$/i)

  if (match === null) return null

  return {
    isIncomplete: false,
    items: ['base', 'components', 'utilities'].map((layer, index) => ({
      label: layer,
      kind: 21,
      data: 'layer',
      sortText: naturalExpand(index),
      textEdit: {
        newText: layer,
        range: {
          start: {
            line: position.line,
            character: position.character - match.groups.partial.length,
          },
          end: position,
        },
      },
    })),
  }
}

function provideScreenDirectiveCompletions(
  state: State,
  document: TextDocument,
  position: Position
): CompletionList {
  if (!isCssContext(state, document, position)) {
    return null
  }

  let text = document.getText({
    start: { line: position.line, character: 0 },
    end: position,
  })

  const match = text.match(/^\s*@screen\s+(?<partial>[^\s]*)$/i)

  if (match === null) return null

  const screens = dlv(state.config, ['screens'], dlv(state.config, ['theme', 'screens'], {}))

  if (!isObject(screens)) return null

  return {
    isIncomplete: false,
    items: Object.keys(screens).map((screen, index) => ({
      label: screen,
      kind: 21,
      data: 'screen',
      sortText: naturalExpand(index),
      textEdit: {
        newText: screen,
        range: {
          start: {
            line: position.line,
            character: position.character - match.groups.partial.length,
          },
          end: position,
        },
      },
    })),
  }
}

function provideCssDirectiveCompletions(
  state: State,
  document: TextDocument,
  position: Position
): CompletionList {
  if (!isCssContext(state, document, position)) {
    return null
  }

  let text = document.getText({
    start: { line: position.line, character: 0 },
    end: position,
  })

  const match = text.match(/^\s*@(?<partial>[a-z]*)$/i)

  if (match === null) return null

  const items: CompletionItem[] = [
    {
      label: '@tailwind',
      documentation: {
        kind: 'markdown' as typeof MarkupKind.Markdown,
        value: `Use the \`@tailwind\` directive to insert Tailwind’s \`base\`, \`components\`, \`utilities\` and \`screens\` styles into your CSS.\n\n[Tailwind CSS Documentation](${docsUrl(
          state.version,
          'functions-and-directives/#tailwind'
        )})`,
      },
    },
    {
      label: '@variants',
      documentation: {
        kind: 'markdown' as typeof MarkupKind.Markdown,
        value: `You can generate \`responsive\`, \`hover\`, \`focus\`, \`active\`, and \`group-hover\` versions of your own utilities by wrapping their definitions in the \`@variants\` directive.\n\n[Tailwind CSS Documentation](${docsUrl(
          state.version,
          'functions-and-directives/#variants'
        )})`,
      },
    },
    {
      label: '@responsive',
      documentation: {
        kind: 'markdown' as typeof MarkupKind.Markdown,
        value: `You can generate responsive variants of your own classes by wrapping their definitions in the \`@responsive\` directive.\n\n[Tailwind CSS Documentation](${docsUrl(
          state.version,
          'functions-and-directives/#responsive'
        )})`,
      },
    },
    {
      label: '@screen',
      documentation: {
        kind: 'markdown' as typeof MarkupKind.Markdown,
        value: `The \`@screen\` directive allows you to create media queries that reference your breakpoints by name instead of duplicating their values in your own CSS.\n\n[Tailwind CSS Documentation](${docsUrl(
          state.version,
          'functions-and-directives/#screen'
        )})`,
      },
    },
    {
      label: '@apply',
      documentation: {
        kind: 'markdown' as typeof MarkupKind.Markdown,
        value: `Use \`@apply\` to inline any existing utility classes into your own custom CSS.\n\n[Tailwind CSS Documentation](${docsUrl(
          state.version,
          'functions-and-directives/#apply'
        )})`,
      },
    },
    ...(semver.gte(state.version, '1.8.0')
      ? [
          {
            label: '@layer',
            documentation: {
              kind: 'markdown' as typeof MarkupKind.Markdown,
              value: `Use the \`@layer\` directive to tell Tailwind which "bucket" a set of custom styles belong to. Valid layers are \`base\`, \`components\`, and \`utilities\`.\n\n[Tailwind CSS Documentation](${docsUrl(
                state.version,
                'functions-and-directives/#layer'
              )})`,
            },
          },
        ]
      : []),
  ]

  return {
    isIncomplete: false,
    items: items.map((item) => ({
      ...item,
      kind: 14,
      data: 'directive',
      textEdit: {
        newText: item.label,
        range: {
          start: {
            line: position.line,
            character: position.character - match.groups.partial.length - 1,
          },
          end: position,
        },
      },
    })),
  }
}

async function provideEmmetCompletions(
  state: State,
  document: TextDocument,
  position: Position
): Promise<CompletionList> {
  let settings = await state.editor.getConfiguration(document.uri)
  if (settings.tailwindCSS.emmetCompletions !== true) return null

  const isHtml = isHtmlContext(state, document, position)
  const isJs = !isHtml && isJsContext(state, document, position)

  const syntax = isHtml ? 'html' : isJs ? 'jsx' : null

  if (syntax === null) {
    return null
  }

  const extractAbbreviationResults = emmetHelper.extractAbbreviation(document, position, true)
  if (
    !extractAbbreviationResults ||
    !emmetHelper.isAbbreviationValid(syntax, extractAbbreviationResults.abbreviation)
  ) {
    return null
  }

  if (
    !isValidLocationForEmmetAbbreviation(document, extractAbbreviationResults.abbreviationRange)
  ) {
    return null
  }

  if (isJs) {
    const abbreviation: string = extractAbbreviationResults.abbreviation
    if (abbreviation.startsWith('this.')) {
      return null
    }
    const symbols = await state.editor.getDocumentSymbols(document.uri)
    if (
      symbols &&
      symbols.find(
        (symbol) =>
          abbreviation === symbol.name ||
          (abbreviation.startsWith(symbol.name + '.') && !/>|\*|\+/.test(abbreviation))
      )
    ) {
      return null
    }
  }

  const emmetItems = emmetHelper.doComplete(document, position, syntax, {})

  if (!emmetItems || !emmetItems.items || emmetItems.items.length !== 1) {
    return null
  }

  // https://github.com/microsoft/vscode/issues/86941
  if (emmetItems.items[0].label === 'widows: ;') {
    return null
  }

  const parts = emmetItems.items[0].label.split('.')
  if (parts.length < 2) return null

  return completionsFromClassList(state, parts[parts.length - 1], {
    start: {
      line: position.line,
      character: position.character - parts[parts.length - 1].length,
    },
    end: position,
  })
}

export async function doComplete(
  state: State,
  document: TextDocument,
  position: Position,
  context?: CompletionContext
) {
  if (state === null) return { items: [], isIncomplete: false }

  const result =
    provideClassNameCompletions(state, document, position, context) ||
    provideCssHelperCompletions(state, document, position) ||
    provideCssDirectiveCompletions(state, document, position) ||
    provideScreenDirectiveCompletions(state, document, position) ||
    provideVariantsDirectiveCompletions(state, document, position) ||
    provideTailwindDirectiveCompletions(state, document, position) ||
    provideLayerDirectiveCompletions(state, document, position) ||
    (await provideCustomClassNameCompletions(state, document, position))

  if (result) return result

  return provideEmmetCompletions(state, document, position)
}

export async function resolveCompletionItem(
  state: State,
  item: CompletionItem
): Promise<CompletionItem> {
  if (['helper', 'directive', 'variant', 'layer', '@tailwind'].includes(item.data)) {
    return item
  }

  if (item.data === 'screen') {
    let screens = dlv(state.config, ['theme', 'screens'], dlv(state.config, ['screens'], {}))
    if (!isObject(screens)) screens = {}
    item.detail = stringifyScreen(screens[item.label] as Screen)
    return item
  }

  if (!Array.isArray(item.data)) {
    return item
  }

  if (state.jit) {
    if (item.kind === 9) return item
    if (item.detail && item.documentation) return item
    let { root, rules } = jit.generateRules(state, [item.data.join(state.separator)])
    if (rules.length === 0) return item
    if (!item.detail) {
      if (rules.length === 1) {
        item.detail = await jit.stringifyDecls(state, rules[0])
      } else {
        item.detail = `${rules.length} rules`
      }
    }
    if (!item.documentation) {
      item.documentation = {
        kind: 'markdown' as typeof MarkupKind.Markdown,
        value: ['```css', await jit.stringifyRoot(state, root), '```'].join('\n'),
      }
    }
    return item
  }

  const className = dlv(state.classNames.classNames, [...item.data, '__info'])
  if (item.kind === 9) {
    item.detail = state.classNames.context[item.data[item.data.length - 1]].join(', ')
  } else {
    item.detail = await getCssDetail(state, className)
    if (!item.documentation) {
      const settings = await state.editor.getConfiguration()
      const css = stringifyCss(item.data.join(':'), className, {
        tabSize: dlv(settings, 'editor.tabSize', 2),
        showPixelEquivalents: dlv(settings, 'tailwindCSS.showPixelEquivalents', true),
        rootFontSize: dlv(settings, 'tailwindCSS.rootFontSize', 16),
      })
      if (css) {
        item.documentation = {
          kind: 'markdown' as typeof MarkupKind.Markdown,
          value: ['```css', css, '```'].join('\n'),
        }
      }
    }
  }
  return item
}

function isContextItem(state: State, keys: string[]): boolean {
  const item = dlv(state.classNames.classNames, [keys])

  if (!isObject(item)) {
    return false
  }
  if (!state.classNames.context[keys[keys.length - 1]]) {
    return false
  }
  if (Object.keys(item).filter((x) => x !== '__info').length > 0) {
    return true
  }

  return isObject(item.__info) && !item.__info.__rule
}

function stringifyDecls(
  obj: any,
  {
    showPixelEquivalents = false,
    rootFontSize = 16,
  }: Partial<{ showPixelEquivalents: boolean; rootFontSize: number }> = {}
): string {
  let props = Object.keys(obj)
  let nonCustomProps = props.filter((prop) => !prop.startsWith('--'))

  if (props.length !== nonCustomProps.length && nonCustomProps.length !== 0) {
    props = nonCustomProps
  }

  return props
    .map((prop) =>
      ensureArray(obj[prop])
        .map((value) => {
          const px = showPixelEquivalents ? remToPx(value, rootFontSize) : undefined
          return `${prop}: ${value}${px ? `/* ${px} */` : ''};`
        })
        .join(' ')
    )
    .join(' ')
}

async function getCssDetail(state: State, className: any): Promise<string> {
  if (Array.isArray(className)) {
    return `${className.length} rules`
  }
  if (className.__rule === true) {
    const settings = await state.editor.getConfiguration()
    return stringifyDecls(removeMeta(className), {
      showPixelEquivalents: dlv(settings, 'tailwindCSS.showPixelEquivalents', true),
      rootFontSize: dlv(settings, 'tailwindCSS.rootFontSize', 16),
    })
  }
  return null
}