ronantakizawa/codereview-bench huggingface dataset:
Repository: facebook/react
File: packages/react-devtools-extensions/webpack.backend.js (JavaScript)

Code before:
module.exports = {
  mode: __DEV__ ? 'development' : 'production',
  devtool: false,
  entry: {
    backend: './src/backend.js',
  },
  output: {
    path: __dirname + '/build',
    filename: 'react_devtools_backend_compact.js',
  },
  node: {
    global: false,
  },
  resolve: {
    alias: {
      react: resolve(builtModulesDir, 'react'),
      'react-debug-tools': resolve(builtModulesDir, 'react-debug-tools'),
      'react-devtools-feature-flags': resolveFeatureFlags(featureFlagTarget),
      'react-dom': resolve(builtModulesDir, 'react-dom'),
      'react-is': resolve(builtModulesDir, 'react-is'),
      scheduler: resolve(builtModulesDir, 'scheduler'),
    },
  },
  optimization: {
    minimize: !__DEV__,
    minimizer: [
      new TerserPlugin({
        terserOptions: {
          compress: {
            unused: true,
            dead_code: true,
          },
          mangle: {
            keep_fnames: true,
          },
          format: {
            comments: false,
          },
        },
        extractComments: false,
      }),
    ],
  },
  plugins: [
    new Webpack.ProvidePlugin({
      process: 'process/browser',
    }),
    new Webpack.DefinePlugin({
      __DEV__: true,
      __PROFILE__: false,
      __DEV____DEV__: true,

Review comment (suggestion):
Same options as in `packages/react-devtools-extensions/webpack.config.js`. I'll merge these two configs once they're similar enough.

Code after:
module.exports = {
  mode: __DEV__ ? 'development' : 'production',
  devtool: false,
  entry: {
    backend: './src/backend.js',
  },
  output: {
    path: __dirname + '/build',
    filename: 'react_devtools_backend_compact.js',
  },
  node: {
    global: false,
  },
  resolve: {
    alias: {
      react: resolve(builtModulesDir, 'react'),
      'react-debug-tools': resolve(builtModulesDir, 'react-debug-tools'),
      'react-devtools-feature-flags': resolveFeatureFlags(featureFlagTarget),
      'react-dom': resolve(builtModulesDir, 'react-dom'),
      'react-is': resolve(builtModulesDir, 'react-is'),
      scheduler: resolve(builtModulesDir, 'scheduler'),
    },
  },
  optimization: {
    minimize: !__DEV__,
    minimizer: [
      new TerserPlugin({
        terserOptions: {
          compress: {
            unused: true,
            dead_code: true,
          },
          mangle: {
            keep_fnames: true,
          },
          format: {
            comments: false,
          },
        },
        extractComments: false,
      }),
    ],
  },
  plugins: [
    new Webpack.ProvidePlugin({
      process: 'process/browser',
    }),
    new Webpack.DefinePlugin({
      __DEV__,
      __PROFILE__: false,
      // By importing `shared/` we may import ReactFeatureFlags
Repository: facebook/react
File: packages/react-client/src/ReactFlightClient.js (JavaScript)

Code before:
  return new ReactPromise(BLOCKED, null, null);
}

function createErrorChunk<T>(
  response: Response,
  error: mixed,
): ErroredChunk<T> {
  // $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors
  return new ReactPromise(ERRORED, null, error);
}

function wakeChunk<T>(
  listeners: Array<InitializationReference | (T => mixed)>,
  value: T,
  chunk: SomeChunk<T>,
): void {
  for (let i = 0; i < listeners.length; i++) {
    const listener = listeners[i];
    if (typeof listener === 'function') {
      listener(value);
    } else {
      fulfillReference(listener, value, chunk);
    }
  }

  if (__DEV__ && chunk.status === INITIALIZED) {
    const resolvedValue = resolveLazy(value);
    if (isReactElementOrArrayLike(resolvedValue) || isLazy(resolvedValue)) {
      const debugInfo = chunk._debugInfo.splice(0);
      if (resolvedValue._debugInfo) {
        // $FlowFixMe[method-unbinding]
        resolvedValue._debugInfo.push.apply(
          resolvedValue._debugInfo,
          debugInfo,
        );
      } else {
        Object.defineProperty(resolvedValue, '_debugInfo', {
          configurable: false,
          enumerable: false,
          writable: true,
          value: debugInfo,
        });
      }
    }
  }
}

function rejectChunk(
  listeners: Array<InitializationReference | (mixed => mixed)>,
  error: mixed,
): void {

Review comment (suggestion):
You can change the type to just accept an initialized chunk since all the callsites except the cycle resolution is doing that.

Then fork the cycle resolution callsite maybe.

Code after:
  return new ReactPromise(BLOCKED, null, null);
}

function createErrorChunk<T>(
  response: Response,
  error: mixed,
): ErroredChunk<T> {
  // $FlowFixMe[invalid-constructor] Flow doesn't support functions as constructors
  return new ReactPromise(ERRORED, null, error);
}

function moveDebugInfoFromChunkToInnerValue<T>(
  chunk: InitializedChunk<T>,
  value: T,
): void {
  // Remove the debug info from the initialized chunk, and add it to the inner
  // value instead. This can be a React element, an array, or an uninitialized
  // Lazy.
  const resolvedValue = resolveLazy(value);
  if (
    typeof resolvedValue === 'object' &&
    resolvedValue !== null &&
    (isArray(resolvedValue) ||
      typeof resolvedValue[ASYNC_ITERATOR] === 'function' ||
      resolvedValue.$$typeof === REACT_ELEMENT_TYPE ||
      resolvedValue.$$typeof === REACT_LAZY_TYPE)
  ) {
    const debugInfo = chunk._debugInfo.splice(0);
    if (isArray(resolvedValue._debugInfo)) {
      // $FlowFixMe[method-unbinding]
      resolvedValue._debugInfo.unshift.apply(
        resolvedValue._debugInfo,
        debugInfo,
      );
    } else {
      Object.defineProperty((resolvedValue: any), '_debugInfo', {
        configurable: false,
        enumerable: false,
        writable: true,
        value: debugInfo,
      });
    }
  }
}

function wakeChunk<T>(
  listeners: Array<InitializationReference | (T => mixed)>,
  value: T,
  chunk: InitializedChunk<T>,
): void {
  for (let i = 0; i < listeners.length; i++) {
Repository: facebook/react
File: packages/react-devtools-shared/src/backend/fiber/renderer.js (JavaScript)

Code before:
    if (isHookThatCanScheduleUpdate(prev)) {
      return prevMemoizedState !== nextMemoizedState;
    }

    return false;
  }

  function getChangedHooksIndices(prev: any, next: any): null | Array<number> {
    if (prev == null || next == null) {
      return null;
    }

    const indices = [];
    let index = 0;

    while (next !== null) {
      if (didStatefulHookChange(prev, next)) {
        indices.push(index);
      }

      // useSyncExternalStore creates 2 internal hooks, but we only count it as 1 user-facing hook
      if (isUseSyncExternalStoreHook(next)) {
        if (next.next !== null) {
          next = next.next;
          prev = prev.next;
        }
      }

      index++;
      next = next.next;
      prev = prev.next;
    }

    return indices;
  }

  function getChangedKeys(prev: any, next: any): null | Array<string> {
    if (prev == null || next == null) {
      return null;
    }

    const keys = new Set([...Object.keys(prev), ...Object.keys(next)]);
    const changedKeys = [];
    // eslint-disable-next-line no-for-of-loops/no-for-of-loops
    for (const key of keys) {
      if (prev[key] !== next[key]) {
        changedKeys.push(key);
      }
    }

    return changedKeys;

Review comment (bug):
We probably don't want to check on `next.next` presence here, it should be implied if the hook object is actually an internal representation of `useSyncExternalStore()`.

I would prefer it to crash instead, if this ever happens, so we spot the gap in our hook parsing logic first.

Code after:
    if (isHookThatCanScheduleUpdate(prev)) {
      return prevMemoizedState !== nextMemoizedState;
    }

    return false;
  }

  function getChangedHooksIndices(prev: any, next: any): null | Array<number> {
    if (prev == null || next == null) {
      return null;
    }

    const indices = [];
    let index = 0;

    while (next !== null) {
      if (didStatefulHookChange(prev, next)) {
        indices.push(index);
      }

      // useSyncExternalStore creates 2 internal hooks, but we only count it as 1 user-facing hook
      if (isUseSyncExternalStoreHook(next)) {
        next = next.next;
        prev = prev.next;
      }

      next = next.next;
      prev = prev.next;
      index++;
    }

    return indices;
  }

  function getChangedKeys(prev: any, next: any): null | Array<string> {
    if (prev == null || next == null) {
      return null;
    }

    const keys = new Set([...Object.keys(prev), ...Object.keys(next)]);
    const changedKeys = [];
    // eslint-disable-next-line no-for-of-loops/no-for-of-loops
    for (const key of keys) {
      if (prev[key] !== next[key]) {
        changedKeys.push(key);
      }
    }

    return changedKeys;
  }
Repository: facebook/react
File: compiler/apps/playground/components/Editor/Output.tsx (TypeScript)

Code before:
    });
    reorderedTabs.set(
      'Output',
      <TextTabContent
        output={errors}
        language="markdown"
        diff={null}
        showInfoPanel={false}></TextTabContent>,
    );
  }
  tabs.forEach((tab, name) => {
    reorderedTabs.set(name, tab);
  });
  return reorderedTabs;
}

function tabifyCached(
  store: Store,
  compilerOutput: CompilerOutput,
): Promise<Map<string, ReactNode>> {
  const key = store;
  if (tabifyCache.has(key)) {
    return tabifyCache.get(key)!;
  }
  const result = tabify(store.source, compilerOutput, store.showInternals);
  tabifyCache.set(key, result);
  return result;
}

function Fallback(): JSX.Element {
  console.log('Fallback');
  return (
    <div className="w-full h-monaco_small sm:h-monaco flex items-center justify-center">
      Loading...
    </div>
  );
}

function utf16ToUTF8(s: string): string {
  return unescape(encodeURIComponent(s));
}

function getSourceMapUrl(code: string, map: string): string | null {
  code = utf16ToUTF8(code);
  map = utf16ToUTF8(map);
  return `https://evanw.github.io/source-map-visualization/#${btoa(
    `${code.length}\0${code}${map.length}\0${map}`,
  )}`;
}

function Output({store, compilerOutput}: Props): JSX.Element {

Review comment (performance):
Since you're using the store as a key this will continue growing forever (potentially on every keystroke) and include the whole store object. This should probably be some form of LRU cache that can clean up the old store keys and promises.

Code after:
  } else if (compilerOutput.kind === 'err') {
    const errors = compilerOutput.error.printErrorMessage(source, {
      eslint: false,
    });
    reorderedTabs.set(
      'Output',
      <TextTabContent
        output={errors}
        language="markdown"
        diff={null}
        showInfoPanel={false}></TextTabContent>,
    );
  }
  tabs.forEach((tab, name) => {
    reorderedTabs.set(name, tab);
  });
  return reorderedTabs;
}

function tabifyCached(
  store: Store,
  compilerOutput: CompilerOutput,
): Promise<Map<string, ReactNode>> {
  const cached = tabifyCache.get(store);
  if (cached) return cached;
  const result = tabify(store.source, compilerOutput, store.showInternals);
  tabifyCache.set(store, result);
  return result;
}

function Fallback(): JSX.Element {
  return (
    <div className="w-full h-monaco_small sm:h-monaco flex items-center justify-center">
      Loading...
    </div>
  );
}

function utf16ToUTF8(s: string): string {
  return unescape(encodeURIComponent(s));
}

function getSourceMapUrl(code: string, map: string): string | null {
  code = utf16ToUTF8(code);
  map = utf16ToUTF8(map);
  return `https://evanw.github.io/source-map-visualization/#${btoa(
    `${code.length}\0${code}${map.length}\0${map}`,
  )}`;
}

function Output({store, compilerOutput}: Props): JSX.Element {
Repository: facebook/react
File: compiler/apps/playground/components/Editor/ConfigEditor.tsx (TypeScript)

Code before:
import {IconChevron} from '../Icons/IconChevron';
import prettyFormat from 'pretty-format';

// @ts-expect-error - webpack asset/source loader handles .d.ts files as strings
import compilerTypeDefs from 'babel-plugin-react-compiler/dist/index.d.ts';

loader.config({monaco});

export default function ConfigEditor({
  appliedOptions,
}: {
  appliedOptions: PluginOptions | null;
}): React.ReactElement {
  const [isExpanded, setIsExpanded] = useState(false);

  return (
    // TODO: Use <Activity> when it is compatible with Monaco: https://github.com/suren-atoyan/monaco-react/issues/753
    <>
      <div
        style={{
          display: isExpanded ? 'block' : 'none',
        }}>
        <ExpandedEditor
          onToggle={() => {
            startTransition(() => {
              addTransitionType('config-panel');
              setIsExpanded(false);
            });
          }}
          appliedOptions={appliedOptions}
        />
      </div>
      <div
        style={{
          display: !isExpanded ? 'block' : 'none',
        }}>
        <CollapsedEditor
          onToggle={() => {
            startTransition(() => {
              addTransitionType('config-panel');
              setIsExpanded(true);
            });
          }}
        />{' '}
      </div>
    </>
  );
}

function ExpandedEditor({
  onToggle,

Review comment (suggestion):
This type could be a constant as its important it matches across usages through these modules but should also be unique from anything used in future unrelated transitions.

You could have something like `apps/playground/lib/transitionTypes.ts` where you export from.

Code after:
import {IconChevron} from '../Icons/IconChevron';
import prettyFormat from 'pretty-format';
import {CONFIG_PANEL_TRANSITION} from '../../lib/transitionTypes';

// @ts-expect-error - webpack asset/source loader handles .d.ts files as strings
import compilerTypeDefs from 'babel-plugin-react-compiler/dist/index.d.ts';

loader.config({monaco});

export default function ConfigEditor({
  appliedOptions,
}: {
  appliedOptions: PluginOptions | null;
}): React.ReactElement {
  const [isExpanded, setIsExpanded] = useState(false);

  return (
    // TODO: Use <Activity> when it is compatible with Monaco: https://github.com/suren-atoyan/monaco-react/issues/753
    <>
      <div
        style={{
          display: isExpanded ? 'block' : 'none',
        }}>
        <ExpandedEditor
          onToggle={() => {
            startTransition(() => {
              addTransitionType(CONFIG_PANEL_TRANSITION);
              setIsExpanded(false);
            });
          }}
          appliedOptions={appliedOptions}
        />
      </div>
      <div
        style={{
          display: !isExpanded ? 'block' : 'none',
        }}>
        <CollapsedEditor
          onToggle={() => {
            startTransition(() => {
              addTransitionType(CONFIG_PANEL_TRANSITION);
              setIsExpanded(true);
            });
          }}
        />
      </div>
    </>
  );
}

function ExpandedEditor({
Repository: facebook/react
File: packages/react/src/ReactServer.fb.js (JavaScript)

Code before:
/**
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

import {enableViewTransition} from 'shared/ReactFeatureFlags';

export {default as __SERVER_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE} from './ReactSharedInternalsServer';

import {forEach, map, count, toArray, only} from './ReactChildren';
import {captureOwnerStack as captureOwnerStackImpl} from './ReactOwnerStack';
import {
  REACT_ACTIVITY_TYPE,
  REACT_FRAGMENT_TYPE,
  REACT_PROFILER_TYPE,
  REACT_STRICT_MODE_TYPE,
  REACT_SUSPENSE_TYPE,
  REACT_SUSPENSE_LIST_TYPE,
  REACT_VIEW_TRANSITION_TYPE,
} from 'shared/ReactSymbols';
import {
  cloneElement,
  createElement,
  isValidElement,
} from './jsx/ReactJSXElement';
import {createRef} from './ReactCreateRef';
import {use, useId, useCallback, useDebugValue, useMemo} from './ReactHooks';
import {forwardRef} from './ReactForwardRef';
import {lazy} from './ReactLazy';
import {memo} from './ReactMemo';
import {cache, cacheSignal} from './ReactCacheServer';

Review comment (suggestion):
To be safe, can you remove the feature flag and just continue exporting it as `unstable_ViewTransition`? I have no idea if turning this off would break our infra. 


Code after:
/**
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

export {default as __SERVER_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE} from './ReactSharedInternalsServer';

import {forEach, map, count, toArray, only} from './ReactChildren';
import {captureOwnerStack as captureOwnerStackImpl} from './ReactOwnerStack';
import {
  REACT_ACTIVITY_TYPE,
  REACT_FRAGMENT_TYPE,
  REACT_PROFILER_TYPE,
  REACT_STRICT_MODE_TYPE,
  REACT_SUSPENSE_TYPE,
  REACT_SUSPENSE_LIST_TYPE,
  REACT_VIEW_TRANSITION_TYPE,
} from 'shared/ReactSymbols';
import {
  cloneElement,
  createElement,
  isValidElement,
} from './jsx/ReactJSXElement';
import {createRef} from './ReactCreateRef';
import {use, useId, useCallback, useDebugValue, useMemo} from './ReactHooks';
import {forwardRef} from './ReactForwardRef';
import {lazy} from './ReactLazy';
import {memo} from './ReactMemo';
import {cache, cacheSignal} from './ReactCacheServer';
import version from 'shared/ReactVersion';
Repository: facebook/react
File: packages/react-reconciler/src/ReactFiberPerformanceTrack.js (JavaScript)

Code before:
          ? 'Cascading Update'
          : renderStartTime - updateTime > 5
            ? 'Update Blocked'
            : 'Update';

      if (__DEV__) {
        const properties = [];
        if (updateComponentName != null) {
          properties.push(['Component name', updateComponentName]);
        }
        if (updateMethodName != null) {
          properties.push(['Method name', updateMethodName]);
        }
        const measureOptions = {
          start: updateTime,
          end: renderStartTime,
          detail: {
            devtools: {
              properties,
              track: currentTrack,
              trackGroup: LANES_TRACK_GROUP,
              color,
            },
          },
        };
        if (label === 'Cascading Update') {
          // $FlowFixMe[prop-missing] - detail is untyped
          measureOptions.detail.rnPerfIssue = reusableCascadingUpdateIssue;
        }

        if (debugTask) {
          debugTask.run(
            // $FlowFixMe[method-unbinding]
            performance.measure.bind(performance, label, measureOptions),
          );
        } else {
          performance.measure(label, measureOptions);
        }
        performance.clearMeasures(label);
      } else {
        console.timeStamp(
          label,
          updateTime,
          renderStartTime,
          currentTrack,
          LANES_TRACK_GROUP,
          color,
        );
      }
    }
  }

Review comment (suggestion):
```suggestion
        if (isSpawnedUpdate) {
```

Code after:
        : isSpawnedUpdate
          ? 'Cascading Update'
          : renderStartTime - updateTime > 5
            ? 'Update Blocked'
            : 'Update';

      if (__DEV__) {
        const properties = [];
        if (updateComponentName != null) {
          properties.push(['Component name', updateComponentName]);
        }
        if (updateMethodName != null) {
          properties.push(['Method name', updateMethodName]);
        }
        const measureOptions = {
          start: updateTime,
          end: renderStartTime,
          detail: {
            devtools: {
              properties,
              track: currentTrack,
              trackGroup: LANES_TRACK_GROUP,
              color,
            },
          },
        };
        if (enablePerformanceIssueReporting && isSpawnedUpdate) {
          // $FlowFixMe[prop-missing] - detail is untyped
          measureOptions.detail.devtools.performanceIssue =
            reusableCascadingUpdateIssue;
        }

        if (debugTask) {
          debugTask.run(
            // $FlowFixMe[method-unbinding]
            performance.measure.bind(performance, label, measureOptions),
          );
        } else {
          performance.measure(label, measureOptions);
        }
        performance.clearMeasures(label);
      } else {
        console.timeStamp(
          label,
          updateTime,
          renderStartTime,
          currentTrack,
          LANES_TRACK_GROUP,
          color,
        );
      }
Repository: facebook/react
File: compiler/packages/babel-plugin-react-compiler/src/CompilerError.ts (TypeScript)

Code before:
      start: {
        line: loc.start.line,
        column: loc.start.column + 1,
      },
      end: {
        line: loc.end.line,
        column: loc.end.column + 1,
      },
    },
    {
      message,
      linesAbove: CODEFRAME_LINES_ABOVE,
      linesBelow: CODEFRAME_LINES_BELOW,
    },
  );
  const lines = printed.split(/\r?\n/);
  if (loc.end.line - loc.start.line < CODEFRAME_MAX_LINES) {
    return printed;
  }
  const pipeIndex = lines[0].indexOf('|');
  return [
    ...lines.slice(
      0,
      CODEFRAME_LINES_ABOVE + CODEFRAME_ABBREVIATED_SOURCE_LINES,
    ),
    '> ' + ' '.repeat(pipeIndex - 2) + '…',
    ...lines.slice(
      -(CODEFRAME_LINES_BELOW + CODEFRAME_ABBREVIATED_SOURCE_LINES),
    ),
  ].join('\n');
}

function printErrorSummary(category: ErrorCategory, message: string): string {
  let heading: string;
  switch (category) {
    case ErrorCategory.AutomaticEffectDependencies:
    case ErrorCategory.CapitalizedCalls:
    case ErrorCategory.Config:
    case ErrorCategory.EffectDerivationsOfState:
    case ErrorCategory.EffectSetState:
    case ErrorCategory.ErrorBoundaries:
    case ErrorCategory.Factories:
    case ErrorCategory.FBT:
    case ErrorCategory.Fire:
    case ErrorCategory.Gating:
    case ErrorCategory.Globals:
    case ErrorCategory.Hooks:
    case ErrorCategory.Immutability:
    case ErrorCategory.Purity:
    case ErrorCategory.Refs:
    case ErrorCategory.RenderSetState:

Review comment (suggestion):
```suggestion
    '> ' + ' '.repeat(pipeIndex - 2) + '| …',
```

Code after:
      start: {
        line: loc.start.line,
        column: loc.start.column + 1,
      },
      end: {
        line: loc.end.line,
        column: loc.end.column + 1,
      },
    },
    {
      message,
      linesAbove: CODEFRAME_LINES_ABOVE,
      linesBelow: CODEFRAME_LINES_BELOW,
    },
  );
  const lines = printed.split(/\r?\n/);
  if (loc.end.line - loc.start.line < CODEFRAME_MAX_LINES) {
    return printed;
  }
  const pipeIndex = lines[0].indexOf('|');
  return [
    ...lines.slice(
      0,
      CODEFRAME_LINES_ABOVE + CODEFRAME_ABBREVIATED_SOURCE_LINES,
    ),
    ' '.repeat(pipeIndex) + '…',
    ...lines.slice(
      -(CODEFRAME_LINES_BELOW + CODEFRAME_ABBREVIATED_SOURCE_LINES),
    ),
  ].join('\n');
}

function printErrorSummary(category: ErrorCategory, message: string): string {
  let heading: string;
  switch (category) {
    case ErrorCategory.AutomaticEffectDependencies:
    case ErrorCategory.CapitalizedCalls:
    case ErrorCategory.Config:
    case ErrorCategory.EffectDerivationsOfState:
    case ErrorCategory.EffectSetState:
    case ErrorCategory.ErrorBoundaries:
    case ErrorCategory.Factories:
    case ErrorCategory.FBT:
    case ErrorCategory.Fire:
    case ErrorCategory.Gating:
    case ErrorCategory.Globals:
    case ErrorCategory.Hooks:
    case ErrorCategory.Immutability:
    case ErrorCategory.Purity:
    case ErrorCategory.Refs:
    case ErrorCategory.RenderSetState: