ronantakizawa/codereview-bench huggingface dataset:
Repository: motion-canvas/motion-canvas
File: packages/core/src/scenes/Random.ts (TypeScript)

Code before:
   * @param from - The start of the range.
   * @param to - The end of the range.
   */
  public nextFloat(from = 0, to = 1) {
    return map(from, to, this.next());
  }

  /**
   * Get the next random integer in the given range.
   *
   * @param from - The start of the range.
   * @param to - The end of the range. Exclusive.
   */
  public nextInt(from = 0, to = 4294967296) {
    let value = Math.floor(map(from, to, this.next()));
    if (value === to) {
      value = from;
    }

    return value;
  }

  // This is an optimization.
  // Since gauss() generates a pair of independent Gaussian random numbers,
  // it returns one immediately and stores the other for the next call to gauss().
  private nextGauss: number | null = null;

  /**
   * Get a random float from a gaussian distribution.
   * @param mean - The mean of the distribution.
   * @param stdev - The standard deviation of the distribution.
   */
  public gauss(mean = 0.0, stdev = 1.0): number {
    let z = this.nextGauss;
    this.nextGauss = null;
    if (z === null) {
      const x2pi = this.next() * 2 * Math.PI;
      const g2rad = Math.sqrt(-2.0 * Math.log(1.0 - this.next()));
      z = Math.cos(x2pi) * g2rad;
      this.nextGauss = Math.sin(x2pi) * g2rad;
    }
    return mean + z * stdev;
  }

  /**
   * Get an array filled with random floats in the given range.
   *
   * @param size - The size of the array.
   * @param from - The start of the range.
   * @param to - The end of the range.
   */

Review comment (refactor):
I can move this to the top of the file or wherever. I thought it was most clear right above the `gauss()` method.

I would also like to test `gauss()` but I'm not sure how. I ran `npx lerna run build` but I don't know how to use the built targets in my test project.

Code after:

  /**
   * @internal
   */
  public static createSeed() {
    return Math.floor(Math.random() * 4294967296);
  }

  /**
   * Get the next random float in the given range.
   *
   * @param from - The start of the range.
   * @param to - The end of the range.
   */
  public nextFloat(from = 0, to = 1) {
    return map(from, to, this.next());
  }

  /**
   * Get the next random integer in the given range.
   *
   * @param from - The start of the range.
   * @param to - The end of the range. Exclusive.
   */
  public nextInt(from = 0, to = 4294967296) {
    let value = Math.floor(map(from, to, this.next()));
    if (value === to) {
      value = from;
    }

    return value;
  }

  /**
   * Get a random float from a gaussian distribution.
   * @param mean - The mean of the distribution.
   * @param stdev - The standard deviation of the distribution.
   */
  public gauss(mean = 0, stdev = 1): number {
    let z = this.nextGauss;
    this.nextGauss = null;
    if (z === null) {
      const x2pi = this.next() * 2 * Math.PI;
      const g2rad = Math.sqrt(-2 * Math.log(1 - this.next()));
      z = Math.cos(x2pi) * g2rad;
      this.nextGauss = Math.sin(x2pi) * g2rad;
    }
    return mean + z * stdev;
  }

  /**
Repository: motion-canvas/motion-canvas
File: packages/ui/src/components/viewport/EditorPreview.tsx (TypeScript)

Code before:
              } else {
                setZoomToFit(false);
                setPosition({x: 0, y: 0});
                setZoom(value);
              }
            }}
            options={zoomOptions}
            value={value}
          />
          <Button
            disabled={state.x === 0 && state.y === 0}
            title={'Recenter'}
            onClick={() => setPosition({x: 0, y: 0})}
          >
            <Recenter />
          </Button>
          <ButtonCheckbox
            title={"Toggle grid [']"}
            onChecked={setGrid}
            checked={grid}
          >
            <GridIcon />
          </ButtonCheckbox>
          <ColorPicker />
          {/* Key is set to the state so that the component renders when the state changes */}
          <Coordinates visibility={coords} viewState={state} viewSize={size} />
        </div>
      </div>
    </ViewportContext.Provider>
  );
}


Review comment (suggestion):
`size.x` and `size.y` should be added to the `ViewportState`.
The state is already exposed via a context which means that you don't need to pass it as a property.
In `Coordinates` you can just do:
```ts
const state = useContext(ViewportContext);
```
To access the viewport state.

Code after:
              } else {
                setZoomToFit(false);
                setPosition({x: 0, y: 0});
                setZoom(value);
              }
            }}
            options={zoomOptions}
            value={value}
          />
          <Button
            disabled={state.x === 0 && state.y === 0}
            title={'Recenter'}
            onClick={() => setPosition({x: 0, y: 0})}
          >
            <Recenter />
          </Button>
          <ButtonCheckbox
            title={"Toggle grid [']"}
            onChecked={setGrid}
            checked={grid}
          >
            <GridIcon />
          </ButtonCheckbox>
          <ColorPicker />
          {coordinateSetting && <Coordinates />}
        </div>
      </div>
    </ViewportContext.Provider>
  );
}
Repository: motion-canvas/motion-canvas
File: packages/ui/src/components/viewport/EditorPreview.tsx (TypeScript)

Code before:
              } else {
                setZoomToFit(false);
                setPosition({x: 0, y: 0});
                setZoom(value);
              }
            }}
            options={zoomOptions}
            value={value}
          />
          <Button
            disabled={state.x === 0 && state.y === 0}
            title={'Recenter'}
            onClick={() => setPosition({x: 0, y: 0})}
          >
            <Recenter />
          </Button>
          <ButtonCheckbox
            title={"Toggle grid [']"}
            onChecked={setGrid}
            checked={grid}
          >
            <GridIcon />
          </ButtonCheckbox>
          <ColorPicker />
          {/* Key is set to the state so that the component renders when the state changes */}
          <Coordinates visibility={coords} viewState={state} viewSize={size} />
        </div>
      </div>
    </ViewportContext.Provider>
  );
}


Review comment (suggestion):
To conditionally toggle a component you simply do:
```ts
{coords && <Coordinates />}
```

Code after:
              } else {
                setZoomToFit(false);
                setPosition({x: 0, y: 0});
                setZoom(value);
              }
            }}
            options={zoomOptions}
            value={value}
          />
          <Button
            disabled={state.x === 0 && state.y === 0}
            title={'Recenter'}
            onClick={() => setPosition({x: 0, y: 0})}
          >
            <Recenter />
          </Button>
          <ButtonCheckbox
            title={"Toggle grid [']"}
            onChecked={setGrid}
            checked={grid}
          >
            <GridIcon />
          </ButtonCheckbox>
          <ColorPicker />
          {coordinateSetting && <Coordinates />}
        </div>
      </div>
    </ViewportContext.Provider>
  );
}
Repository: motion-canvas/motion-canvas
File: packages/core/src/scenes/Inspectable.ts (TypeScript)

Code before:
   *
   * @remarks
   * This method can be used to overlay additional information about an
   * element on top of the animation.
   *
   * @param element - The element for which to draw an overlay.
   * @param matrix - A local-to-screen matrix.
   * @param context - The context to draw with.
   */
  drawOverlay(
    element: InspectedElement,
    matrix: DOMMatrix,
    context: CanvasRenderingContext2D,
  ): void;

  /**
   * Transform the absolute mouse coordinates into the scene's coordinate system.
   *
   * @param x - The x coordinate.
   * @param y - The y coordinate.
   * @param size - (Optional) The size from the shared meta settings. Used to calculate coordinate offsets
   */
  transformMousePosition(
    x: number,
    y: number,
    size?: {width: number; height: number},
  ): Vector2 | null;
}

export function isInspectable(value: any): value is Inspectable {
  return value && typeof value === 'object' && 'validateInspection' in value;
}


Review comment (suggestion):
There's no need to pass this value all the way from the editor. Scenes have access to the size of the project via the `this.size` property.

Code after:
   *
   * @remarks
   * This method can be used to overlay additional information about an
   * element on top of the animation.
   *
   * @param element - The element for which to draw an overlay.
   * @param matrix - A local-to-screen matrix.
   * @param context - The context to draw with.
   */
  drawOverlay(
    element: InspectedElement,
    matrix: DOMMatrix,
    context: CanvasRenderingContext2D,
  ): void;

  /**
   * Transform the absolute mouse coordinates into the scene's coordinate system.
   *
   * @param x - The x coordinate.
   * @param y - The y coordinate.
   */
  transformMousePosition(x: number, y: number): Vector2 | null;
}

export function isInspectable(value: any): value is Inspectable {
  return value && typeof value === 'object' && 'validateInspection' in value;
}
Repository: motion-canvas/motion-canvas
File: packages/2d/src/scenes/Scene2D.ts (TypeScript)

Code before:
    if (node) {
      this.execute(() => {
        node.drawOverlay(
          context,
          matrix
            .scale(1 / this.resolutionScale, 1 / this.resolutionScale)
            .multiplySelf(node.localToWorld()),
        );
      });
    }
  }

  public transformMousePosition(
    x: number,
    y: number,
    size?: {width: number; height: number},
  ): Vector2 | null {
    if (size !== undefined) {
      x -= size.width / 2;
      y -= size.height / 2;
    }

    x = Math.round(x);
    y = Math.round(y);

    return new Vector2(x, y);
  }

  public registerNode(node: Node, key?: string): string {
    const className = node.constructor?.name ?? 'unknown';
    this.nodeCounters[className] ??= 0;
    const counter = this.nodeCounters[className]++;

    key ??= `${this.name}/${className}[${counter}]`;
    this.registeredNodes[key] = node;
    return key;
  }

  public getNode(key: any): Node | null {
    if (typeof key !== 'string') return null;
    return this.registeredNodes[key] ?? null;
  }

  protected recreateView() {
    this.execute(() => {
      const size = this.getSize();
      this.view = new View2D({
        position: size.scale(this.resolutionScale / 2),
        scale: this.resolutionScale,
        assetHash: this.assetHash,
        size,

Review comment (suggestion):
Coordinates shouldn't be transformed manually - you should use the view matrix instead.
This is the same logic we use for hit detection:
```suggestion
    return new Vector2(x, y)
      .scale(this.resolutionScale)
      .transformAsPoint(this.getView().localToParent().inverse());
```

Code after:
    if (node) {
      this.execute(() => {
        node.drawOverlay(
          context,
          matrix
            .scale(1 / this.resolutionScale, 1 / this.resolutionScale)
            .multiplySelf(node.localToWorld()),
        );
      });
    }
  }

  public transformMousePosition(x: number, y: number): Vector2 | null {
    return new Vector2(x, y)
      .scale(this.resolutionScale)
      .transformAsPoint(this.getView().localToParent().inverse());
  }

  public registerNode(node: Node, key?: string): string {
    const className = node.constructor?.name ?? 'unknown';
    this.nodeCounters[className] ??= 0;
    const counter = this.nodeCounters[className]++;

    key ??= `${this.name}/${className}[${counter}]`;
    this.registeredNodes[key] = node;
    return key;
  }

  public getNode(key: any): Node | null {
    if (typeof key !== 'string') return null;
    return this.registeredNodes[key] ?? null;
  }

  protected recreateView() {
    this.execute(() => {
      const size = this.getSize();
      this.view = new View2D({
        position: size.scale(this.resolutionScale / 2),
        scale: this.resolutionScale,
        assetHash: this.assetHash,
        size,
      });
    });
  }
}
Repository: motion-canvas/motion-canvas
File: packages/ui/src/components/viewport/Coordinates.tsx (TypeScript)

Code before:
import {useEffect, useState} from 'react';
import {useCallback, useContext} from 'preact/hooks';
import {
  useCurrentScene,
  useDocumentEvent,
  useSharedSettings,
} from '../../hooks';
import {ViewportContext} from './ViewportContext';
import {isInspectable} from '@motion-canvas/core';
import clsx from 'clsx';
import styles from '@motion-canvas/ui/src/components/controls/Controls.module.scss';

export function Coordinates() {
  const [mousePos, setMousePos] = useState({x: 0, y: 0});
  const [hover, setHover] = useState(true);

  const state = useContext(ViewportContext);
  const settings = {
    ...useSharedSettings(),
  };
  const scene = useCurrentScene();

  useEffect(() => {
    const handleMouseMove = (event: {x: number; y: number}) => {
      if (!isInspectable(scene)) return;
      const absoluteCoords = {
        x: event.x - state.size.x,
        y: event.y - state.size.y,
      };

      absoluteCoords.x -= state.x + state.width / 2;
      absoluteCoords.y -= state.y + state.height / 2;
      absoluteCoords.x /= state.zoom;
      absoluteCoords.y /= state.zoom;
      absoluteCoords.x += settings.size.width / 2;
      absoluteCoords.y += settings.size.height / 2;

Review comment (suggestion):
```suggestion
import styles from '../controls/Controls.module.scss';
```

Code after:
import {useEffect, useState} from 'react';
import {useCallback, useContext} from 'preact/hooks';
import {
  useCurrentScene,
  useDocumentEvent,
  useSharedSettings,
} from '../../hooks';
import {ViewportContext} from './ViewportContext';
import {isInspectable} from '@motion-canvas/core';
import styles from '../controls/Controls.module.scss';

export function Coordinates() {
  const [mousePos, setMousePos] = useState({x: 0, y: 0});
  const [hover, setHover] = useState(true);

  const state = useContext(ViewportContext);
  const settings = {
    ...useSharedSettings(),
  };
  const scene = useCurrentScene();

  useEffect(() => {
    const handleMouseMove = (event: {x: number; y: number}) => {
      if (!isInspectable(scene)) return;
      const absoluteCoords = {
        x: event.x - state.size.x,
        y: event.y - state.size.y,
      };

      absoluteCoords.x -= state.x + state.width / 2;
      absoluteCoords.y -= state.y + state.height / 2;
      absoluteCoords.x /= state.zoom;
      absoluteCoords.y /= state.zoom;
      absoluteCoords.x += settings.size.width / 2;
      absoluteCoords.y += settings.size.height / 2;
Repository: motion-canvas/motion-canvas
File: packages/ui/src/components/viewport/Coordinates.tsx (TypeScript)

Code before:

    document.addEventListener('mousemove', handleMouseMove);

    return () => {
      document.removeEventListener('mousemove', handleMouseMove);
    };
  }, [state]);

  // Below method is used for the copy to clipboard keybind
  useDocumentEvent(
    'keydown',
    useCallback(
      async event => {
        if (document.activeElement.tagName !== 'INPUT' && event.key === 'p') {
          const positionString = `${mousePos.x}, ${mousePos.y}`;
          await window.navigator.clipboard.writeText(positionString);
        }
      },
      [mousePos],
    ),
  );

  return (
    <>
      {hover && (
        <div title={'Coordinates'} className={clsx(styles.input)}>
          ({mousePos.x}, {mousePos.y})
        </div>
      )}
    </>
  );
}


Review comment (suggestion):
`clsx` is for joining multiple classes together
```suggestion
        <div title={'Coordinates'} className={styles.input}>
```

Code after:
    };

    document.addEventListener('mousemove', handleMouseMove);

    return () => {
      document.removeEventListener('mousemove', handleMouseMove);
    };
  }, [state]);

  // Below method is used for the copy to clipboard keybind
  useDocumentEvent(
    'keydown',
    useCallback(
      async event => {
        if (document.activeElement.tagName !== 'INPUT' && event.key === 'p') {
          const positionString = `${mousePos.x}, ${mousePos.y}`;
          await window.navigator.clipboard.writeText(positionString);
        }
      },
      [mousePos],
    ),
  );

  return (
    <>
      {hover && (
        <div title={'Coordinates'} className={styles.input}>
          ({mousePos.x}, {mousePos.y})
        </div>
      )}
    </>
  );
}
Repository: motion-canvas/motion-canvas
File: packages/core/src/app/SettingsMetadata.ts (TypeScript)

Code before:
import {
  BoolMetaField,
  ColorMetaField,
  MetaField,
  ObjectMetaField,
  Vector2MetaField,
} from '../meta';
import {Vector2, Color} from '../types';

/**
 * Create a runtime representation of the settings metadata.
 */
export function createSettingsMetadata() {
  return new ObjectMetaField('Application Settings', {
    version: new MetaField('version', 1),
    appearance: new ObjectMetaField('Appearance', {
      color: new ColorMetaField('accent color', new Color('#33a6ff')).describe(
        'The accent color for the user interface. (Leave empty to use the default color)',
      ),
      font: new BoolMetaField('legacy font', false).describe(
        "Use the 'JetBrains Mono' font for the user interface.",
      ),
      coordinates: new BoolMetaField('coordinates', true).describe(
        'Display coordinates within the preview window.',
      ),
    }),
    defaults: new ObjectMetaField('Defaults', {
      background: new ColorMetaField('background', null).describe(
        'The default background color used in new projects.',
      ),
      size: new Vector2MetaField(
        'resolution',
        new Vector2(1920, 1080),
      ).describe('The default resolution used in new projects.'),
    }),
  });
}

/**
 * A runtime representation of the settings metadata.
 */
export type SettingsMetadata = ReturnType<typeof createSettingsMetadata>;


Review comment (suggestion):
```suggestion
        'Display mouse coordinates within the preview window.',
```

Code after:
import {
  BoolMetaField,
  ColorMetaField,
  MetaField,
  ObjectMetaField,
  Vector2MetaField,
} from '../meta';
import {Vector2, Color} from '../types';

/**
 * Create a runtime representation of the settings metadata.
 */
export function createSettingsMetadata() {
  return new ObjectMetaField('Application Settings', {
    version: new MetaField('version', 1),
    appearance: new ObjectMetaField('Appearance', {
      color: new ColorMetaField('accent color', new Color('#33a6ff')).describe(
        'The accent color for the user interface. (Leave empty to use the default color)',
      ),
      font: new BoolMetaField('legacy font', false).describe(
        "Use the 'JetBrains Mono' font for the user interface.",
      ),
      coordinates: new BoolMetaField('coordinates', true).describe(
        'Display mouse coordinates within the preview window.',
      ),
    }),
    defaults: new ObjectMetaField('Defaults', {
      background: new ColorMetaField('background', null).describe(
        'The default background color used in new projects.',
      ),
      size: new Vector2MetaField(
        'resolution',
        new Vector2(1920, 1080),
      ).describe('The default resolution used in new projects.'),
    }),
  });
}

/**
 * A runtime representation of the settings metadata.
 */
export type SettingsMetadata = ReturnType<typeof createSettingsMetadata>;
Repository: motion-canvas/motion-canvas
File: packages/2d/src/components/Latex.ts (TypeScript)

Code before:
import {useLogger} from '@motion-canvas/core/lib/utils';

const Adaptor = liteAdaptor();
RegisterHTMLHandler(Adaptor);

const JaxDocument = mathjax.document('', {
  // eslint-disable-next-line @typescript-eslint/naming-convention
  InputJax: new TeX({packages: AllPackages}),
  // eslint-disable-next-line @typescript-eslint/naming-convention
  OutputJax: new SVG({fontCache: 'local'}),
});

export interface LatexProps extends ImgProps {
  tex?: SignalValue<string>;
  renderProps?: SignalValue<OptionList>;
}

/**
 * A node for rendering equations with LaTeX.
 *
 * @preview
 * ```tsx editor
 * import {Latex} from '@motion-canvas/2d/lib/components';
 * import {makeScene2D} from '@motion-canvas/2d/lib/scenes';
 * import {waitFor} from '@motion-canvas/core/lib/flow';
 * import {createRef} from '@motion-canvas/core/lib/utils';
 *
 * export default makeScene2D(function* (view) {
 *   const tex = createRef<Latex>();
 *   view.add(
 *     <Latex
 *       ref={tex}
 *       // Note how this uses \color to set the color.
 *       tex="{\color{white} ax^2+bx+c=0 \implies x=\frac{-b \pm \sqrt{b^2-4ac}}{2a}}"
 *       y={0}
 *       width={600} // height and width can calculate based on each other
 *     />,
 *   );
 *
 *   yield* waitFor(2);
 *   yield* tex().opacity(0, 1);
 *   yield* waitFor(2);
 *   yield* tex().opacity(1, 1);
 * });
 * ```
 */
export class Latex extends Img {
  private static svgContentsPool: Record<string, string> = {};

  private readonly imageElement = document.createElement('img');


Review comment (suggestion):
Since `3.9.0` [all entities should be imported from the main entry of our packages](https://motioncanvas.io/blog/version-3.9.0#new-features)

Code after:
import {useLogger} from '@motion-canvas/core/lib/utils';

const Adaptor = liteAdaptor();
RegisterHTMLHandler(Adaptor);

const JaxDocument = mathjax.document('', {
  // eslint-disable-next-line @typescript-eslint/naming-convention
  InputJax: new TeX({packages: AllPackages}),
  // eslint-disable-next-line @typescript-eslint/naming-convention
  OutputJax: new SVG({fontCache: 'local'}),
});

export interface LatexProps extends ImgProps {
  tex?: SignalValue<string>;
  renderProps?: SignalValue<OptionList>;
}

/**
 * A node for rendering equations with LaTeX.
 *
 * @preview
 * ```tsx editor
 * import {Latex, makeScene2D} from '@motion-canvas/2d';
 *
 * export default makeScene2D(function* (view) {
 *   view.add(
 *     <Latex
 *       // Note how this uses \color to set the color.
 *       tex="{\color{white} ax^2+bx+c=0 \implies x=\frac{-b \pm \sqrt{b^2-4ac}}{2a}}"
 *       width={600} // height and width can calculate based on each other
 *     />,
 *   );
 * });
 * ```
 */
export class Latex extends Img {
  private static svgContentsPool: Record<string, string> = {};

  private readonly imageElement = document.createElement('img');

  @initial({})
  @signal()
  public declare readonly options: SimpleSignal<OptionList, this>;

  @signal()
  public declare readonly tex: SimpleSignal<string, this>;

  public constructor(props: LatexProps) {
    super(props);
  }