ronantakizawa/codereview-bench huggingface dataset:
Repository: freeCodeCamp/freeCodeCamp
File: client/utils/gatsby/page-loading.ts (TypeScript)

Code before:
// Gatsby's Link component has the following features:
// - When a Link component is in the viewport, Gatsby starts a low-priority request for the linked page's resources
// - When a Link component is hovered, Gatsby starts a high-priority request for the linked page's resources
//
// These functions are to mimic those behaviors to help cover cases
// where we want to preload a page but we don't show the link of the page on the screen.
//
// Refs:
// - https://v3.gatsbyjs.com/docs/reference/built-in-components/gatsby-link/#link-drives-gatsbys-fast-page-navigation
// - https://github.com/gatsbyjs/gatsby/discussions/20568#discussioncomment-104944

// Ref: https://github.com/gatsbyjs/gatsby/blob/721e9d1cf4a53604cddb7901003046bd3649836c/packages/gatsby-link/src/index.js#L74-L79
export const lowPriorityPreload = (path: string | null) => {
  if (!window.___loader) return;

  if (path) {
    window.___loader.enqueue(path);
  }
};

// Ref: https://github.com/gatsbyjs/gatsby/blob/721e9d1cf4a53604cddb7901003046bd3649836c/packages/gatsby-link/src/index.js#L150-L155
export const highPriorityPreload = (path: string | null) => {
  if (!window.___loader) return;

  if (path) {
    window.___loader.hovering(path);
  }
};


Review comment (suggestion):
Gatsby injects this `___loader` property to `window`, so it should be there. But I'm adding a check just in case.

Code after:
/**
 * The function is useful in cases where we want to preload a page
 * but the link of the page isn't rendered on the screen.
 * For more details, see https://github.com/freeCodeCamp/freeCodeCamp/pull/55472.
 */
export const preloadPage = (path: string | null) => {
  if (!window.___loader || !path) return;

  window.___loader.hovering(path);
};
Repository: freeCodeCamp/freeCodeCamp
File: client/utils/declarations.d.ts (TypeScript)

Code before:
declare global {
  interface Window {
    // This is a feature Gatsby adds to the `window` object.
    // https://github.com/gatsbyjs/gatsby/blob/deb41cdfefbefe0c170b5dd7c10a19ba2b338f6e/packages/gatsby/cache-dir/production-app.js#L28
    ___loader: {
      enqueue: (path: string | null) => void;
      hovering: (path: string | null) => void;
    };
  }
}

export {};


Review comment (suggestion):
```suggestion
```
Are you planning to use this? If not we can skip it.

Code after:
declare global {
  interface Window {
    // This is a feature Gatsby adds to the `window` object.
    // https://github.com/gatsbyjs/gatsby/blob/deb41cdfefbefe0c170b5dd7c10a19ba2b338f6e/packages/gatsby/cache-dir/production-app.js#L28
    ___loader: {
      hovering: (path: string | null) => void;
    };
  }
}

export {};
Repository: freeCodeCamp/freeCodeCamp
File: tools/scripts/seed/seed-demo-user.js (JavaScript)

Code before:
const path = require('path');
const debug = require('debug');
const { MongoClient } = require('mongodb');

require('dotenv').config({ path: path.resolve(__dirname, '../../../.env') });
const {
  demoUser,
  blankUser,
  publicUser,
  fullyCertifiedUser,
  userIds
} = require('./user-data');

const args = process.argv.slice(2);

const allowedArgs = [
  '--donor',
  '--top-contributor',
  '--unset-privacy-terms',
  '--seed-trophy-challenges',
  '--unset-full-stack-cert',
  'certified-user'
];

// Check for invalid arguments
args.forEach(arg => {
  if (!allowedArgs.includes(arg))
    throw new Error(
      `Invalid argument ${arg}. Allowed arguments are ${allowedArgs.join(', ')}`
    );
});

const log = debug('fcc:tools:seedLocalAuthUser');
const { MONGOHQ_URL } = process.env;

function handleError(err, client) {
  if (err) {
    console.error('Oh noes!! Error seeding local auth user.');
    console.error(err);
    try {
      client.close();
    } catch (e) {
      // no-op
    } finally {
      /* eslint-disable-next-line no-process-exit */
      process.exit(1);

Review comment (suggestion):
I wanted to set the option to `--unset-cert` and allow adding cert name as an argument, so that we can run:

```
pnpm seed:certified-user --unset-cert [certName]
```

But I don't think I can achieve that with the current setup, so I just went with `--unset-full-stack-cert`.

Code after:
const { parseArgs } = require('node:util');

const path = require('path');
const debug = require('debug');
const { MongoClient } = require('mongodb');

require('dotenv').config({ path: path.resolve(__dirname, '../../../.env') });
const {
  demoUser,
  blankUser,
  publicUser,
  fullyCertifiedUser,
  userIds
} = require('./user-data');

const options = {
  'set-true': { type: 'string', multiple: true },
  'top-contributor': { type: 'boolean' },
  'set-false': { type: 'string', multiple: true },
  'seed-trophy-challenges': { type: 'boolean' },
  'certified-user': { type: 'boolean' }
};

const { values: argValues } = parseArgs({ options });

const log = debug('fcc:tools:seedLocalAuthUser');
const { MONGOHQ_URL } = process.env;

function handleError(err, client) {
  if (err) {
    console.error('Oh noes!! Error seeding local auth user.');
    console.error(err);
    try {
      client.close();
    } catch (e) {
      // no-op
    } finally {
      /* eslint-disable-next-line no-process-exit */
      process.exit(1);
    }
  }
}

const trophyChallenges = [
  {
    id: '647f85d407d29547b3bee1bb',
Repository: freeCodeCamp/freeCodeCamp
File: api/src/schemas/donate/update-stripe-card.ts (TypeScript)

Code before:
import { Type } from '@fastify/type-provider-typebox';

export const updateStripeCard = {
  response: {
    200: Type.Object({
      sessionId: Type.String()
    }),
    default: Type.Object({
      message: Type.Literal('Something went wrong.'),
      type: Type.Literal('danger')
    })
  }
};


Review comment (suggestion):
```suggestion
import { Type } from '@fastify/type-provider-typebox';
import { genericError } from '../types';
```

Code after:
import { Type } from '@fastify/type-provider-typebox';
import { genericError } from '../types';

export const updateStripeCard = {
  body: Type.Object({}),
  response: {
    200: Type.Object({
      sessionId: Type.String()
    }),
    default: genericError
  }
};
Repository: freeCodeCamp/freeCodeCamp
File: client/src/components/profile/components/certifications.tsx (TypeScript)

Code before:
    <li>
      <ButtonLink
        block
        size='large'
        href={`/certification/${username}/${cert.certSlug}`}
      >
        {t('buttons.view-cert-title', {
          certTitle: t(`certification.title.${cert.certSlug}`)
        })}
      </ButtonLink>
      <Spacer size='small' />
    </li>
  );
}

function Certificates({
  currentCerts,
  legacyCerts,
  hasLegacyCert,
  hasModernCert,
  username
}: CertificationProps): JSX.Element {
  const { t } = useTranslation();
  return (
    <FullWidthRow className='certifications'>
      <h2>{t('profile.fcc-certs')}</h2>
      <br />
      {hasModernCert && currentCerts ? (
        <ul aria-labelledby='fcc-certifications'>
          {currentCerts
            .filter(({ show }) => show)
            .map(cert => (
              <CertButton key={cert.certSlug} cert={cert} username={username} />
            ))}
        </ul>
      ) : (
        <p className='text-center'>{t('profile.no-certs')}</p>
      )}
      {hasLegacyCert ? (
        <div>
          <Spacer size='medium' />
          <h3>{t('settings.headings.legacy-certs')}</h3>
          <Spacer size='medium' />
          {legacyCerts && (
            <ul>
              {legacyCerts
                .filter(({ show }) => show)
                .map(cert => (
                  <CertButton
                    key={cert.certSlug}
                    cert={cert}

Review comment (suggestion):
h2 needs an `id` so that `ul` can reference to.

```suggestion
      <h2 id="fcc-certifications">{t('profile.fcc-certs')}</h2>
```

Code after:
    <li>
      <ButtonLink
        block
        size='large'
        href={`/certification/${username}/${cert.certSlug}`}
      >
        {t('buttons.view-cert-title', {
          certTitle: t(`certification.title.${cert.certSlug}`)
        })}
      </ButtonLink>
      <Spacer size='small' />
    </li>
  );
}

function Certificates({
  currentCerts,
  legacyCerts,
  hasLegacyCert,
  hasModernCert,
  username
}: CertificationProps): JSX.Element {
  const { t } = useTranslation();
  return (
    <FullWidthRow className='profile-certifications'>
      <h2 id='fcc-certifications'>{t('profile.fcc-certs')}</h2>
      <br />
      {hasModernCert && currentCerts ? (
        <ul aria-labelledby='fcc-certifications'>
          {currentCerts
            .filter(({ show }) => show)
            .map(cert => (
              <CertButton key={cert.certSlug} cert={cert} username={username} />
            ))}
        </ul>
      ) : (
        <p className='text-center'>{t('profile.no-certs')}</p>
      )}
      {hasLegacyCert && (
        <div>
          <Spacer size='medium' />
          <h3 id='legacy-certifications'>
            {t('settings.headings.legacy-certs')}
          </h3>
          <Spacer size='medium' />
          {legacyCerts && (
            <>
              <ul aria-labelledby='legacy-certifications'>
                {legacyCerts
                  .filter(({ show }) => show)
                  .map(cert => (
Repository: freeCodeCamp/freeCodeCamp
File: client/src/templates/Challenges/classic/lower-jaw.tsx (TypeScript)

Code before:
  const isAttemptsLargerThanTest =
    currentAttempts &&
    testsLength &&
    (currentAttempts >= testsLength || currentAttempts >= 3);

  const isDesktop = window.innerWidth > MAX_MOBILE_WIDTH;
  const isMacOS = navigator.userAgent.includes('Mac OS');

  const checkButtonText = isDesktop
    ? isMacOS
      ? t('buttons.check-code-3')
      : t('buttons.check-code')
    : t('buttons.check-code-2');

  const showSignInButton = !isSignedIn && challengeIsCompleted;

  let buttonText;
  if (isDesktop) {
    if (isMacOS) {
      buttonText = t('buttons.submit-and-go-3');
    } else {
      buttonText = t('buttons.submit-and-go-2');
    }
  } else {
    buttonText = t('buttons.submit-and-go');
  }

  return (
    <div className='action-row-container'>
      {showSignInButton && (
        <>
          <a
            href={`${apiLocation}/signin`}
            className='btn-cta btn btn-block'
            onClick={() => {
              callGA({
                event: 'sign_in'
              });
            }}
          >
            {t('learn.sign-in-save')}
          </a>
          <Spacer size='xxSmall' />
        </>
      )}
      <Button
        data-playwright-test-label='lowerJaw-submit-button'
        block
        onClick={tryToSubmitChallenge}
        {...(!challengeIsCompleted && { 'aria-hidden': true })}
        ref={submitButtonRef}

Review comment (suggestion):
```suggestion
const submitButtonText = isDesktop
  ? isMacOS
    ? t('buttons.submit-and-go-3')
    : t('buttons.submit-and-go')
  : t('buttons.submit-and-go-2');
```

Code after:
  const isAttemptsLargerThanTest =
    currentAttempts &&
    testsLength &&
    (currentAttempts >= testsLength || currentAttempts >= 3);

  const isDesktop = window.innerWidth > MAX_MOBILE_WIDTH;
  const isMacOS = navigator.userAgent.includes('Mac OS');

  const checkButtonText = isDesktop
    ? isMacOS
      ? t('buttons.check-code-3')
      : t('buttons.check-code')
    : t('buttons.check-code-2');

  const submitButtonText = isDesktop
    ? isMacOS
      ? t('buttons.submit-and-go-3')
      : t('buttons.submit-and-go-2')
    : t('buttons.submit-and-go');

  const showSignInButton = !isSignedIn && challengeIsCompleted;

  return (
    <div className='action-row-container'>
      {showSignInButton && (
        <>
          <a
            href={`${apiLocation}/signin`}
            className='btn-cta btn btn-block'
            onClick={() => {
              callGA({
                event: 'sign_in'
              });
            }}
          >
            {t('learn.sign-in-save')}
          </a>
          <Spacer size='xxSmall' />
        </>
      )}
      <Button
        data-playwright-test-label='lowerJaw-submit-button'
        block
        onClick={tryToSubmitChallenge}
        {...(!challengeIsCompleted && { 'aria-hidden': true })}
        ref={submitButtonRef}
      >
        {submitButtonText}
      </Button>
      <div
        className={
Repository: freeCodeCamp/freeCodeCamp
File: client/src/components/settings/exam-token.tsx (TypeScript)

Code before:
import React, { useState } from 'react';
import { Button, Panel, Modal, Spacer } from '@freecodecamp/ui';
import { useTranslation } from 'react-i18next';
import { FullWidthRow } from '../helpers';
import { generateExamToken } from '../../utils/ajax';

function ExamToken(): JSX.Element {
  const [examToken, setExamToken] = useState('');
  const [examTokenError, setExamTokenError] = useState('');

  const [recentlyGenerated, setRecentlyGenerated] = useState(false);
  const [generatedExamToken, setGeneratedExamToken] = useState(false);

  const [copySuccess, setCopySuccess] = useState('');
  const [copyError, setCopyError] = useState('');

  const debouncedSetRecentlyGenerated = () => {
    setRecentlyGenerated(true);
    setTimeout(() => setRecentlyGenerated(false), 10000);
  };
  const { t } = useTranslation();

  const getToken = async () => {
    try {
      const response = await generateExamToken();

      const {
        data: { data: token }
      } = response;
      setExamToken(token.examEnvironmentAuthorizationToken);
      setExamTokenError('');
    } catch (e) {
      setExamTokenError(t('exam-token.error'));
    }

Review comment (suggestion):
Shall we change these errors to `string | null`?

That is clearer than string or empty string.

Code after:
import React, { useState } from 'react';
import { Button, Panel, Modal, Spacer } from '@freecodecamp/ui';
import { useTranslation } from 'react-i18next';
import { FullWidthRow } from '../helpers';
import { generateExamToken } from '../../utils/ajax';

function ExamToken(): JSX.Element {
  const [examToken, setExamToken] = useState<string | null>(null);
  const [examTokenError, setExamTokenError] = useState<string | null>(null);

  const [recentlyGenerated, setRecentlyGenerated] = useState(false);

  const [copySuccess, setCopySuccess] = useState<string | null>(null);
  const [copyError, setCopyError] = useState<string | null>(null);

  const { t } = useTranslation();

  const getToken = async () => {
    try {
      const response = await generateExamToken();

      const {
        data: {
          data: { examEnvironmentAuthorizationToken }
        }
      } = response;
      setExamToken(examEnvironmentAuthorizationToken);
      setExamTokenError('');
    } catch (e) {
      setExamTokenError(t('exam-token.error'));
    }

    setRecentlyGenerated(true);
    setTimeout(() => setRecentlyGenerated(false), 10000);
Repository: freeCodeCamp/freeCodeCamp
File: client/src/components/settings/exam-token.tsx (TypeScript)

Code before:
            {t('buttons.copy')}
          </Button>
          <Spacer size='s' />
          <Button
            onClick={() => {
              setGeneratedExamToken(false);
              setCopySuccess('');
              setCopyError('');
            }}
          >
            {t('buttons.close')}
          </Button>
        </Modal.Footer>
      </Modal>
      <Panel variant='info'>
        <Panel.Heading>{t('exam-token.exam-token')}</Panel.Heading>
        <Panel.Body>
          <p>{t('exam-token.note')}</p>
          <strong>{t('exam-token.invalidation')}</strong>
          <Spacer size='s' />
          <Button
            block={true}
            disabled={recentlyGenerated}
            onClick={() => {
              setGeneratedExamToken(true);
              getToken().catch(e => console.error(e));
            }}
          >
            {t('exam-token.generate-exam-token')}
          </Button>
        </Panel.Body>
      </Panel>
    </FullWidthRow>
  );
}

ExamToken.displayName = 'ExamToken';

export default ExamToken;


Review comment (bug):
This never throws, because everything is in a `try...catch`.

So, we should either handle the error here, or not catch anything.

Code after:
          <Spacer size='s' />
          <Button
            onClick={() => {
              setExamToken(null);
              setCopySuccess(null);
              setCopyError(null);
            }}
          >
            {t('buttons.close')}
          </Button>
        </Modal.Footer>
      </Modal>
      <Panel variant='info' id='exam-environment-authorization-token'>
        <Panel.Heading>{t('exam-token.exam-token')}</Panel.Heading>
        <Panel.Body>
          <p>{t('exam-token.note')}</p>
          <strong>{t('exam-token.invalidation')}</strong>
          <Spacer size='s' />
          <Button
            block={true}
            disabled={recentlyGenerated}
            onClick={() => void getToken()}
          >
            {t('exam-token.generate-exam-token')}
          </Button>
        </Panel.Body>
      </Panel>
    </FullWidthRow>
  );
}

ExamToken.displayName = 'ExamToken';

export default ExamToken;
Repository: freeCodeCamp/freeCodeCamp
File: client/src/components/settings/exam-token.tsx (TypeScript)

Code before:
import React, { useState } from 'react';
import { Button, Panel, Modal, Spacer } from '@freecodecamp/ui';
import { useTranslation } from 'react-i18next';
import { FullWidthRow } from '../helpers';
import { generateExamToken } from '../../utils/ajax';

function ExamToken(): JSX.Element {
  const [examToken, setExamToken] = useState<string | null>(null);
  const [examTokenError, setExamTokenError] = useState<string | null>(null);

  const [recentlyGenerated, setRecentlyGenerated] = useState(false);
  const [generatedExamToken, setGeneratedExamToken] = useState(false);

  const [copySuccess, setCopySuccess] = useState<string | null>(null);
  const [copyError, setCopyError] = useState<string | null>(null);

  const debouncedSetRecentlyGenerated = () => {
    setRecentlyGenerated(true);
    setTimeout(() => setRecentlyGenerated(false), 10000);
  };
  const { t } = useTranslation();

  const getToken = async () => {
    try {
      const response = await generateExamToken();

      const {
        data: {
          data: { examEnvironmentAuthorizationToken }
        }
      } = response;
      setExamToken(examEnvironmentAuthorizationToken);
      setExamTokenError('');
    } catch (e) {
      setExamTokenError(t('exam-token.error'));
    }

    debouncedSetRecentlyGenerated();
  };

  return (
    <FullWidthRow>
      <Modal
        open={generatedExamToken}
        onClose={() => {

Review comment (suggestion):
```suggestion
```
We might as well inline this, since it's just two lines quite descriptive code. Also, it's not a debounce, it's just a temporary delay.

Code after:
import React, { useState } from 'react';
import { Button, Panel, Modal, Spacer } from '@freecodecamp/ui';
import { useTranslation } from 'react-i18next';
import { FullWidthRow } from '../helpers';
import { generateExamToken } from '../../utils/ajax';

function ExamToken(): JSX.Element {
  const [examToken, setExamToken] = useState<string | null>(null);
  const [examTokenError, setExamTokenError] = useState<string | null>(null);

  const [recentlyGenerated, setRecentlyGenerated] = useState(false);

  const [copySuccess, setCopySuccess] = useState<string | null>(null);
  const [copyError, setCopyError] = useState<string | null>(null);

  const { t } = useTranslation();

  const getToken = async () => {
    try {
      const response = await generateExamToken();

      const {
        data: {
          data: { examEnvironmentAuthorizationToken }
        }
      } = response;
      setExamToken(examEnvironmentAuthorizationToken);
      setExamTokenError('');
    } catch (e) {
      setExamTokenError(t('exam-token.error'));
    }

    setRecentlyGenerated(true);
    setTimeout(() => setRecentlyGenerated(false), 10000);
  };

  return (
    <FullWidthRow>
      <Modal
        open={!!examToken}
        onClose={() => {
          setExamToken(null);
          setCopySuccess(null);
          setCopyError(null);
        }}
Repository: freeCodeCamp/freeCodeCamp
File: client/src/components/settings/exam-token.tsx (TypeScript)

Code before:
import React, { useState } from 'react';
import { Button, Panel, Modal, Spacer } from '@freecodecamp/ui';
import { useTranslation } from 'react-i18next';
import { FullWidthRow } from '../helpers';
import { generateExamToken } from '../../utils/ajax';

function ExamToken(): JSX.Element {
  const [examToken, setExamToken] = useState<string | null>(null);
  const [examTokenError, setExamTokenError] = useState<string | null>(null);

  const [recentlyGenerated, setRecentlyGenerated] = useState(false);
  const [generatedExamToken, setGeneratedExamToken] = useState(false);

  const [copySuccess, setCopySuccess] = useState<string | null>(null);
  const [copyError, setCopyError] = useState<string | null>(null);

  const debouncedSetRecentlyGenerated = () => {
    setRecentlyGenerated(true);
    setTimeout(() => setRecentlyGenerated(false), 10000);
  };
  const { t } = useTranslation();

  const getToken = async () => {
    try {
      const response = await generateExamToken();

      const {
        data: {
          data: { examEnvironmentAuthorizationToken }
        }
      } = response;
      setExamToken(examEnvironmentAuthorizationToken);
      setExamTokenError('');
    } catch (e) {
      setExamTokenError(t('exam-token.error'));
    }


Review comment (suggestion):
```suggestion
```
We don't need this. Either we have an `examToken`, in which case we show the modal, or we don't, in which case we don't.

Code after:
import React, { useState } from 'react';
import { Button, Panel, Modal, Spacer } from '@freecodecamp/ui';
import { useTranslation } from 'react-i18next';
import { FullWidthRow } from '../helpers';
import { generateExamToken } from '../../utils/ajax';

function ExamToken(): JSX.Element {
  const [examToken, setExamToken] = useState<string | null>(null);
  const [examTokenError, setExamTokenError] = useState<string | null>(null);

  const [recentlyGenerated, setRecentlyGenerated] = useState(false);

  const [copySuccess, setCopySuccess] = useState<string | null>(null);
  const [copyError, setCopyError] = useState<string | null>(null);

  const { t } = useTranslation();

  const getToken = async () => {
    try {
      const response = await generateExamToken();

      const {
        data: {
          data: { examEnvironmentAuthorizationToken }
        }
      } = response;
      setExamToken(examEnvironmentAuthorizationToken);
      setExamTokenError('');
    } catch (e) {
      setExamTokenError(t('exam-token.error'));
    }

    setRecentlyGenerated(true);
    setTimeout(() => setRecentlyGenerated(false), 10000);
  };

  return (