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

Code before:
      }
    })
  }

  suggest('ring-offset', () => [
    {
      values: ['current', 'inherit', 'transparent'],
      valueThemeKeys: ['--ring-offset-color', '--color'],
      modifiers: Array.from({ length: 21 }, (_, index) => `${index * 5}`),
    },
    {
      values: ['0', '1', '2', '4', '8'],
      valueThemeKeys: ['--ring-offset-width'],
    },
  ])

  utilities.functional('@container', (candidate) => {
    let value: string | null = null
    if (candidate.value === null) {
      value = 'inline-size'
    } else if (candidate.value.kind === 'arbitrary') {
      value = candidate.value.value
    } else if (candidate.value.kind === 'named' && candidate.value.value === 'normal') {
      value = 'normal'
    } else if (
      featureFlagVersion('4.2.0', '0.0.0-insiders') &&
      candidate.value.kind === 'named' &&
      candidate.value.value === 'size'
    ) {
      value = 'size'
    }

    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: true,
    },
  ])

  return utilities
}

Review comment (suggestion):
The main reason I added this is such that we can merge these kinds of PRs instead of keeping them open until we are ready to release a `4.2.x` with new features.

Code after:
      }
    })
  }

  suggest('ring-offset', () => [
    {
      values: ['current', 'inherit', 'transparent'],
      valueThemeKeys: ['--ring-offset-color', '--color'],
      modifiers: Array.from({ length: 21 }, (_, index) => `${index * 5}`),
    },
    {
      values: ['0', '1', '2', '4', '8'],
      valueThemeKeys: ['--ring-offset-width'],
    },
  ])

  utilities.functional('@container', (candidate) => {
    let value: string | null = null
    if (candidate.value === null) {
      value = 'inline-size'
    } else if (candidate.value.kind === 'arbitrary') {
      value = candidate.value.value
    } else if (candidate.value.kind === 'named' && candidate.value.value === 'normal') {
      value = 'normal'
    } else if (
      enableContainerSizeUtility &&
      candidate.value.kind === 'named' &&
      candidate.value.value === 'size'
    ) {
      value = 'size'
    }

    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: true,
    },
  ])

  return utilities
}
Repository: tailwindlabs/tailwindcss
File: packages/tailwindcss/src/value-parser.ts (TypeScript)

Code before:

  let ast: ValueAstNode[] = []

  let stack: (ValueFunctionNode | null)[] = []

  let parent = null as ValueFunctionNode | null

  let buffer = ''

  let peekChar

  for (let i = 0; i < input.length; i++) {
    let currentChar = input.charCodeAt(i)

    switch (currentChar) {
      // Current character is a `\` therefore the next character is escaped,
      // consume it together with the next character and continue.
      case BACKSLASH: {
        buffer += input[i] + input[i + 1]
        i++
        break
      }

      // Typically for math operators they have to have spaces around them. But
      // therea re situations in `theme(colors.red.500/10)` where we use `/`
      // without spaces. Let's make srue this is a separate word as well.
      case SLASH: {
        // 1. Handle everything before the separator as a word
        // Handle everything before the closing paren as a word
        if (buffer.length > 0) {
          let node = word(buffer)
          if (parent) {
            parent.nodes.push(node)
          } else {
            ast.push(node)
          }
          buffer = ''
        }

        // 2. Track the `/` as a word on its own
        let node = word(input[i])
        if (parent) {
          parent.nodes.push(node)
        } else {
          ast.push(node)
        }

        break
      }

      // Space and commas are bundled into separators

Review comment (suggestion):
```suggestion
      // Typically for math operators, they have to have spaces around them. But
      // there are situations in `theme(colors.red.500/10)` where we use `/`
      // without spaces. Let's make sure this is a separate word as well.
```

Code after:

  let ast: ValueAstNode[] = []

  let stack: (ValueFunctionNode | null)[] = []

  let parent = null as ValueFunctionNode | null

  let buffer = ''

  let peekChar

  for (let i = 0; i < input.length; i++) {
    let currentChar = input.charCodeAt(i)

    switch (currentChar) {
      // Current character is a `\` therefore the next character is escaped,
      // consume it together with the next character and continue.
      case BACKSLASH: {
        buffer += input[i] + input[i + 1]
        i++
        break
      }

      // Typically for math operators, they have to have spaces around them. But
      // there are situations in `theme(colors.red.500/10)` where we use `/`
      // without spaces. Let's make sure this is a separate word as well.
      case SLASH: {
        // 1. Handle everything before the separator as a word
        // Handle everything before the closing paren as a word
        if (buffer.length > 0) {
          let node = word(buffer)
          if (parent) {
            parent.nodes.push(node)
          } else {
            ast.push(node)
          }
          buffer = ''
        }

        // 2. Track the `/` as a word on its own
        let node = word(input[i])
        if (parent) {
          parent.nodes.push(node)
        } else {
          ast.push(node)
        }

        break
      }

      // Space and commas are bundled into separators
Repository: tailwindlabs/tailwindcss
File: packages/tailwindcss/src/constant-fold-declaration.test.ts (TypeScript)

Code before:
import { expect, it } from 'vitest'
import { constantFoldDeclaration } from './constant-fold-declaration'

it.each([
  // Simple expression
  ['calc(1 + 1)', '2'],
  ['calc(3 - 2)', '1'],
  ['calc(2 * 3)', '6'],
  ['calc(8 / 2)', '4'],

  // Nested
  ['calc(1 + calc(1 + 1))', '3'],
  ['calc(3 - calc(1 + 2))', '0'],
  ['calc(2 * calc(1 + 3))', '8'],
  ['calc(8 / calc(2 + 2))', '2'],
  ['calc(1 + (1 + 1))', '3'],
  ['calc(3 - (1 + 2))', '0'],
  ['calc(2 * (1 + 3))', '8'],
  ['calc(8 / (2 + 2))', '2'],

  // With units
  ['calc(1rem * 2)', '2rem'],
  ['calc(2rem - 0.5rem)', '1.5rem'],
  ['calc(3rem * 6)', '18rem'],
  ['calc(5rem / 2)', '2.5rem'],
])('should constant fold `%s` into `%s`', (input, expected) => {
  expect(constantFoldDeclaration(input)).toBe(expected)
})

it.each([
  ['calc(1rem * 2%)'],
  ['calc(1rem * 2px)'],
  ['calc(2rem - 6)'],
  ['calc(3rem * 3dvw)'],
  ['calc(3rem * 2dvh)'],
  ['calc(5rem / 17px)'],
])('should not constant fold different units `%s`', (input) => {
  expect(constantFoldDeclaration(input)).toBe(input)
})

it.each([
  ['calc(0 * 100vw)'],
  ['calc(0 * calc(1 * 2))'],
  ['calc(0 * var(--foo))'],
  ['calc(0 * calc(var(--spacing) * 32))'],

  ['calc(100vw * 0)'],
  ['calc(calc(1 * 2) * 0)'],
  ['calc(var(--foo) * 0)'],
  ['calc(calc(var(--spacing, 0.25rem) * 32) * 0)'],

Review comment (suggestion):
Some additional tests / comments:

```suggestion
  ['calc(5rem / 2)', '2.5rem'],

  // Nested partial evaluation
  ['calc(calc(1 + 2) + 2rem)', 'calc(3 + 2rem)'],

  // Evaluation only handles two operands right now, this can change in the future
  ['calc(1 + 2 + 3)', 'calc(1 + 2 + 3)'],
```


Code after:
import { expect, it } from 'vitest'
import { constantFoldDeclaration } from './constant-fold-declaration'

it.each([
  // Simple expression
  ['calc(1 + 1)', '2'],
  ['calc(3 - 2)', '1'],
  ['calc(2 * 3)', '6'],
  ['calc(8 / 2)', '4'],

  // Nested
  ['calc(1 + calc(1 + 1))', '3'],
  ['calc(3 - calc(1 + 2))', '0'],
  ['calc(2 * calc(1 + 3))', '8'],
  ['calc(8 / calc(2 + 2))', '2'],
  ['calc(1 + (1 + 1))', '3'],
  ['calc(3 - (1 + 2))', '0'],
  ['calc(2 * (1 + 3))', '8'],
  ['calc(8 / (2 + 2))', '2'],

  // With units
  ['calc(1rem * 2)', '2rem'],
  ['calc(2rem - 0.5rem)', '1.5rem'],
  ['calc(3rem * 6)', '18rem'],
  ['calc(5rem / 2)', '2.5rem'],

  // Nested partial evaluation
  ['calc(calc(1 + 2) + 2rem)', 'calc(3 + 2rem)'],

  // Evaluation only handles two operands right now, this can change in the future
  ['calc(1 + 2 + 3)', 'calc(1 + 2 + 3)'],
])('should constant fold `%s` into `%s`', (input, expected) => {
  expect(constantFoldDeclaration(input)).toBe(expected)
})

it.each([
  ['calc(1rem * 2%)'],
  ['calc(1rem * 2px)'],
  ['calc(2rem - 6)'],
  ['calc(3rem * 3dvw)'],
  ['calc(3rem * 2dvh)'],
  ['calc(5rem / 17px)'],
])('should not constant fold different units `%s`', (input) => {
  expect(constantFoldDeclaration(input)).toBe(input)
})

it.each([
  ['calc(0 * 100vw)'],
  ['calc(0 * calc(1 * 2))'],
  ['calc(0 * var(--foo))'],
Repository: tailwindlabs/tailwindcss
File: packages/@tailwindcss-vite/src/index.ts (TypeScript)

Code before:

          let root = roots.get(id)

          let result = await root.generate(src, (file) => this.addWatchFile(file), I)
          if (!result) {
            roots.delete(id)
            return src
          }

          DEBUG && I.end('[@tailwindcss/vite] Generate CSS (serve)')
          return result
        },
      },
    },

    {
      // Step 2 (full build): Generate CSS
      name: '@tailwindcss/vite:generate:build',
      apply: 'build',
      enforce: 'pre',

      transform: {
        filter: {
          id: {
            exclude: [/\/\.vite\//, SPECIAL_QUERY_RE, COMMON_JS_PROXY_RE],
            include: [/css(?:\?.*)?$/, /&lang\.css/, INLINE_STYLE_ID_RE],
          },
        },
        async handler(src, id) {
          if (!isPotentialCssRootFile(id)) return

          using I = new Instrumentation()
          DEBUG && I.start('[@tailwindcss/vite] Generate CSS (build)')

          let root = roots.get(id)

          let result = await root.generate(src, (file) => this.addWatchFile(file), I)
          if (!result) {
            roots.delete(id)
            return src
          }
          DEBUG && I.end('[@tailwindcss/vite] Generate CSS (build)')

          if (shouldOptimize) {
            DEBUG && I.start('[@tailwindcss/vite] Optimize CSS')
            result = optimize(result.code, {
              minify,
              map: result.map,
            })
            DEBUG && I.end('[@tailwindcss/vite] Optimize CSS')
          }

Review comment (suggestion):
```suggestion
            include: [/\.css(?:\?.*)?$/, /&lang\.css/, INLINE_STYLE_ID_RE],
```

Code after:

          let root = roots.get(id)

          let result = await root.generate(src, (file) => this.addWatchFile(file), I)
          if (!result) {
            roots.delete(id)
            return src
          }

          DEBUG && I.end('[@tailwindcss/vite] Generate CSS (serve)')
          return result
        },
      },
    },

    {
      // Step 2 (full build): Generate CSS
      name: '@tailwindcss/vite:generate:build',
      apply: 'build',
      enforce: 'pre',

      transform: {
        filter: {
          id: {
            exclude: [/\/\.vite\//, SPECIAL_QUERY_RE, COMMON_JS_PROXY_RE],
            include: [/\.css(?:\?.*)?$/, /&lang\.css/, INLINE_STYLE_ID_RE],
          },
        },
        async handler(src, id) {
          if (!isPotentialCssRootFile(id)) return

          using I = new Instrumentation()
          DEBUG && I.start('[@tailwindcss/vite] Generate CSS (build)')

          let root = roots.get(id)

          let result = await root.generate(src, (file) => this.addWatchFile(file), I)
          if (!result) {
            roots.delete(id)
            return src
          }
          DEBUG && I.end('[@tailwindcss/vite] Generate CSS (build)')

          if (shouldOptimize) {
            DEBUG && I.start('[@tailwindcss/vite] Optimize CSS')
            result = optimize(result.code, {
              minify,
              map: result.map,
            })
            DEBUG && I.end('[@tailwindcss/vite] Optimize CSS')
          }
Repository: tailwindlabs/tailwindcss
File: packages/tailwindcss/src/index.ts (TypeScript)

Code before:

      customUtilities.push(utility)
    }

    // Collect paths from `@source` at-rules
    if (node.name === '@source') {
      if (node.nodes.length > 0) {
        throw new Error('`@source` cannot have a body.')
      }

      if (ctx.parent !== null) {
        throw new Error('`@source` cannot be nested.')
      }

      let not = false
      let inline = false
      let path = node.params

      if (path[0] === 'n' && path.startsWith('not ')) {
        not = true
        path = path.slice(4)
      }

      if (path[0] === 'i' && path.startsWith('inline(')) {
        inline = true
        path = path.slice(7, -1).trim();
      }

      if (
        (path[0] === '"' && path[path.length - 1] !== '"') ||
        (path[0] === "'" && path[path.length - 1] !== "'") ||
        (path[0] !== "'" && path[0] !== '"')
      ) {
        throw new Error('`@source` paths must be quoted.')
      }

      let source = path.slice(1, -1)

      if (inline) {
        let destination = not ? ignoredCandidates : inlineCandidates
        let sources = segment(source, ' ')
        for (let source of sources) {
          for (let candidate of expand(source)) {
            destination.push(candidate)
          }
        }
      } else {
        sources.push({
          base: ctx.context.base as string,
          pattern: source,
          negated: not,

Review comment (suggestion):
```suggestion
        path = path.slice(7, -1).trim()
```

Code after:

      customUtilities.push(utility)
    }

    // Collect paths from `@source` at-rules
    if (node.name === '@source') {
      if (node.nodes.length > 0) {
        throw new Error('`@source` cannot have a body.')
      }

      if (ctx.parent !== null) {
        throw new Error('`@source` cannot be nested.')
      }

      let not = false
      let inline = false
      let path = node.params

      if (path[0] === 'n' && path.startsWith('not ')) {
        not = true
        path = path.slice(4)
      }

      if (path[0] === 'i' && path.startsWith('inline(')) {
        inline = true
        path = path.slice(7, -1).trim()
      }

      if (
        (path[0] === '"' && path[path.length - 1] !== '"') ||
        (path[0] === "'" && path[path.length - 1] !== "'") ||
        (path[0] !== "'" && path[0] !== '"')
      ) {
        throw new Error('`@source` paths must be quoted.')
      }

      let source = path.slice(1, -1)

      if (inline) {
        let destination = not ? ignoredCandidates : inlineCandidates
        let sources = segment(source, ' ')
        for (let source of sources) {
          for (let candidate of expand(source)) {
            destination.push(candidate)
          }
        }
      } else {
        sources.push({
          base: ctx.context.base as string,
          pattern: source,
          negated: not,
Repository: tannerlinsley/react-query
File: src/queryCache.js (JavaScript)

Code before:
      queryFn,
      { force, ...config },
    ] = getQueryArgs(args)

    config = {
      ...defaultConfigRef.current,
      ...config,
    }

    const query = cache._buildQuery(queryKey, queryVariables, queryFn, config)

    // Don't prefetch queries that are fresh, unless force is passed
    if (query.state.isStale || force) {
      // Trigger a fetch and return the promise
      try {
        const res = await query.fetch()
        query.wasPrefetched = true
        return res
      } catch (err) {
        if (config.throwOnError) {
          throw err
        }
      }
    } else {
      return Promise.resolve(query.state.data)
    }
  }

  cache.setQueryData = (queryKey, updater, { exact } = {}) => {
    let queries = findQueries(queryKey, { exact })

    if (!queries) {
      queries = [
        cache._buildQuery(
          queryKey,
          undefined,
          () => new Promise(noop),
          defaultConfigRef.current
        ),
      ]
    }

    queries.forEach(d => d.setData(updater))
  }

  function makeQuery(options) {
    const reducer = options.config.queryReducer || defaultQueryReducer

    const noQueryHash = typeof options.queryHash === 'undefined'

    const initialData =

Review comment (suggestion):
Because this is async already, the `Promise.resolve` is redundant along with the else statement. I suggest this:
```suggestion
    }
    
    return query.state.data
```

Code after:
      queryFn,
      { force, ...config },
    ] = getQueryArgs(args)

    config = {
      ...defaultConfigRef.current,
      ...config,
    }

    const query = cache._buildQuery(queryKey, queryVariables, queryFn, config)

    // Don't prefetch queries that are fresh, unless force is passed
    if (query.state.isStale || force) {
      // Trigger a fetch and return the promise
      try {
        const res = await query.fetch()
        query.wasPrefetched = true
        return res
      } catch (err) {
        if (config.throwOnError) {
          throw err
        }
      }
    }
    
    return query.state.data
  }

  cache.setQueryData = (queryKey, updater, { exact } = {}) => {
    let queries = findQueries(queryKey, { exact })

    if (!queries) {
      queries = [
        cache._buildQuery(
          queryKey,
          undefined,
          () => new Promise(noop),
          defaultConfigRef.current
        ),
      ]
    }

    queries.forEach(d => d.setData(updater))
  }

  function makeQuery(options) {
    const reducer = options.config.queryReducer || defaultQueryReducer

    const noQueryHash = typeof options.queryHash === 'undefined'

    const initialData =
Repository: tannerlinsley/react-query
File: src/tests/useQuery.test.js (JavaScript)

Code before:
    await waitForElement(() => rendered.getByText('Status: loading'))
    await waitForElement(() => [
      rendered.getByText('Status: success'),
      rendered.getByText('Data: data'),
    ])
  })

  it('should not mark query as fetching, when using initialData', async () => {
    function Page() {
      const query = useQuery('key', () => {}, { initialData: 'data' })

      return (
        <div>
          <div>{query.data}</div>
          <div data-testid="isFetching">{`${query.isFetching}`}</div>
        </div>
      )
    }

    const rendered = render(<Page />)

    rendered.getByText('data')
    expect(rendered.getByTestId('isFetching').textContent).toBe('false')
  })

  it('should initialize state properly, when initialData is undefined', async () => {
    function Page() {
      const query = useQuery('key', () => {}, { initialData: 0 })

      return (
        <div>
          <div>{query.data}</div>
          <div data-testid="isFetching">{`${query.isFetching}`}</div>
          <div data-testid="status">{query.status}</div>
        </div>
      )
    }

    const rendered = render(<Page />)

    rendered.getByText('0')
    expect(rendered.getByTestId('isFetching').textContent).toBe('false')
    expect(rendered.getByTestId('status').textContent).toBe('success')
  })
})


Review comment (suggestion):
```suggestion
  it('should initialize state properly, when initialData is falsy', async () => {
```

Code after:
    await waitForElement(() => rendered.getByText('Status: loading'))
    await waitForElement(() => [
      rendered.getByText('Status: success'),
      rendered.getByText('Data: data'),
    ])
  })

  it('should not mark query as fetching, when using initialData', async () => {
    function Page() {
      const query = useQuery('key', () => {}, { initialData: 'data' })

      return (
        <div>
          <div>{query.data}</div>
          <div data-testid="isFetching">{`${query.isFetching}`}</div>
        </div>
      )
    }

    const rendered = render(<Page />)

    rendered.getByText('data')
    expect(rendered.getByTestId('isFetching').textContent).toBe('false')
  })

  it('should initialize state properly, when initialData is falsy', async () => {
    function Page() {
      const query = useQuery('key', () => {}, { initialData: 0 })

      return (
        <div>
          <div>{query.data}</div>
          <div data-testid="isFetching">{`${query.isFetching}`}</div>
          <div data-testid="status">{query.status}</div>
        </div>
      )
    }

    const rendered = render(<Page />)

    rendered.getByText('0')
    expect(rendered.getByTestId('isFetching').textContent).toBe('false')
    expect(rendered.getByTestId('status').textContent).toBe('success')
  })
})
Repository: tannerlinsley/react-query
File: src/tests/useInfiniteQuery.test.js (JavaScript)

Code before:
      rendered.getByText('Page 1: 3'),
    ])
  })

  it('should compute canFetchMore correctly using initialData', async () => {
    function Page() {
      const fetchCountRef = React.useRef(0)
      const {
        status,
        data,
        error,
        isFetching,
        isFetchingMore,
        fetchMore,
        canFetchMore,
        refetch,
      } = useInfiniteQuery(
        'items',
        (key, nextId = 0) => fetchItems(nextId, fetchCountRef.current++),
        {
          initialData: [initialItems(0), initialItems(1)],
          getFetchMore: (lastGroup, allGroups) => lastGroup.nextId,
        }
      )

      expect(canFetchMore).not.toBeUndefined()

      return (
        <div>
          <h1>Pagination</h1>
          {status === 'loading' ? (
            'Loading...'
          ) : status === 'error' ? (
            <span>Error: {error.message}</span>
          ) : (
            <>
              <div>Data:</div>
              {data.map((page, i) => (
                <div key={i}>
                  <div>
                    Page {i}: {page.ts}
                  </div>
                  <div key={i}>
                    {page.items.map(item => (
                      <p key={item}>Item: {item}</p>
                    ))}
                  </div>
                </div>
              ))}
              <div>
                <button

Review comment (suggestion):
I don't think you can use expect inside a component.
I would rather render `canFetchMore` inside a dom element and check it after component is rendered.
(In this case `canFetchMore` should be stringified, so "undefined" can be rendered as string)

Code after:
      rendered.getByText('Page 1: 3'),
    ])
  })

  it('should compute canFetchMore correctly using initialData', async () => {
    function Page() {
      const fetchCountRef = React.useRef(0)
      const {
        status,
        data,
        error,
        isFetching,
        isFetchingMore,
        fetchMore,
        canFetchMore,
        refetch,
      } = useInfiniteQuery(
        'items',
        (key, nextId = 0) => fetchItems(nextId, fetchCountRef.current++),
        {
          initialData: [initialItems(0)],
          getFetchMore: (lastGroup, allGroups) => lastGroup.nextId,
        }
      )

      return (
        <div>
          <h1>Pagination</h1>
          {status === 'loading' ? (
            'Loading...'
          ) : status === 'error' ? (
            <span>Error: {error.message}</span>
          ) : (
            <>
              <div>Data:</div>
              {data.map((page, i) => (
                <div key={i}>
                  <div>
                    Page {i}: {page.ts}
                  </div>
                  <div key={i}>
                    {page.items.map(item => (
                      <p key={item}>Item: {item}</p>
                    ))}
                  </div>
                </div>
              ))}
              <div>
                <button
                  onClick={() => fetchMore()}
                  disabled={!canFetchMore || isFetchingMore}