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

Code before:

          keys.push(key.slice(namespace.length))
        }
      }
    }

    return keys
  }

  get(themeKeys: (ThemeKey | `${ThemeKey}-${string}`)[]): string | null {
    for (let key of themeKeys) {
      let value = this.values.get(key)
      if (value) {
        return value.value
      }
    }

    return null
  }

  hasDefault(key: string): boolean {
    return ((this.values.get(key)?.options ?? 0) & ThemeOptions.DEFAULT) === ThemeOptions.DEFAULT
  }

  getOptions(key: string) {
    return this.values.get(key)?.options ?? 0
  }

  entries() {
    return this.values.entries()
  }

  #clearNamespace(namespace: string) {
    for (let key of this.values.keys()) {
      if (key.startsWith(namespace)) {
        this.values.delete(key)
      }
    }
  }

  #resolveKey(candidateValue: string | null, themeKeys: ThemeKey[]): string | null {
    for (let key of themeKeys) {
      let themeKey =
        candidateValue !== null ? escape(`${key}-${candidateValue.replaceAll('.', '_')}`) : key

      if (this.values.has(themeKey)) {
        return themeKey
      }
    }

    return null

Review comment (suggestion):
This might be better for readability:
```suggestion
    return this.values.get(key)?.options ?? ThemeOptions.NONE
```

Code after:

          keys.push(key.slice(namespace.length))
        }
      }
    }

    return keys
  }

  get(themeKeys: (ThemeKey | `${ThemeKey}-${string}`)[]): string | null {
    for (let key of themeKeys) {
      let value = this.values.get(key)
      if (value) {
        return value.value
      }
    }

    return null
  }

  hasDefault(key: string): boolean {
    return (this.getOptions(key) & ThemeOptions.DEFAULT) === ThemeOptions.DEFAULT
  }

  getOptions(key: string) {
    return this.values.get(key)?.options ?? ThemeOptions.NONE
  }

  entries() {
    return this.values.entries()
  }

  #clearNamespace(namespace: string) {
    for (let key of this.values.keys()) {
      if (key.startsWith(namespace)) {
        this.values.delete(key)
      }
    }
  }

  #resolveKey(candidateValue: string | null, themeKeys: ThemeKey[]): string | null {
    for (let key of themeKeys) {
      let themeKey =
        candidateValue !== null ? escape(`${key}-${candidateValue.replaceAll('.', '_')}`) : key

      if (this.values.has(themeKey)) {
        return themeKey
      }
    }

    return null
Repository: tailwindlabs/tailwindcss
File: packages/tailwindcss/src/index.ts (TypeScript)

Code before:
        tailwindUtilitiesNode.nodes = newNodes
        compiledCss = toCss(ast)
      }

      return compiledCss
    },
  }
}

export async function __unstable__loadDesignSystem(css: string, opts: CompileOptions = {}) {
  let result = await parseCss(css, opts)
  return result.designSystem
}

function getVersion() {
  if (process.env.VERSION) {
    return process.env.VERSION
  } else {
    return version
  }
}

export default function postcssPluginWarning() {
  throw new Error(`It looks like you're trying to use the \`tailwindcss\` package as a PostCSS plugin. This is no longer possible since Tailwind CSS v4.

If you want to continue to use Tailwind CSS with PostCSS, please install \`@tailwindcss/postcss\` and change your PostCSS config file.`)
}


Review comment (suggestion):
```suggestion
  throw new Error(`It looks like you're trying to use \`tailwindcss\` directly as a PostCSS plugin. The PostCSS plugin has moved to a separate package, so to continue using Tailwind CSS with PostCSS you'll need to install \`@tailwindcss/postcss\` and update your PostCSS configuration.`)
```

Code after:
        tailwindUtilitiesNode.nodes = newNodes
        compiledCss = toCss(ast)
      }

      return compiledCss
    },
  }
}

export async function __unstable__loadDesignSystem(css: string, opts: CompileOptions = {}) {
  let result = await parseCss(css, opts)
  return result.designSystem
}

function getVersion() {
  if (process.env.VERSION) {
    return process.env.VERSION
  } else {
    return version
  }
}

export default function postcssPluginWarning() {
  throw new Error(
    `It looks like you're trying to use \`tailwindcss\` directly as a PostCSS plugin. The PostCSS plugin has moved to a separate package, so to continue using Tailwind CSS with PostCSS you'll need to install \`@tailwindcss/postcss\` and update your PostCSS configuration.`,
  )
}
Repository: tailwindlabs/tailwindcss
File: packages/tailwindcss/src/utilities.ts (TypeScript)

Code before:
      ['contain', cssContainValue],
    ])

    functionalUtility('contain', {
      themeKeys: [],
      handle: (value) => [decl('contain', value)],
    })
  }

  staticUtility('forced-color-adjust-none', [['forced-color-adjust', 'none']])
  staticUtility('forced-color-adjust-auto', [['forced-color-adjust', 'auto']])

  functionalUtility('leading', {
    themeKeys: ['--line-height'],
    handle: (value) => [
      atRoot([property('--tw-leading')]),
      decl('--tw-leading', value),
      decl('line-height', value),
    ],
  })

  functionalUtility('tracking', {
    supportsNegative: true,
    themeKeys: ['--letter-spacing'],
    handle: (value) => [
      atRoot([property('--tw-leading')]),
      decl('--tw-tracking', value),
      decl('letter-spacing', value),
    ],
  })

  staticUtility('antialiased', [
    ['-webkit-font-smoothing', 'antialiased'],
    ['-moz-osx-font-smoothing', 'grayscale'],
  ])

  staticUtility('subpixel-antialiased', [
    ['-webkit-font-smoothing', 'auto'],
    ['-moz-osx-font-smoothing', 'auto'],
  ])

  {
    let cssFontVariantNumericValue =
      'var(--tw-ordinal,) var(--tw-slashed-zero,) var(--tw-numeric-figure,) var(--tw-numeric-spacing,) var(--tw-numeric-fraction,)'
    let fontVariantNumericProperties = () => {
      return atRoot([
        property('--tw-ordinal'),
        property('--tw-slashed-zero'),
        property('--tw-numeric-figure'),
        property('--tw-numeric-spacing'),
        property('--tw-numeric-fraction'),

Review comment (suggestion):
```suggestion
      atRoot([property('--tw-tracking')]),
```

Code after:
      ['contain', cssContainValue],
    ])

    functionalUtility('contain', {
      themeKeys: [],
      handle: (value) => [decl('contain', value)],
    })
  }

  staticUtility('forced-color-adjust-none', [['forced-color-adjust', 'none']])
  staticUtility('forced-color-adjust-auto', [['forced-color-adjust', 'auto']])

  functionalUtility('leading', {
    themeKeys: ['--line-height'],
    handle: (value) => [
      atRoot([property('--tw-leading')]),
      decl('--tw-leading', value),
      decl('line-height', value),
    ],
  })

  functionalUtility('tracking', {
    supportsNegative: true,
    themeKeys: ['--letter-spacing'],
    handle: (value) => [
      atRoot([property('--tw-tracking')]),
      decl('--tw-tracking', value),
      decl('letter-spacing', value),
    ],
  })

  staticUtility('antialiased', [
    ['-webkit-font-smoothing', 'antialiased'],
    ['-moz-osx-font-smoothing', 'grayscale'],
  ])

  staticUtility('subpixel-antialiased', [
    ['-webkit-font-smoothing', 'auto'],
    ['-moz-osx-font-smoothing', 'auto'],
  ])

  {
    let cssFontVariantNumericValue =
      'var(--tw-ordinal,) var(--tw-slashed-zero,) var(--tw-numeric-figure,) var(--tw-numeric-spacing,) var(--tw-numeric-fraction,)'
    let fontVariantNumericProperties = () => {
      return atRoot([
        property('--tw-ordinal'),
        property('--tw-slashed-zero'),
        property('--tw-numeric-figure'),
        property('--tw-numeric-spacing'),
        property('--tw-numeric-fraction'),
Repository: tailwindlabs/tailwindcss
File: packages/tailwindcss/src/compat/config.test.ts (TypeScript)

Code before:

  let compiler = await compile(input, {
    loadConfig: async () => ({
      theme: {
        extend: {
          aria: {
            polite: 'live="polite"',
          },
          supports: {
            'child-combinator': 'h2 > p',
          },
          data: {
            checked: 'ui~="checked"',
          },
        },
      },
    }),
  })

  expect(
    compiler.build([
      'aria-polite:underline',
      'supports-child-combinator:underline',
      'data-checked:underline',

      // Ensure core utility still works
      'aria-hidden:flex',
      'supports-grid:flex',
      'data-foo:flex',

      // print variants should be at the end, like it is in the core utility
      'print:flex',
    ]),
  ).toMatchInlineSnapshot(`
    ".aria-polite\\:underline {
      &[aria-live="polite"] {
        text-decoration-line: underline;
      }
    }
    .aria-hidden\\:flex {
      &[aria-hidden="true"] {
        display: flex;
      }
    }
    .data-checked\\:underline {
      &[data-ui~="checked"] {
        text-decoration-line: underline;
      }
    }
    .data-foo\\:flex {
      &[data-foo] {

Review comment (suggestion):
```suggestion
      // Ensure core variants still work
```

Code after:

  let compiler = await compile(input, {
    loadConfig: async () => ({
      theme: {
        extend: {
          aria: {
            polite: 'live="polite"',
          },
          supports: {
            'child-combinator': 'selector(h2 > p)',
            foo: 'bar',
          },
          data: {
            checked: 'ui~="checked"',
          },
        },
      },
    }),
  })

  expect(
    compiler.build([
      'aria-polite:underline',
      'supports-child-combinator:underline',
      'supports-foo:underline',
      'data-checked:underline',

      // Ensure core variants still work
      'aria-hidden:flex',
      'supports-grid:flex',
      'data-foo:flex',

      // The `print` variant should still be sorted last, even after registering
      // the other custom variants.
      'print:flex',
    ]),
  ).toMatchInlineSnapshot(`
    ".aria-polite\\:underline {
      &[aria-live="polite"] {
        text-decoration-line: underline;
      }
    }
    .aria-hidden\\:flex {
      &[aria-hidden="true"] {
        display: flex;
      }
    }
    .data-checked\\:underline {
      &[data-ui~="checked"] {
        text-decoration-line: underline;
      }
Repository: tailwindlabs/tailwindcss
File: packages/tailwindcss/src/compat/config.test.ts (TypeScript)

Code before:
          aria: {
            polite: 'live="polite"',
          },
          supports: {
            'child-combinator': 'h2 > p',
          },
          data: {
            checked: 'ui~="checked"',
          },
        },
      },
    }),
  })

  expect(
    compiler.build([
      'aria-polite:underline',
      'supports-child-combinator:underline',
      'data-checked:underline',

      // Ensure core utility still works
      'aria-hidden:flex',
      'supports-grid:flex',
      'data-foo:flex',

      // print variants should be at the end, like it is in the core utility
      'print:flex',
    ]),
  ).toMatchInlineSnapshot(`
    ".aria-polite\\:underline {
      &[aria-live="polite"] {
        text-decoration-line: underline;
      }
    }
    .aria-hidden\\:flex {
      &[aria-hidden="true"] {
        display: flex;
      }
    }
    .data-checked\\:underline {
      &[data-ui~="checked"] {
        text-decoration-line: underline;
      }
    }
    .data-foo\\:flex {
      &[data-foo] {
        display: flex;
      }
    }
    .supports-child-combinator\\:underline {
      @supports (h2 > p) {

Review comment (suggestion):
```suggestion
      // The `print` variant should still be sorted last, even after registering
      // the other custom variants.
```

Code after:
          aria: {
            polite: 'live="polite"',
          },
          supports: {
            'child-combinator': 'selector(h2 > p)',
            foo: 'bar',
          },
          data: {
            checked: 'ui~="checked"',
          },
        },
      },
    }),
  })

  expect(
    compiler.build([
      'aria-polite:underline',
      'supports-child-combinator:underline',
      'supports-foo:underline',
      'data-checked:underline',

      // Ensure core variants still work
      'aria-hidden:flex',
      'supports-grid:flex',
      'data-foo:flex',

      // The `print` variant should still be sorted last, even after registering
      // the other custom variants.
      'print:flex',
    ]),
  ).toMatchInlineSnapshot(`
    ".aria-polite\\:underline {
      &[aria-live="polite"] {
        text-decoration-line: underline;
      }
    }
    .aria-hidden\\:flex {
      &[aria-hidden="true"] {
        display: flex;
      }
    }
    .data-checked\\:underline {
      &[data-ui~="checked"] {
        text-decoration-line: underline;
      }
    }
    .data-foo\\:flex {
      &[data-foo] {
        display: flex;
      }
Repository: tailwindlabs/tailwindcss
File: packages/tailwindcss/src/css-functions.test.ts (TypeScript)

Code before:
      expect(
        await compileCss(
          css`
            @tailwind utilities;
            @theme {
              --breakpoint-sm: 40rem;
              --color-red-500: #f00;
            }
          `,
          ['sm:[--color:theme(colors.red[500])]'],
        ),
      ).toMatchInlineSnapshot(`
        "@media (width >= 40rem) {
          .sm\\:\\[--color\\:theme\\(colors\\.red\\[500\\]\\)\\] {
            --color: red;
          }
        }

        :root {
          --breakpoint-sm: 40rem;
          --color-red-500: red;
        }"
      `)
    })

    test('values that dont exist dont produce candidates', async () => {
      // This guarantees that valid candidates still make it through when some are invalid
      expect(
        await compileCss(
          css`
            @tailwind utilities;
            @theme reference {
              --radius-sm: 2rem;
            }
          `,
          [
            'rounded-[theme(--radius-sm)]',
            'rounded-[theme(i.do.not.exist)]',
            'rounded-[theme(--i-do-not-exist)]',
          ],
        ),
      ).toMatchInlineSnapshot(`
        ".rounded-\\[theme\\(--radius-sm\\)\\] {
          border-radius: 2rem;
        }"
      `)

      // This guarantees no output for the following candidates
      expect(
        await compileCss(
          css`

Review comment (suggestion):
```suggestion
    test("values that don't exist don't produce candidates", async () => {
```

Code after:
          .custom {
            --custom-value: theme(${value});
          }
        `)

        let startOfCustomClass = compiled.indexOf('.custom {\n')
        let endOfCustomClass = compiled.indexOf('}', startOfCustomClass)

        let customClassRule = compiled
          .slice(startOfCustomClass + '.custom {\n'.length, endOfCustomClass)
          .replace('--custom-value:', '')
          .trim()
          .slice(0, -1)

        expect(customClassRule).toBe(result)
      })
    })
  })

  describe('in candidates', () => {
    test('sm:[--color:theme(colors.red[500])]', async () => {
      expect(
        await compileCss(
          css`
            @tailwind utilities;
            @theme {
              --breakpoint-sm: 40rem;
              --color-red-500: #f00;
            }
          `,
          ['sm:[--color:theme(colors.red[500])]'],
        ),
      ).toMatchInlineSnapshot(`
        "@media (width >= 40rem) {
          .sm\\:\\[--color\\:theme\\(colors\\.red\\[500\\]\\)\\] {
            --color: red;
          }
        }

        :root {
          --breakpoint-sm: 40rem;
          --color-red-500: red;
        }"
      `)
    })

    test("values that don't exist don't produce candidates", async () => {
      // This guarantees that valid candidates still make it through when some are invalid
      expect(
        await compileCss(
          css`
Repository: tailwindlabs/tailwindcss
File: packages/tailwindcss/src/design-system.ts (TypeScript)

Code before:

  // Used by IntelliSense
  candidatesToCss(classes: string[]): (string | null)[]
}

export function buildDesignSystem(theme: Theme): DesignSystem {
  let utilities = createUtilities(theme)
  let variants = createVariants(theme)

  let parsedVariants = new DefaultMap((variant) => parseVariant(variant, designSystem))
  let parsedCandidates = new DefaultMap((candidate) =>
    Array.from(parseCandidate(candidate, designSystem)),
  )
  let compiledAstNodes = new DefaultMap<Candidate>((candidate) =>
    compileAstNodes(candidate, designSystem),
  )

  let designSystem: DesignSystem = {
    theme,
    utilities,
    variants,

    // How to mark important utilities
    // - wrap with a selector (any string)
    // - add an !important (true)
    // - do nothing (false)
    important: false,

    candidatesToCss(classes: string[]) {
      let result: (string | null)[] = []

      for (let className of classes) {
        let { astNodes } = compileCandidates([className], this)
        if (astNodes.length === 0) {
          result.push(null)
        } else {
          result.push(toCss(astNodes))
        }
      }

      return result
    },

    getClassOrder(classes) {
      return getClassOrder(this, classes)
    },
    getClassList() {
      return getClassList(this)
    },
    getVariants() {
      return getVariants(this)

Review comment (suggestion):
I think we can improve this comment a bit. Took a stab at it, but not sure if it is much better:

```suggestion
    // Strategies:
    // - `string` — wrap each rule with the provided selector
    // - `true`   — add `!important` to every declaration
    // - `false`  — do nothing
```

Code after:

  getVariantOrder(): Map<Variant, number>
  resolveThemeValue(path: string): string | undefined

  // Used by IntelliSense
  candidatesToCss(classes: string[]): (string | null)[]
}

export function buildDesignSystem(theme: Theme): DesignSystem {
  let utilities = createUtilities(theme)
  let variants = createVariants(theme)

  let parsedVariants = new DefaultMap((variant) => parseVariant(variant, designSystem))
  let parsedCandidates = new DefaultMap((candidate) =>
    Array.from(parseCandidate(candidate, designSystem)),
  )
  let compiledAstNodes = new DefaultMap<Candidate>((candidate) =>
    compileAstNodes(candidate, designSystem),
  )

  let designSystem: DesignSystem = {
    theme,
    utilities,
    variants,

    invalidCandidates: new Set(),
    important: false,

    candidatesToCss(classes: string[]) {
      let result: (string | null)[] = []

      for (let className of classes) {
        let wasInvalid = false

        let { astNodes } = compileCandidates([className], this, {
          onInvalidCandidate(candidate) {
            wasInvalid = true
          },
        })

        if (astNodes.length === 0 || wasInvalid) {
          result.push(null)
        } else {
          result.push(toCss(astNodes))
        }
      }

      return result
    },

    getClassOrder(classes) {
Repository: tailwindlabs/tailwindcss
File: packages/tailwindcss/src/important.test.ts (TypeScript)

Code before:
import { expect, test } from 'vitest'
import { compile } from '.'

const css = String.raw

test('Utilities can be wrapped in a selector', async () => {
  // This is the v4 equivalent of `important: "#app"` from v3
  let input = css`
    @import 'tailwindcss/utilities' selector(#app);
  `

  let compiler = await compile(input, {
    loadStylesheet: async (id: string, base: string) => ({
      base,
      content: '@tailwind utilities;',
    }),
  })

  expect(compiler.build(['underline', 'hover:line-through'])).toMatchInlineSnapshot(`
    ".underline {
      #app & {
        text-decoration-line: underline;
      }
    }
    .hover\\:line-through {
      #app & {
        &:hover {
          @media (hover: hover) {
            text-decoration-line: line-through;
          }
        }
      }
    }
    "

Review comment (suggestion):
Was this the final syntax we wanted? I'm fine with it, but it's not super clear what this does (could be a documentation problem).

But it's almost like you want:

If you are talking about the feature:
```suggestion
    @import 'tailwindcss/utilities' important(#app);
```

If you are talking about what it does:
```suggestion
    @import 'tailwindcss/utilities' wrapper(#app);
```

Don't like either option so think `selector` is fine, but still writing this down just in case.

Code after:
import { expect, test } from 'vitest'
import { compile } from '.'

const css = String.raw

test('Utilities can be wrapped in a selector', async () => {
  // This is the v4 equivalent of `important: "#app"` from v3
  let input = css`
    #app {
      @tailwind utilities;
    }
  `

  let compiler = await compile(input)

  expect(compiler.build(['underline', 'hover:line-through'])).toMatchInlineSnapshot(`
    "#app {
      .underline {
        text-decoration-line: underline;
      }
      .hover\\:line-through {
        &:hover {
          @media (hover: hover) {
            text-decoration-line: line-through;
          }
        }
      }
    }
    "
  `)
})

test('Utilities can be marked with important', async () => {
  // This is the v4 equivalent of `important: true` from v3
Repository: tailwindlabs/tailwindcss
File: packages/tailwindcss/src/utilities.ts (TypeScript)

Code before:
    }

    if (value === null) return

    if (candidate.modifier) {
      return [decl('container-type', value), decl('container-name', candidate.modifier.value)]
    }

    return [decl('container-type', value)]
  })

  suggest('@container', () => [
    {
      values: ['normal'],
      valueThemeKeys: [],
      hasDefaultValue: false,
    },
  ])

  return utilities
}

export function isPositiveInteger(value: any) {
  let num = Number(value)
  return Number.isInteger(num) && num >= 0
}


Review comment (suggestion):
I think this is probably fine for now but wonder if there's a better place for these types of functions. We already export a couple other things from this file so whatever, but maybe we should consider moving some of this stuff to the `infer-data-types.ts` module where there's a lot of other similar types of functions, or rethink where we put this stuff in general.

Code after:
        let value: string | null = candidate.value.value
        let type = candidate.value.dataType ?? inferDataType(value, ['color', 'length'])

        switch (type) {
          case 'length': {
            if (candidate.modifier) return
            return [
              decl('--tw-ring-offset-width', value),
              decl('--tw-ring-offset-shadow', ringOffsetShadowValue),
            ]
          }
          default: {
            value = asColor(value, candidate.modifier)
            if (value === null) return

            return [decl('--tw-ring-offset-color', value)]
          }
        }
      }

      // `--tw-ring-offset-width` property
      {
        let value = theme.resolve(candidate.value.value, ['--ring-offset-width'])
        if (value) {
          if (candidate.modifier) return
          return [
            decl('--tw-ring-offset-width', value),
            decl('--tw-ring-offset-shadow', ringOffsetShadowValue),
          ]
        } else if (isPositiveInteger(candidate.value.value)) {
          if (candidate.modifier) return
          return [
            decl('--tw-ring-offset-width', `${candidate.value.value}px`),
            decl('--tw-ring-offset-shadow', ringOffsetShadowValue),
          ]
        }
      }

      // `--tw-ring-offset-color` property
      {
        let value = resolveThemeColor(candidate, theme, ['--ring-offset-color', '--color'])
        if (value) {
          return [decl('--tw-ring-offset-color', value)]
        }
      }
    })
  }

  suggest('ring-offset', () => [
    {
      values: ['current', 'inherit', 'transparent'],