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

Code before:
      }

      .bg-tomato {
        background-color: #e10c04;
      }"
    `)
  })

  test('wrapping `@theme` with `@media theme(inline)` behaves like `@theme inline` to support `@import` statements', () => {
    expect(
      compileCss(
        css`
          @media theme(inline) {
            @theme {
              --color-tomato: #e10c04;
              --color-potato: #ac855b;
              --color-primary: var(--primary);
            }
          }

          @tailwind utilities;
        `,
        ['bg-tomato', 'bg-potato', 'bg-primary'],
      ),
    ).toMatchInlineSnapshot(`
      ".bg-potato {
        background-color: #ac855b;
      }

      .bg-primary {
        background-color: var(--primary);
      }

      .bg-tomato {
        background-color: #e10c04;
      }"
    `)
  })

  test('`inline` and `reference` can be used together', () => {
    expect(
      compileCss(
        css`
          @theme reference inline {
            --color-tomato: #e10c04;
            --color-potato: #ac855b;
            --color-primary: var(--primary);
          }

          @tailwind utilities;
        `,

Review comment (suggestion):
I think this should contain the `:root` with the variables. It currently behaves as if we wrote `@media theme(inline reference)`.

```css
:root {
  --color-tomato: #e10c04;
  --color-potato: #ac855b;
  --color-primary: var(--primary);
}
```

Code after:
      }

      .bg-tomato {
        background-color: #e10c04;
      }"
    `)
  })

  test('wrapping `@theme` with `@media theme(inline)` behaves like `@theme inline` to support `@import` statements', () => {
    expect(
      compileCss(
        css`
          @media theme(inline) {
            @theme {
              --color-tomato: #e10c04;
              --color-potato: #ac855b;
              --color-primary: var(--primary);
            }
          }

          @tailwind utilities;
        `,
        ['bg-tomato', 'bg-potato', 'bg-primary'],
      ),
    ).toMatchInlineSnapshot(`
      ":root {
        --color-tomato: #e10c04;
        --color-potato: #ac855b;
        --color-primary: var(--primary);
      }

      .bg-potato {
        background-color: #ac855b;
      }

      .bg-primary {
        background-color: var(--primary);
      }

      .bg-tomato {
        background-color: #e10c04;
      }"
    `)
  })

  test('`inline` and `reference` can be used together', () => {
    expect(
      compileCss(
        css`
          @theme reference inline {
            --color-tomato: #e10c04;
Repository: tailwindlabs/tailwindcss
File: packages/tailwindcss/src/index.ts (TypeScript)

Code before:
        // CSS. This currently assumes that we only add new ast nodes and never
        // remove any.
        if (previousAstNodeCount === newNodes.length) {
          return compiledCss
        }

        previousAstNodeCount = newNodes.length

        tailwindUtilitiesNode.nodes = newNodes
        compiledCss = toCss(ast)
      }

      return compiledCss
    },
  }
}

export function __unstable__loadDesignSystem(css: string) {
  // Find all `@theme` declarations
  let theme = new Theme()
  let ast = CSS.parse(css)

  walk(ast, (node) => {
    if (node.kind !== 'rule') return
    if (node.selector !== '@theme' && !node.selector.startsWith('@theme ')) return
    let [_, ...themeOptions] = segment(node.selector, ' ')
    let isReference = themeOptions.includes('reference')
    let isInline = themeOptions.includes('inline')

    // Record all custom properties in the `@theme` declaration
    walk([node], (node) => {
      if (node.kind !== 'declaration') return
      if (!node.property.startsWith('--')) return

      theme.add(node.property, node.value, { isReference, isInline })
    })
  })

  return buildDesignSystem(theme)
}


Review comment (suggestion):
```suggestion
    let themeOptions = segment(node.selector, ' ')
```

Code after:
      // If no new candidates were added, we can return the original CSS. This
      // currently assumes that we only add new candidates and never remove any.
      if (!didChange) {
        return compiledCss
      }

      if (tailwindUtilitiesNode) {
        let newNodes = compileCandidates(allValidCandidates, designSystem, {
          onInvalidCandidate,
        }).astNodes

        // If no new ast nodes were generated, then we can return the original
        // CSS. This currently assumes that we only add new ast nodes and never
        // remove any.
        if (previousAstNodeCount === newNodes.length) {
          return compiledCss
        }

        previousAstNodeCount = newNodes.length

        tailwindUtilitiesNode.nodes = newNodes
        compiledCss = toCss(ast)
      }

      return compiledCss
    },
  }
}

export function __unstable__loadDesignSystem(css: string) {
  // Find all `@theme` declarations
  let theme = new Theme()
  let ast = CSS.parse(css)

  walk(ast, (node) => {
    if (node.kind !== 'rule') return
    if (node.selector !== '@theme' && !node.selector.startsWith('@theme ')) return
    let { isReference, isInline } = parseThemeOptions(node.selector)

    // Record all custom properties in the `@theme` declaration
    walk([node], (node) => {
      if (node.kind !== 'declaration') return
      if (!node.property.startsWith('--')) return

      theme.add(node.property, node.value, { isReference, isInline })
    })
  })

  return buildDesignSystem(theme)
}
Repository: tailwindlabs/tailwindcss
File: packages/tailwindcss/src/index.ts (TypeScript)

Code before:
        if (previousAstNodeCount === newNodes.length) {
          return compiledCss
        }

        previousAstNodeCount = newNodes.length

        tailwindUtilitiesNode.nodes = newNodes
        compiledCss = toCss(ast)
      }

      return compiledCss
    },
  }
}

export function __unstable__loadDesignSystem(css: string) {
  // Find all `@theme` declarations
  let theme = new Theme()
  let ast = CSS.parse(css)

  walk(ast, (node) => {
    if (node.kind !== 'rule') return
    if (node.selector !== '@theme' && !node.selector.startsWith('@theme ')) return
    let [_, ...themeOptions] = segment(node.selector, ' ')
    let isReference = themeOptions.includes('reference')
    let isInline = themeOptions.includes('inline')

    // Record all custom properties in the `@theme` declaration
    walk([node], (node) => {
      if (node.kind !== 'declaration') return
      if (!node.property.startsWith('--')) return

      theme.add(node.property, node.value, { isReference, isInline })
    })
  })

  return buildDesignSystem(theme)
}


Review comment (suggestion):
```suggestion
    let isReference = themeOptions.includes('reference', 1)
    let isInline = themeOptions.includes('inline', 1)
```

Code after:
      if (!didChange) {
        return compiledCss
      }

      if (tailwindUtilitiesNode) {
        let newNodes = compileCandidates(allValidCandidates, designSystem, {
          onInvalidCandidate,
        }).astNodes

        // If no new ast nodes were generated, then we can return the original
        // CSS. This currently assumes that we only add new ast nodes and never
        // remove any.
        if (previousAstNodeCount === newNodes.length) {
          return compiledCss
        }

        previousAstNodeCount = newNodes.length

        tailwindUtilitiesNode.nodes = newNodes
        compiledCss = toCss(ast)
      }

      return compiledCss
    },
  }
}

export function __unstable__loadDesignSystem(css: string) {
  // Find all `@theme` declarations
  let theme = new Theme()
  let ast = CSS.parse(css)

  walk(ast, (node) => {
    if (node.kind !== 'rule') return
    if (node.selector !== '@theme' && !node.selector.startsWith('@theme ')) return
    let { isReference, isInline } = parseThemeOptions(node.selector)

    // Record all custom properties in the `@theme` declaration
    walk([node], (node) => {
      if (node.kind !== 'declaration') return
      if (!node.property.startsWith('--')) return

      theme.add(node.property, node.value, { isReference, isInline })
    })
  })

  return buildDesignSystem(theme)
}
Repository: tailwindlabs/tailwindcss
File: crates/node/src/lib.rs (Rust)

Code before:
  pub files: Vec<String>,
  pub candidates: Vec<String>,
}

#[napi]
impl ScanResult {
  #[napi]
  pub fn scan_files(&self, _input: Vec<ChangedContent>) -> Vec<String> {
    let result = tailwindcss_oxide::scan_dir(tailwindcss_oxide::ScanOptions {
      base: self.base.clone(),
      sources: self.sources.clone().into_iter().map(Into::into).collect(),
    });

    result.candidates
  }
}

#[derive(Debug, Clone)]
#[napi(object)]
pub struct GlobEntry {
  pub base: String,
  pub pattern: String,
}

impl From<GlobEntry> for tailwindcss_oxide::GlobEntry {
  fn from(glob: GlobEntry) -> Self {
    tailwindcss_oxide::GlobEntry {
      base: glob.base,
      pattern: glob.pattern,
    }
  }
}

impl From<tailwindcss_oxide::GlobEntry> for GlobEntry {
  fn from(glob: tailwindcss_oxide::GlobEntry) -> Self {
    GlobEntry {
      base: glob.base,
      pattern: glob.pattern,
    }
  }
}

#[derive(Debug, Clone)]
#[napi(object)]
pub struct ScanOptions {
  /// Base path to start scanning from
  pub base: String,
  /// Glob sources
  pub sources: Option<Vec<GlobEntry>>,
}


Review comment (suggestion):
Public API uses `scanDirResult.scanFiles()` for incremental rebuilds. Right now we will do a full scan behind the scenes.

Good idea, @philipp-spiess!

Code after:
  pub files: Vec<String>,
  pub candidates: Vec<String>,
}

#[napi]
impl ScanResult {
  #[napi]
  pub fn scan_files(&self, input: Vec<ChangedContent>) -> Vec<String> {
    let result = tailwindcss_oxide::scan_dir(tailwindcss_oxide::ScanOptions {
      base: self.base.clone(),
      sources: self.sources.clone().into_iter().map(Into::into).collect(),
    });

    let mut unique_candidates: HashSet<String> = HashSet::from_iter(result.candidates);
    let candidates_from_files: HashSet<String> = HashSet::from_iter(tailwindcss_oxide::scan_files(
      input.into_iter().map(Into::into).collect(),
      IO::Parallel as u8 | Parsing::Parallel as u8,
    ));

    unique_candidates.extend(candidates_from_files);

    unique_candidates
      .into_iter()
      .map(|x| x.to_string())
      .collect()
  }
}

#[derive(Debug, Clone)]
#[napi(object)]
pub struct GlobEntry {
  pub base: String,
  pub pattern: String,
}

impl From<GlobEntry> for tailwindcss_oxide::GlobEntry {
  fn from(glob: GlobEntry) -> Self {
    tailwindcss_oxide::GlobEntry {
      base: glob.base,
      pattern: glob.pattern,
    }
  }
}

impl From<tailwindcss_oxide::GlobEntry> for GlobEntry {
  fn from(glob: tailwindcss_oxide::GlobEntry) -> Self {
    GlobEntry {
      base: glob.base,
      pattern: glob.pattern,
    }
  }
Repository: tailwindlabs/tailwindcss
File: packages/tailwindcss/src/utilities.test.ts (TypeScript)

Code before:
        ['foo', 'hover:foo', 'bar'],
      ),
    ).toMatchInlineSnapshot(`
      ".bar {
        z-index: 10;
      }

      .bar .baz {
        z-index: 20;
      }

      .foo {
        flex-direction: column;
        text-decoration-line: underline;
        display: flex;
      }

      .hover\\:foo:hover {
        flex-direction: column;
        text-decoration-line: underline;
        display: flex;
      }"
    `)
  })

  test('custom utilities with `@apply` causing circular dependencies should error', () => {
    expect(() =>
      compileCss(
        css`
          @utility foo {
            @apply font-bold hover:bar;
          }

          @utility bar {
            @apply dark:foo;
          }

          @tailwind utilities;
        `,
        ['foo', 'bar'],
      ),
    ).toThrowError(/Maximum call stack/)
  })
})


Review comment (refactor):
We should probably add a test verifying that apply of other `@utility`s work in an `@utility` — not just for the circular dep error case.


Code after:
        .text-sm {
          font-size: var(--font-size-sm, .875rem);
          line-height: var(--font-size-sm--line-height, 1.25rem);
          text-rendering: optimizelegibility;
        }
      }"
    `)
  })

  test('can override the default value of a functional utility', async () => {
    let { build } = await compile(css`
      @layer utilities {
        @tailwind utilities;
      }

      @theme reference {
        --radius-xl: 16px;
      }

      @utility rounded {
        border-radius: 50rem;
      }
    `)
    let compiled = build(['rounded', 'rounded-xl', 'rounded-[33px]'])

    expect(optimizeCss(compiled).trim()).toMatchInlineSnapshot(`
      "@layer utilities {
        .rounded {
          border-radius: 50rem;
        }

        .rounded-\\[33px\\] {
          border-radius: 33px;
        }

        .rounded-xl {
          border-radius: var(--radius-xl, 16px);
        }
      }"
    `)
  })

  test('custom utilities are sorted by used properties', async () => {
    let { build } = await compile(css`
      @layer utilities {
        @tailwind utilities;
      }

      @utility push-left {
        right: 100%;
      }
Repository: tailwindlabs/tailwindcss
File: packages/@tailwindcss-vite/src/index.ts (TypeScript)

Code before:
          if (file.handled) {
            continue
          }

          let css = await generateOptimizedCss(file.content, id, (file) => this.addWatchFile(file))

          // These plugins have side effects which, during build, results in CSS
          // being written to the output dir. We need to run them here to ensure
          // the CSS is written before the bundle is generated.
          await transformWithPlugins(this, id, css)

          file.handled = true
        }
      },
    },
  ] satisfies Plugin[]
}

function getExtension(id: string) {
  let [filename] = id.split('?', 2)
  return path.extname(filename).slice(1)
}

function isTailwindCssFile(id: string, src: string) {
  const extension = getExtension(id)
  const isCssFile = extension === 'css' || (extension === 'vue' && id.includes('&lang.css'))
  return isCssFile && src.includes('@tailwind')
}

function optimizeCss(
  input: string,
  { file = 'input.css', minify = false }: { file?: string; minify?: boolean } = {},
) {
  return transform({
    filename: file,
    code: Buffer.from(input),
    minify,
    sourceMap: false,
    drafts: {
      customMedia: true,
    },
    nonStandard: {
      deepSelectorCombinator: true,
    },
    include: Features.Nesting,
    exclude: Features.LogicalProperties,
    targets: {
      safari: (16 << 16) | (4 << 8),
    },
    errorRecovery: true,
  }).code.toString()

Review comment (suggestion):
```suggestion
  let extension = getExtension(id)
  let isCssFile = extension === 'css' || (extension === 'vue' && id.includes('&lang.css'))
```

Code after:
          if (file.handled) {
            continue
          }

          let css = await generateOptimizedCss(file.content, id, (file) => this.addWatchFile(file))

          // These plugins have side effects which, during build, results in CSS
          // being written to the output dir. We need to run them here to ensure
          // the CSS is written before the bundle is generated.
          await transformWithPlugins(this, id, css)

          file.handled = true
        }
      },
    },
  ] satisfies Plugin[]
}

function getExtension(id: string) {
  let [filename] = id.split('?', 2)
  return path.extname(filename).slice(1)
}

function isTailwindCssFile(id: string, src: string) {
  let extension = getExtension(id)
  let isCssFile = extension === 'css' || (extension === 'vue' && id.includes('&lang.css'))
  return isCssFile && src.includes('@tailwind')
}

function optimizeCss(
  input: string,
  { file = 'input.css', minify = false }: { file?: string; minify?: boolean } = {},
) {
  return transform({
    filename: file,
    code: Buffer.from(input),
    minify,
    sourceMap: false,
    drafts: {
      customMedia: true,
    },
    nonStandard: {
      deepSelectorCombinator: true,
    },
    include: Features.Nesting,
    exclude: Features.LogicalProperties,
    targets: {
      safari: (16 << 16) | (4 << 8),
    },
    errorRecovery: true,
  }).code.toString()
Repository: tailwindlabs/tailwindcss
File: packages/tailwindcss/src/plugin-api.ts (TypeScript)

Code before:
          }

          let ast = objectToAst(fn(value, { modifier }))
          substituteAtApply(ast, designSystem)
          return ast
        })
      }
    },
  }
}

export function registerPlugins(plugins: Plugin[], designSystem: DesignSystem, ast: AstNode[]) {
  let pluginApi = buildPluginApi(designSystem, ast)

  for (let plugin of plugins) {
    if ('__isOptionsFunction' in plugin) {
      // Happens with `plugin.withOptions()` and no options were passed
      // e.g. `require("my-plugin")` instead of `require("my-plugin")(options)`
      plugin().handler(pluginApi)
    } else if ('handler' in plugin) {
      // Happens with `plugin(…)`:
      // e.g. `require("my-plugin")`
      //
      // or with `plugin.withOptions()` and the user passed options
      // e.g. `require("my-plugin")(options)`
      plugin.handler(pluginApi)
    } else {
      // Just a plain function without using the plugin(…) API
      plugin(pluginApi)
    }
  }
}


Review comment (suggestion):
I wonder if this is better or not 🤔

```suggestion
    if (Object.hasOwn(plugin, '__isOptionsFunction')) {
```

Code after:
            // For arbitrary values, return `null` to avoid falling through to the next utility
            return candidate.value?.kind === 'arbitrary' ? null : undefined
          }

          if (isColor && modifier) {
            value = withAlpha(value, modifier)
          }

          if (candidate.negative) {
            value = withNegative(value, candidate)
          }

          let ast = objectToAst(fn(value, { modifier }))
          substituteAtApply(ast, designSystem)
          return ast
        })
      }
    },
  }
}

export function registerPlugins(plugins: Plugin[], designSystem: DesignSystem, ast: AstNode[]) {
  let pluginApi = buildPluginApi(designSystem, ast)

  for (let plugin of plugins) {
    if ('__isOptionsFunction' in plugin) {
      // Happens with `plugin.withOptions()` when no options were passed:
      // e.g. `require("my-plugin")` instead of `require("my-plugin")(options)`
      plugin().handler(pluginApi)
    } else if ('handler' in plugin) {
      // Happens with `plugin(…)`:
      // e.g. `require("my-plugin")`
      //
      // or with `plugin.withOptions()` when the user passed options:
      // e.g. `require("my-plugin")(options)`
      plugin.handler(pluginApi)
    } else {
      // Just a plain function without using the plugin(…) API
      plugin(pluginApi)
    }
  }
}
Repository: tailwindlabs/tailwindcss
File: packages/tailwindcss/src/index.test.ts (TypeScript)

Code before:
              addVariant('hocus', '&:hover, &:focus')
            }
          },
        },
      ),
    ).rejects.toThrowErrorMatchingInlineSnapshot(`[Error: \`@plugin\` must have a path.]`))

  test('@plugin cannot be nested.', () =>
    expect(
      compile(
        css`
          div {
            @plugin "my-plugin";
          }
        `,
        {
          loadPlugin: async () => {
            return ({ addVariant }: PluginAPI) => {
              addVariant('hocus', '&:hover, &:focus')
            }
          },
        },
      ),
    ).rejects.toThrowErrorMatchingInlineSnapshot(`[Error: \`@plugin\` cannot be nested.]`))

  test('@plugin can provide options', async () => {
    expect.hasAssertions()

    let { build } = await compile(
      css`
        @tailwind utilities;
        @plugin "my-plugin" {
          color: red;
        }
      `,
      {
        loadPlugin: async () => {
          return plugin.withOptions((options) => {
            expect(options).toEqual({
              color: 'red',
            })

            return ({ addUtilities }) => {
              addUtilities({
                '.text-primary': {
                  color: options.color,
                },
              })
            }
          })
        },

Review comment (suggestion):
```suggestion
  test('@plugin can accept options', async () => {
```

Code after:
              addVariant('hocus', '&:hover, &:focus')
            }
          },
        },
      ),
    ).rejects.toThrowErrorMatchingInlineSnapshot(`[Error: \`@plugin\` must have a path.]`))

  test('@plugin cannot be nested.', () =>
    expect(
      compile(
        css`
          div {
            @plugin "my-plugin";
          }
        `,
        {
          loadPlugin: async () => {
            return ({ addVariant }: PluginAPI) => {
              addVariant('hocus', '&:hover, &:focus')
            }
          },
        },
      ),
    ).rejects.toThrowErrorMatchingInlineSnapshot(`[Error: \`@plugin\` cannot be nested.]`))

  test('@plugin can accept options', async () => {
    expect.hasAssertions()

    let { build } = await compile(
      css`
        @tailwind utilities;
        @plugin "my-plugin" {
          color: red;
        }
      `,
      {
        loadPlugin: async () => {
          return plugin.withOptions((options) => {
            expect(options).toEqual({
              color: 'red',
            })

            return ({ addUtilities }) => {
              addUtilities({
                '.text-primary': {
                  color: options.color,
                },
              })
            }
          })
        },
Repository: tailwindlabs/tailwindcss
File: packages/tailwindcss/src/index.test.ts (TypeScript)

Code before:
            expect(options).toEqual({
              color: 'red',
            })

            return ({ addUtilities }) => {
              addUtilities({
                '.text-primary': {
                  color: options.color,
                },
              })
            }
          })
        },
      },
    )

    let compiled = build(['text-primary'])

    expect(optimizeCss(compiled).trim()).toMatchInlineSnapshot(`
      ".text-primary {
        color: red;
      }"
    `)
  })

  test('@plugin options can specify null, booleans, or numbers', async () => {
    expect.hasAssertions()

    await compile(
      css`
        @tailwind utilities;
        @plugin "my-plugin" {
          is-null: null;
          is-true: true;
          is-false: false;
          is-int: 1234567;
          is-float: 1.35;
          is-sci: 1.35e-5;
          is-str-null: 'null';
          is-str-true: 'true';
          is-str-false: 'false';
          is-str-int: '1234567';
          is-str-float: '1.35';
          is-str-sci: '1.35e-5';
          is-arr: foo, bar;
          is-arr-mixed: null, true, false, 1234567, 1.35, foo, 'bar', 'true';
        }
      `,
      {
        loadPlugin: async () => {
          return plugin.withOptions((options) => {

Review comment (suggestion):
```suggestion
  test('@plugin options can be null, booleans, string, numbers, or arrays including those types', async () => {
```

Code after:
            expect(options).toEqual({
              color: 'red',
            })

            return ({ addUtilities }) => {
              addUtilities({
                '.text-primary': {
                  color: options.color,
                },
              })
            }
          })
        },
      },
    )

    let compiled = build(['text-primary'])

    expect(optimizeCss(compiled).trim()).toMatchInlineSnapshot(`
      ".text-primary {
        color: red;
      }"
    `)
  })

  test('@plugin options can be null, booleans, string, numbers, or arrays including those types', async () => {
    expect.hasAssertions()

    await compile(
      css`
        @tailwind utilities;
        @plugin "my-plugin" {
          is-null: null;
          is-true: true;
          is-false: false;
          is-int: 1234567;
          is-float: 1.35;
          is-sci: 1.35e-5;
          is-str-null: 'null';
          is-str-true: 'true';
          is-str-false: 'false';
          is-str-int: '1234567';
          is-str-float: '1.35';
          is-str-sci: '1.35e-5';
          is-arr: foo, bar;
          is-arr-mixed: null, true, false, 1234567, 1.35, foo, 'bar', 'true';
        }
      `,
      {
        loadPlugin: async () => {
          return plugin.withOptions((options) => {