ronantakizawa/codereview-bench huggingface dataset:
Repository: freeCodeCamp/freeCodeCamp
File: e2e/image-picture-check.spec.ts (TypeScript)

Code before:
import { test, expect } from '@playwright/test';

test.describe('Picture input field', () => {
  test.use({ storageState: 'playwright/.auth/certified-user.json' });

  test.beforeEach(async ({ page }) => {
    await page.goto('/settings');
  });

  test('Should be possible to type', async ({ page }) => {
    const pictureInput = page.locator('#about-picture-input');
    await pictureInput.fill('');
    await pictureInput.fill('twaha');
    await expect(pictureInput).toHaveAttribute('value', 'twaha');
  });

  test('Show an error message if an incorrect url was submitted', async ({
    page
  }) => {
    const pictureInput = page.locator('#about-picture-input');
    await pictureInput.fill('');
    await pictureInput.fill(
      'https://s3.amazonaws.com/freecodecamp/camper-image'
    );
    await expect(
      page.locator('text=URL must link directly to an image file')
    ).toBeVisible();
  });

  test('Can submit a correct URL', async ({ page }) => {
    const pictureInput = page.locator('#about-picture-input');
    await pictureInput.fill('');
    await pictureInput.fill(
      'https://s3.amazonaws.com/freecodecamp/camper-image-placeholder.png'
    );


Review comment (suggestion):
Could we use `getByLabel()` here instead? 🙂 That will help ensure the input has an associated label, which is an a11y requirement.

```suggestion
    const pictureInput = page.getByLabel('Picture');
```

Code after:
import { test, expect } from '@playwright/test';

test.describe('Picture input field', () => {
  test.use({ storageState: 'playwright/.auth/certified-user.json' });

  test.beforeEach(async ({ page }) => {
    await page.goto('/settings');
  });

  test('Should be possible to type', async ({ page }) => {
    const pictureInput = page.getByLabel('Picture');
    await pictureInput.fill('');
    await pictureInput.fill('twaha');
    await expect(pictureInput).toHaveAttribute('value', 'twaha');
  });

  test('Show an error message if an incorrect url was submitted', async ({
    page
  }) => {
    const pictureInput = page.getByLabel('Picture');
    await pictureInput.fill('');
    await pictureInput.fill(
      'https://s3.amazonaws.com/freecodecamp/camper-image'
    );
    await expect(
      page.getByText('URL must link directly to an image file')
    ).toBeVisible();
  });

  test('Can submit a correct URL', async ({ page }) => {
    const pictureInput = page.getByLabel('Picture');
    await pictureInput.fill('');
    await pictureInput.fill(
      'https://s3.amazonaws.com/freecodecamp/camper-image-placeholder.png'
    );
Repository: freeCodeCamp/freeCodeCamp
File: e2e/image-picture-check.spec.ts (TypeScript)

Code before:
import { test, expect } from '@playwright/test';

test.describe('Picture input field', () => {
  test.use({ storageState: 'playwright/.auth/certified-user.json' });

  test.beforeEach(async ({ page }) => {
    await page.goto('/settings');
  });

  test('Should be possible to type', async ({ page }) => {
    const pictureInput = page.locator('#about-picture-input');
    await pictureInput.fill('');
    await pictureInput.fill('twaha');
    await expect(pictureInput).toHaveAttribute('value', 'twaha');
  });

  test('Show an error message if an incorrect url was submitted', async ({
    page
  }) => {
    const pictureInput = page.locator('#about-picture-input');
    await pictureInput.fill('');
    await pictureInput.fill(
      'https://s3.amazonaws.com/freecodecamp/camper-image'
    );
    await expect(
      page.locator('text=URL must link directly to an image file')
    ).toBeVisible();
  });

  test('Can submit a correct URL', async ({ page }) => {
    const pictureInput = page.locator('#about-picture-input');
    await pictureInput.fill('');
    await pictureInput.fill(
      'https://s3.amazonaws.com/freecodecamp/camper-image-placeholder.png'
    );

    await page.waitForTimeout(500);
    const saveButton = page.locator('#camper-identity button:has-text("Save")');
    await expect(saveButton).toBeEnabled();
  });
});


Review comment (suggestion):
```suggestion
    const pictureInput = page.getByLabel('Picture');
```

Code after:
import { test, expect } from '@playwright/test';

test.describe('Picture input field', () => {
  test.use({ storageState: 'playwright/.auth/certified-user.json' });

  test.beforeEach(async ({ page }) => {
    await page.goto('/settings');
  });

  test('Should be possible to type', async ({ page }) => {
    const pictureInput = page.getByLabel('Picture');
    await pictureInput.fill('');
    await pictureInput.fill('twaha');
    await expect(pictureInput).toHaveAttribute('value', 'twaha');
  });

  test('Show an error message if an incorrect url was submitted', async ({
    page
  }) => {
    const pictureInput = page.getByLabel('Picture');
    await pictureInput.fill('');
    await pictureInput.fill(
      'https://s3.amazonaws.com/freecodecamp/camper-image'
    );
    await expect(
      page.getByText('URL must link directly to an image file')
    ).toBeVisible();
  });

  test('Can submit a correct URL', async ({ page }) => {
    const pictureInput = page.getByLabel('Picture');
    await pictureInput.fill('');
    await pictureInput.fill(
      'https://s3.amazonaws.com/freecodecamp/camper-image-placeholder.png'
    );

    const form = page.getByTestId('camper-identity');
    const saveButton = form.getByRole('button', { name: 'Save' });
    await expect(saveButton).toBeEnabled();
  });
});
Repository: freeCodeCamp/freeCodeCamp
File: e2e/image-picture-check.spec.ts (TypeScript)

Code before:
  test.beforeEach(async ({ page }) => {
    await page.goto('/settings');
  });

  test('Should be possible to type', async ({ page }) => {
    const pictureInput = page.locator('#about-picture-input');
    await pictureInput.fill('');
    await pictureInput.fill('twaha');
    await expect(pictureInput).toHaveAttribute('value', 'twaha');
  });

  test('Show an error message if an incorrect url was submitted', async ({
    page
  }) => {
    const pictureInput = page.locator('#about-picture-input');
    await pictureInput.fill('');
    await pictureInput.fill(
      'https://s3.amazonaws.com/freecodecamp/camper-image'
    );
    await expect(
      page.locator('text=URL must link directly to an image file')
    ).toBeVisible();
  });

  test('Can submit a correct URL', async ({ page }) => {
    const pictureInput = page.locator('#about-picture-input');
    await pictureInput.fill('');
    await pictureInput.fill(
      'https://s3.amazonaws.com/freecodecamp/camper-image-placeholder.png'
    );

    await page.waitForTimeout(500);
    const saveButton = page.locator('#camper-identity button:has-text("Save")');
    await expect(saveButton).toBeEnabled();
  });
});


Review comment (suggestion):
```suggestion
    const pictureInput = page.getByLabel('Picture');
```

Code after:
  test.beforeEach(async ({ page }) => {
    await page.goto('/settings');
  });

  test('Should be possible to type', async ({ page }) => {
    const pictureInput = page.getByLabel('Picture');
    await pictureInput.fill('');
    await pictureInput.fill('twaha');
    await expect(pictureInput).toHaveAttribute('value', 'twaha');
  });

  test('Show an error message if an incorrect url was submitted', async ({
    page
  }) => {
    const pictureInput = page.getByLabel('Picture');
    await pictureInput.fill('');
    await pictureInput.fill(
      'https://s3.amazonaws.com/freecodecamp/camper-image'
    );
    await expect(
      page.getByText('URL must link directly to an image file')
    ).toBeVisible();
  });

  test('Can submit a correct URL', async ({ page }) => {
    const pictureInput = page.getByLabel('Picture');
    await pictureInput.fill('');
    await pictureInput.fill(
      'https://s3.amazonaws.com/freecodecamp/camper-image-placeholder.png'
    );

    const form = page.getByTestId('camper-identity');
    const saveButton = form.getByRole('button', { name: 'Save' });
    await expect(saveButton).toBeEnabled();
  });
});
Repository: freeCodeCamp/freeCodeCamp
File: client/src/templates/Challenges/components/scene/scene.tsx (TypeScript)

Code before:
import React, { useEffect, useState, useRef } from 'react'; //, ReactElement } from 'react';
import { Col } from '@freecodecamp/ui';
import { t } from 'i18next';
import { FullScene } from '../../../../redux/prop-types';
import { Loader } from '../../../../components/helpers';
import ClosedCaptionsIcon from '../../../../assets/icons/closedcaptions';
import { sounds, images, backgrounds, characterAssets } from './scene-assets';
import Character from './character';

import './scene.css';

export function Scene({
  scene,
  isPlaying,
  setIsPlaying
}: {
  scene: FullScene;
  isPlaying: boolean;
  setIsPlaying: (shouldPlay: boolean) => void;
}): JSX.Element {
  const { setup, commands } = scene;
  const { audio, alwaysShowDialogue } = setup;

  const audioTimestamp =
    audio.startTimestamp !== null && audio.finishTimestamp !== null
      ? `#t=${audio.startTimestamp},${audio.finishTimestamp}`
      : '';


Review comment (suggestion):
I think we should pull the `t` function from the `useTranslation` hook instead.

```tsx
import { useTranslation } from 'react-i18next';

const { t } = useTranslation();

<img alt={t('buttons.play-scene')} />
```

The `useTranslation` hook has some rendering logic to ensure the component only renders once the conditions are met (eg. the translation strings are ready).

Code after:
import React, { useEffect, useState, useRef } from 'react'; //, ReactElement } from 'react';
import { Col } from '@freecodecamp/ui';
import { useTranslation } from 'react-i18next';
import { FullScene } from '../../../../redux/prop-types';
import { Loader } from '../../../../components/helpers';
import ClosedCaptionsIcon from '../../../../assets/icons/closedcaptions';
import { sounds, images, backgrounds, characterAssets } from './scene-assets';
import Character from './character';

import './scene.css';

export function Scene({
  scene,
  isPlaying,
  setIsPlaying
}: {
  scene: FullScene;
  isPlaying: boolean;
  setIsPlaying: (shouldPlay: boolean) => void;
}): JSX.Element {
  const { t } = useTranslation();
  const { setup, commands } = scene;
  const { audio, alwaysShowDialogue } = setup;

  const audioTimestamp =
    audio.startTimestamp !== null && audio.finishTimestamp !== null
      ? `#t=${audio.startTimestamp},${audio.finishTimestamp}`
      : '';
Repository: freeCodeCamp/freeCodeCamp
File: client/src/client-only-routes/show-certification.tsx (TypeScript)

Code before:
    isValidCert,
    createFlashMessage,
    signedInUserName,
    location: { pathname }
  } = props;

  if (!isValidCert) {
    createFlashMessage(certificateMissingErrorMessage);
    return <RedirectHome />;
  }

  const { pending, complete, errored } = fetchState;

  if (pending) {
    return <Loader fullScreen={true} />;
  }

  if (!pending && errored) {
    createFlashMessage(standardErrorMessage);
    return <RedirectHome />;
  }

  if (!pending && !complete && !errored) {
    createFlashMessage(reallyWeirdErrorMessage);
    return <RedirectHome />;
  }

  const {
    date,
    name: userFullName = null,
    username,
    certTitle,
    certSlug,
    completionTime
  } = cert;

  const { user } = props;

  const displayName = userFullName ?? username;

  const certDate = new Date(date);
  const certYear = certDate.getFullYear();
  const certMonth = certDate.getMonth();
  const certURL = `https://freecodecamp.org${pathname}`;

  const donationCloseBtn = (
    <div>
      <Button
        block={true}
        size='small'
        variant='primary'

Review comment (suggestion):
```suggestion
  if (errored || !complete || !isValidCert) {
```

Code after:
    isValidCert,
    createFlashMessage,
    signedInUserName,
    location: { pathname }
  } = props;
  const { pending, complete, errored } = fetchState;

  useEffect(() => {
    if (!isValidCert) {
      createFlashMessage(certificateMissingErrorMessage);
    } else if (!pending && errored) {
      createFlashMessage(standardErrorMessage);
    } else if (!pending && !complete && !errored) {
      createFlashMessage(reallyWeirdErrorMessage);
    }
  }, [isValidCert, createFlashMessage, pending, errored, complete]);

  if (!isValidCert) {
    return <RedirectHome />;
  }

  if (pending) {
    return <Loader fullScreen={true} />;
  }

  if (errored || !complete) {
    return <RedirectHome />;
  }

  const {
    date,
    name: userFullName = null,
    username,
    certTitle,
    certSlug,
    completionTime
  } = cert;

  const { user } = props;

  const displayName = userFullName ?? username;

  const certDate = new Date(date);
  const certYear = certDate.getFullYear();
  const certMonth = certDate.getMonth();
  const certURL = `https://freecodecamp.org${pathname}`;

  const donationCloseBtn = (
    <div>
      <Button
        block={true}
Repository: freeCodeCamp/freeCodeCamp
File: e2e/intro-page.spec.ts (TypeScript)

Code before:
import { test, expect } from '@playwright/test';

test.describe('Certification intro page', () => {
  test('Should render', async ({ page }) => {
    await page.goto('/learn/coding-interview-prep');
    await expect(
      page.locator(
        "text=If you're looking for free coding exercises to prepare for your next job interview, we've got you covered."
      )
    ).toBeVisible();
    await expect(page).toHaveTitle('Coding Interview Prep | freeCodeCamp.org');
  });
});


Review comment (suggestion):
Nit:

```suggestion
      page.getByText(
        'If you're looking for free coding exercises to prepare for your next job interview, we've got you covered.'
      )
```

(You might want to make this change locally, since Prettier could get involved.)

Code after:
import { test, expect } from '@playwright/test';

test.describe('Certification intro page', () => {
  test('Should render', async ({ page }) => {
    await page.goto('/learn/coding-interview-prep');
    await expect(
      page.getByText(
        "If you're looking for free coding exercises to prepare for your next job interview, we've got you covered."
      )
    ).toBeVisible();
    await expect(page).toHaveTitle('Coding Interview Prep | freeCodeCamp.org');
  });
});
Repository: freeCodeCamp/freeCodeCamp
File: shared/config/donation-settings.ts (TypeScript)

Code before:
  Stripe = 'stripe',
  StripeCard = 'stripe card'
}

export const stripeProductIds = {
  live: {
    month: {
      500: 'prod_Cc9bIxB2NvjpLy',
      1000: 'prod_BuiSxWk7jGSFlJ',
      2000: 'prod_IElpZVK7kOn6Fe',
      4000: 'prod_IElq1foW39g3Cx'
    }
  },
  staging: {
    month: {
      500: 'prod_GD1GGbJsqQaupl',
      1000: 'prod_GD1IzNEXfSCGgy',
      2000: 'prod_IEkNp8M03xvsuB',
      4000: 'prod_IEkPebxS63mVbs'
    }
  }
};

export const allStripeProductIdsArray = Object.values(stripeProductIds)
  .flatMap(env => Object.values(env))
  .flatMap(duration => Object.values(duration));


Review comment (suggestion):
```suggestion
} as const;

export const allStripeProductIdsArray = [
  ...Object.values(stripeProductIds['live']['month']),
  ...Object.values(stripeProductIds['staging']['month'])
];
```
Bit more readable, imo. Also, it's stricter type-wise (it has the literals, not the just `string`)

Code after:
  Stripe = 'stripe',
  StripeCard = 'stripe card'
}

const stripeProductIds = {
  live: {
    month: {
      500: 'prod_Cc9bIxB2NvjpLy',
      1000: 'prod_BuiSxWk7jGSFlJ',
      2000: 'prod_IElpZVK7kOn6Fe',
      4000: 'prod_IElq1foW39g3Cx'
    }
  },
  staging: {
    month: {
      500: 'prod_GD1GGbJsqQaupl',
      1000: 'prod_GD1IzNEXfSCGgy',
      2000: 'prod_IEkNp8M03xvsuB',
      4000: 'prod_IEkPebxS63mVbs'
    }
  }
};

export const allStripeProductIdsArray = [
  ...Object.values(stripeProductIds['live']['month']),
  ...Object.values(stripeProductIds['staging']['month'])
];
Repository: freeCodeCamp/freeCodeCamp
File: shared/config/donation-settings.ts (TypeScript)

Code before:

export enum PaymentProvider {
  Paypal = 'paypal',
  Patreon = 'patreon',
  Stripe = 'stripe',
  StripeCard = 'stripe card'
}

export const stripeProductIds = {
  live: {
    month: {
      500: 'prod_Cc9bIxB2NvjpLy',
      1000: 'prod_BuiSxWk7jGSFlJ',
      2000: 'prod_IElpZVK7kOn6Fe',
      4000: 'prod_IElq1foW39g3Cx'
    }
  },
  staging: {
    month: {
      500: 'prod_GD1GGbJsqQaupl',
      1000: 'prod_GD1IzNEXfSCGgy',
      2000: 'prod_IEkNp8M03xvsuB',
      4000: 'prod_IEkPebxS63mVbs'
    }
  }
};

export const allStripeProductIdsArray = Object.values(stripeProductIds)
  .flatMap(env => Object.values(env))
  .flatMap(duration => Object.values(duration));


Review comment (suggestion):
```suggestion
const stripeProductIds = {
  live: {
    month: {
      500: 'prod_Cc9bIxB2NvjpLy',
      1000: 'prod_BuiSxWk7jGSFlJ',
      2000: 'prod_IElpZVK7kOn6Fe',
      4000: 'prod_IElq1foW39g3Cx'
    }
  },
  staging: {
    month: {
      500: 'prod_GD1GGbJsqQaupl',
      1000: 'prod_GD1IzNEXfSCGgy',
      2000: 'prod_IEkNp8M03xvsuB',
      4000: 'prod_IEkPebxS63mVbs'
    }
  }
};
```
What is this for? It's not imported anywhere.

Code after:

export enum PaymentProvider {
  Paypal = 'paypal',
  Patreon = 'patreon',
  Stripe = 'stripe',
  StripeCard = 'stripe card'
}

const stripeProductIds = {
  live: {
    month: {
      500: 'prod_Cc9bIxB2NvjpLy',
      1000: 'prod_BuiSxWk7jGSFlJ',
      2000: 'prod_IElpZVK7kOn6Fe',
      4000: 'prod_IElq1foW39g3Cx'
    }
  },
  staging: {
    month: {
      500: 'prod_GD1GGbJsqQaupl',
      1000: 'prod_GD1IzNEXfSCGgy',
      2000: 'prod_IEkNp8M03xvsuB',
      4000: 'prod_IEkPebxS63mVbs'
    }
  }
};

export const allStripeProductIdsArray = [
  ...Object.values(stripeProductIds['live']['month']),
  ...Object.values(stripeProductIds['staging']['month'])
];
Repository: freeCodeCamp/freeCodeCamp
File: client/src/components/Donation/wallets-button.tsx (TypeScript)

Code before:
    void pr.canMakePayment().then(result => {
      if (result) setPaymentRequest(pr);
    });

    return () => {
      setPaymentRequest(null);
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [label, amount, stripe, postPayment, handlePaymentButtonLoad]);

  const displayError = (errorMessage: string): void => {
    onDonationStateChange({
      redirecting: false,
      processing: false,
      success: false,
      error: errorMessage
    });
  };

  return (
    <form className='wallets-form'>
      {paymentRequest && (
        <PaymentRequestButtonElement
          onClick={() => {
            if (paymentMethod) {
              displayError(t('donate.refresh-needed'));
            }
          }}
          onReady={() => handlePaymentButtonLoad('stripe')}
          options={{
            style: {
              paymentRequestButton: {
                type: 'default',
                theme: theme === Themes.Night ? 'light' : 'dark',
                height: '43px'
              }
            },
            paymentRequest
          }}
        />
      )}
    </form>
  );
};

export default function InjectedCheckoutForm(props: WrapperProps): JSX.Element {
  return (
    <ElementsConsumer>
      {({ stripe }: { stripe: Stripe | null }) => (
        <WalletsButton stripe={stripe} {...props} />
      )}

Review comment (suggestion):
It's not clear why having a payment method should result in an error being displayed. I would have assumed the opposite, so perhaps this needs a different name or a comment to clarify.

Code after:
      if (result) setPaymentRequest(pr);
    });

    return () => {
      setPaymentRequest(null);
    };
  }, [
    label,
    amount,
    stripe,
    postPayment,
    handlePaymentButtonLoad,
    duration,
    displayError,
    t
  ]);

  return (
    <form className='wallets-form'>
      {paymentRequest && (
        <PaymentRequestButtonElement
          onReady={() => handlePaymentButtonLoad('stripe')}
          options={{
            style: {
              paymentRequestButton: {
                type: 'default',
                theme: theme === Themes.Night ? 'light' : 'dark',
                height: '43px'
              }
            },
            paymentRequest
          }}
        />
      )}
    </form>
  );
};

export default function InjectedCheckoutForm(props: WrapperProps): JSX.Element {
  return (
    <ElementsConsumer>
      {({ stripe }: { stripe: Stripe | null }) => (
        <WalletsButton stripe={stripe} {...props} />
      )}
    </ElementsConsumer>
  );
}
Repository: freeCodeCamp/freeCodeCamp
File: client/src/components/Donation/wallets-button.tsx (TypeScript)

Code before:
import { DonationApprovalData, PostPayment } from './types';

interface WrapperProps {
  label: string;
  amount: number;
  theme: Themes;
  duration: DonationDuration;
  postPayment: (arg0: PostPayment) => void;
  onDonationStateChange: (donationState: DonationApprovalData) => void;
  handlePaymentButtonLoad: (provider: 'stripe' | 'paypal') => void;
}
interface WalletsButtonProps extends WrapperProps {
  stripe: Stripe | null;
}

const WalletsButton = ({
  stripe,
  label,
  amount,
  theme,
  duration,
  postPayment,
  onDonationStateChange,
  handlePaymentButtonLoad
}: WalletsButtonProps) => {
  const [paymentMethod, setpaymentMethod] = useState<PaymentMethod | null>(
    null
  );
  const [paymentRequest, setPaymentRequest] = useState<PaymentRequest | null>(
    null
  );
  const { t } = useTranslation();

  useEffect(() => {
    if (!stripe) {
      return;
    }

    const pr = stripe.paymentRequest({
      country: 'US',
      currency: 'usd',
      total: { label, amount },
      requestPayerName: true,
      requestPayerEmail: true,
      disableWallets: ['browserCard']
    });

    pr.on('paymentmethod', async event => {
      setpaymentMethod(event.paymentMethod);
      const {
        payerEmail,

Review comment (suggestion):
```suggestion
  const [paymentMethod, setPaymentMethod] = useState<PaymentMethod | null>(
```
Nit.

Code after:
import { DonationApprovalData, PostPayment } from './types';

interface WrapperProps {
  label: string;
  amount: number;
  theme: Themes;
  duration: DonationDuration;
  postPayment: (arg0: PostPayment) => void;
  onDonationStateChange: (donationState: DonationApprovalData) => void;
  handlePaymentButtonLoad: (provider: 'stripe' | 'paypal') => void;
}
interface WalletsButtonProps extends WrapperProps {
  stripe: Stripe | null;
}

const WalletsButton = ({
  stripe,
  label,
  amount,
  theme,
  duration,
  postPayment,
  onDonationStateChange,
  handlePaymentButtonLoad
}: WalletsButtonProps) => {
  const [paymentRequest, setPaymentRequest] = useState<PaymentRequest | null>(
    null
  );
  const { t } = useTranslation();

  const displayError = useCallback(
    (errorMessage: string): void => {
      onDonationStateChange({
        redirecting: false,
        processing: false,
        success: false,
        error: errorMessage
      });
    },
    [onDonationStateChange]
  );

  useEffect(() => {
    if (!stripe) {
      return;
    }

    const pr = stripe.paymentRequest({
      country: 'US',
      currency: 'usd',
      total: { label, amount },