generateRules.js 25.4 KB
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
import postcss from 'postcss'
import selectorParser from 'postcss-selector-parser'
import parseObjectStyles from '../util/parseObjectStyles'
import isPlainObject from '../util/isPlainObject'
import prefixSelector from '../util/prefixSelector'
import { updateAllClasses, filterSelectorsForClass, getMatchingTypes } from '../util/pluginUtils'
import log from '../util/log'
import * as sharedState from './sharedState'
import { formatVariantSelector, finalizeSelector } from '../util/formatVariantSelector'
import { asClass } from '../util/nameClass'
import { normalize } from '../util/dataTypes'
import { isValidVariantFormatString, parseVariant } from './setupContextUtils'
import isValidArbitraryValue from '../util/isValidArbitraryValue'
import { splitAtTopLevelOnly } from '../util/splitAtTopLevelOnly.js'
import { flagEnabled } from '../featureFlags'

let classNameParser = selectorParser((selectors) => {
  return selectors.first.filter(({ type }) => type === 'class').pop().value
})

export function getClassNameFromSelector(selector) {
  return classNameParser.transformSync(selector)
}

// Generate match permutations for a class candidate, like:
// ['ring-offset-blue', '100']
// ['ring-offset', 'blue-100']
// ['ring', 'offset-blue-100']
// Example with dynamic classes:
// ['grid-cols', '[[linename],1fr,auto]']
// ['grid', 'cols-[[linename],1fr,auto]']
function* candidatePermutations(candidate) {
  let lastIndex = Infinity

  while (lastIndex >= 0) {
    let dashIdx
    let wasSlash = false

    if (lastIndex === Infinity && candidate.endsWith(']')) {
      let bracketIdx = candidate.indexOf('[')

      // If character before `[` isn't a dash or a slash, this isn't a dynamic class
      // eg. string[]
      if (candidate[bracketIdx - 1] === '-') {
        dashIdx = bracketIdx - 1
      } else if (candidate[bracketIdx - 1] === '/') {
        dashIdx = bracketIdx - 1
        wasSlash = true
      } else {
        dashIdx = -1
      }
    } else if (lastIndex === Infinity && candidate.includes('/')) {
      dashIdx = candidate.lastIndexOf('/')
      wasSlash = true
    } else {
      dashIdx = candidate.lastIndexOf('-', lastIndex)
    }

    if (dashIdx < 0) {
      break
    }

    let prefix = candidate.slice(0, dashIdx)
    let modifier = candidate.slice(wasSlash ? dashIdx : dashIdx + 1)

    lastIndex = dashIdx - 1

    // TODO: This feels a bit hacky
    if (prefix === '' || modifier === '/') {
      continue
    }

    yield [prefix, modifier]
  }
}

function applyPrefix(matches, context) {
  if (matches.length === 0 || context.tailwindConfig.prefix === '') {
    return matches
  }

  for (let match of matches) {
    let [meta] = match
    if (meta.options.respectPrefix) {
      let container = postcss.root({ nodes: [match[1].clone()] })
      let classCandidate = match[1].raws.tailwind.classCandidate

      container.walkRules((r) => {
        // If this is a negative utility with a dash *before* the prefix we
        // have to ensure that the generated selector matches the candidate

        // Not doing this will cause `-tw-top-1` to generate the class `.tw--top-1`
        // The disconnect between candidate <-> class can cause @apply to hard crash.
        let shouldPrependNegative = classCandidate.startsWith('-')

        r.selector = prefixSelector(
          context.tailwindConfig.prefix,
          r.selector,
          shouldPrependNegative
        )
      })

      match[1] = container.nodes[0]
    }
  }

  return matches
}

function applyImportant(matches, classCandidate) {
  if (matches.length === 0) {
    return matches
  }
  let result = []

  for (let [meta, rule] of matches) {
    let container = postcss.root({ nodes: [rule.clone()] })
    container.walkRules((r) => {
      r.selector = updateAllClasses(
        filterSelectorsForClass(r.selector, classCandidate),
        (className) => {
          if (className === classCandidate) {
            return `!${className}`
          }
          return className
        }
      )
      r.walkDecls((d) => (d.important = true))
    })
    result.push([{ ...meta, important: true }, container.nodes[0]])
  }

  return result
}

// Takes a list of rule tuples and applies a variant like `hover`, sm`,
// whatever to it. We used to do some extra caching here to avoid generating
// a variant of the same rule more than once, but this was never hit because
// we cache at the entire selector level further up the tree.
//
// Technically you can get a cache hit if you have `hover:focus:text-center`
// and `focus:hover:text-center` in the same project, but it doesn't feel
// worth the complexity for that case.

function applyVariant(variant, matches, context) {
  if (matches.length === 0) {
    return matches
  }

  /** @type {{modifier: string | null, value: string | null}} */
  let args = { modifier: null, value: sharedState.NONE }

  // Retrieve "modifier"
  {
    let match = /(.*)\/(.*)$/g.exec(variant)
    if (match) {
      variant = match[1]
      args.modifier = match[2]

      if (!flagEnabled(context.tailwindConfig, 'generalizedModifiers')) {
        return []
      }
    }
  }

  // Retrieve "arbitrary value"
  if (variant.endsWith(']') && !variant.startsWith('[')) {
    // We either have:
    //   @[200px]
    //   group-[:hover]
    //
    // But we don't want:
    //   @-[200px]        (`-` is incorrect)
    //   group[:hover]    (`-` is missing)
    let match = /(.)(-?)\[(.*)\]/g.exec(variant)
    if (match) {
      let [, char, seperator, value] = match
      // @-[200px] case
      if (char === '@' && seperator === '-') return []
      // group[:hover] case
      if (char !== '@' && seperator === '') return []

      variant = variant.replace(`${seperator}[${value}]`, '')
      args.value = value
    }
  }

  // Register arbitrary variants
  if (isArbitraryValue(variant) && !context.variantMap.has(variant)) {
    let selector = normalize(variant.slice(1, -1))

    if (!isValidVariantFormatString(selector)) {
      return []
    }

    let fn = parseVariant(selector)

    let sort = context.offsets.recordVariant(variant)

    context.variantMap.set(variant, [[sort, fn]])
  }

  if (context.variantMap.has(variant)) {
    let variantFunctionTuples = context.variantMap.get(variant).slice()
    let result = []

    for (let [meta, rule] of matches) {
      // Don't generate variants for user css
      if (meta.layer === 'user') {
        continue
      }

      let container = postcss.root({ nodes: [rule.clone()] })

      for (let [variantSort, variantFunction, containerFromArray] of variantFunctionTuples) {
        let clone = (containerFromArray ?? container).clone()
        let collectedFormats = []

        function prepareBackup() {
          // Already prepared, chicken out
          if (clone.raws.neededBackup) {
            return
          }
          clone.raws.neededBackup = true
          clone.walkRules((rule) => (rule.raws.originalSelector = rule.selector))
        }

        function modifySelectors(modifierFunction) {
          prepareBackup()
          clone.each((rule) => {
            if (rule.type !== 'rule') {
              return
            }

            rule.selectors = rule.selectors.map((selector) => {
              return modifierFunction({
                get className() {
                  return getClassNameFromSelector(selector)
                },
                selector,
              })
            })
          })

          return clone
        }

        let ruleWithVariant = variantFunction({
          // Public API
          get container() {
            prepareBackup()
            return clone
          },
          separator: context.tailwindConfig.separator,
          modifySelectors,

          // Private API for now
          wrap(wrapper) {
            let nodes = clone.nodes
            clone.removeAll()
            wrapper.append(nodes)
            clone.append(wrapper)
          },
          format(selectorFormat) {
            collectedFormats.push(selectorFormat)
          },
          args,
        })

        // It can happen that a list of format strings is returned from within the function. In that
        // case, we have to process them as well. We can use the existing `variantSort`.
        if (Array.isArray(ruleWithVariant)) {
          for (let [idx, variantFunction] of ruleWithVariant.entries()) {
            // This is a little bit scary since we are pushing to an array of items that we are
            // currently looping over. However, you can also think of it like a processing queue
            // where you keep handling jobs until everything is done and each job can queue more
            // jobs if needed.
            variantFunctionTuples.push([
              context.offsets.applyParallelOffset(variantSort, idx),
              variantFunction,

              // If the clone has been modified we have to pass that back
              // though so each rule can use the modified container
              clone.clone(),
            ])
          }
          continue
        }

        if (typeof ruleWithVariant === 'string') {
          collectedFormats.push(ruleWithVariant)
        }

        if (ruleWithVariant === null) {
          continue
        }

        // We had to backup selectors, therefore we assume that somebody touched
        // `container` or `modifySelectors`. Let's see if they did, so that we
        // can restore the selectors, and collect the format strings.
        if (clone.raws.neededBackup) {
          delete clone.raws.neededBackup
          clone.walkRules((rule) => {
            let before = rule.raws.originalSelector
            if (!before) return
            delete rule.raws.originalSelector
            if (before === rule.selector) return // No mutation happened

            let modified = rule.selector

            // Rebuild the base selector, this is what plugin authors would do
            // as well. E.g.: `${variant}${separator}${className}`.
            // However, plugin authors probably also prepend or append certain
            // classes, pseudos, ids, ...
            let rebuiltBase = selectorParser((selectors) => {
              selectors.walkClasses((classNode) => {
                classNode.value = `${variant}${context.tailwindConfig.separator}${classNode.value}`
              })
            }).processSync(before)

            // Now that we know the original selector, the new selector, and
            // the rebuild part in between, we can replace the part that plugin
            // authors need to rebuild with `&`, and eventually store it in the
            // collectedFormats. Similar to what `format('...')` would do.
            //
            // E.g.:
            //                   variant: foo
            //                  selector: .markdown > p
            //      modified (by plugin): .foo .foo\\:markdown > p
            //    rebuiltBase (internal): .foo\\:markdown > p
            //                    format: .foo &
            collectedFormats.push(modified.replace(rebuiltBase, '&'))
            rule.selector = before
          })
        }

        // This tracks the originating layer for the variant
        // For example:
        // .sm:underline {} is a variant of something in the utilities layer
        // .sm:container {} is a variant of the container component
        clone.nodes[0].raws.tailwind = { ...clone.nodes[0].raws.tailwind, parentLayer: meta.layer }

        let withOffset = [
          {
            ...meta,
            sort: context.offsets.applyVariantOffset(
              meta.sort,
              variantSort,
              Object.assign(args, context.variantOptions.get(variant))
            ),
            collectedFormats: (meta.collectedFormats ?? []).concat(collectedFormats),
            isArbitraryVariant: isArbitraryValue(variant),
          },
          clone.nodes[0],
        ]
        result.push(withOffset)
      }
    }

    return result
  }

  return []
}

function parseRules(rule, cache, options = {}) {
  // PostCSS node
  if (!isPlainObject(rule) && !Array.isArray(rule)) {
    return [[rule], options]
  }

  // Tuple
  if (Array.isArray(rule)) {
    return parseRules(rule[0], cache, rule[1])
  }

  // Simple object
  if (!cache.has(rule)) {
    cache.set(rule, parseObjectStyles(rule))
  }

  return [cache.get(rule), options]
}

const IS_VALID_PROPERTY_NAME = /^[a-z_-]/

function isValidPropName(name) {
  return IS_VALID_PROPERTY_NAME.test(name)
}

/**
 * @param {string} declaration
 * @returns {boolean}
 */
function looksLikeUri(declaration) {
  // Quick bailout for obvious non-urls
  // This doesn't support schemes that don't use a leading // but that's unlikely to be a problem
  if (!declaration.includes('://')) {
    return false
  }

  try {
    const url = new URL(declaration)
    return url.scheme !== '' && url.host !== ''
  } catch (err) {
    // Definitely not a valid url
    return false
  }
}

function isParsableNode(node) {
  let isParsable = true

  node.walkDecls((decl) => {
    if (!isParsableCssValue(decl.name, decl.value)) {
      isParsable = false
      return false
    }
  })

  return isParsable
}

function isParsableCssValue(property, value) {
  // We don't want to to treat [https://example.com] as a custom property
  // Even though, according to the CSS grammar, it's a totally valid CSS declaration
  // So we short-circuit here by checking if the custom property looks like a url
  if (looksLikeUri(`${property}:${value}`)) {
    return false
  }

  try {
    postcss.parse(`a{${property}:${value}}`).toResult()
    return true
  } catch (err) {
    return false
  }
}

function extractArbitraryProperty(classCandidate, context) {
  let [, property, value] = classCandidate.match(/^\[([a-zA-Z0-9-_]+):(\S+)\]$/) ?? []

  if (value === undefined) {
    return null
  }

  if (!isValidPropName(property)) {
    return null
  }

  if (!isValidArbitraryValue(value)) {
    return null
  }

  let normalized = normalize(value)

  if (!isParsableCssValue(property, normalized)) {
    return null
  }

  let sort = context.offsets.arbitraryProperty()

  return [
    [
      { sort, layer: 'utilities' },
      () => ({
        [asClass(classCandidate)]: {
          [property]: normalized,
        },
      }),
    ],
  ]
}

function* resolveMatchedPlugins(classCandidate, context) {
  if (context.candidateRuleMap.has(classCandidate)) {
    yield [context.candidateRuleMap.get(classCandidate), 'DEFAULT']
  }

  yield* (function* (arbitraryPropertyRule) {
    if (arbitraryPropertyRule !== null) {
      yield [arbitraryPropertyRule, 'DEFAULT']
    }
  })(extractArbitraryProperty(classCandidate, context))

  let candidatePrefix = classCandidate
  let negative = false

  const twConfigPrefix = context.tailwindConfig.prefix

  const twConfigPrefixLen = twConfigPrefix.length

  const hasMatchingPrefix =
    candidatePrefix.startsWith(twConfigPrefix) || candidatePrefix.startsWith(`-${twConfigPrefix}`)

  if (candidatePrefix[twConfigPrefixLen] === '-' && hasMatchingPrefix) {
    negative = true
    candidatePrefix = twConfigPrefix + candidatePrefix.slice(twConfigPrefixLen + 1)
  }

  if (negative && context.candidateRuleMap.has(candidatePrefix)) {
    yield [context.candidateRuleMap.get(candidatePrefix), '-DEFAULT']
  }

  for (let [prefix, modifier] of candidatePermutations(candidatePrefix)) {
    if (context.candidateRuleMap.has(prefix)) {
      yield [context.candidateRuleMap.get(prefix), negative ? `-${modifier}` : modifier]
    }
  }
}

function splitWithSeparator(input, separator) {
  if (input === sharedState.NOT_ON_DEMAND) {
    return [sharedState.NOT_ON_DEMAND]
  }

  return splitAtTopLevelOnly(input, separator)
}

function* recordCandidates(matches, classCandidate) {
  for (const match of matches) {
    match[1].raws.tailwind = {
      ...match[1].raws.tailwind,
      classCandidate,
      preserveSource: match[0].options?.preserveSource ?? false,
    }

    yield match
  }
}

function* resolveMatches(candidate, context, original = candidate) {
  let separator = context.tailwindConfig.separator
  let [classCandidate, ...variants] = splitWithSeparator(candidate, separator).reverse()
  let important = false

  if (classCandidate.startsWith('!')) {
    important = true
    classCandidate = classCandidate.slice(1)
  }

  if (flagEnabled(context.tailwindConfig, 'variantGrouping')) {
    if (classCandidate.startsWith('(') && classCandidate.endsWith(')')) {
      let base = variants.slice().reverse().join(separator)
      for (let part of splitAtTopLevelOnly(classCandidate.slice(1, -1), ',')) {
        yield* resolveMatches(base + separator + part, context, original)
      }
    }
  }

  // TODO: Reintroduce this in ways that doesn't break on false positives
  // function sortAgainst(toSort, against) {
  //   return toSort.slice().sort((a, z) => {
  //     return bigSign(against.get(a)[0] - against.get(z)[0])
  //   })
  // }
  // let sorted = sortAgainst(variants, context.variantMap)
  // if (sorted.toString() !== variants.toString()) {
  //   let corrected = sorted.reverse().concat(classCandidate).join(':')
  //   throw new Error(`Class ${candidate} should be written as ${corrected}`)
  // }

  for (let matchedPlugins of resolveMatchedPlugins(classCandidate, context)) {
    let matches = []
    let typesByMatches = new Map()

    let [plugins, modifier] = matchedPlugins
    let isOnlyPlugin = plugins.length === 1

    for (let [sort, plugin] of plugins) {
      let matchesPerPlugin = []

      if (typeof plugin === 'function') {
        for (let ruleSet of [].concat(plugin(modifier, { isOnlyPlugin }))) {
          let [rules, options] = parseRules(ruleSet, context.postCssNodeCache)
          for (let rule of rules) {
            matchesPerPlugin.push([{ ...sort, options: { ...sort.options, ...options } }, rule])
          }
        }
      }
      // Only process static plugins on exact matches
      else if (modifier === 'DEFAULT' || modifier === '-DEFAULT') {
        let ruleSet = plugin
        let [rules, options] = parseRules(ruleSet, context.postCssNodeCache)
        for (let rule of rules) {
          matchesPerPlugin.push([{ ...sort, options: { ...sort.options, ...options } }, rule])
        }
      }

      if (matchesPerPlugin.length > 0) {
        let matchingTypes = Array.from(
          getMatchingTypes(
            sort.options?.types ?? [],
            modifier,
            sort.options ?? {},
            context.tailwindConfig
          )
        ).map(([_, type]) => type)

        if (matchingTypes.length > 0) {
          typesByMatches.set(matchesPerPlugin, matchingTypes)
        }

        matches.push(matchesPerPlugin)
      }
    }

    if (isArbitraryValue(modifier)) {
      if (matches.length > 1) {
        // Partition plugins in 2 categories so that we can start searching in the plugins that
        // don't have `any` as a type first.
        let [withAny, withoutAny] = matches.reduce(
          (group, plugin) => {
            let hasAnyType = plugin.some(([{ options }]) =>
              options.types.some(({ type }) => type === 'any')
            )

            if (hasAnyType) {
              group[0].push(plugin)
            } else {
              group[1].push(plugin)
            }
            return group
          },
          [[], []]
        )

        function findFallback(matches) {
          // If only a single plugin matches, let's take that one
          if (matches.length === 1) {
            return matches[0]
          }

          // Otherwise, find the plugin that creates a valid rule given the arbitrary value, and
          // also has the correct type which preferOnConflicts the plugin in case of clashes.
          return matches.find((rules) => {
            let matchingTypes = typesByMatches.get(rules)
            return rules.some(([{ options }, rule]) => {
              if (!isParsableNode(rule)) {
                return false
              }

              return options.types.some(
                ({ type, preferOnConflict }) => matchingTypes.includes(type) && preferOnConflict
              )
            })
          })
        }

        // Try to find a fallback plugin, because we already know that multiple plugins matched for
        // the given arbitrary value.
        let fallback = findFallback(withoutAny) ?? findFallback(withAny)
        if (fallback) {
          matches = [fallback]
        }

        // We couldn't find a fallback plugin which means that there are now multiple plugins that
        // generated css for the current candidate. This means that the result is ambiguous and this
        // should not happen. We won't generate anything right now, so let's report this to the user
        // by logging some options about what they can do.
        else {
          let typesPerPlugin = matches.map(
            (match) => new Set([...(typesByMatches.get(match) ?? [])])
          )

          // Remove duplicates, so that we can detect proper unique types for each plugin.
          for (let pluginTypes of typesPerPlugin) {
            for (let type of pluginTypes) {
              let removeFromOwnGroup = false

              for (let otherGroup of typesPerPlugin) {
                if (pluginTypes === otherGroup) continue

                if (otherGroup.has(type)) {
                  otherGroup.delete(type)
                  removeFromOwnGroup = true
                }
              }

              if (removeFromOwnGroup) pluginTypes.delete(type)
            }
          }

          let messages = []

          for (let [idx, group] of typesPerPlugin.entries()) {
            for (let type of group) {
              let rules = matches[idx]
                .map(([, rule]) => rule)
                .flat()
                .map((rule) =>
                  rule
                    .toString()
                    .split('\n')
                    .slice(1, -1) // Remove selector and closing '}'
                    .map((line) => line.trim())
                    .map((x) => `      ${x}`) // Re-indent
                    .join('\n')
                )
                .join('\n\n')

              messages.push(
                `  Use \`${candidate.replace('[', `[${type}:`)}\` for \`${rules.trim()}\``
              )
              break
            }
          }

          log.warn([
            `The class \`${candidate}\` is ambiguous and matches multiple utilities.`,
            ...messages,
            `If this is content and not a class, replace it with \`${candidate
              .replace('[', '&lsqb;')
              .replace(']', '&rsqb;')}\` to silence this warning.`,
          ])
          continue
        }
      }

      matches = matches.map((list) => list.filter((match) => isParsableNode(match[1])))
    }

    matches = matches.flat()
    matches = Array.from(recordCandidates(matches, classCandidate))
    matches = applyPrefix(matches, context)

    if (important) {
      matches = applyImportant(matches, classCandidate)
    }

    for (let variant of variants) {
      matches = applyVariant(variant, matches, context)
    }

    for (let match of matches) {
      match[1].raws.tailwind = { ...match[1].raws.tailwind, candidate }

      // Apply final format selector
      if (match[0].collectedFormats) {
        let finalFormat = formatVariantSelector('&', ...match[0].collectedFormats)
        let container = postcss.root({ nodes: [match[1].clone()] })
        container.walkRules((rule) => {
          if (inKeyframes(rule)) return

          rule.selector = finalizeSelector(finalFormat, {
            selector: rule.selector,
            candidate: original,
            base: candidate
              .split(new RegExp(`\\${context?.tailwindConfig?.separator ?? ':'}(?![^[]*\\])`))
              .pop(),
            isArbitraryVariant: match[0].isArbitraryVariant,

            context,
          })
        })
        match[1] = container.nodes[0]
      }

      yield match
    }
  }
}

function inKeyframes(rule) {
  return rule.parent && rule.parent.type === 'atrule' && rule.parent.name === 'keyframes'
}

function getImportantStrategy(important) {
  if (important === true) {
    return (rule) => {
      if (inKeyframes(rule)) {
        return
      }

      rule.walkDecls((d) => {
        if (d.parent.type === 'rule' && !inKeyframes(d.parent)) {
          d.important = true
        }
      })
    }
  }

  if (typeof important === 'string') {
    return (rule) => {
      if (inKeyframes(rule)) {
        return
      }

      rule.selectors = rule.selectors.map((selector) => {
        return `${important} ${selector}`
      })
    }
  }
}

function generateRules(candidates, context) {
  let allRules = []
  let strategy = getImportantStrategy(context.tailwindConfig.important)

  for (let candidate of candidates) {
    if (context.notClassCache.has(candidate)) {
      continue
    }

    if (context.candidateRuleCache.has(candidate)) {
      allRules = allRules.concat(Array.from(context.candidateRuleCache.get(candidate)))
      continue
    }

    let matches = Array.from(resolveMatches(candidate, context))

    if (matches.length === 0) {
      context.notClassCache.add(candidate)
      continue
    }

    context.classCache.set(candidate, matches)

    let rules = context.candidateRuleCache.get(candidate) ?? new Set()
    context.candidateRuleCache.set(candidate, rules)

    for (const match of matches) {
      let [{ sort, options }, rule] = match

      if (options.respectImportant && strategy) {
        let container = postcss.root({ nodes: [rule.clone()] })
        container.walkRules(strategy)
        rule = container.nodes[0]
      }

      let newEntry = [sort, rule]
      rules.add(newEntry)
      context.ruleCache.add(newEntry)
      allRules.push(newEntry)
    }
  }

  return allRules
}

function isArbitraryValue(input) {
  return input.startsWith('[') && input.endsWith(']')
}

export { resolveMatches, generateRules }