Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions client/src/templates/Challenges/classic/editor.css
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,16 @@ textarea.inputarea {
display: none;
}

.lower-jaw-check-row {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}

.lower-jaw-check-row .lower-jaw-check-button {
flex: 1 1 240px;
}

@keyframes example {
from {
background-color: var(--highlight-background);
Expand Down
83 changes: 83 additions & 0 deletions client/src/templates/Challenges/classic/lower-jaw.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import React from 'react';
import { describe, expect, it, vi } from 'vitest';
import { render, screen } from '@testing-library/react';
import { challengeTypes } from '@freecodecamp/shared/config/challenge-types';

import type { ChallengeMeta } from '../../../redux/prop-types';
import { LowerJaw } from './lower-jaw';

vi.mock('../../../../src/utils/get-words', () => ({
randomCompliment: () => 'great work'
}));

const baseProps = {
completedPercent: 0,
isPythonPreviewRunning: false,
challengeIsCompleted: false,
openHelpModal: vi.fn(),
tryToExecuteChallenge: vi.fn(),
tryToSubmitChallenge: vi.fn(),
testsLength: 1,
attempts: 0,
openResetModal: vi.fn(),
isSignedIn: true,
updateContainer: vi.fn(),
runPythonPreview: vi.fn(),
cancelPythonPreview: vi.fn()
};

const getChallengeMeta = (challengeType: number): ChallengeMeta =>
({
superBlock: 'python-for-everybody',
block: 'introduction-to-python',
challengeType
}) as ChallengeMeta;

describe('LowerJaw python controls', () => {
it('renders Run Code button for python challenges when not running', () => {
render(
<LowerJaw
{...baseProps}
challengeMeta={getChallengeMeta(challengeTypes.python)}
/>
);

expect(
screen.getByRole('button', { name: /run code/i })
).toBeInTheDocument();
expect(
screen.queryByRole('button', { name: /cancel/i })
).not.toBeInTheDocument();
});

it('renders Cancel button for python challenges when running', () => {
render(
<LowerJaw
{...baseProps}
isPythonPreviewRunning={true}
challengeMeta={getChallengeMeta(challengeTypes.python)}
/>
);

expect(screen.getByRole('button', { name: /cancel/i })).toBeInTheDocument();
expect(
screen.queryByRole('button', { name: /run code/i })
).not.toBeInTheDocument();
});

it('does not render Run Code or Cancel buttons for non-python challenges', () => {
render(
<LowerJaw
{...baseProps}
challengeMeta={getChallengeMeta(challengeTypes.modern)}
/>
);

expect(
screen.queryByRole('button', { name: /run code/i })
).not.toBeInTheDocument();
expect(
screen.queryByRole('button', { name: /cancel/i })
).not.toBeInTheDocument();
});
});
82 changes: 63 additions & 19 deletions client/src/templates/Challenges/classic/lower-jaw.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import { createSelector } from 'reselect';
import { Button, Spacer } from '@freecodecamp/ui';
import { connect } from 'react-redux';
import { challengeTypes } from '@freecodecamp/shared/config/challenge-types';
import Fail from '../../../assets/icons/fail';
import LightBulb from '../../../assets/icons/lightbulb';
import GreenPass from '../../../assets/icons/green-pass';
Expand All @@ -19,8 +20,10 @@
import Quote from '../../../assets/icons/quote';
import {
challengeMetaSelector,
completedPercentageSelector
completedPercentageSelector,
pythonPreviewRunningSelector
} from '../redux/selectors';
import { cancelPythonPreview, runPythonPreview } from '../redux/actions';
import callGA from '../../../analytics/call-ga';

interface LowerJawPanelProps extends ShareProps {
Expand Down Expand Up @@ -49,6 +52,7 @@
interface LowerJawProps {
challengeMeta: ChallengeMeta;
completedPercent: number;
isPythonPreviewRunning: boolean;
hint?: string;
challengeIsCompleted: boolean;
openHelpModal: () => void;
Expand All @@ -59,17 +63,30 @@
openResetModal: () => void;
isSignedIn: boolean;
updateContainer: () => void;
runPythonPreview: () => void;
cancelPythonPreview: () => void;
}

const mapStateToProps = createSelector(
challengeMetaSelector,
completedPercentageSelector,
(challengeMeta: ChallengeMeta, completedPercent: number) => ({
pythonPreviewRunningSelector,
(
challengeMeta: ChallengeMeta,
completedPercent: number,
isPythonPreviewRunning: boolean
) => ({
challengeMeta,
completedPercent
completedPercent,
isPythonPreviewRunning
})
);

const mapDispatchToProps = {
runPythonPreview,
cancelPythonPreview
};

const sentenceArray = [
'learn.sorry-try-again',
'learn.sorry-keep-trying',
Expand Down Expand Up @@ -185,100 +202,103 @@

const isBlockCompleted = 100;

const LowerJaw = ({
challengeMeta: { superBlock, block },
export const LowerJaw = ({
challengeMeta: { superBlock, block, challengeType },
completedPercent,
isPythonPreviewRunning,
openHelpModal,
challengeIsCompleted,
hint,
tryToExecuteChallenge,
tryToSubmitChallenge,
attempts,
testsLength,
openResetModal,
isSignedIn,
updateContainer
updateContainer,
runPythonPreview,
cancelPythonPreview
}: LowerJawProps): JSX.Element => {
const [shownHint, setShownHint] = useState(hint);
const [quote, setQuote] = useState(randomCompliment());
const [runningTests, setRunningTests] = useState(false);
const [testFeedbackHeight, setTestFeedbackHeight] = useState(0);
const [shownAttempts, setShownAttempts] = useState(attempts);
const [isFeedbackHidden, setIsFeedbackHidden] = useState(true);
const { t } = useTranslation();
const testFeedbackRef = React.createRef<HTMLDivElement>();

const checkYourCodeButtonRef = useRef<HTMLButtonElement>(null);
const submitButtonRef = useRef<HTMLButtonElement>(null);
const [focusManagementCompleted, setFocusManagementCompleted] =
useState(false);
const isCheckYourCodeButtonClicked = () => {
const activeElement = document.activeElement;
// Need to check Submit button as well because if it has focus then it is
// implied that Check Your Code button was clicked.
return (
activeElement === checkYourCodeButtonRef.current ||
activeElement === submitButtonRef.current
);
};

const showShareButton =
challengeIsCompleted && completedPercent === isBlockCompleted;

// Attempts should only be zero when the step is reset, so we should reset
// the state here.
if (attempts !== shownAttempts && attempts === 0) {
setShownAttempts(0);
setRunningTests(false);
setIsFeedbackHidden(false);
setShownHint('');
}
useEffect(() => {
if (attempts > shownAttempts) {
//hide the feedback from SR until the "Running tests" are displayed and removed.
setIsFeedbackHidden(true);
setRunningTests(true);
//to prevent the changing attempts value from immediately triggering a new
//render, the rendered component only depends on shownAttempts. Since
//shownAttempts is updated with when the feedback is hidden, the screen
//reader should only read out the new message. Note: this starts with the
//second encouragement since attempts starts at 1.
setShownAttempts(attempts);
//display the test feedback contents.
setTimeout(() => {
setRunningTests(false);
setIsFeedbackHidden(false);
}, 300);
}
}, [attempts, shownAttempts]);

useEffect(() => {
// Since there's no guarantee that hint and attempts update in the same
// render, hints have to be updated separately.
if (hint) setShownHint(hint);
}, [hint]);

useEffect(() => {
if (challengeIsCompleted) {
// If Ctrl + Enter was used then we don't need to worry about setting
// focus, just leave it where it is. In NVDA, Ctrl + Enter will trigger
// a code check if focus is on a button in the tabs row. So it is not
// enough to only check whether the focus is in the editor.
if (!isCheckYourCodeButtonClicked()) {
setFocusManagementCompleted(true);
return;
}
// Delay focusing Submit button so that screen reader will announce
// it after the test results.
setQuote(randomCompliment());
setTimeout(() => {
submitButtonRef.current?.focus();
setFocusManagementCompleted(true);
}, 500);
}
}, [challengeIsCompleted]);

// ToDo: turn it into a grid to remove the need for useEffect.

Check notice on line 301 in client/src/templates/Challenges/classic/lower-jaw.tsx

View check run for this annotation

codefactor.io / CodeFactor

client/src/templates/Challenges/classic/lower-jaw.tsx#L301

Unexpected 'todo' comment: 'ToDo: turn it into a grid to remove the...'. (no-warning-comments)
// eslint-disable-next-line react-hooks/exhaustive-deps
useEffect(() => {
if (testFeedbackRef.current) {
Expand Down Expand Up @@ -310,6 +330,12 @@
: t('buttons.submit-and-go');

const showSignInButton = !isSignedIn && challengeIsCompleted;
const isPythonChallenge =
challengeType === challengeTypes.python ||
challengeType === challengeTypes.multifilePythonCertProject ||
challengeType === challengeTypes.pyLab ||
challengeType === challengeTypes.dailyChallengePy;
const showPythonRunControls = isPythonChallenge && !challengeIsCompleted;

return (
<div className='action-row-container'>
Expand Down Expand Up @@ -343,18 +369,36 @@
challengeIsCompleted && !focusManagementCompleted ? 'sr-only' : ''
}
>
<Button
data-playwright-test-label='lowerJaw-check-button'
block
onClick={tryToExecuteChallenge}
{...(challengeIsCompleted &&
!focusManagementCompleted && { tabIndex: -1 })}
{...(challengeIsCompleted &&
focusManagementCompleted && { 'aria-hidden': true })}
ref={checkYourCodeButtonRef}
>
{checkButtonText}
</Button>
<div className='lower-jaw-check-row'>
<Button
data-playwright-test-label='lowerJaw-check-button'
className='lower-jaw-check-button'
onClick={tryToExecuteChallenge}
{...(challengeIsCompleted &&
!focusManagementCompleted && { tabIndex: -1 })}
{...(challengeIsCompleted &&
focusManagementCompleted && { 'aria-hidden': true })}
ref={checkYourCodeButtonRef}
>
{checkButtonText}
</Button>
{showPythonRunControls &&
(isPythonPreviewRunning ? (
<Button
data-playwright-test-label='lowerJaw-python-cancel-button'
onClick={cancelPythonPreview}
>
{t('buttons.cancel')}
</Button>
) : (
<Button
data-playwright-test-label='lowerJaw-python-run-button'
onClick={runPythonPreview}
>
Run Code
</Button>
))}
</div>
</div>
{/* Using aria-live=polite instead of assertive works better with ORCA */}
<div
Expand Down Expand Up @@ -419,4 +463,4 @@

LowerJaw.displayName = 'LowerJaw';

export default connect(mapStateToProps)(LowerJaw);
export default connect(mapStateToProps, mapDispatchToProps)(LowerJaw);
13 changes: 11 additions & 2 deletions client/src/templates/Challenges/classic/xterm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@ import React, { MutableRefObject, useEffect, useRef } from 'react';
import type { IDisposable, Terminal } from 'xterm';
import type { FitAddon } from 'xterm-addon-fit';
import { useTranslation } from 'react-i18next';
import { useDispatch } from 'react-redux';

import { registerTerminal } from '../utils/python-worker-handler';
import { setPythonPreviewRunning } from '../redux/actions';
import './xterm.css';
import './xterm-original.css';

Expand All @@ -26,6 +28,7 @@ export const XtermTerminal = ({
dimensions?: { height: number; width: number };
}) => {
const termContainerRef = useRef<HTMLDivElement | null>(null);
const dispatch = useDispatch();
const { t } = useTranslation();

useEffect(() => {
Expand Down Expand Up @@ -120,15 +123,21 @@ export const XtermTerminal = ({

outputForScreenReader.textContent = '';
};
registerTerminal({ print, input, reset });
registerTerminal({
print,
input,
reset,
stopped: () => dispatch(setPythonPreviewRunning(false)),
runComplete: () => dispatch(setPythonPreviewRunning(false))
});
}

void createTerminal();

return () => {
term?.dispose();
};
}, [xtermFitRef, t]);
}, [dispatch, xtermFitRef, t]);

useEffect(() => {
if (xtermFitRef.current) xtermFitRef.current.fit();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,12 @@
align-items: center;
}

.independent-lower-jaw .independent-check-actions {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}

.independent-lower-jaw .hint-container button {
height: 30px;
font-size: 1.5rem;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import React from 'react';
import { render, screen } from '@testing-library/react';
import { describe, it, expect, vi } from 'vitest';
import { challengeTypes } from '@freecodecamp/shared/config/challenge-types';
import type { ChallengeMeta, Test } from '../../../redux/prop-types';
import { SuperBlocks } from '@freecodecamp/shared/config/curriculum';
import { IndependentLowerJaw } from './independent-lower-jaw';
Expand All @@ -22,6 +23,9 @@ const baseProps = {
openResetModal: vi.fn(),
executeChallenge: vi.fn(),
submitChallenge: vi.fn(),
runPythonPreview: vi.fn(),
cancelPythonPreview: vi.fn(),
isPythonPreviewRunning: false,
tests: passingTests,
isSignedIn: true,
challengeMeta: baseChallengeMeta,
Expand Down Expand Up @@ -63,3 +67,55 @@ describe('<IndependentLowerJaw />', () => {
expect(screen.queryByTestId('share-on-x')).not.toBeInTheDocument();
});
});

describe('IndependentLowerJaw python controls', () => {
it('renders Run Code button for python challenges when not running', () => {
render(
<IndependentLowerJaw
{...baseProps}
tests={[{ text: 'test', testString: 'test code', pass: false }]}
challengeType={challengeTypes.python}
/>
);

expect(
screen.getByRole('button', { name: /run code/i })
).toBeInTheDocument();
expect(
screen.queryByRole('button', { name: /cancel/i })
).not.toBeInTheDocument();
});

it('renders Cancel button for python challenges when running', () => {
render(
<IndependentLowerJaw
{...baseProps}
tests={[{ text: 'test', testString: 'test code', pass: false }]}
isPythonPreviewRunning={true}
challengeType={challengeTypes.python}
/>
);

expect(screen.getByRole('button', { name: /cancel/i })).toBeInTheDocument();
expect(
screen.queryByRole('button', { name: /run code/i })
).not.toBeInTheDocument();
});

it('does not render Run Code or Cancel buttons for non-python challenges', () => {
render(
<IndependentLowerJaw
{...baseProps}
tests={[{ text: 'test', testString: 'test code', pass: false }]}
challengeType={challengeTypes.modern}
/>
);

expect(
screen.queryByRole('button', { name: /run code/i })
).not.toBeInTheDocument();
expect(
screen.queryByRole('button', { name: /cancel/i })
).not.toBeInTheDocument();
});
});
Loading
Loading