ronantakizawa/codereview-bench huggingface dataset:
Repository: tailwindlabs/tailwindcss
File: packages/tailwindcss/src/utilities.test.ts (TypeScript)

Code before:
    compileCss(
      css`
        @theme {
          --perspective-dramatic: 100px;
          --perspective-normal: 500px;
        }
        @tailwind utilities;
      `,
      [
        'perspective-normal',
        'perspective-dramatic',
        'perspective-none',
        'perspective-123',
        'perspective-[456px]',
      ],
    ),
  ).toMatchInlineSnapshot(`
    ":root {
      --perspective-dramatic: 100px;
      --perspective-normal: 500px;
    }

    .perspective-\\[456px\\] {
      perspective: 456px;
    }

    .perspective-dramatic {
      perspective: 100px;
    }

    .perspective-none {
      perspective: none;
    }

    .perspective-normal {
      perspective: 500px;
    }"
  `)
  expect(run(['perspective', '-perspective', 'perspective-potato'])).toEqual('')
})

test('cursor', () => {
  expect(
    compileCss(
      css`
        @theme {
          --cursor-custom: url(/my-cursor.png);
        }
        @tailwind utilities;
      `,
      [

Review comment (suggestion):
I think we should move the `perspective-123` example to the expect below where we explicitly test that it doesn't generate anything.

Code after:
    compileCss(
      css`
        @theme {
          --perspective-dramatic: 100px;
          --perspective-normal: 500px;
        }
        @tailwind utilities;
      `,
      ['perspective-normal', 'perspective-dramatic', 'perspective-none', 'perspective-[456px]'],
    ),
  ).toMatchInlineSnapshot(`
    ":root {
      --perspective-dramatic: 100px;
      --perspective-normal: 500px;
    }

    .perspective-\\[456px\\] {
      perspective: 456px;
    }

    .perspective-dramatic {
      perspective: 100px;
    }

    .perspective-none {
      perspective: none;
    }

    .perspective-normal {
      perspective: 500px;
    }"
  `)
  expect(run(['perspective', '-perspective', 'perspective-potato', 'perspective-123'])).toEqual('')
})

test('cursor', () => {
  expect(
    compileCss(
      css`
        @theme {
          --cursor-custom: url(/my-cursor.png);
        }
        @tailwind utilities;
      `,
      [
        'cursor-auto',
        'cursor-default',
        'cursor-pointer',
        'cursor-wait',
        'cursor-text',
        'cursor-move',
Repository: tailwindlabs/tailwindcss
File: packages/tailwindcss/src/utilities.ts (TypeScript)

Code before:

    if (value === null) return

    return [skewProperties(), decl('transform', value)]
  })
  suggest('transform', () => [
    {
      hasDefaultValue: true,
    },
  ])

  staticUtility('transform-cpu', [
    ['transform', 'translate(0, 0) var(--tw-skew-x,) var(--tw-skew-y,)'],
  ])
  staticUtility('transform-gpu', [
    ['transform', 'translate3d(0, 0, 0) var(--tw-skew-x,) var(--tw-skew-y,)'],
  ])
  staticUtility('transform-none', [
    ['translate', 'none'],
    ['rotate', 'none'],
    ['scale', 'none'],
    ['transform', 'none'],
  ])

  /**
   * @css `transform-style`
   */
  staticUtility('transform-flat', [['transform-style', 'flat']])
  staticUtility('transform-3d', [['transform-style', 'preserve-3d']])

  /**
   * @css `transform-box`
   */
  staticUtility('transform-content', [['transform-box', 'content-box']])
  staticUtility('transform-border', [['transform-box', 'border-box']])
  staticUtility('transform-fill', [['transform-box', 'fill-box']])
  staticUtility('transform-stroke', [['transform-box', 'stroke-box']])
  staticUtility('transform-view', [['transform-box', 'view-box']])

  /**
   * @css `backface-visibility`
   */
  staticUtility('backface-visible', [['backface-visibility', 'visible']])
  staticUtility('backface-hidden', [['backface-visibility', 'hidden']])

  /**
   * @css `cursor`
   */
  for (let value of [
    'auto',
    'default',

Review comment (suggestion):
This could probably be an `else` with `null` dropped from type.

Code after:
    ['scale', 'var(--tw-scale-x) var(--tw-scale-y) var(--tw-scale-z)'],
  ])

  /**
   * @css `perspective`
   */
  staticUtility('perspective-none', [['perspective', 'none']])
  functionalUtility('perspective', {
    themeKeys: ['--perspective'],
    handle: (value) => [decl('perspective', value)],
  })

  /**
   * @css `transform`
   */
  utilities.functional('transform', (candidate) => {
    if (candidate.negative) return

    let value: string | null = null
    if (!candidate.value) {
      value = 'var(--tw-skew-x) var(--tw-skew-y)'
    } else if (candidate.value.kind === 'arbitrary') {
      value = candidate.value.value
    }

    if (value === null) return

    return [skewProperties(), decl('transform', value)]
  })
  suggest('transform', () => [
    {
      hasDefaultValue: true,
    },
  ])

  staticUtility('transform-cpu', [['transform', 'var(--tw-skew-x) var(--tw-skew-y)']])
  staticUtility('transform-gpu', [['transform', 'translateZ(0) var(--tw-skew-x) var(--tw-skew-y)']])
  staticUtility('transform-none', [['transform', 'none']])

  /**
   * @css `transform-style`
   */
  staticUtility('transform-flat', [['transform-style', 'flat']])
  staticUtility('transform-3d', [['transform-style', 'preserve-3d']])

  /**
   * @css `transform-box`
   */
  staticUtility('transform-content', [['transform-box', 'content-box']])
  staticUtility('transform-border', [['transform-box', 'border-box']])
  staticUtility('transform-fill', [['transform-box', 'fill-box']])
Repository: tailwindlabs/tailwindcss
File: packages/tailwindcss/src/theme.ts (TypeScript)

Code before:
  | '--max-width'
  | '--min-height'
  | '--min-width'
  | '--object-position'
  | '--opacity'
  | '--order'
  | '--outline-color'
  | '--outline-width'
  | '--outline-offset'
  | '--padding'
  | '--placeholder-color'
  | '--perspective'
  | '--perspective-origin'
  | '--radius'
  | '--ring-color'
  | '--ring-offset-color'
  | '--ring-offset-width'
  | '--ring-width'
  | '--rotate'
  | '--saturate'
  | '--scale'
  | '--scroll-margin'
  | '--scroll-padding'
  | '--sepia'
  | '--shadow'
  | `--shadow-${string}`
  | '--size'
  | '--skew'
  | '--space'
  | '--spacing'
  | '--stroke'
  | '--stroke-width'
  | '--text-color'
  | '--text-decoration-color'
  | '--text-decoration-thickness'
  | '--text-indent'
  | '--text-underline-offset'
  | '--transform-origin'
  | '--transition-delay'
  | '--transition-duration'
  | '--transition-property'
  | '--transition-timing-function'
  | '--translate'
  | '--width'
  | '--z-index'

export type ColorThemeKey =
  | '--color'
  | '--accent-color'
  | '--background-color'
  | '--border-color'

Review comment (suggestion):
I think a better way of doing this would be to update the `get` function instead:

```diff
-  get(themeKeys: ThemeKey[]): string | null {
+  get(themeKeys: (ThemeKey | `${ThemeKey}-${string}`)[]): string | null {
```

That way you get this for free for every theme key, but only when using `theme.get(…)`

Code after:
  | '--min-height'
  | '--min-width'
  | '--object-position'
  | '--opacity'
  | '--order'
  | '--outline-color'
  | '--outline-width'
  | '--outline-offset'
  | '--padding'
  | '--placeholder-color'
  | '--perspective'
  | '--perspective-origin'
  | '--radius'
  | '--ring-color'
  | '--ring-offset-color'
  | '--ring-offset-width'
  | '--ring-width'
  | '--rotate'
  | '--saturate'
  | '--scale'
  | '--scroll-margin'
  | '--scroll-padding'
  | '--sepia'
  | '--shadow'
  | '--size'
  | '--skew'
  | '--space'
  | '--spacing'
  | '--stroke'
  | '--stroke-width'
  | '--text-color'
  | '--text-decoration-color'
  | '--text-decoration-thickness'
  | '--text-indent'
  | '--text-underline-offset'
  | '--transform-origin'
  | '--transition-delay'
  | '--transition-duration'
  | '--transition-property'
  | '--transition-timing-function'
  | '--translate'
  | '--width'
  | '--z-index'

export type ColorThemeKey =
  | '--color'
  | '--accent-color'
  | '--background-color'
  | '--border-color'
  | '--box-shadow-color'
  | '--caret-color'
Repository: tailwindlabs/tailwindcss
File: packages/tailwindcss/src/variants.test.ts (TypeScript)

Code before:
    }

    .nth-last-\\[2n\\+1_of_\\.foo\\]\\:flex:nth-last-child(odd of .foo) {
      display: flex;
    }

    .nth-of-type-3\\:flex:nth-of-type(3) {
      display: flex;
    }

    .nth-of-type-\\[2n\\+1\\]\\:flex:nth-of-type(odd) {
      display: flex;
    }

    .nth-last-of-type-3\\:flex:nth-last-of-type(3) {
      display: flex;
    }

    .nth-last-of-type-\\[2n\\+1\\]\\:flex:nth-last-of-type(odd) {
      display: flex;
    }"
  `)

  expect(
    run(['nth-foo:flex', 'nth-of-type-foo:flex', 'nth-last-foo:flex', 'nth-last-of-type-foo:flex']),
  ).toMatchInlineSnapshot(`""`)
})

test('container queries', () => {
  expect(
    compileCss(
      css`
        @theme {
          --width-lg: 1024px;
        }
        @tailwind utilities;
      `,
      [
        '@lg:flex',
        '@lg/name:flex',
        '@[123px]:flex',
        '@[456px]/name:flex',

        '@min-lg:flex',
        '@min-lg/name:flex',
        '@min-[123px]:flex',
        '@min-[456px]/name:flex',

        '@max-lg:flex',
        '@max-lg/name:flex',
        '@max-[123px]:flex',

Review comment (suggestion):
Nit: let's use `.toEqual('')` instead, that way it's similar to the other cases and that way we guarantee that we never accidentally update a snapshot (if it starts producing results all of a sudden)

Code after:
    }

    .nth-last-\\[2n\\+1_of_\\.foo\\]\\:flex:nth-last-child(odd of .foo) {
      display: flex;
    }

    .nth-of-type-3\\:flex:nth-of-type(3) {
      display: flex;
    }

    .nth-of-type-\\[2n\\+1\\]\\:flex:nth-of-type(odd) {
      display: flex;
    }

    .nth-last-of-type-3\\:flex:nth-last-of-type(3) {
      display: flex;
    }

    .nth-last-of-type-\\[2n\\+1\\]\\:flex:nth-last-of-type(odd) {
      display: flex;
    }"
  `)

  expect(
    run(['nth-foo:flex', 'nth-of-type-foo:flex', 'nth-last-foo:flex', 'nth-last-of-type-foo:flex']),
  ).toEqual('')
})

test('container queries', () => {
  expect(
    compileCss(
      css`
        @theme {
          --width-lg: 1024px;
        }
        @tailwind utilities;
      `,
      [
        '@lg:flex',
        '@lg/name:flex',
        '@[123px]:flex',
        '@[456px]/name:flex',

        '@min-lg:flex',
        '@min-lg/name:flex',
        '@min-[123px]:flex',
        '@min-[456px]/name:flex',

        '@max-lg:flex',
        '@max-lg/name:flex',
        '@max-[123px]:flex',
Repository: tailwindlabs/tailwindcss
File: packages/tailwindcss/src/compile.ts (TypeScript)

Code before:
  }
}

export function compileAstNodes(rawCandidate: string, designSystem: DesignSystem) {
  let candidate = designSystem.parseCandidate(rawCandidate)
  if (candidate === null) return null

  let nodes: AstNode[] = []

  // Handle arbitrary properties
  if (candidate.kind === 'arbitrary') {
    let compileFn = designSystem.utilities.getArbitrary()

    // Build the node
    let compiledNodes = compileFn(candidate)
    if (compiledNodes === undefined) return null

    nodes = compiledNodes
  }

  // Handle named utilities
  else if (candidate.kind === 'static' || candidate.kind === 'functional') {
    // Safety: At this point it is safe to use TypeScript's non-null assertion
    // operator because if the `candidate.root` didn't exist, `parseCandidate`
    // would have returned `null` and we would have returned early resulting
    // in not hitting this code path.
    let fns = designSystem.utilities.get(candidate.root)

    // Build the node
    let compiledNodes: AstNode[] | undefined

    for (let i = fns.length - 1; i >= 0; i--) {
      let fn = fns[i]

      if (candidate.kind !== fn.kind) continue

      compiledNodes = fn.compileFn(candidate)
      if (compiledNodes) break
    }

    if (compiledNodes === undefined) return null

    nodes = compiledNodes
  }

  let propertySort = getPropertySort(nodes)

  if (candidate.important) {
    applyImportant(nodes)
  }


Review comment (suggestion):
You removed the non-null assertion operator so I think the comment above can also be removed now :)


```suggestion
```

(This doesn't allow me to suggestion the deletion of all 4 lines though so you have to do so manually)


Code after:
  }
}

export function compileAstNodes(rawCandidate: string, designSystem: DesignSystem) {
  let candidate = designSystem.parseCandidate(rawCandidate)
  if (candidate === null) return null

  let nodes: AstNode[] = []

  // Handle arbitrary properties
  if (candidate.kind === 'arbitrary') {
    let compileFn = designSystem.utilities.getArbitrary()

    // Build the node
    let compiledNodes = compileFn(candidate)
    if (compiledNodes === undefined) return null

    nodes = compiledNodes
  }

  // Handle named utilities
  else if (candidate.kind === 'static' || candidate.kind === 'functional') {
    let fns = designSystem.utilities.get(candidate.root)

    // Build the node
    let compiledNodes: AstNode[] | undefined

    for (let i = fns.length - 1; i >= 0; i--) {
      let fn = fns[i]

      if (candidate.kind !== fn.kind) continue

      compiledNodes = fn.compileFn(candidate)
      if (compiledNodes) break
    }

    if (compiledNodes === undefined) return null

    nodes = compiledNodes
  }

  let propertySort = getPropertySort(nodes)

  if (candidate.important) {
    applyImportant(nodes)
  }

  let node: Rule = {
    kind: 'rule',
    selector: `.${escape(rawCandidate)}`,
    nodes,
Repository: tailwindlabs/tailwindcss
File: packages/tailwindcss/src/utilities.ts (TypeScript)

Code before:
export class Utilities {
  private arbitraryFn!: CompileFn<'arbitrary'>
  private utilities = new DefaultMap<
    string,
    {
      kind: 'static' | 'functional'
      compileFn: CompileFn<any>
    }[]
  >(() => [])

  private completions = new Map<string, () => SuggestionGroup[]>()

  static(name: string, compileFn: CompileFn<'static'>) {
    this.utilities.get(name).push({ kind: 'static', compileFn })
  }

  functional(name: string, compileFn: CompileFn<'functional'>) {
    this.utilities.get(name).push({ kind: 'functional', compileFn })
  }

  arbitrary(compileFn: CompileFn<'arbitrary'>) {
    this.arbitraryFn = compileFn
  }

  has(name: string, kind: 'static' | 'functional') {
    return this.utilities.has(name) && this.utilities.get(name).some((fn) => fn.kind === kind)
  }

  get(name: string) {
    return this.utilities.has(name) ? this.utilities.get(name) : []
  }

  getCompletions(name: string): SuggestionGroup[] {
    return this.completions.get(name)?.() ?? []
  }

  suggest(name: string, groups: () => SuggestionGroup[]) {
    // TODO: We are calling this multiple times on purpose but ideally only ever
    // once per utility root.
    this.completions.set(name, groups)
  }

  keys(kind: 'static' | 'functional') {
    return Array.from(this.utilities.keys()).filter((key) => this.has(key, kind))
  }

  getArbitrary() {
    return this.arbitraryFn
  }
}


Review comment (suggestion):
Q: Does it make sense to store the utilities on a per-kind basis? This way we can do the lookup once and don't need to do the `.some()` part ever 🤔

Code after:
export class Utilities {
  private arbitraryFn!: CompileFn<'arbitrary'>
  private utilities = new DefaultMap<
    string,
    {
      kind: 'static' | 'functional'
      compileFn: CompileFn<any>
    }[]
  >(() => [])

  private completions = new Map<string, () => SuggestionGroup[]>()

  static(name: string, compileFn: CompileFn<'static'>) {
    this.utilities.get(name).push({ kind: 'static', compileFn })
  }

  functional(name: string, compileFn: CompileFn<'functional'>) {
    this.utilities.get(name).push({ kind: 'functional', compileFn })
  }

  arbitrary(compileFn: CompileFn<'arbitrary'>) {
    this.arbitraryFn = compileFn
  }

  has(name: string, kind: 'static' | 'functional') {
    return this.utilities.has(name) && this.utilities.get(name).some((fn) => fn.kind === kind)
  }

  get(name: string) {
    return this.utilities.has(name) ? this.utilities.get(name) : []
  }

  getCompletions(name: string): SuggestionGroup[] {
    return this.completions.get(name)?.() ?? []
  }

  suggest(name: string, groups: () => SuggestionGroup[]) {
    // TODO: We are calling this multiple times on purpose but ideally only ever
    // once per utility root.
    this.completions.set(name, groups)
  }

  keys(kind: 'static' | 'functional') {
    let keys: string[] = []

    for (let [key, fns] of this.utilities.entries()) {
      for (let fn of fns) {
        if (fn.kind === kind) {
          keys.push(key)
          break
        }
Repository: tailwindlabs/tailwindcss
File: packages/internal-postcss-fix-relative-paths/src/index.ts (TypeScript)

Code before:
import path from 'node:path'
import type { AtRule, Plugin } from 'postcss'

const SINGLE_QUOTE = "'"
const DOUBLE_QUOTE = '"'

export default function fixRelativePathsPlugin(): Plugin {
  // Retain a list of touched at-rules to avoid infinite loops
  let touched: WeakSet<AtRule> = new WeakSet()

  function fixRelativePath(atRule: AtRule) {
    let rootPath = atRule.root().source?.input.file
    if (!rootPath) {
      return
    }

    let inputFilePath = atRule.source?.input.file
    if (!inputFilePath) {
      return
    }

    if (touched.has(atRule)) {
      return
    }

    let value = atRule.params[0]

    let quote =
      value[0] === DOUBLE_QUOTE && value[value.length - 1] === DOUBLE_QUOTE
        ? DOUBLE_QUOTE
        : value[0] === SINGLE_QUOTE && value[value.length - 1] === SINGLE_QUOTE
          ? SINGLE_QUOTE
          : null
    if (!quote) {
      return
    }
    let glob = atRule.params.slice(1, -1)


Review comment (suggestion):
I simplified this. `Node` has a `root()` method that walks up the tree for you.

It also stops at Root instead of a Document (an optional parent node of Root)

Code after:
import path from 'node:path'
import type { AtRule, Plugin } from 'postcss'
import { normalizePath } from './normalize-path'

const SINGLE_QUOTE = "'"
const DOUBLE_QUOTE = '"'

export default function fixRelativePathsPlugin(): Plugin {
  // Retain a list of touched at-rules to avoid infinite loops
  let touched: WeakSet<AtRule> = new WeakSet()

  function fixRelativePath(atRule: AtRule) {
    let rootPath = atRule.root().source?.input.file
    if (!rootPath) {
      return
    }

    let inputFilePath = atRule.source?.input.file
    if (!inputFilePath) {
      return
    }

    if (touched.has(atRule)) {
      return
    }

    let value = atRule.params[0]

    let quote =
      value[0] === DOUBLE_QUOTE && value[value.length - 1] === DOUBLE_QUOTE
        ? DOUBLE_QUOTE
        : value[0] === SINGLE_QUOTE && value[value.length - 1] === SINGLE_QUOTE
          ? SINGLE_QUOTE
          : null
    if (!quote) {
      return
    }
    let glob = atRule.params.slice(1, -1)
Repository: tailwindlabs/tailwindcss
File: packages/internal-postcss-fix-relative-paths/src/index.ts (TypeScript)

Code before:
import path from 'node:path'
import type { AtRule, Plugin } from 'postcss'

const SINGLE_QUOTE = "'"
const DOUBLE_QUOTE = '"'

export default function fixRelativePathsPlugin(): Plugin {
  // Retain a list of touched at-rules to avoid infinite loops
  let touched: WeakSet<AtRule> = new WeakSet()

  function fixRelativePath(atRule: AtRule) {
    let rootPath = atRule.root().source?.input.file
    if (!rootPath) {
      return
    }

    let inputFilePath = atRule.source?.input.file
    if (!inputFilePath) {
      return
    }

    if (touched.has(atRule)) {
      return
    }

    let value = atRule.params[0]

    let quote =
      value[0] === DOUBLE_QUOTE && value[value.length - 1] === DOUBLE_QUOTE
        ? DOUBLE_QUOTE
        : value[0] === SINGLE_QUOTE && value[value.length - 1] === SINGLE_QUOTE
          ? SINGLE_QUOTE
          : null
    if (!quote) {
      return
    }
    let glob = atRule.params.slice(1, -1)

    // Handle eventual negative rules. We only support one level of negation.
    let negativePrefix = ''
    if (glob.startsWith('!')) {
      glob = glob.slice(1)
      negativePrefix = '!'

Review comment (suggestion):
`atRule` isn't nullable so one of the `?` could be removed

Code after:
import path from 'node:path'
import type { AtRule, Plugin } from 'postcss'
import { normalizePath } from './normalize-path'

const SINGLE_QUOTE = "'"
const DOUBLE_QUOTE = '"'

export default function fixRelativePathsPlugin(): Plugin {
  // Retain a list of touched at-rules to avoid infinite loops
  let touched: WeakSet<AtRule> = new WeakSet()

  function fixRelativePath(atRule: AtRule) {
    let rootPath = atRule.root().source?.input.file
    if (!rootPath) {
      return
    }

    let inputFilePath = atRule.source?.input.file
    if (!inputFilePath) {
      return
    }

    if (touched.has(atRule)) {
      return
    }

    let value = atRule.params[0]

    let quote =
      value[0] === DOUBLE_QUOTE && value[value.length - 1] === DOUBLE_QUOTE
        ? DOUBLE_QUOTE
        : value[0] === SINGLE_QUOTE && value[value.length - 1] === SINGLE_QUOTE
          ? SINGLE_QUOTE
          : null
    if (!quote) {
      return
    }
    let glob = atRule.params.slice(1, -1)

    // Handle eventual negative rules. We only support one level of negation.
    let negativePrefix = ''
    if (glob.startsWith('!')) {
      glob = glob.slice(1)
Repository: tailwindlabs/tailwindcss
File: packages/internal-postcss-fix-relative-paths/src/index.ts (TypeScript)

Code before:
import path from 'node:path'
import type { AtRule, Container, Plugin } from 'postcss'

const SINGLE_QUOTE = "'"
const DOUBLE_QUOTE = '"'

export default function fixRelativePathsPlugin(): Plugin {
  // Retain a list of touched at-rules to avoid infinite loops
  let touched: WeakSet<AtRule> = new WeakSet()

  function fixRelativePath(atRule: AtRule) {
    let rootPath = getRoot(atRule)?.source?.input.file
    if (!rootPath) {
      return
    }

    let inputFilePath = atRule?.source?.input.file
    if (!inputFilePath) {
      return
    }

    if (touched.has(atRule)) {
      return
    }

    let value = atRule.params[0]

    let quote =

Review comment (suggestion):
I inlined a corrected version of the `normalize-path` NPM package (specifically regarding network shares and UNC paths) and used that method to cleanup the code slightly.

Code after:
import path from 'node:path'
import type { AtRule, Plugin } from 'postcss'
import { normalizePath } from './normalize-path'

const SINGLE_QUOTE = "'"
const DOUBLE_QUOTE = '"'

export default function fixRelativePathsPlugin(): Plugin {
  // Retain a list of touched at-rules to avoid infinite loops
  let touched: WeakSet<AtRule> = new WeakSet()

  function fixRelativePath(atRule: AtRule) {
    let rootPath = atRule.root().source?.input.file
    if (!rootPath) {
      return
    }

    let inputFilePath = atRule.source?.input.file
    if (!inputFilePath) {
      return
    }

    if (touched.has(atRule)) {
      return
    }

    let value = atRule.params[0]