Gugu8 commited on
Commit
899c8f8
·
verified ·
1 Parent(s): 4767293

Add github_code/freeCodeCamp__freeCodeCamp from GitHub (part 4)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +4 -0
  2. github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/classic/mobile-layout.test.tsx +145 -0
  3. github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/classic/mobile-layout.tsx +343 -0
  4. github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/classic/multifile-editor.tsx +173 -0
  5. github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/classic/react-types-license +21 -0
  6. github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/classic/react-types.json +0 -0
  7. github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/classic/saved-challenges.test.ts +143 -0
  8. github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/classic/saved-challenges.ts +30 -0
  9. github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/classic/show.tsx +593 -0
  10. github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/classic/xterm-original.css +231 -0
  11. github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/classic/xterm.css +3 -0
  12. github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/classic/xterm.tsx +148 -0
  13. github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/codeally/codeally.css +3 -0
  14. github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/codeally/codespaces-instructions.tsx +211 -0
  15. github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/codeally/local-instructions.tsx +131 -0
  16. github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/codeally/project-submit.test.ts +37 -0
  17. github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/codeally/project-submit.ts +17 -0
  18. github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/codeally/rdb-local-logout-alert.tsx +21 -0
  19. github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/codeally/rdb-step-1-instructions.tsx +32 -0
  20. github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/codeally/rdb-step-2-instructions.tsx +33 -0
  21. github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/codeally/show.tsx +399 -0
  22. github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/assignments.css +4 -0
  23. github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/assignments.tsx +68 -0
  24. github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/bread-crumb.test.tsx +39 -0
  25. github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/bread-crumb.tsx +44 -0
  26. github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/challenge-description.css +17 -0
  27. github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/challenge-description.test.tsx +31 -0
  28. github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/challenge-description.tsx +50 -0
  29. github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/challenge-explanation.css +3 -0
  30. github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/challenge-explanation.tsx +41 -0
  31. github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/challenge-heading.css +10 -0
  32. github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/challenge-heading.tsx +28 -0
  33. github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/challenge-title.css +117 -0
  34. github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/challenge-title.test.tsx +57 -0
  35. github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/challenge-title.tsx +41 -0
  36. github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/challenge-transcript.css +19 -0
  37. github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/challenge-transcript.test.tsx +114 -0
  38. github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/challenge-transcript.tsx +76 -0
  39. github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/completion-modal.css +113 -0
  40. github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/completion-modal.test.tsx +390 -0
  41. github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/completion-modal.tsx +228 -0
  42. github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/custom-monaco-editor.css +9 -0
  43. github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/custom-monaco-editor.tsx +101 -0
  44. github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/daily-challenge-bread-crumb.test.tsx +48 -0
  45. github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/daily-challenge-bread-crumb.tsx +43 -0
  46. github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/fill-in-the-blanks.test.tsx +87 -0
  47. github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/fill-in-the-blanks.tsx +217 -0
  48. github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/help-modal.css +15 -0
  49. github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/help-modal.test.tsx +305 -0
  50. github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/help-modal.tsx +350 -0
.gitattributes CHANGED
@@ -59,3 +59,7 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
61
  code_syntax_dataset_1GB.csv filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
61
  code_syntax_dataset_1GB.csv filter=lfs diff=lfs merge=lfs -text
62
+ github_code/freeCodeCamp__freeCodeCamp/client/static/fonts/noto-sans-japanese/NotoSansJP-Black.woff filter=lfs diff=lfs merge=lfs -text
63
+ github_code/freeCodeCamp__freeCodeCamp/client/static/fonts/noto-sans-japanese/NotoSansJP-Bold.woff filter=lfs diff=lfs merge=lfs -text
64
+ github_code/freeCodeCamp__freeCodeCamp/client/static/fonts/noto-sans-japanese/NotoSansJP-Light.woff filter=lfs diff=lfs merge=lfs -text
65
+ github_code/freeCodeCamp__freeCodeCamp/client/static/fonts/noto-sans-japanese/NotoSansJP-Regular.woff filter=lfs diff=lfs merge=lfs -text
github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/classic/mobile-layout.test.tsx ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React from 'react';
2
+ import { render, screen, fireEvent } from '@testing-library/react';
3
+ import userEvent from '@testing-library/user-event';
4
+ import { describe, it, expect, vi } from 'vitest';
5
+ import { MobileLayout } from './mobile-layout';
6
+
7
+ vi.mock('i18next', () => ({
8
+ default: {
9
+ t: (key: string) => key
10
+ }
11
+ }));
12
+
13
+ vi.mock('../components/independent-lower-jaw', () => ({
14
+ default: () => <div data-testid='independent-lower-jaw' />
15
+ }));
16
+
17
+ const mockProps = {
18
+ editor: <div>Editor</div>,
19
+ hasEditableBoundaries: false,
20
+ hasPreview: false,
21
+ instructions: <div>Instructions</div>,
22
+ notes: '',
23
+ preview: <div>Preview</div>,
24
+ onPreviewResize: vi.fn(),
25
+ windowTitle: 'Test Title',
26
+ showPreviewPortal: false,
27
+ showPreviewPane: false,
28
+ removePortalWindow: vi.fn(),
29
+ setShowPreviewPortal: vi.fn(),
30
+ setShowPreviewPane: vi.fn(),
31
+ portalWindow: null,
32
+ updateUsingKeyboardInTablist: vi.fn(),
33
+ testOutput: <div>Test Output</div>,
34
+ usesMultifileEditor: false,
35
+ usesTerminal: false
36
+ };
37
+
38
+ const renderMobileLayout = (
39
+ props: Partial<React.ComponentProps<typeof MobileLayout>> = {}
40
+ ) => render(<MobileLayout {...mockProps} {...props} />);
41
+
42
+ describe('<MobileLayout />', () => {
43
+ it('renders instructions, code, console, preview, portal controls, and the lower jaw when preview is available', () => {
44
+ renderMobileLayout({
45
+ hasPreview: true,
46
+ showPreviewPane: true
47
+ });
48
+
49
+ expect(screen.getByRole('tablist')).toBeInTheDocument();
50
+ expect(
51
+ screen.getByRole('tab', { name: 'learn.editor-tabs.instructions' })
52
+ ).toBeInTheDocument();
53
+ expect(
54
+ screen.getByRole('tab', { name: 'learn.editor-tabs.code' })
55
+ ).toBeInTheDocument();
56
+ expect(
57
+ screen.getByRole('tab', { name: 'learn.editor-tabs.console' })
58
+ ).toBeInTheDocument();
59
+ expect(
60
+ screen.getByRole('tab', { name: 'learn.editor-tabs.preview' })
61
+ ).toBeInTheDocument();
62
+ expect(
63
+ screen.getByRole('button', { name: 'aria.move-preview-to-new-window' })
64
+ ).toBeInTheDocument();
65
+ expect(screen.getByTestId('independent-lower-jaw')).toBeInTheDocument();
66
+ });
67
+
68
+ it('renders instructions, code, console, and the lower jaw when preview is unavailable', () => {
69
+ renderMobileLayout({
70
+ hasPreview: false
71
+ });
72
+
73
+ expect(screen.getByRole('tablist')).toBeInTheDocument();
74
+ expect(
75
+ screen.getByRole('tab', { name: 'learn.editor-tabs.instructions' })
76
+ ).toBeInTheDocument();
77
+ expect(
78
+ screen.getByRole('tab', { name: 'learn.editor-tabs.code' })
79
+ ).toBeInTheDocument();
80
+ expect(
81
+ screen.getByRole('tab', { name: 'learn.editor-tabs.console' })
82
+ ).toBeInTheDocument();
83
+ expect(
84
+ screen.queryByRole('tab', { name: 'learn.editor-tabs.preview' })
85
+ ).not.toBeInTheDocument();
86
+ expect(
87
+ screen.queryByRole('button', { name: 'aria.move-preview-to-new-window' })
88
+ ).not.toBeInTheDocument();
89
+ expect(screen.getByTestId('independent-lower-jaw')).toBeInTheDocument();
90
+ });
91
+
92
+ it('renders the lower jaw for challenges with editable boundaries', () => {
93
+ renderMobileLayout({ hasEditableBoundaries: true });
94
+
95
+ expect(screen.getByTestId('independent-lower-jaw')).toBeInTheDocument();
96
+ });
97
+
98
+ it('should render language selector when isDailyCodingChallenge is true', () => {
99
+ renderMobileLayout({
100
+ isDailyCodingChallenge: true,
101
+ dailyCodingChallengeLanguage: 'javascript'
102
+ });
103
+ expect(screen.getByText('JS')).toBeInTheDocument();
104
+ });
105
+
106
+ it('should not render language selector when isDailyCodingChallenge is false', () => {
107
+ renderMobileLayout({ isDailyCodingChallenge: false });
108
+ expect(screen.queryByText('JS')).not.toBeInTheDocument();
109
+ expect(screen.queryByText('PY')).not.toBeInTheDocument();
110
+ });
111
+
112
+ it('should call setDailyCodingChallengeLanguage when a language is selected', () => {
113
+ const setDailyCodingChallengeLanguage = vi.fn();
114
+ renderMobileLayout({
115
+ isDailyCodingChallenge: true,
116
+ dailyCodingChallengeLanguage: 'javascript',
117
+ setDailyCodingChallengeLanguage
118
+ });
119
+
120
+ // Open dropdown
121
+ fireEvent.click(screen.getByText('JS'));
122
+
123
+ // Click Python option
124
+ fireEvent.click(screen.getByText('Python'));
125
+
126
+ expect(setDailyCodingChallengeLanguage).toHaveBeenCalledWith('python');
127
+ });
128
+
129
+ it('renders notes in the notes tab for multifile editor challenges', async () => {
130
+ const user = userEvent.setup();
131
+ render(
132
+ <MobileLayout
133
+ {...mockProps}
134
+ notes='<p>This is a test note</p>'
135
+ usesMultifileEditor={true}
136
+ />
137
+ );
138
+
139
+ await user.click(
140
+ screen.getByRole('tab', { name: 'learn.editor-tabs.notes' })
141
+ );
142
+
143
+ expect(screen.getByText('This is a test note')).toBeVisible();
144
+ });
145
+ });
github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/classic/mobile-layout.tsx ADDED
@@ -0,0 +1,343 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import i18next from 'i18next';
2
+ import React, { Component } from 'react';
3
+ import { faWindowRestore } from '@fortawesome/free-solid-svg-icons';
4
+ import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
5
+ import { createSelector } from 'reselect';
6
+ import { connect } from 'react-redux';
7
+ import store from 'store';
8
+ import {
9
+ Tabs,
10
+ TabsContent,
11
+ TabsTrigger,
12
+ TabsList,
13
+ Dropdown,
14
+ MenuItem
15
+ } from '@freecodecamp/ui';
16
+ import { DailyCodingChallengeLanguages } from '../../../redux/prop-types';
17
+
18
+ import {
19
+ removePortalWindow,
20
+ setShowPreviewPortal,
21
+ setShowPreviewPane
22
+ } from '../redux/actions';
23
+ import {
24
+ portalWindowSelector,
25
+ showPreviewPortalSelector,
26
+ showPreviewPaneSelector
27
+ } from '../redux/selectors';
28
+ import { isRtlLanguage } from '../../../utils/is-rtl-language';
29
+ import PreviewPortal from '../components/preview-portal';
30
+ import Notes from '../components/notes';
31
+ import IndependentLowerJaw from '../components/independent-lower-jaw';
32
+ import EditorTabs from './editor-tabs';
33
+
34
+ interface MobileLayoutProps {
35
+ editor: JSX.Element | null;
36
+ hasEditableBoundaries: boolean;
37
+ hasPreview: boolean;
38
+ instructions: JSX.Element;
39
+ isDailyCodingChallenge?: boolean;
40
+ dailyCodingChallengeLanguage?: DailyCodingChallengeLanguages;
41
+ setDailyCodingChallengeLanguage?: (
42
+ language: DailyCodingChallengeLanguages
43
+ ) => void;
44
+ notes: string;
45
+ preview: JSX.Element;
46
+ onPreviewResize: () => void;
47
+ windowTitle: string;
48
+ showPreviewPortal: boolean;
49
+ showPreviewPane: boolean;
50
+ removePortalWindow: () => void;
51
+ setShowPreviewPortal: (arg: boolean) => void;
52
+ setShowPreviewPane: (arg: boolean) => void;
53
+ portalWindow: null | Window;
54
+ updateUsingKeyboardInTablist: (arg0: boolean) => void;
55
+ testOutput: JSX.Element;
56
+ usesMultifileEditor: boolean;
57
+ usesTerminal: boolean;
58
+ }
59
+
60
+ const tabs = {
61
+ editor: 'editor',
62
+ preview: 'preview',
63
+ console: 'console',
64
+ notes: 'notes',
65
+ instructions: 'instructions'
66
+ } as const;
67
+
68
+ type Tab = keyof typeof tabs;
69
+
70
+ interface MobileLayoutState {
71
+ currentTab: Tab;
72
+ }
73
+
74
+ const mapDispatchToProps = {
75
+ removePortalWindow,
76
+ setShowPreviewPortal,
77
+ setShowPreviewPane
78
+ };
79
+
80
+ const mapStateToProps = createSelector(
81
+ showPreviewPortalSelector,
82
+ showPreviewPaneSelector,
83
+ portalWindowSelector,
84
+
85
+ (
86
+ showPreviewPortal: boolean,
87
+ showPreviewPane: boolean,
88
+ portalWindow: null | Window
89
+ ) => ({
90
+ showPreviewPortal,
91
+ showPreviewPane,
92
+ portalWindow
93
+ })
94
+ );
95
+
96
+ export class MobileLayout extends Component<
97
+ MobileLayoutProps,
98
+ MobileLayoutState
99
+ > {
100
+ static displayName: string;
101
+
102
+ state: MobileLayoutState = {
103
+ currentTab: this.props.hasEditableBoundaries
104
+ ? tabs.editor
105
+ : tabs.instructions
106
+ };
107
+
108
+ switchTab = (tab: string): void => {
109
+ this.setState({
110
+ currentTab: tab as Tab
111
+ });
112
+ };
113
+
114
+ handleKeyDown = (): void => this.props.updateUsingKeyboardInTablist(true);
115
+
116
+ handleClick = (): void => this.props.updateUsingKeyboardInTablist(false);
117
+
118
+ render(): JSX.Element {
119
+ const { currentTab } = this.state;
120
+ const {
121
+ hasEditableBoundaries,
122
+ instructions,
123
+ editor,
124
+ testOutput,
125
+ hasPreview,
126
+ notes,
127
+ preview,
128
+ onPreviewResize,
129
+ showPreviewPane,
130
+ showPreviewPortal,
131
+ removePortalWindow,
132
+ setShowPreviewPane,
133
+ setShowPreviewPortal,
134
+ portalWindow,
135
+ windowTitle,
136
+ usesMultifileEditor,
137
+ usesTerminal,
138
+ isDailyCodingChallenge,
139
+ dailyCodingChallengeLanguage,
140
+ setDailyCodingChallengeLanguage
141
+ } = this.props;
142
+
143
+ const handleLanguageChange = (
144
+ language: DailyCodingChallengeLanguages
145
+ ): void => {
146
+ store.set('dailyCodingChallengeLanguage', language);
147
+ if (setDailyCodingChallengeLanguage) {
148
+ setDailyCodingChallengeLanguage(language);
149
+ }
150
+ };
151
+
152
+ const displayPreviewPane = hasPreview && showPreviewPane;
153
+ const displayPreviewPortal = hasPreview && showPreviewPortal;
154
+
155
+ const togglePane = (pane: string): void => {
156
+ if (pane === 'showPreviewPane') {
157
+ if (!showPreviewPane && showPreviewPortal) {
158
+ setShowPreviewPortal(false);
159
+ }
160
+ setShowPreviewPane(!showPreviewPane);
161
+ portalWindow?.close();
162
+ removePortalWindow();
163
+ } else if (pane === 'showPreviewPortal') {
164
+ if (!showPreviewPortal && showPreviewPane) {
165
+ setShowPreviewPane(false);
166
+ }
167
+ setShowPreviewPortal(!showPreviewPortal);
168
+ if (showPreviewPortal) {
169
+ portalWindow?.close();
170
+ removePortalWindow();
171
+ }
172
+ } else {
173
+ setShowPreviewPane(true);
174
+ setShowPreviewPortal(false);
175
+ }
176
+ };
177
+
178
+ // sets screen reader text for the portal button
179
+ function getPortalBtnSrText() {
180
+ // preview open in main window
181
+ let portalBtnSrText = i18next.t('aria.move-preview-to-new-window');
182
+
183
+ // preview open in external window
184
+ if (showPreviewPortal && !showPreviewPane) {
185
+ portalBtnSrText = i18next.t('aria.close-external-preview-window');
186
+ }
187
+
188
+ return portalBtnSrText;
189
+ }
190
+
191
+ const previewTriggerText =
192
+ usesTerminal == false
193
+ ? 'learn.editor-tabs.preview'
194
+ : 'learn.editor-tabs.terminal';
195
+
196
+ // Unlike the desktop layout the mobile version does not have an ActionRow,
197
+ // but still needs a way to switch between the different tabs.
198
+ return (
199
+ <>
200
+ <Tabs
201
+ id='mobile-layout'
202
+ dir={isRtlLanguage ? 'rtl' : 'ltr'}
203
+ className={hasEditableBoundaries ? 'has-editable-boundaries' : ''}
204
+ onKeyDown={this.handleKeyDown}
205
+ onMouseDown={this.handleClick}
206
+ onTouchStart={this.handleClick}
207
+ defaultValue={currentTab}
208
+ onValueChange={this.switchTab}
209
+ {...(hasPreview && { 'data-haspreview': 'true' })}
210
+ >
211
+ <TabsList className='nav-lists'>
212
+ {isDailyCodingChallenge && (
213
+ <Dropdown>
214
+ <Dropdown.Toggle
215
+ className='mobile-lang-selector-toggle'
216
+ id='mobile-language-selector'
217
+ >
218
+ {dailyCodingChallengeLanguage === 'javascript'
219
+ ? 'JS'
220
+ : 'PY'}{' '}
221
+ </Dropdown.Toggle>
222
+ <Dropdown.Menu>
223
+ <MenuItem onClick={() => handleLanguageChange('javascript')}>
224
+ JavaScript
225
+ </MenuItem>
226
+ <MenuItem onClick={() => handleLanguageChange('python')}>
227
+ Python
228
+ </MenuItem>
229
+ </Dropdown.Menu>
230
+ </Dropdown>
231
+ )}
232
+ {!hasEditableBoundaries && (
233
+ <TabsTrigger value={tabs.instructions}>
234
+ {i18next.t('learn.editor-tabs.instructions')}
235
+ </TabsTrigger>
236
+ )}
237
+ <TabsTrigger value={tabs.editor}>
238
+ {i18next.t('learn.editor-tabs.code')}
239
+ </TabsTrigger>
240
+ {!!notes && usesMultifileEditor && (
241
+ <TabsTrigger value={tabs.notes}>
242
+ {i18next.t('learn.editor-tabs.notes')}
243
+ </TabsTrigger>
244
+ )}
245
+ <TabsTrigger value={tabs.console}>
246
+ {i18next.t('learn.editor-tabs.console')}
247
+ </TabsTrigger>
248
+ {hasPreview && (
249
+ <TabsTrigger value={tabs.preview}>
250
+ {i18next.t(previewTriggerText)}
251
+ </TabsTrigger>
252
+ )}
253
+ </TabsList>
254
+
255
+ <TabsContent
256
+ tabIndex={-1}
257
+ className='tab-content'
258
+ value={tabs.editor}
259
+ >
260
+ {usesMultifileEditor && <EditorTabs />}
261
+ {editor}
262
+ </TabsContent>
263
+ {!hasEditableBoundaries && (
264
+ <TabsContent
265
+ tabIndex={-1}
266
+ className='tab-content'
267
+ value={tabs.instructions}
268
+ >
269
+ {instructions}
270
+ </TabsContent>
271
+ )}
272
+ <TabsContent
273
+ tabIndex={-1}
274
+ className='tab-content'
275
+ value={tabs.console}
276
+ >
277
+ {testOutput}
278
+ </TabsContent>
279
+ {!!notes && usesMultifileEditor && (
280
+ <TabsContent
281
+ tabIndex={-1}
282
+ className='tab-content'
283
+ value={tabs.notes}
284
+ >
285
+ <Notes notes={notes} />
286
+ </TabsContent>
287
+ )}
288
+ {hasPreview && (
289
+ <TabsContent
290
+ tabIndex={-1}
291
+ className='tab-content'
292
+ data-playwright-test-label='preview-pane'
293
+ value={tabs.preview}
294
+ forceMount
295
+ // forceMount causes the preview tabpanel to never be hidden,
296
+ // so we need to manually add it when preview is not active.
297
+ {...(this.state.currentTab === 'preview' ? {} : { hidden: true })}
298
+ >
299
+ <div className='portal-button-wrap'>
300
+ <button
301
+ className='portal-button'
302
+ aria-expanded={!!showPreviewPortal}
303
+ onClick={() => togglePane('showPreviewPortal')}
304
+ >
305
+ <span className='sr-only'>{getPortalBtnSrText()}</span>
306
+ <FontAwesomeIcon icon={faWindowRestore} />
307
+ </button>
308
+ </div>
309
+ {displayPreviewPane && preview}
310
+ {showPreviewPortal && (
311
+ <p className='preview-external-window'>
312
+ {i18next.t('learn.preview-external-window')}
313
+ </p>
314
+ )}
315
+ </TabsContent>
316
+ )}
317
+ <IndependentLowerJaw />
318
+ {hasPreview && this.state.currentTab !== 'preview' && (
319
+ <div className='portal-button-wrap'>
320
+ <button
321
+ className='portal-button'
322
+ aria-expanded={!!showPreviewPortal}
323
+ onClick={() => togglePane('showPreviewPortal')}
324
+ >
325
+ <span className='sr-only'>{getPortalBtnSrText()}</span>
326
+ <FontAwesomeIcon icon={faWindowRestore} />
327
+ </button>
328
+ </div>
329
+ )}
330
+ </Tabs>
331
+ {displayPreviewPortal && (
332
+ <PreviewPortal onResize={onPreviewResize} windowTitle={windowTitle}>
333
+ {preview}
334
+ </PreviewPortal>
335
+ )}
336
+ </>
337
+ );
338
+ }
339
+ }
340
+
341
+ MobileLayout.displayName = 'MobileLayout';
342
+
343
+ export default connect(mapStateToProps, mapDispatchToProps)(MobileLayout);
github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/classic/multifile-editor.tsx ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useRef } from 'react';
2
+ import { connect } from 'react-redux';
3
+ import { ReflexContainer, ReflexElement, ReflexSplitter } from 'react-reflex';
4
+ import { createSelector } from 'reselect';
5
+ import { isDonationModalOpenSelector } from '../../../redux/selectors';
6
+ import {
7
+ canFocusEditorSelector,
8
+ visibleEditorsSelector
9
+ } from '../redux/selectors';
10
+ import { getTargetEditor } from '../utils/get-target-editor';
11
+ import { isRtlLanguage } from '../../../utils/is-rtl-language';
12
+ import './editor.css';
13
+ import Editor, { type EditorProps } from './editor';
14
+
15
+ export type VisibleEditors = {
16
+ indexhtml?: boolean;
17
+ indexjsx?: boolean;
18
+ stylescss?: boolean;
19
+ scriptjs?: boolean;
20
+ indexts?: boolean;
21
+ indextsx?: boolean;
22
+ mainpy?: boolean;
23
+ tsconfigjson?: boolean;
24
+ };
25
+ type MultifileEditorProps = Pick<
26
+ EditorProps,
27
+ | 'usesMultifileEditor'
28
+ | 'showProjectPreview'
29
+ | 'title'
30
+ | 'resizeProps'
31
+ | 'isUsingKeyboardInTablist'
32
+ | 'isMobileLayout'
33
+ | 'initialTests'
34
+ | 'editorRef'
35
+ | 'containerRef'
36
+ | 'block'
37
+ | 'superBlock'
38
+ | 'challengeFiles'
39
+ | 'description'
40
+ // We use dimensions to trigger a re-render of the editor
41
+ | 'dimensions'
42
+ > & {
43
+ visibleEditors: VisibleEditors;
44
+ };
45
+
46
+ const mapStateToProps = createSelector(
47
+ visibleEditorsSelector,
48
+ canFocusEditorSelector,
49
+ isDonationModalOpenSelector,
50
+ (visibleEditors: VisibleEditors, canFocus: boolean, open) => ({
51
+ visibleEditors,
52
+ canFocus: open ? false : canFocus
53
+ })
54
+ );
55
+
56
+ const MultifileEditor = (props: MultifileEditorProps) => {
57
+ const {
58
+ block,
59
+ superBlock,
60
+ challengeFiles,
61
+ containerRef,
62
+ description,
63
+ editorRef,
64
+ initialTests,
65
+ isMobileLayout,
66
+ isUsingKeyboardInTablist,
67
+ resizeProps,
68
+ title,
69
+ visibleEditors: {
70
+ stylescss,
71
+ indexhtml,
72
+ scriptjs,
73
+ indexts,
74
+ indexjsx,
75
+ indextsx,
76
+ mainpy,
77
+ tsconfigjson
78
+ },
79
+ usesMultifileEditor,
80
+ showProjectPreview
81
+ } = props;
82
+ // TODO: the tabs mess up the rendering (scroll doesn't work properly and
83
+ // the in-editor description)
84
+
85
+ const reflexProps = {
86
+ propagateDimensions: true
87
+ };
88
+
89
+ const targetEditor = getTargetEditor(challengeFiles);
90
+
91
+ // Only one editor should be focused and that should happen once, after it has
92
+ // been mounted. This ref allows the editors to coordinate, without having to
93
+ // resort to redux.
94
+ const canFocusOnMountRef = useRef(true);
95
+
96
+ const editorKeys = [];
97
+
98
+ // The order of the keys should match the order set by sortChallengeFiles
99
+ if (indexjsx) editorKeys.push('indexjsx');
100
+ if (indextsx) editorKeys.push('indextsx');
101
+ if (indexhtml) editorKeys.push('indexhtml');
102
+ if (stylescss) editorKeys.push('stylescss');
103
+ if (scriptjs) editorKeys.push('scriptjs');
104
+ if (mainpy) editorKeys.push('mainpy');
105
+ if (indexts) editorKeys.push('indexts');
106
+ if (tsconfigjson) editorKeys.push('tsconfigjson');
107
+
108
+ const editorAndSplitterKeys = editorKeys.reduce((acc: string[] | [], key) => {
109
+ if (acc.length === 0) {
110
+ return [key];
111
+ } else {
112
+ return [...acc, `${key}-splitter`, key];
113
+ }
114
+ }, []);
115
+
116
+ if (isRtlLanguage) {
117
+ editorAndSplitterKeys.reverse();
118
+ }
119
+
120
+ return (
121
+ <ReflexContainer
122
+ orientation='horizontal'
123
+ {...reflexProps}
124
+ {...resizeProps}
125
+ className='editor-container'
126
+ >
127
+ <ReflexElement flex={10} {...reflexProps} {...resizeProps}>
128
+ <ReflexContainer orientation='vertical'>
129
+ {editorAndSplitterKeys.map(key => {
130
+ const isSplitter = key.endsWith('-splitter');
131
+ if (isSplitter) {
132
+ return (
133
+ <ReflexSplitter propagate={true} {...resizeProps} key={key} />
134
+ );
135
+ } else {
136
+ return (
137
+ <ReflexElement
138
+ data-playwright-test-label={`editor-container-${key}`}
139
+ {...reflexProps}
140
+ {...resizeProps}
141
+ key={key}
142
+ >
143
+ <Editor
144
+ canFocusOnMountRef={canFocusOnMountRef}
145
+ block={block}
146
+ superBlock={superBlock}
147
+ challengeFiles={challengeFiles}
148
+ containerRef={containerRef}
149
+ description={targetEditor === key ? description : ''}
150
+ editorRef={editorRef}
151
+ fileKey={key}
152
+ initialTests={initialTests}
153
+ isMobileLayout={isMobileLayout}
154
+ isUsingKeyboardInTablist={isUsingKeyboardInTablist}
155
+ resizeProps={resizeProps}
156
+ dimensions={props.dimensions ?? { height: 0, width: 0 }}
157
+ title={title}
158
+ usesMultifileEditor={usesMultifileEditor}
159
+ showProjectPreview={showProjectPreview}
160
+ />
161
+ </ReflexElement>
162
+ );
163
+ }
164
+ })}
165
+ </ReflexContainer>
166
+ </ReflexElement>
167
+ </ReflexContainer>
168
+ );
169
+ };
170
+
171
+ MultifileEditor.displayName = 'MultifileEditor';
172
+
173
+ export default connect(mapStateToProps)(MultifileEditor);
github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/classic/react-types-license ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) Microsoft Corporation.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE
github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/classic/react-types.json ADDED
The diff for this file is too large to render. See raw diff
 
github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/classic/saved-challenges.test.ts ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, it, expect } from 'vitest';
2
+ import type {
3
+ ChallengeFile,
4
+ SavedChallengeFile
5
+ } from '../../../redux/prop-types';
6
+ import { mergeChallengeFiles } from './saved-challenges';
7
+
8
+ const jsChallenge = {
9
+ contents: 'js contents',
10
+ fileKey: 'jsFileKey',
11
+ name: 'name',
12
+ ext: 'js' as const,
13
+ history: [],
14
+ seed: 'original js contents',
15
+ path: 'index.js'
16
+ };
17
+
18
+ const cssChallenge = {
19
+ contents: 'css contents',
20
+ fileKey: 'cssFileKey',
21
+ name: 'name',
22
+ ext: 'css' as const,
23
+ history: [],
24
+ seed: 'original css contents',
25
+ path: 'styles.css'
26
+ };
27
+
28
+ const htmlChallenge = {
29
+ contents: 'html contents',
30
+ fileKey: 'htmlFileKey',
31
+ name: 'name',
32
+ ext: 'html' as const,
33
+ history: [],
34
+ seed: 'original html contents',
35
+ path: 'index.html'
36
+ };
37
+
38
+ const savedJsChallenge: SavedChallengeFile = {
39
+ contents: 'saved js contents',
40
+ fileKey: 'jsFileKey',
41
+ name: 'name',
42
+ ext: 'js' as const
43
+ };
44
+
45
+ const savedCssChallenge: SavedChallengeFile = {
46
+ contents: 'saved css contents',
47
+ fileKey: 'cssFileKey',
48
+ name: 'name',
49
+ ext: 'css' as const
50
+ };
51
+
52
+ const savedHtmlChallenge: SavedChallengeFile = {
53
+ contents: 'saved html contents',
54
+ fileKey: 'htmlFileKey',
55
+ name: 'name',
56
+ ext: 'html' as const
57
+ };
58
+
59
+ describe('mergeChallengeFiles', () => {
60
+ it('should return files if savedChallengeFiles is undefined', () => {
61
+ const files: ChallengeFile[] = [htmlChallenge];
62
+ const savedChallengeFiles = undefined;
63
+
64
+ const result = mergeChallengeFiles(files, savedChallengeFiles);
65
+
66
+ expect(result).toEqual(files);
67
+ });
68
+
69
+ it('should return an empty array if files is undefined', () => {
70
+ const files = undefined;
71
+ const savedChallengeFiles = [savedJsChallenge];
72
+
73
+ const result = mergeChallengeFiles(files, savedChallengeFiles);
74
+
75
+ expect(result).toEqual([]);
76
+ });
77
+
78
+ it('should return files if savedChallengeFiles has a different length', () => {
79
+ const files: ChallengeFile[] = [cssChallenge];
80
+ const savedChallengeFiles: SavedChallengeFile[] = [
81
+ savedCssChallenge,
82
+ savedJsChallenge
83
+ ];
84
+
85
+ const result = mergeChallengeFiles(files, savedChallengeFiles);
86
+
87
+ expect(result).toEqual(files);
88
+ });
89
+
90
+ it('should return files if the fileKey properties do not match', () => {
91
+ const files: ChallengeFile[] = [jsChallenge, cssChallenge];
92
+ const savedChallengeFiles: SavedChallengeFile[] = [
93
+ savedHtmlChallenge,
94
+ savedCssChallenge
95
+ ];
96
+
97
+ const result = mergeChallengeFiles(files, savedChallengeFiles);
98
+
99
+ expect(result).toEqual(files);
100
+ });
101
+
102
+ it('should use the contents from the saved file', () => {
103
+ const files: ChallengeFile[] = [cssChallenge, htmlChallenge, jsChallenge];
104
+ const savedChallengeFiles = [
105
+ savedJsChallenge,
106
+ savedCssChallenge,
107
+ savedHtmlChallenge
108
+ ];
109
+
110
+ const result = mergeChallengeFiles(files, savedChallengeFiles);
111
+
112
+ expect(result).toEqual([
113
+ {
114
+ ...cssChallenge,
115
+ contents: savedCssChallenge.contents
116
+ },
117
+ {
118
+ ...htmlChallenge,
119
+ contents: savedHtmlChallenge.contents
120
+ },
121
+ {
122
+ ...jsChallenge,
123
+ contents: savedJsChallenge.contents
124
+ }
125
+ ]);
126
+ });
127
+
128
+ it('should not mutate the original files and savedChallengeFiles arrays', () => {
129
+ const files: ChallengeFile[] = [jsChallenge, cssChallenge];
130
+ const savedChallengeFiles: SavedChallengeFile[] = [
131
+ savedJsChallenge,
132
+ savedCssChallenge
133
+ ];
134
+
135
+ const filesCopy = JSON.parse(JSON.stringify(files));
136
+ const savedFilesCopy = JSON.parse(JSON.stringify(savedChallengeFiles));
137
+
138
+ mergeChallengeFiles(files, savedChallengeFiles);
139
+
140
+ expect(files).toEqual(filesCopy);
141
+ expect(savedChallengeFiles).toEqual(savedFilesCopy);
142
+ });
143
+ });
github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/classic/saved-challenges.ts ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { ChallengeFile, SavedChallengeFile } from '../../../redux/prop-types';
2
+
3
+ export function mergeChallengeFiles(
4
+ files?: ChallengeFile[] | null,
5
+ savedFiles?: SavedChallengeFile[] | null
6
+ ): ChallengeFile[] {
7
+ if (!files) return [];
8
+ if (!savedFiles) return files;
9
+ if (files.length !== savedFiles.length) return files;
10
+
11
+ const sortedChallengeFiles = files.toSorted((a, b) =>
12
+ a.fileKey.localeCompare(b.fileKey)
13
+ );
14
+ const sortedSavedChallengeFiles = savedFiles.toSorted((a, b) =>
15
+ a.fileKey.localeCompare(b.fileKey)
16
+ );
17
+
18
+ const fileKeysMatch = sortedChallengeFiles.every(
19
+ (file, index) => file.fileKey === sortedSavedChallengeFiles[index].fileKey
20
+ );
21
+
22
+ if (!fileKeysMatch) return files;
23
+
24
+ return sortedChallengeFiles.map((file, index) => ({
25
+ ...file,
26
+ contents: sortedSavedChallengeFiles[index].contents,
27
+ editableRegionBoundaries:
28
+ sortedSavedChallengeFiles[index].editableRegionBoundaries
29
+ }));
30
+ }
github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/classic/show.tsx ADDED
@@ -0,0 +1,593 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { graphql } from 'gatsby';
2
+ import React, { useState, useEffect, useRef } from 'react';
3
+ import Helmet from 'react-helmet';
4
+ import { useTranslation } from 'react-i18next';
5
+ import { connect } from 'react-redux';
6
+ import { HandlerProps } from 'react-reflex';
7
+ import { useMediaQuery } from 'react-responsive';
8
+ import { bindActionCreators, Dispatch } from 'redux';
9
+ import store from 'store';
10
+ import { editor } from 'monaco-editor';
11
+ import type { FitAddon } from '@xterm/addon-fit';
12
+
13
+ import { useFeature } from '@growthbook/growthbook-react';
14
+ import { challengeTypes } from '@freecodecamp/shared/config/challenge-types';
15
+ import LearnLayout from '../../../components/layouts/learn';
16
+ import { MAX_MOBILE_WIDTH } from '../../../../config/misc';
17
+
18
+ import type {
19
+ ChallengeFiles,
20
+ ChallengeMeta,
21
+ ChallengeNode,
22
+ Hooks,
23
+ DailyCodingChallengeLanguages,
24
+ DailyCodingChallengeNode,
25
+ DailyCodingChallengePageContext,
26
+ PageContext,
27
+ ResizeProps,
28
+ SavedChallenge,
29
+ SavedChallengeFiles,
30
+ Test
31
+ } from '../../../redux/prop-types';
32
+ import { isContained } from '../../../utils/is-contained';
33
+ import ChallengeDescription from '../components/challenge-description';
34
+ import Hotkeys from '../components/hotkeys';
35
+ import ResetModal from '../components/reset-modal';
36
+ import ChallengeTitle from '../components/challenge-title';
37
+ import CompletionModal from '../components/completion-modal';
38
+ import HelpModal from '../components/help-modal';
39
+ import ShortcutsModal from '../components/shortcuts-modal';
40
+ import MobileAppModal from '../components/mobile-app-modal';
41
+ import Output from '../components/output';
42
+ import Preview, { type PreviewProps } from '../components/preview';
43
+ import ProjectPreviewModal from '../components/project-preview-modal';
44
+ import SidePanel from '../components/side-panel';
45
+ import VideoModal from '../components/video-modal';
46
+ import {
47
+ cancelTests,
48
+ challengeMounted,
49
+ createFiles,
50
+ executeChallenge,
51
+ initConsole,
52
+ initTests,
53
+ initHooks,
54
+ initVisibleEditors,
55
+ previewMounted,
56
+ updateChallengeMeta,
57
+ openModal,
58
+ setEditorFocusability,
59
+ setIsAdvancing
60
+ } from '../redux/actions';
61
+ import {
62
+ challengeFilesSelector,
63
+ consoleOutputSelector,
64
+ isChallengeCompletedSelector
65
+ } from '../redux/selectors';
66
+ import { savedChallengesSelector } from '../../../redux/selectors';
67
+ import { getGuideUrl } from '../utils';
68
+ import { preloadPage } from '../../../../utils/gatsby/page-loading';
69
+ import envData from '../../../../config/env.json';
70
+ import { getChallengePaths } from '../utils/challenge-paths';
71
+ import { challengeHasPreview, isJavaScriptChallenge } from '../utils/build';
72
+ import { XtermTerminal } from './xterm';
73
+ import MultifileEditor from './multifile-editor';
74
+ import DesktopLayout from './desktop-layout';
75
+ import MobileLayout from './mobile-layout';
76
+ import { mergeChallengeFiles } from './saved-challenges';
77
+
78
+ import './classic.css';
79
+ import '../components/test-frame.css';
80
+
81
+ const mapStateToProps = (state: unknown) => ({
82
+ challengeFiles: challengeFilesSelector(state) as ChallengeFiles,
83
+ output: consoleOutputSelector(state) as string,
84
+ isChallengeCompleted: isChallengeCompletedSelector(state),
85
+ savedChallenges: savedChallengesSelector(state) as SavedChallenge[]
86
+ });
87
+
88
+ const mapDispatchToProps = (dispatch: Dispatch) =>
89
+ bindActionCreators(
90
+ {
91
+ createFiles,
92
+ initConsole,
93
+ initTests,
94
+ initHooks,
95
+ initVisibleEditors,
96
+ updateChallengeMeta,
97
+ challengeMounted,
98
+ executeChallenge,
99
+ cancelTests,
100
+ previewMounted,
101
+ openModal,
102
+ setEditorFocusability,
103
+ setIsAdvancing
104
+ },
105
+ dispatch
106
+ );
107
+
108
+ interface ShowClassicProps extends Pick<PreviewProps, 'previewMounted'> {
109
+ cancelTests: () => void;
110
+ challengeMounted: (arg0: string) => void;
111
+ createFiles: (arg0: ChallengeFiles | SavedChallengeFiles) => void;
112
+ dailyCodingChallengeLanguage: DailyCodingChallengeLanguages;
113
+ data: { challengeNode: ChallengeNode | DailyCodingChallengeNode };
114
+ executeChallenge: (options?: { showCompletionModal: boolean }) => void;
115
+ challengeFiles: ChallengeFiles;
116
+ initConsole: (arg0: string) => void;
117
+ initTests: (tests: Test[]) => void;
118
+ initHooks: (hooks?: Hooks) => void;
119
+ initVisibleEditors: () => void;
120
+ isChallengeCompleted: boolean;
121
+ isDailyCodingChallenge?: boolean;
122
+ output: string;
123
+ pageContext: PageContext | DailyCodingChallengePageContext;
124
+ updateChallengeMeta: (arg0: ChallengeMeta) => void;
125
+ openModal: (modal: string) => void;
126
+ setDailyCodingChallengeLanguage: (
127
+ language: DailyCodingChallengeLanguages
128
+ ) => void;
129
+ setEditorFocusability: (canFocus: boolean) => void;
130
+ setIsAdvancing: (arg: boolean) => void;
131
+ savedChallenges: SavedChallenge[];
132
+ }
133
+
134
+ interface ReflexLayout {
135
+ codePane: { flex: number };
136
+ editorPane: { flex: number };
137
+ instructionPane: { flex: number };
138
+ notesPane: { flex: number };
139
+ previewPane: { flex: number };
140
+ testsPane: { flex: number };
141
+ }
142
+
143
+ interface RenderEditorArgs {
144
+ isMobileLayout: boolean;
145
+ isUsingKeyboardInTablist: boolean;
146
+ }
147
+
148
+ const REFLEX_LAYOUT = 'challenge-layout';
149
+ const BASE_LAYOUT = {
150
+ codePane: { flex: 1 },
151
+ editorPane: { flex: 1 },
152
+ instructionPane: { flex: 1 },
153
+ previewPane: { flex: 0.7 },
154
+ notesPane: { flex: 0.7 },
155
+ testsPane: { flex: 0.3 }
156
+ };
157
+
158
+ const StepPreview = ({
159
+ dimensions,
160
+ disableIframe,
161
+ previewMounted,
162
+ challengeType,
163
+ xtermFitRef
164
+ }: Pick<PreviewProps, 'disableIframe' | 'previewMounted'> & {
165
+ challengeType: number;
166
+ xtermFitRef: React.MutableRefObject<FitAddon | null>;
167
+ dimensions?: { width: number; height: number };
168
+ }) => {
169
+ return challengeType === challengeTypes.python ||
170
+ challengeType === challengeTypes.multifilePythonCertProject ||
171
+ challengeType === challengeTypes.pyLab ||
172
+ challengeType === challengeTypes.dailyChallengePy ? (
173
+ <XtermTerminal dimensions={dimensions} xtermFitRef={xtermFitRef} />
174
+ ) : (
175
+ <Preview disableIframe={disableIframe} previewMounted={previewMounted} />
176
+ );
177
+ };
178
+
179
+ // The newline is important, because this text ends up in a `pre` element.
180
+ const defaultOutput = `
181
+ /**
182
+ * Your test output will go here
183
+ */`;
184
+
185
+ function ShowClassic({
186
+ challengeFiles,
187
+ data: {
188
+ challengeNode: {
189
+ challenge: {
190
+ challengeFiles: seedChallengeFiles,
191
+ block,
192
+ demoType,
193
+ title,
194
+ description,
195
+ instructions,
196
+ id,
197
+ hooks,
198
+ tests,
199
+ challengeType,
200
+ hasEditableBoundaries = false,
201
+ superBlock,
202
+ helpCategory,
203
+ forumTopicId,
204
+ usesMultifileEditor,
205
+ notes,
206
+ videoUrl,
207
+ translationPending,
208
+ saveSubmissionToDB
209
+ }
210
+ }
211
+ },
212
+ pageContext: {
213
+ challengeMeta,
214
+ challengeMeta: { isFirstStep, nextChallengePath },
215
+ projectPreview: { challengeData }
216
+ },
217
+ createFiles,
218
+ cancelTests,
219
+ challengeMounted,
220
+ initConsole,
221
+ initTests,
222
+ initHooks,
223
+ initVisibleEditors,
224
+ dailyCodingChallengeLanguage,
225
+ isDailyCodingChallenge = false,
226
+ setDailyCodingChallengeLanguage,
227
+ updateChallengeMeta,
228
+ openModal,
229
+ setIsAdvancing,
230
+ savedChallenges,
231
+ isChallengeCompleted,
232
+ output,
233
+ executeChallenge,
234
+ previewMounted
235
+ }: ShowClassicProps) {
236
+ const { t } = useTranslation();
237
+ const [resizing, setResizing] = useState(false);
238
+ const [usingKeyboardInTablist, setUsingKeyboardInTablist] = useState(false);
239
+ const containerRef = useRef<HTMLElement>(null);
240
+ const editorRef = useRef<editor.IStandaloneCodeEditor>();
241
+ const instructionsPanelRef = useRef<HTMLDivElement>(null);
242
+ const xtermFitRef = useRef<FitAddon | null>(null);
243
+ const isMobile = useMediaQuery({
244
+ query: `(max-width: ${MAX_MOBILE_WIDTH}px)`
245
+ });
246
+
247
+ const guideUrl = getGuideUrl({ forumTopicId, title, block, superBlock });
248
+
249
+ const blockNameTitle = `${t(
250
+ `intro:${superBlock}.blocks.${block}.title`
251
+ )}: ${title}`;
252
+ const windowTitle = `${blockNameTitle} | freeCodeCamp.org`;
253
+ const openConsole = isJavaScriptChallenge({ challengeType });
254
+ const hasPreview = challengeHasPreview({ challengeType });
255
+ const getLayoutState = () => {
256
+ const reflexLayout = store.get(REFLEX_LAYOUT) as ReflexLayout | null;
257
+
258
+ // Check that the layout values stored are valid (exist in base layout). If
259
+ // not valid, it will fallback to the base layout values and be set on next
260
+ // user resize.
261
+ const isValidLayout =
262
+ reflexLayout &&
263
+ isContained(Object.keys(BASE_LAYOUT), Object.keys(reflexLayout));
264
+
265
+ if (!isValidLayout) store.remove(REFLEX_LAYOUT);
266
+
267
+ return isValidLayout ? reflexLayout : BASE_LAYOUT;
268
+ };
269
+
270
+ const onPreviewResize = () => xtermFitRef.current?.fit();
271
+
272
+ // layout: Holds the information of the panes sizes for desktop view
273
+ const [layout, setLayout] = useState(getLayoutState());
274
+
275
+ const onStopResize = (event: HandlerProps) => {
276
+ setResizing(false);
277
+ // 'name' is used to identify the Elements whose layout is stored.
278
+ const { name, flex } = event.component.props;
279
+
280
+ // onStopResize can be called multiple times before the state changes, so
281
+ // we need an updater function to ensure all updates are applied.
282
+ setLayout(l => {
283
+ const newLayout = name ? { ...l, [name]: { flex } } : l;
284
+ store.set(REFLEX_LAYOUT, newLayout);
285
+ return newLayout;
286
+ });
287
+ };
288
+
289
+ const setHtmlHeight = () => {
290
+ const vh = String(window.innerHeight - 1);
291
+ document.documentElement.style.height = vh + 'px';
292
+ };
293
+ const onResize = () => {
294
+ setResizing(true);
295
+ };
296
+ const resizeProps: ResizeProps = {
297
+ onResize,
298
+ onStopResize
299
+ };
300
+
301
+ const updateUsingKeyboardInTablist = (
302
+ usingKeyboardInTablist: boolean
303
+ ): void => {
304
+ setUsingKeyboardInTablist(usingKeyboardInTablist);
305
+ };
306
+
307
+ // AB testing Pre-fetch in the Spanish locale
308
+ const isPreFetchEnabled = useFeature('prefetch_ab_test').on;
309
+
310
+ const showSidePanelTests = isMobile || !hasEditableBoundaries;
311
+
312
+ // Show test
313
+
314
+ useEffect(() => {
315
+ if (
316
+ isPreFetchEnabled &&
317
+ (envData as { clientLocale: string }).clientLocale === 'espanol'
318
+ ) {
319
+ preloadPage(nextChallengePath);
320
+ }
321
+ }, [nextChallengePath, isPreFetchEnabled]);
322
+
323
+ useEffect(() => {
324
+ initializeComponent(title);
325
+
326
+ window.addEventListener('resize', setHtmlHeight);
327
+ setHtmlHeight();
328
+
329
+ return () => {
330
+ createFiles([]);
331
+ cancelTests();
332
+ window.removeEventListener('resize', setHtmlHeight);
333
+ };
334
+ // eslint-disable-next-line react-hooks/exhaustive-deps
335
+ }, [dailyCodingChallengeLanguage]);
336
+
337
+ const initializeComponent = (title: string): void => {
338
+ initConsole('');
339
+
340
+ const savedChallenge = savedChallenges?.find(challenge => {
341
+ return challenge.id === challengeMeta.id;
342
+ });
343
+
344
+ createFiles(
345
+ mergeChallengeFiles(seedChallengeFiles, savedChallenge?.challengeFiles)
346
+ );
347
+
348
+ initTests(tests);
349
+ initHooks(hooks);
350
+
351
+ initVisibleEditors();
352
+
353
+ // Typically, this kind of preview only appears on the first step of a
354
+ // project and is shown (once) automatically. In contrast, labs are more
355
+ // freeform, so the preview is shown on demand.
356
+ if (demoType === 'onLoad') openModal('projectPreview');
357
+ const challengePaths = getChallengePaths({
358
+ currentCurriculumPaths: challengeMeta
359
+ });
360
+
361
+ updateChallengeMeta({
362
+ ...challengeMeta,
363
+ title,
364
+ challengeType,
365
+ helpCategory,
366
+ description,
367
+ ...challengePaths
368
+ });
369
+ challengeMounted(challengeMeta.id);
370
+ setIsAdvancing(false);
371
+ };
372
+
373
+ const renderInstructionsPanel = ({ hasDemo }: { hasDemo: boolean }) => {
374
+ return (
375
+ <SidePanel
376
+ challengeDescription={
377
+ <ChallengeDescription
378
+ description={description}
379
+ instructions={instructions}
380
+ superBlock={superBlock}
381
+ challengeId={id}
382
+ block={block}
383
+ />
384
+ }
385
+ challengeTitle={
386
+ <ChallengeTitle
387
+ isCompleted={isChallengeCompleted}
388
+ translationPending={translationPending}
389
+ >
390
+ {title}
391
+ </ChallengeTitle>
392
+ }
393
+ instructionsPanelRef={instructionsPanelRef}
394
+ hasDemo={hasDemo}
395
+ showSidePanelTests={showSidePanelTests}
396
+ />
397
+ );
398
+ };
399
+
400
+ const renderEditor = ({
401
+ isMobileLayout,
402
+ isUsingKeyboardInTablist
403
+ }: RenderEditorArgs) => {
404
+ return (
405
+ challengeFiles && (
406
+ <MultifileEditor
407
+ challengeFiles={challengeFiles}
408
+ block={block}
409
+ superBlock={superBlock}
410
+ containerRef={containerRef}
411
+ description={description}
412
+ editorRef={editorRef}
413
+ initialTests={tests}
414
+ isMobileLayout={isMobileLayout}
415
+ isUsingKeyboardInTablist={isUsingKeyboardInTablist}
416
+ resizeProps={resizeProps}
417
+ title={title}
418
+ usesMultifileEditor={usesMultifileEditor}
419
+ showProjectPreview={demoType === 'onLoad'}
420
+ />
421
+ )
422
+ );
423
+ };
424
+
425
+ const usesTerminal =
426
+ challengeType === challengeTypes.python ||
427
+ challengeType === challengeTypes.multifilePythonCertProject ||
428
+ challengeType === challengeTypes.pyLab ||
429
+ challengeType === challengeTypes.dailyChallengePy;
430
+
431
+ return (
432
+ <Hotkeys
433
+ challengeType={challengeType}
434
+ executeChallenge={executeChallenge}
435
+ containerRef={containerRef}
436
+ instructionsPanelRef={instructionsPanelRef}
437
+ usesMultifileEditor={usesMultifileEditor}
438
+ editorRef={editorRef}
439
+ >
440
+ <LearnLayout>
441
+ <Helmet title={windowTitle} />
442
+ {isMobile ? (
443
+ <MobileLayout
444
+ editor={renderEditor({
445
+ isMobileLayout: true,
446
+ isUsingKeyboardInTablist: usingKeyboardInTablist
447
+ })}
448
+ hasEditableBoundaries={hasEditableBoundaries}
449
+ hasPreview={hasPreview}
450
+ isDailyCodingChallenge={isDailyCodingChallenge}
451
+ dailyCodingChallengeLanguage={dailyCodingChallengeLanguage}
452
+ setDailyCodingChallengeLanguage={setDailyCodingChallengeLanguage}
453
+ instructions={renderInstructionsPanel({
454
+ hasDemo: demoType === 'onClick'
455
+ })}
456
+ notes={notes}
457
+ onPreviewResize={onPreviewResize}
458
+ preview={
459
+ <StepPreview
460
+ challengeType={challengeType}
461
+ disableIframe={resizing}
462
+ previewMounted={previewMounted}
463
+ xtermFitRef={xtermFitRef}
464
+ />
465
+ }
466
+ windowTitle={windowTitle}
467
+ testOutput={
468
+ <Output defaultOutput={defaultOutput} output={output} />
469
+ }
470
+ updateUsingKeyboardInTablist={updateUsingKeyboardInTablist}
471
+ usesMultifileEditor={usesMultifileEditor}
472
+ usesTerminal={usesTerminal}
473
+ />
474
+ ) : (
475
+ <DesktopLayout
476
+ challengeFiles={challengeFiles}
477
+ challengeType={challengeType}
478
+ editor={renderEditor({
479
+ isMobileLayout: false,
480
+ isUsingKeyboardInTablist: usingKeyboardInTablist
481
+ })}
482
+ hasEditableBoundaries={hasEditableBoundaries}
483
+ hasPreview={hasPreview}
484
+ instructions={renderInstructionsPanel({
485
+ hasDemo: demoType === 'onClick'
486
+ })}
487
+ isDailyCodingChallenge={isDailyCodingChallenge}
488
+ dailyCodingChallengeLanguage={dailyCodingChallengeLanguage}
489
+ setDailyCodingChallengeLanguage={setDailyCodingChallengeLanguage}
490
+ isFirstStep={isFirstStep}
491
+ layoutState={layout}
492
+ notes={notes}
493
+ onPreviewResize={onPreviewResize}
494
+ preview={
495
+ <StepPreview
496
+ challengeType={challengeType}
497
+ disableIframe={resizing}
498
+ previewMounted={previewMounted}
499
+ xtermFitRef={xtermFitRef}
500
+ />
501
+ }
502
+ resizeProps={resizeProps}
503
+ testOutput={
504
+ <Output defaultOutput={defaultOutput} output={output} />
505
+ }
506
+ windowTitle={windowTitle}
507
+ startWithConsoleShown={openConsole}
508
+ />
509
+ )}
510
+ <CompletionModal />
511
+ <HelpModal
512
+ challengeTitle={title}
513
+ challengeBlock={block}
514
+ superBlock={superBlock}
515
+ guideUrl={guideUrl}
516
+ videoUrl={videoUrl}
517
+ />
518
+ <VideoModal videoUrl={videoUrl} />
519
+ <ResetModal
520
+ saveSubmissionToDB={saveSubmissionToDB}
521
+ challengeTitle={title}
522
+ />
523
+ <ProjectPreviewModal
524
+ challengeData={challengeData}
525
+ closeText={t('buttons.start-coding')}
526
+ previewTitle={
527
+ demoType === 'onClick'
528
+ ? t('learn.demo-project-title')
529
+ : t('learn.project-preview-title')
530
+ }
531
+ />
532
+ <ShortcutsModal />
533
+ <MobileAppModal superBlock={superBlock} />
534
+ </LearnLayout>
535
+ </Hotkeys>
536
+ );
537
+ }
538
+
539
+ ShowClassic.displayName = 'ShowClassic';
540
+
541
+ export default connect(mapStateToProps, mapDispatchToProps)(ShowClassic);
542
+
543
+ export const query = graphql`
544
+ query ClassicChallenge($id: String!) {
545
+ challengeNode(id: { eq: $id }) {
546
+ challenge {
547
+ block
548
+ demoType
549
+ title
550
+ description
551
+ id
552
+ hasEditableBoundaries
553
+ instructions
554
+ notes
555
+ challengeType
556
+ helpCategory
557
+ videoUrl
558
+ superBlock
559
+ translationPending
560
+ forumTopicId
561
+ hooks {
562
+ beforeAll
563
+ beforeEach
564
+ afterEach
565
+ afterAll
566
+ }
567
+ fields {
568
+ slug
569
+ }
570
+ required {
571
+ link
572
+ src
573
+ }
574
+ usesMultifileEditor
575
+ challengeFiles {
576
+ fileKey
577
+ ext
578
+ name
579
+ contents
580
+ head
581
+ tail
582
+ editableRegionBoundaries
583
+ history
584
+ }
585
+ saveSubmissionToDB
586
+ tests {
587
+ text
588
+ testString
589
+ }
590
+ }
591
+ }
592
+ }
593
+ `;
github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/classic/xterm-original.css ADDED
@@ -0,0 +1,231 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Copyright (c) 2014 The xterm.js authors. All rights reserved.
3
+ * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)
4
+ * https://github.com/chjj/term.js
5
+ * @license MIT
6
+ *
7
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ * of this software and associated documentation files (the "Software"), to deal
9
+ * in the Software without restriction, including without limitation the rights
10
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ * copies of the Software, and to permit persons to whom the Software is
12
+ * furnished to do so, subject to the following conditions:
13
+ *
14
+ * The above copyright notice and this permission notice shall be included in
15
+ * all copies or substantial portions of the Software.
16
+ *
17
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23
+ * THE SOFTWARE.
24
+ *
25
+ * Originally forked from (with the author's permission):
26
+ * Fabrice Bellard's javascript vt100 for jslinux:
27
+ * http://bellard.org/jslinux/
28
+ * Copyright (c) 2011 Fabrice Bellard
29
+ * The original design remains. The terminal itself
30
+ * has been extended to include xterm CSI codes, among
31
+ * other features.
32
+ */
33
+
34
+ /**
35
+ * Default styles for xterm.js
36
+ */
37
+
38
+ .xterm {
39
+ cursor: text;
40
+ position: relative;
41
+ user-select: none;
42
+ -ms-user-select: none;
43
+ -webkit-user-select: none;
44
+ }
45
+
46
+ .xterm.focus,
47
+ .xterm:focus {
48
+ outline: none;
49
+ }
50
+
51
+ .xterm .xterm-helpers {
52
+ position: absolute;
53
+ top: 0;
54
+ /**
55
+ * The z-index of the helpers must be higher than the canvases in order for
56
+ * IMEs to appear on top.
57
+ */
58
+ z-index: 5;
59
+ }
60
+
61
+ .xterm .xterm-helper-textarea {
62
+ padding: 0;
63
+ border: 0;
64
+ margin: 0;
65
+ /* Move textarea out of the screen to the far left, so that the cursor is not visible */
66
+ position: absolute;
67
+ opacity: 0;
68
+ left: -9999em;
69
+ top: 0;
70
+ width: 0;
71
+ height: 0;
72
+ z-index: -5;
73
+ /** Prevent wrapping so the IME appears against the textarea at the correct position */
74
+ white-space: nowrap;
75
+ overflow: hidden;
76
+ resize: none;
77
+ }
78
+
79
+ .xterm .composition-view {
80
+ /* TODO: Composition position got messed up somewhere */
81
+ background: #000;
82
+ color: #fff;
83
+ display: none;
84
+ position: absolute;
85
+ white-space: nowrap;
86
+ z-index: 1;
87
+ }
88
+
89
+ .xterm .composition-view.active {
90
+ display: block;
91
+ }
92
+
93
+ .xterm .xterm-viewport {
94
+ /* On OS X this is required in order for the scroll bar to appear fully opaque */
95
+ background-color: #000;
96
+ overflow-y: scroll;
97
+ cursor: default;
98
+ position: absolute;
99
+ right: 0;
100
+ left: 0;
101
+ top: 0;
102
+ bottom: 0;
103
+ }
104
+
105
+ .xterm .xterm-screen {
106
+ position: relative;
107
+ }
108
+
109
+ .xterm .xterm-screen canvas {
110
+ position: absolute;
111
+ left: 0;
112
+ top: 0;
113
+ }
114
+
115
+ .xterm .xterm-scroll-area {
116
+ visibility: hidden;
117
+ }
118
+
119
+ .xterm-char-measure-element {
120
+ display: inline-block;
121
+ visibility: hidden;
122
+ position: absolute;
123
+ top: 0;
124
+ left: -9999em;
125
+ line-height: normal;
126
+ }
127
+
128
+ .xterm.enable-mouse-events {
129
+ /* When mouse events are enabled (eg. tmux), revert to the standard pointer cursor */
130
+ cursor: default;
131
+ }
132
+
133
+ .xterm.xterm-cursor-pointer,
134
+ .xterm .xterm-cursor-pointer {
135
+ cursor: pointer;
136
+ }
137
+
138
+ .xterm.column-select.focus {
139
+ /* Column selection mode */
140
+ cursor: crosshair;
141
+ }
142
+
143
+ .xterm .xterm-accessibility,
144
+ .xterm .xterm-message {
145
+ position: absolute;
146
+ left: 0;
147
+ top: 0;
148
+ bottom: 0;
149
+ right: 0;
150
+ z-index: 10;
151
+ color: transparent;
152
+ pointer-events: none;
153
+ }
154
+
155
+ .xterm .live-region {
156
+ position: absolute;
157
+ left: -9999px;
158
+ width: 1px;
159
+ height: 1px;
160
+ overflow: hidden;
161
+ }
162
+
163
+ .xterm-dim {
164
+ /* Dim should not apply to background, so the opacity of the foreground color is applied
165
+ * explicitly in the generated class and reset to 1 here */
166
+ opacity: 1 !important;
167
+ }
168
+
169
+ .xterm-underline-1 {
170
+ text-decoration: underline;
171
+ }
172
+ .xterm-underline-2 {
173
+ text-decoration: double underline;
174
+ }
175
+ .xterm-underline-3 {
176
+ text-decoration: wavy underline;
177
+ }
178
+ .xterm-underline-4 {
179
+ text-decoration: dotted underline;
180
+ }
181
+ .xterm-underline-5 {
182
+ text-decoration: dashed underline;
183
+ }
184
+
185
+ .xterm-overline {
186
+ text-decoration: overline;
187
+ }
188
+
189
+ .xterm-overline.xterm-underline-1 {
190
+ text-decoration: overline underline;
191
+ }
192
+ .xterm-overline.xterm-underline-2 {
193
+ text-decoration: overline double underline;
194
+ }
195
+ .xterm-overline.xterm-underline-3 {
196
+ text-decoration: overline wavy underline;
197
+ }
198
+ .xterm-overline.xterm-underline-4 {
199
+ text-decoration: overline dotted underline;
200
+ }
201
+ .xterm-overline.xterm-underline-5 {
202
+ text-decoration: overline dashed underline;
203
+ }
204
+
205
+ .xterm-strikethrough {
206
+ text-decoration: line-through;
207
+ }
208
+
209
+ .xterm-screen .xterm-decoration-container .xterm-decoration {
210
+ z-index: 6;
211
+ position: absolute;
212
+ }
213
+
214
+ .xterm-screen
215
+ .xterm-decoration-container
216
+ .xterm-decoration.xterm-decoration-top-layer {
217
+ z-index: 7;
218
+ }
219
+
220
+ .xterm-decoration-overview-ruler {
221
+ z-index: 8;
222
+ position: absolute;
223
+ top: 0;
224
+ right: 0;
225
+ pointer-events: none;
226
+ }
227
+
228
+ .xterm-decoration-top {
229
+ z-index: 2;
230
+ position: relative;
231
+ }
github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/classic/xterm.css ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ .xterm-screen {
2
+ height: 100vh !important;
3
+ }
github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/classic/xterm.tsx ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { MutableRefObject, useEffect, useRef } from 'react';
2
+ import type { FitAddon } from '@xterm/addon-fit';
3
+ import type { IDisposable, Terminal } from '@xterm/xterm';
4
+ import { useTranslation } from 'react-i18next';
5
+
6
+ import { registerTerminal } from '../utils/python-worker-handler';
7
+ import './xterm.css';
8
+ import './xterm-original.css';
9
+
10
+ const registerServiceWorker = async () => {
11
+ if ('serviceWorker' in navigator) {
12
+ try {
13
+ await navigator.serviceWorker.register('/python-input-sw.js');
14
+ } catch (error) {
15
+ console.error(`Registration failed`);
16
+ console.error(error);
17
+ }
18
+ }
19
+ };
20
+
21
+ export const XtermTerminal = ({
22
+ xtermFitRef,
23
+ dimensions
24
+ }: {
25
+ xtermFitRef: MutableRefObject<FitAddon | null>;
26
+ dimensions?: { height: number; width: number };
27
+ }) => {
28
+ const termContainerRef = useRef<HTMLDivElement | null>(null);
29
+ const { t } = useTranslation();
30
+
31
+ useEffect(() => {
32
+ void registerServiceWorker();
33
+
34
+ let term: Terminal | null;
35
+
36
+ async function createTerminal() {
37
+ const disposables: IDisposable[] = [];
38
+ const { Terminal } = await import('@xterm/xterm');
39
+ const { FitAddon } = await import('@xterm/addon-fit');
40
+
41
+ // Setting convertEol so that \n is converted to \r\n. Otherwise the terminal
42
+ // will interpret \n as line feed and just move the cursor to the next line.
43
+ // convertEol makes every \n a \r\n.
44
+ term = new Terminal({ convertEol: true });
45
+ const fitAddon = new FitAddon();
46
+ xtermFitRef.current = fitAddon;
47
+ term.loadAddon(fitAddon);
48
+ if (termContainerRef.current) term.open(termContainerRef.current);
49
+ fitAddon.fit();
50
+
51
+ // xterm does provide a11y support via the `screenReaderMode` option.
52
+ // However, the mode only works best if the user interacts with the terminal directly.
53
+ // Since we feed the content to xterm, it's better to control the output a11y ourselves.
54
+ const termContainerDiv =
55
+ termContainerRef.current?.querySelector('.xterm');
56
+ const outputForScreenReader = document.createElement('div');
57
+
58
+ outputForScreenReader.setAttribute('role', 'region');
59
+ outputForScreenReader.setAttribute(
60
+ 'aria-label',
61
+ t('aria.terminal-output')
62
+ );
63
+ outputForScreenReader.classList.add('sr-only');
64
+ termContainerDiv?.appendChild(outputForScreenReader);
65
+
66
+ const print = (text?: string) => {
67
+ term?.writeln(`${text ?? ''}`);
68
+ outputForScreenReader.textContent = text ?? '';
69
+ };
70
+
71
+ // TODO: prevent user from moving cursor outside the current input line and
72
+ // handle insertion and deletion properly. While backspace and delete don't
73
+ // seem to work, we can use "\x1b[0K" to clear from the cursor to the end.
74
+ // Also, we should not add special characters to the userinput string.
75
+ const input = (text?: string) => {
76
+ print(text);
77
+ let userinput = '';
78
+ // Eslint is correct that this only gets assigned once, but we can't use
79
+ // const because the declaration (before keyListener is defined) and
80
+ // assignment (after keyListener is defined) must be separate.
81
+ // eslint-disable-next-line prefer-const
82
+ let disposable: IDisposable | undefined;
83
+
84
+ const done = () => {
85
+ disposable?.dispose();
86
+ navigator.serviceWorker.controller?.postMessage(
87
+ JSON.stringify({
88
+ type: 'msg',
89
+ value: userinput
90
+ })
91
+ );
92
+ };
93
+
94
+ const keyListener = (key: string) => {
95
+ if (key === '\u007F' || key === '\b') {
96
+ // Backspace or delete key
97
+ term?.write('\b \b'); // Move cursor back, replace character with space, then move cursor back again
98
+ userinput = userinput.slice(0, -1); // Remove the last character from userinput
99
+ }
100
+ if (key == '\r') {
101
+ term?.write('\r\n');
102
+ done();
103
+ } else {
104
+ userinput += key;
105
+ term?.write(key);
106
+ }
107
+ };
108
+
109
+ disposable = term?.onData(keyListener); // Listen for key events and store the disposable
110
+ if (disposable) disposables.push(disposable);
111
+ };
112
+ const reset = () => {
113
+ // Ironically, term.reset(), while synchronous, is not a reliable way to
114
+ // reset the terminal. It does not clear the input buffer, so old print
115
+ // statements can still appear. The \x1bc (ESC c) escape sequence triggers
116
+ // a full terminal reset, which is what we want.
117
+ term?.write('\x1bc');
118
+ disposables.forEach(disposable => disposable.dispose());
119
+ disposables.length = 0;
120
+
121
+ outputForScreenReader.textContent = '';
122
+ };
123
+ registerTerminal({ print, input, reset });
124
+ }
125
+
126
+ void createTerminal();
127
+
128
+ return () => {
129
+ term?.dispose();
130
+ };
131
+ }, [xtermFitRef, t]);
132
+
133
+ useEffect(() => {
134
+ if (xtermFitRef.current) xtermFitRef.current.fit();
135
+
136
+ // dimensions is an implicit dependency, since it's not directly used by the
137
+ // effect, but fitAddon.fit() needs to be called whenever the container size
138
+ // changes.
139
+ }, [xtermFitRef, dimensions]);
140
+
141
+ return (
142
+ <div
143
+ data-playwright-test-label='xterm-terminal'
144
+ style={{ height: dimensions?.height }}
145
+ ref={termContainerRef}
146
+ ></div>
147
+ );
148
+ };
github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/codeally/codeally.css ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ button[aria-described-by='codeally-cookie-warning'] {
2
+ font-size: 1.1rem;
3
+ }
github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/codeally/codespaces-instructions.tsx ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React from 'react';
2
+ import { Trans, useTranslation } from 'react-i18next';
3
+ import { Spacer, Button, Callout } from '@freecodecamp/ui';
4
+
5
+ import { CodeAllyButton } from '../../../components/growth-book/codeally-button';
6
+
7
+ interface CodespacesInstructionsProps {
8
+ challengeType: number;
9
+ copyUrl: () => void;
10
+ copyUserToken: () => void;
11
+ generateUserToken: () => Promise<void>;
12
+ isSignedIn: boolean;
13
+ title: string;
14
+ userToken: string | null;
15
+ }
16
+
17
+ export function CodespacesInstructions({
18
+ challengeType,
19
+ copyUrl,
20
+ copyUserToken,
21
+ generateUserToken,
22
+ isSignedIn,
23
+ title,
24
+ userToken
25
+ }: CodespacesInstructionsProps) {
26
+ const { t } = useTranslation();
27
+
28
+ function openCodespaces() {
29
+ const codespacesUrl = `https://codespaces.new/freeCodeCamp/rdb-alpha`;
30
+
31
+ window.open(codespacesUrl, '_blank');
32
+ }
33
+
34
+ return (
35
+ <div className='ca-description'>
36
+ <p>{t('learn.codespaces.intro')}</p>
37
+ <CodespacesContinueAlert title={title} />
38
+ <ol>
39
+ <li>
40
+ <Trans i18nKey='learn.codespaces.step-1'>
41
+ <a
42
+ href='https://github.com/signup'
43
+ rel='noopener noreferrer'
44
+ target='_blank'
45
+ >
46
+ placeholder
47
+ </a>
48
+ </Trans>
49
+ </li>
50
+ {isSignedIn && (
51
+ <>
52
+ <Spacer size='xs' />
53
+ <p>{t('learn.local.sub-step-heading')}</p>
54
+ <ol>
55
+ <li>{t('learn.local.sub-step-1')}</li>
56
+ <Spacer size='xxs' />
57
+ <Button
58
+ disabled={!!userToken}
59
+ block={true}
60
+ onClick={() => void generateUserToken()}
61
+ >
62
+ {t('learn.local.generate-token-btn')}
63
+ </Button>
64
+ <Spacer size='xs' />
65
+ <li>{t('learn.local.sub-step-2')}</li>
66
+ <Spacer size='xxs' />
67
+ <Button
68
+ disabled={!userToken}
69
+ block={true}
70
+ onClick={copyUserToken}
71
+ >
72
+ {t('learn.local.copy-token-btn')}
73
+ </Button>
74
+ <Spacer size='xs' />
75
+ <li>
76
+ <Trans i18nKey='learn.codespaces.sub-step-3'>
77
+ <a
78
+ href='https://github.com/settings/codespaces/secrets/new'
79
+ rel='noopener noreferrer'
80
+ target='_blank'
81
+ >
82
+ Codespaces secrets page
83
+ </a>
84
+ </Trans>
85
+ </li>
86
+ <li>
87
+ <Trans i18nKey='learn.codespaces.sub-step-4'>
88
+ <code>placeholder</code>
89
+ </Trans>
90
+ </li>
91
+ <li>
92
+ <Trans i18nKey='learn.codespaces.sub-step-5'>
93
+ <code>placeholder</code>
94
+ </Trans>
95
+ </li>
96
+ <Spacer size='xxs' />
97
+ <CodespacesLogoutAlert course={title} />
98
+ <Spacer size='xxs' />
99
+ <li>
100
+ <Trans i18nKey='learn.codespaces.sub-step-6'>
101
+ <code>placeholder</code>
102
+ <code>placeholder</code>
103
+ </Trans>
104
+ </li>
105
+ <li>
106
+ <Trans i18nKey='learn.codespaces.sub-step-7'>
107
+ <code>placeholder</code>
108
+ </Trans>
109
+ </li>
110
+ </ol>
111
+ <Spacer size='s' />
112
+ </>
113
+ )}
114
+ <li>{t('learn.codespaces.step-2')}</li>
115
+ <li style={{ listStyle: 'none' }}>
116
+ <Spacer size='xxs' />
117
+ <CodeAllyButton
118
+ challengeType={challengeType}
119
+ onClick={openCodespaces}
120
+ />
121
+ </li>
122
+ </ol>
123
+ <ol start={3}>
124
+ <li>{t('learn.codespaces.step-3')}</li>
125
+ <li>
126
+ {t('learn.codespaces.step-4')}
127
+ <ul>
128
+ <li>{t('learn.codespaces.step-5')}</li>
129
+ <li>
130
+ <Trans i18nKey='learn.codespaces.step-6'>
131
+ <code>placeholder</code>
132
+ </Trans>
133
+ </li>
134
+ <li>
135
+ <Trans i18nKey='learn.codespaces.step-7'>
136
+ <code>placeholder</code>
137
+ </Trans>
138
+ </li>
139
+ <li>
140
+ <Trans i18nKey='learn.codespaces.step-8'>
141
+ <code>placeholder</code>
142
+ </Trans>
143
+ </li>
144
+ <li>{t('learn.local.step-6')}</li>
145
+ <li>{t('learn.local.step-7')}</li>
146
+ <Spacer size='xxs' />
147
+ <Button block={true} onClick={copyUrl}>
148
+ {t('learn.local.copy-url')}
149
+ </Button>
150
+ <Spacer size='xs' />
151
+ <li>{t('learn.local.step-8')}</li>
152
+ </ul>
153
+ </li>
154
+ <li>{t('learn.codespaces.step-9')}</li>
155
+ </ol>
156
+ </div>
157
+ );
158
+ }
159
+
160
+ interface CodespacesContinueAlertProps {
161
+ title: string;
162
+ }
163
+
164
+ function CodespacesContinueAlert({ title }: CodespacesContinueAlertProps) {
165
+ const { t } = useTranslation();
166
+ return (
167
+ <>
168
+ <Callout variant='note' label={t('misc.note')}>
169
+ <Trans values={{ title }} i18nKey='learn.codespaces.continue-project'>
170
+ <a
171
+ href='https://github.com/codespaces'
172
+ rel='noopener noreferrer'
173
+ target='_blank'
174
+ >
175
+ placeholder
176
+ </a>
177
+ </Trans>
178
+ <Spacer size='m' />
179
+ <Trans i18nKey='learn.codespaces.learn-more'>
180
+ <a
181
+ href='https://forum.freecodecamp.org/t/relational-database-curriculum-in-codespaces/761449'
182
+ rel='noopener noreferrer'
183
+ target='_blank'
184
+ >
185
+ placeholder
186
+ </a>
187
+ </Trans>
188
+ </Callout>
189
+ <Spacer size='xs' />
190
+ <Callout variant='caution' label={t('misc.caution')}>
191
+ {t('learn.codespaces.reuse-tab-warning')}
192
+ </Callout>
193
+ </>
194
+ );
195
+ }
196
+
197
+ interface CodespacesLogoutAlertProps {
198
+ course: string;
199
+ }
200
+
201
+ function CodespacesLogoutAlert({
202
+ course
203
+ }: CodespacesLogoutAlertProps): JSX.Element {
204
+ const { t } = useTranslation();
205
+
206
+ return (
207
+ <Callout variant='caution' label={t('misc.caution')}>
208
+ {t('learn.codespaces.logout-warning', { course })}
209
+ </Callout>
210
+ );
211
+ }
github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/codeally/local-instructions.tsx ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React from 'react';
2
+ import { Trans, useTranslation } from 'react-i18next';
3
+ import { Spacer, Button } from '@freecodecamp/ui';
4
+
5
+ import { Link } from '../../../components/helpers';
6
+ import RdbLocalLogoutAlert from './rdb-local-logout-alert';
7
+
8
+ interface LocalInstructionsProps {
9
+ copyUrl: () => void;
10
+ copyUserToken: () => void;
11
+ generateUserToken: () => Promise<void>;
12
+ isSignedIn: boolean;
13
+ title: string;
14
+ userToken: string | null;
15
+ }
16
+
17
+ export function LocalInstructions({
18
+ copyUrl,
19
+ copyUserToken,
20
+ generateUserToken,
21
+ isSignedIn,
22
+ title,
23
+ userToken
24
+ }: LocalInstructionsProps) {
25
+ const { t } = useTranslation();
26
+
27
+ return (
28
+ <div className='ca-description'>
29
+ <p>{t('learn.local.intro')}</p>
30
+ <ul>
31
+ <li>
32
+ <Link external={true} to='https://docs.docker.com/engine/'>
33
+ Docker Engine
34
+ </Link>
35
+ </li>
36
+ <li>
37
+ <Trans i18nKey='learn.local.download-vscode'>
38
+ <Link external={true} to='https://code.visualstudio.com/download'>
39
+ placeholder
40
+ </Link>
41
+ <Link
42
+ external={true}
43
+ to='https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-containers'
44
+ >
45
+ placeholder
46
+ </Link>
47
+ </Trans>
48
+ </li>
49
+ <li>
50
+ <Link external={true} to='https://git-scm.com/downloads'>
51
+ Git
52
+ </Link>
53
+ </li>
54
+ </ul>
55
+ <Spacer size='m' />
56
+ <p>{t('learn.local.heading')}</p>
57
+ <ol>
58
+ <li>
59
+ <Trans i18nKey='learn.local.step-1'>
60
+ <code>placeholder</code>
61
+ </Trans>
62
+ </li>
63
+ <li>
64
+ <Trans i18nKey='learn.local.step-2'>
65
+ <code>placeholder</code>
66
+ <code>placeholder</code>
67
+ <code>placeholder</code>
68
+ </Trans>
69
+ </li>
70
+ {isSignedIn && (
71
+ <>
72
+ <Spacer size='s' />
73
+ <p>{t('learn.local.sub-step-heading')}</p>
74
+ <ol>
75
+ <li>{t('learn.local.sub-step-1')}</li>
76
+ <Spacer size='xxs' />
77
+ <Button
78
+ disabled={!!userToken}
79
+ block={true}
80
+ onClick={() => void generateUserToken()}
81
+ >
82
+ {t('learn.local.generate-token-btn')}
83
+ </Button>
84
+ <Spacer size='xs' />
85
+ <li>{t('learn.local.sub-step-2')}</li>
86
+ <Spacer size='xxs' />
87
+ <Button
88
+ disabled={!userToken}
89
+ block={true}
90
+ onClick={copyUserToken}
91
+ >
92
+ {t('learn.local.copy-token-btn')}
93
+ </Button>
94
+ <Spacer size='xs' />
95
+ <li>
96
+ <Trans i18nKey='learn.local.sub-step-3'>
97
+ <code>placeholder</code>
98
+ <code>placeholder</code>
99
+ <code>placeholder</code>
100
+ </Trans>
101
+ </li>
102
+ <Spacer size='xs' />
103
+ <RdbLocalLogoutAlert title={title} />
104
+ </ol>
105
+ <Spacer size='s' />
106
+ </>
107
+ )}
108
+ <li>
109
+ <Trans i18nKey='learn.local.step-3'>
110
+ <code>placeholder</code>
111
+ </Trans>
112
+ </li>
113
+ <li>{t('learn.local.step-4')}</li>
114
+ <li>
115
+ <Trans i18nKey='learn.local.step-5'>
116
+ <code>placeholder</code>
117
+ </Trans>
118
+ </li>
119
+ <li>{t('learn.local.step-6')}</li>
120
+ <li>{t('learn.local.step-7')}</li>
121
+ <Spacer size='xxs' />
122
+ <Button block={true} onClick={copyUrl}>
123
+ {t('learn.local.copy-url')}
124
+ </Button>
125
+ <Spacer size='xs' />
126
+ <li>{t('learn.local.step-8')}</li>
127
+ <li>{t('learn.local.step-9')}</li>
128
+ </ol>
129
+ </div>
130
+ );
131
+ }
github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/codeally/project-submit.test.ts ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, expect, test } from 'vitest';
2
+
3
+ import { isCodeAllyProjectCompleted } from './project-submit';
4
+
5
+ const challengeId = '5e601c775ac9d0ecd8b94aff';
6
+
7
+ describe('isCodeAllyProjectCompleted', () => {
8
+ test('returns false when the project has not been completed', () => {
9
+ expect(
10
+ isCodeAllyProjectCompleted({
11
+ challengeId,
12
+ completedChallenges: [],
13
+ partiallyCompletedChallenges: []
14
+ })
15
+ ).toBe(false);
16
+ });
17
+
18
+ test('returns true when the project is partially completed', () => {
19
+ expect(
20
+ isCodeAllyProjectCompleted({
21
+ challengeId,
22
+ completedChallenges: [],
23
+ partiallyCompletedChallenges: [{ id: challengeId }]
24
+ })
25
+ ).toBe(true);
26
+ });
27
+
28
+ test('returns true when the project is completed', () => {
29
+ expect(
30
+ isCodeAllyProjectCompleted({
31
+ challengeId,
32
+ completedChallenges: [{ id: challengeId }],
33
+ partiallyCompletedChallenges: []
34
+ })
35
+ ).toBe(true);
36
+ });
37
+ });
github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/codeally/project-submit.ts ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ type ChallengeWithId = {
2
+ id: string;
3
+ };
4
+
5
+ export function isCodeAllyProjectCompleted({
6
+ challengeId,
7
+ completedChallenges,
8
+ partiallyCompletedChallenges
9
+ }: {
10
+ challengeId: string;
11
+ completedChallenges: ChallengeWithId[];
12
+ partiallyCompletedChallenges: ChallengeWithId[];
13
+ }): boolean {
14
+ return [...partiallyCompletedChallenges, ...completedChallenges].some(
15
+ challenge => challenge.id === challengeId
16
+ );
17
+ }
github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/codeally/rdb-local-logout-alert.tsx ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React from 'react';
2
+ import { useTranslation } from 'react-i18next';
3
+ import { Callout } from '@freecodecamp/ui';
4
+
5
+ interface RdbLocalLogoutAlertProps {
6
+ title: string;
7
+ }
8
+
9
+ function RdbLocalLogoutAlert({ title }: RdbLocalLogoutAlertProps): JSX.Element {
10
+ const { t } = useTranslation();
11
+
12
+ return (
13
+ <Callout variant='caution' label={t('misc.caution')}>
14
+ {t('learn.local.logout-warning', { course: title })}
15
+ </Callout>
16
+ );
17
+ }
18
+
19
+ RdbLocalLogoutAlert.displayName = 'RdbLocalLogoutAlert';
20
+
21
+ export default RdbLocalLogoutAlert;
github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/codeally/rdb-step-1-instructions.tsx ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React from 'react';
2
+ import { useTranslation } from 'react-i18next';
3
+ import { Spacer } from '@freecodecamp/ui';
4
+
5
+ import ChallengeHeading from '../components/challenge-heading';
6
+ import PrismFormatted from '../components/prism-formatted';
7
+
8
+ interface RdbStep1InstructionsProps {
9
+ instructions: string;
10
+ isCompleted: boolean;
11
+ }
12
+
13
+ function RdbStep1Instructions({
14
+ instructions,
15
+ isCompleted
16
+ }: RdbStep1InstructionsProps): JSX.Element {
17
+ const { t } = useTranslation();
18
+
19
+ return (
20
+ <>
21
+ <ChallengeHeading heading={t('learn.step-1')} isCompleted={isCompleted} />
22
+ <Spacer size='m' />
23
+ <div className='ca-description'>{t('learn.runs-in-vm')}</div>
24
+ <Spacer size='m' />
25
+ <PrismFormatted text={instructions} />
26
+ </>
27
+ );
28
+ }
29
+
30
+ RdbStep1Instructions.displayName = 'RdbStep1Instructions';
31
+
32
+ export default RdbStep1Instructions;
github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/codeally/rdb-step-2-instructions.tsx ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React from 'react';
2
+
3
+ import { useTranslation } from 'react-i18next';
4
+ import { Spacer } from '@freecodecamp/ui';
5
+
6
+ import ChallengeHeading from '../components/challenge-heading';
7
+ import PrismFormatted from '../components/prism-formatted';
8
+
9
+ interface RdbStep2InstructionsProps {
10
+ notes: string;
11
+ isCompleted: boolean;
12
+ }
13
+
14
+ function RdbStep2Instructions({
15
+ isCompleted,
16
+ notes
17
+ }: RdbStep2InstructionsProps): JSX.Element {
18
+ const { t } = useTranslation();
19
+
20
+ return (
21
+ <>
22
+ <ChallengeHeading heading={t('learn.step-2')} isCompleted={isCompleted} />
23
+ <Spacer size='m' />
24
+ <div className='ca-description'>{t('learn.submit-public-url')}</div>
25
+ <Spacer size='m' />
26
+ <PrismFormatted text={notes} />
27
+ </>
28
+ );
29
+ }
30
+
31
+ RdbStep2Instructions.displayName = 'RdbStep2Instructions';
32
+
33
+ export default RdbStep2Instructions;
github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/codeally/show.tsx ADDED
@@ -0,0 +1,399 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Package Utilities
2
+ import { graphql } from 'gatsby';
3
+ import React, { Fragment, useEffect, useRef } from 'react';
4
+ import Helmet from 'react-helmet';
5
+ import type { TFunction } from 'i18next';
6
+ import { withTranslation } from 'react-i18next';
7
+ import { connect } from 'react-redux';
8
+ import { bindActionCreators } from 'redux';
9
+ import type { Dispatch } from 'redux';
10
+ import { createSelector } from 'reselect';
11
+ import { Container, Col, Row, Spacer } from '@freecodecamp/ui';
12
+ import { useFeature } from '@growthbook/growthbook-react';
13
+
14
+ // Local Utilities
15
+ import LearnLayout from '../../../components/layouts/learn';
16
+ import ChallengeTitle from '../components/challenge-title';
17
+ import PrismFormatted from '../components/prism-formatted';
18
+ import { challengeTypes } from '@freecodecamp/shared/config/challenge-types';
19
+ import CompletionModal from '../components/completion-modal';
20
+ import HelpModal from '../components/help-modal';
21
+ import Hotkeys from '../components/hotkeys';
22
+ import { updateUserToken } from '../../../redux/actions';
23
+ import {
24
+ completedChallengesSelector,
25
+ partiallyCompletedChallengesSelector,
26
+ isSignedInSelector,
27
+ userTokenSelector
28
+ } from '../../../redux/selectors';
29
+ import {
30
+ challengeMounted,
31
+ updateChallengeMeta,
32
+ openModal,
33
+ updateSolutionFormValues,
34
+ initTests
35
+ } from '../redux/actions';
36
+ import { isChallengeCompletedSelector } from '../redux/selectors';
37
+ import { createFlashMessage } from '../../../components/Flash/redux';
38
+ import {
39
+ ChallengeNode,
40
+ ChallengeMeta,
41
+ CompletedChallenge,
42
+ Test
43
+ } from '../../../redux/prop-types';
44
+ import ProjectToolPanel from '../projects/tool-panel';
45
+ import { getChallengePaths } from '../utils/challenge-paths';
46
+ import SolutionForm from '../projects/solution-form';
47
+ import { FlashMessages } from '../../../components/Flash/redux/flash-messages';
48
+ import { SuperBlocks } from '@freecodecamp/shared/config/curriculum';
49
+ import { CodeAllyDown } from '../../../components/growth-book/codeally-down';
50
+ import { postUserToken } from '../../../utils/ajax';
51
+ import RdbStep1Instructions from './rdb-step-1-instructions';
52
+ import RdbStep2Instructions from './rdb-step-2-instructions';
53
+ import { LocalInstructions } from './local-instructions';
54
+
55
+ import './codeally.css';
56
+ import { CodespacesInstructions } from './codespaces-instructions';
57
+ import { isCodeAllyProjectCompleted } from './project-submit';
58
+
59
+ // Redux
60
+ const mapStateToProps = createSelector(
61
+ completedChallengesSelector,
62
+ isChallengeCompletedSelector,
63
+ isSignedInSelector,
64
+ partiallyCompletedChallengesSelector,
65
+ userTokenSelector,
66
+ (
67
+ completedChallenges: CompletedChallenge[],
68
+ isChallengeCompleted: boolean,
69
+ isSignedIn: boolean,
70
+ partiallyCompletedChallenges: CompletedChallenge[],
71
+ userToken: string | null
72
+ ) => ({
73
+ completedChallenges,
74
+ isChallengeCompleted,
75
+ isSignedIn,
76
+ partiallyCompletedChallenges,
77
+ userToken
78
+ })
79
+ );
80
+
81
+ const mapDispatchToProps = (dispatch: Dispatch) =>
82
+ bindActionCreators(
83
+ {
84
+ challengeMounted,
85
+ createFlashMessage,
86
+ openCompletionModal: () => openModal('completion'),
87
+ initTests,
88
+ updateUserToken,
89
+ updateChallengeMeta,
90
+ updateSolutionFormValues
91
+ },
92
+ dispatch
93
+ );
94
+
95
+ // Types
96
+ interface ShowCodeAllyProps {
97
+ challengeMounted: (arg0: string) => void;
98
+ completedChallenges: CompletedChallenge[];
99
+ createFlashMessage: typeof createFlashMessage;
100
+ data: { challengeNode: ChallengeNode };
101
+ initTests: (xs: Test[]) => void;
102
+ isChallengeCompleted: boolean;
103
+ isSignedIn: boolean;
104
+ openCompletionModal: () => void;
105
+ pageContext: {
106
+ challengeMeta: ChallengeMeta;
107
+ };
108
+ partiallyCompletedChallenges: CompletedChallenge[];
109
+ t: TFunction;
110
+ updateChallengeMeta: (arg0: ChallengeMeta) => void;
111
+ updateUserToken: (arg0: string) => void;
112
+ updateSolutionFormValues: () => void;
113
+ userToken: string | null;
114
+ }
115
+
116
+ function ShowCodeAlly({
117
+ completedChallenges,
118
+ data,
119
+ isChallengeCompleted,
120
+ isSignedIn,
121
+ partiallyCompletedChallenges,
122
+ t,
123
+ updateSolutionFormValues,
124
+ userToken,
125
+ updateUserToken,
126
+ createFlashMessage,
127
+ challengeMounted,
128
+ initTests,
129
+ pageContext: { challengeMeta },
130
+ updateChallengeMeta,
131
+ openCompletionModal
132
+ }: ShowCodeAllyProps) {
133
+ const container = useRef<HTMLElement>(null);
134
+
135
+ const {
136
+ challengeNode: {
137
+ challenge: {
138
+ block,
139
+ challengeType,
140
+ tests,
141
+ description,
142
+ helpCategory,
143
+ id: challengeId,
144
+ instructions,
145
+ notes,
146
+ superBlock,
147
+ title,
148
+ translationPending,
149
+ url
150
+ }
151
+ }
152
+ } = data;
153
+ const blockNameTitle = `${t(
154
+ `intro:${superBlock}.blocks.${block}.title`
155
+ )}: ${title}`;
156
+ const windowTitle = `${blockNameTitle} | freeCodeCamp.org`;
157
+
158
+ const isPartiallyCompleted = partiallyCompletedChallenges.some(
159
+ challenge => challenge.id === challengeId
160
+ );
161
+
162
+ const isCompleted = completedChallenges.some(
163
+ challenge => challenge.id === challengeId
164
+ );
165
+
166
+ useEffect(() => {
167
+ initTests(tests);
168
+ const challengePaths = getChallengePaths({
169
+ currentCurriculumPaths: challengeMeta
170
+ });
171
+ updateChallengeMeta({
172
+ ...challengeMeta,
173
+ title,
174
+ challengeType,
175
+ helpCategory,
176
+ description,
177
+ ...challengePaths
178
+ });
179
+ challengeMounted(challengeMeta.id);
180
+ // hack to ensure the container is focused after the component mounts
181
+ // and Gatsby doesn't interfere with the focus.
182
+ requestAnimationFrame(() => container.current?.focus());
183
+ // This effect should be run once on mount
184
+ // eslint-disable-next-line react-hooks/exhaustive-deps
185
+ }, []);
186
+
187
+ const handleSubmit = ({
188
+ showCompletionModal
189
+ }: {
190
+ showCompletionModal: boolean;
191
+ }) => {
192
+ if (
193
+ !isCodeAllyProjectCompleted({
194
+ challengeId,
195
+ completedChallenges,
196
+ partiallyCompletedChallenges
197
+ })
198
+ ) {
199
+ createFlashMessage({
200
+ type: 'danger',
201
+ message: FlashMessages.CompleteProjectFirst
202
+ });
203
+ } else if (showCompletionModal) {
204
+ openCompletionModal();
205
+ }
206
+ };
207
+
208
+ const rdbLocalInstructions = useFeature('rdb-local-instructions');
209
+ const rdbCodespacesInstructions = useFeature('rdb-codespaces-instructions');
210
+
211
+ const coderoadTutorial = `https://raw.githubusercontent.com/${url}/main/tutorial.json`;
212
+
213
+ async function generateUserToken() {
214
+ const createUserTokenResponse = await postUserToken();
215
+ const { data = { userToken: null } } = createUserTokenResponse;
216
+
217
+ if (data?.userToken) {
218
+ updateUserToken(data.userToken);
219
+ createFlashMessage({
220
+ type: 'success',
221
+ message: FlashMessages.UserTokenGenerated
222
+ });
223
+ } else {
224
+ createFlashMessage({
225
+ type: 'danger',
226
+ message: FlashMessages.UserTokenGenerateError
227
+ });
228
+ }
229
+ }
230
+
231
+ function copyUserToken() {
232
+ navigator.clipboard.writeText(userToken ?? '').then(
233
+ () => {
234
+ createFlashMessage({
235
+ type: 'success',
236
+ message: FlashMessages.UserTokenCopied
237
+ });
238
+ },
239
+ () => {
240
+ createFlashMessage({
241
+ type: 'danger',
242
+ message: FlashMessages.UserTokenCopyError
243
+ });
244
+ }
245
+ );
246
+ }
247
+
248
+ function copyUrl() {
249
+ navigator.clipboard.writeText(coderoadTutorial ?? '').then(
250
+ () => {
251
+ createFlashMessage({
252
+ type: 'success',
253
+ message: FlashMessages.CourseUrlCopied
254
+ });
255
+ },
256
+ () => {
257
+ createFlashMessage({
258
+ type: 'danger',
259
+ message: FlashMessages.CourseUrlCopyError
260
+ });
261
+ }
262
+ );
263
+ }
264
+
265
+ const setups = [
266
+ {
267
+ name: t('learn.codespaces.summary'),
268
+ component: CodespacesInstructions,
269
+ on: rdbCodespacesInstructions.on
270
+ },
271
+ {
272
+ name: t('learn.local.summary'),
273
+ component: LocalInstructions,
274
+ on: rdbLocalInstructions.on
275
+ }
276
+ ];
277
+
278
+ const setupsToShow = setups.filter(setup => {
279
+ return setup.on;
280
+ });
281
+
282
+ return (
283
+ <Hotkeys containerRef={container}>
284
+ <LearnLayout>
285
+ <Helmet title={windowTitle} />
286
+ <Container>
287
+ <Row>
288
+ <Col md={8} mdOffset={2} sm={10} smOffset={1} xs={12}>
289
+ <Spacer size='m' />
290
+ {superBlock === SuperBlocks.RelationalDb && <CodeAllyDown />}
291
+ <Spacer size='m' />
292
+ <ChallengeTitle
293
+ isCompleted={isChallengeCompleted}
294
+ translationPending={translationPending}
295
+ >
296
+ {title}
297
+ </ChallengeTitle>
298
+ <Spacer size='m' />
299
+ <PrismFormatted text={description} />
300
+ <Spacer size='m' />
301
+
302
+ {setupsToShow.map(({ name, component: SetupComponent }, i) => (
303
+ <Fragment key={name}>
304
+ <details
305
+ open={i === 0}
306
+ style={{ border: '1px solid #ccc', padding: '16px' }}
307
+ >
308
+ <summary>{name}</summary>
309
+ <Spacer size='s' />
310
+ <SetupComponent
311
+ {...{
312
+ challengeType,
313
+ copyUrl,
314
+ copyUserToken,
315
+ generateUserToken,
316
+ isSignedIn,
317
+ title,
318
+ userToken
319
+ }}
320
+ />
321
+ </details>
322
+ <Spacer size='s' />
323
+ </Fragment>
324
+ ))}
325
+
326
+ <Spacer size='m' />
327
+ {isSignedIn && challengeType === challengeTypes.codeAllyCert && (
328
+ <>
329
+ <div className='ca-description'>
330
+ {t('learn.complete-both-steps')}
331
+ </div>
332
+ <hr />
333
+ <Spacer size='m' />
334
+ <RdbStep1Instructions
335
+ instructions={instructions}
336
+ isCompleted={isPartiallyCompleted || isCompleted}
337
+ />
338
+ <hr />
339
+ <Spacer size='m' />
340
+ <RdbStep2Instructions
341
+ isCompleted={isCompleted}
342
+ notes={notes}
343
+ />
344
+ <Spacer size='m' />
345
+ <SolutionForm
346
+ challengeType={challengeType}
347
+ description={description}
348
+ onSubmit={handleSubmit}
349
+ updateSolutionForm={updateSolutionFormValues}
350
+ />
351
+ </>
352
+ )}
353
+
354
+ <ProjectToolPanel />
355
+ <br />
356
+ <Spacer size='m' />
357
+ </Col>
358
+ <CompletionModal />
359
+ <HelpModal
360
+ challengeTitle={title}
361
+ challengeBlock={block}
362
+ superBlock={superBlock}
363
+ />
364
+ </Row>
365
+ </Container>
366
+ </LearnLayout>
367
+ </Hotkeys>
368
+ );
369
+ }
370
+
371
+ export default connect(
372
+ mapStateToProps,
373
+ mapDispatchToProps
374
+ )(withTranslation()(ShowCodeAlly));
375
+
376
+ // GraphQL
377
+ export const query = graphql`
378
+ query CodeAllyChallenge($id: String!) {
379
+ challengeNode(id: { eq: $id }) {
380
+ challenge {
381
+ block
382
+ challengeType
383
+ description
384
+ helpCategory
385
+ id
386
+ instructions
387
+ notes
388
+ superBlock
389
+ tests {
390
+ text
391
+ testString
392
+ }
393
+ title
394
+ translationPending
395
+ url
396
+ }
397
+ }
398
+ }
399
+ `;
github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/assignments.css ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ .assignments-not-complete {
2
+ text-align: center;
3
+ color: var(--danger-color);
4
+ }
github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/assignments.tsx ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React from 'react';
2
+ import { useTranslation } from 'react-i18next';
3
+ import { Spacer } from '@freecodecamp/ui';
4
+
5
+ import ChallengeHeading from './challenge-heading';
6
+ import PrismFormatted from './prism-formatted';
7
+ import { getChallengeContentLangProps } from '../../../utils/challenge-content-lang';
8
+
9
+ import './assignments.css';
10
+
11
+ type AssignmentsProps = {
12
+ assignments: string[];
13
+ allAssignmentsCompleted: boolean;
14
+ handleAssignmentChange: (
15
+ event: React.ChangeEvent<HTMLInputElement>,
16
+ totalAssignments: number
17
+ ) => void;
18
+ superBlock?: string;
19
+ };
20
+
21
+ function Assignments({
22
+ assignments,
23
+ allAssignmentsCompleted,
24
+ handleAssignmentChange,
25
+ superBlock
26
+ }: AssignmentsProps): JSX.Element {
27
+ const { t } = useTranslation();
28
+ const contentLangProps = getChallengeContentLangProps(superBlock);
29
+ return (
30
+ <>
31
+ <ChallengeHeading
32
+ heading={t('learn.assignments', { count: assignments.length })}
33
+ />
34
+ <div className='video-quiz-options'>
35
+ {assignments.map((assignment, index) => (
36
+ <label className='video-quiz-option-label' key={index}>
37
+ <input
38
+ name='assignment'
39
+ type='checkbox'
40
+ onChange={event =>
41
+ handleAssignmentChange(event, assignments.length)
42
+ }
43
+ />
44
+ <PrismFormatted
45
+ className={'video-quiz-option'}
46
+ text={assignment}
47
+ {...contentLangProps}
48
+ />
49
+ <Spacer size='m' />
50
+ </label>
51
+ ))}
52
+ </div>
53
+ {!allAssignmentsCompleted && (
54
+ <>
55
+ <Spacer size='m' />
56
+ <div className='assignments-not-complete'>
57
+ {t('learn.assignment-not-complete', { count: assignments.length })}
58
+ </div>
59
+ </>
60
+ )}
61
+ <Spacer size='m' />
62
+ </>
63
+ );
64
+ }
65
+
66
+ Assignments.displayName = 'Assignments';
67
+
68
+ export default Assignments;
github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/bread-crumb.test.tsx ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React from 'react';
2
+ import { render, screen } from '@testing-library/react';
3
+ import { describe, expect, test, vi } from 'vitest';
4
+
5
+ import BreadCrumb from './bread-crumb';
6
+
7
+ vi.mock('i18next', () => ({
8
+ default: {
9
+ t: (key: string) => key
10
+ }
11
+ }));
12
+
13
+ describe('<BreadCrumb />', () => {
14
+ test('renders superblock and block links', () => {
15
+ render(
16
+ <BreadCrumb
17
+ block='workshop-cat-photo-app'
18
+ superBlock='responsive-web-design-v9'
19
+ />
20
+ );
21
+
22
+ expect(
23
+ screen.getByRole('navigation', { name: 'aria.breadcrumb-nav' })
24
+ ).toBeInTheDocument();
25
+ expect(
26
+ screen.getByRole('link', {
27
+ name: 'intro:responsive-web-design-v9.title'
28
+ })
29
+ ).toHaveAttribute('href', '/learn/responsive-web-design-v9');
30
+ expect(
31
+ screen.getByRole('link', {
32
+ name: 'intro:responsive-web-design-v9.blocks.workshop-cat-photo-app.title'
33
+ })
34
+ ).toHaveAttribute(
35
+ 'href',
36
+ '/learn/responsive-web-design-v9/#workshop-cat-photo-app'
37
+ );
38
+ });
39
+ });
github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/bread-crumb.tsx ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import i18next from 'i18next';
2
+ import React from 'react';
3
+ import { useTranslation } from 'react-i18next';
4
+ import { Link } from '../../../components/helpers/index';
5
+
6
+ import './challenge-title.css';
7
+
8
+ interface BreadCrumbProps {
9
+ block: string;
10
+ superBlock: string;
11
+ }
12
+
13
+ function BreadCrumb({ block, superBlock }: BreadCrumbProps): JSX.Element {
14
+ const { t } = useTranslation();
15
+ return (
16
+ <nav
17
+ className='challenge-title-breadcrumbs'
18
+ aria-label={t('aria.breadcrumb-nav')}
19
+ >
20
+ <ol data-playwright-test-label='breadcrumb-desktop'>
21
+ <li className='breadcrumb-left'>
22
+ <Link
23
+ state={{ breadcrumbBlockClick: block }}
24
+ to={`/learn/${superBlock}`}
25
+ >
26
+ <span>{i18next.t(`intro:${superBlock}.title`)}</span>
27
+ </Link>
28
+ </li>
29
+ <li className='breadcrumb-right'>
30
+ <Link
31
+ state={{ breadcrumbBlockClick: block }}
32
+ to={`/learn/${superBlock}/#${block}`}
33
+ >
34
+ {i18next.t(`intro:${superBlock}.blocks.${block}.title`)}
35
+ </Link>
36
+ </li>
37
+ </ol>
38
+ </nav>
39
+ );
40
+ }
41
+
42
+ BreadCrumb.displayName = 'BreadCrumb';
43
+
44
+ export default BreadCrumb;
github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/challenge-description.css ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .challenge-instructions blockquote {
2
+ background-color: var(--tertiary-background);
3
+ color: var(--tertiary-color);
4
+ padding: 10px;
5
+ width: 100%;
6
+ margin: 0;
7
+ margin-bottom: 1.45rem;
8
+ font-size: 0.9rem;
9
+ }
10
+
11
+ #description ol li a {
12
+ word-break: break-all;
13
+ }
14
+
15
+ #description ol li {
16
+ line-height: 1.5;
17
+ }
github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/challenge-description.test.tsx ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React from 'react';
2
+ import { render, screen } from '@testing-library/react';
3
+ import { describe, expect, test } from 'vitest';
4
+
5
+ import ChallengeDescription from './challenge-description';
6
+
7
+ describe('<ChallengeDescription />', () => {
8
+ test('renders description links with their attributes', () => {
9
+ render(
10
+ <ChallengeDescription
11
+ block='write-your-first-code-using-c-sharp'
12
+ challengeId='647f85d407d29547b3bee1bb'
13
+ description='View <a href="https://learn.microsoft.com/users/me/achievements#trophies-section" target="_blank" rel="noreferrer">your achievements page</a>.'
14
+ />
15
+ );
16
+
17
+ expect(screen.getByText(/View/)).toBeInTheDocument();
18
+ expect(
19
+ screen.getByRole('link', { name: 'your achievements page' })
20
+ ).toHaveAttribute(
21
+ 'href',
22
+ 'https://learn.microsoft.com/users/me/achievements#trophies-section'
23
+ );
24
+ expect(
25
+ screen.getByRole('link', { name: 'your achievements page' })
26
+ ).toHaveAttribute('target', '_blank');
27
+ expect(
28
+ screen.getByRole('link', { name: 'your achievements page' })
29
+ ).toHaveAttribute('rel', 'noreferrer');
30
+ });
31
+ });
github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/challenge-description.tsx ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useEffect } from 'react';
2
+ import { initializeMathJax, isMathJaxAllowed } from '../../../utils/math-jax';
3
+ import PrismFormatted from './prism-formatted';
4
+ import './challenge-description.css';
5
+ import { generateGithubLink } from '../../../components/create-github-link';
6
+ import { getChallengeContentLangProps } from '../../../utils/challenge-content-lang';
7
+
8
+ type Props = {
9
+ description?: string;
10
+ instructions?: string;
11
+ superBlock?: string;
12
+ challengeId: string;
13
+ block: string;
14
+ };
15
+
16
+ const ChallengeDescription = ({
17
+ description,
18
+ instructions,
19
+ superBlock,
20
+ challengeId,
21
+ block
22
+ }: Props) => {
23
+ useEffect(() => {
24
+ if (superBlock && isMathJaxAllowed(superBlock)) {
25
+ initializeMathJax();
26
+ }
27
+ }, [superBlock]);
28
+
29
+ const githubLink = generateGithubLink(challengeId, block);
30
+ const contentLangProps = getChallengeContentLangProps(superBlock);
31
+ return (
32
+ <div
33
+ className={'challenge-instructions mathjax-support'}
34
+ data-playwright-test-label='challenge-description'
35
+ data-github-link={githubLink}
36
+ >
37
+ {description && (
38
+ <PrismFormatted text={description} {...contentLangProps} />
39
+ )}
40
+ {instructions && description && <hr />}
41
+ {instructions && (
42
+ <PrismFormatted text={instructions} {...contentLangProps} />
43
+ )}
44
+ </div>
45
+ );
46
+ };
47
+
48
+ ChallengeDescription.displayName = 'ChallengeDescription';
49
+
50
+ export default ChallengeDescription;
github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/challenge-explanation.css ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ .challenge-summary {
2
+ cursor: pointer;
3
+ }
github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/challenge-explanation.tsx ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React from 'react';
2
+ import { useTranslation } from 'react-i18next';
3
+ import { Spacer } from '@freecodecamp/ui';
4
+ import { SuperBlocks } from '@freecodecamp/shared/config/curriculum';
5
+ import PrismFormatted from './prism-formatted';
6
+ import { getChallengeContentLangProps } from '../../../utils/challenge-content-lang';
7
+
8
+ import './challenge-explanation.css';
9
+
10
+ interface ChallengeExplanationProps {
11
+ explanation: string;
12
+ superBlock: SuperBlocks;
13
+ }
14
+
15
+ function ChallengeExplanation({
16
+ explanation,
17
+ superBlock
18
+ }: ChallengeExplanationProps): JSX.Element {
19
+ const { t } = useTranslation();
20
+
21
+ return (
22
+ <>
23
+ <details>
24
+ <summary className='challenge-summary'>
25
+ {t('learn.explanation')}
26
+ </summary>
27
+ <Spacer size='m' />
28
+ <PrismFormatted
29
+ className={'line-numbers'}
30
+ text={explanation}
31
+ {...getChallengeContentLangProps(superBlock)}
32
+ />
33
+ </details>
34
+ <Spacer size='m' />
35
+ </>
36
+ );
37
+ }
38
+
39
+ ChallengeExplanation.displayName = 'ChallengeExplanation';
40
+
41
+ export default ChallengeExplanation;
github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/challenge-heading.css ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ .challenge-heading-wrap {
2
+ display: flex;
3
+ gap: 7px;
4
+ align-items: center;
5
+ justify-content: center;
6
+ }
7
+
8
+ .challenge-heading {
9
+ font-size: 16px;
10
+ }
github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/challenge-heading.tsx ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React from 'react';
2
+ import { useTranslation } from 'react-i18next';
3
+ import GreenPass from '../../../assets/icons/green-pass';
4
+
5
+ import './challenge-heading.css';
6
+
7
+ interface ChallengeHeadingProps {
8
+ heading: string;
9
+ isCompleted?: boolean;
10
+ }
11
+
12
+ function ChallengeHeading({
13
+ heading,
14
+ isCompleted = false
15
+ }: ChallengeHeadingProps): JSX.Element {
16
+ const { t } = useTranslation();
17
+
18
+ return (
19
+ <div className='challenge-heading-wrap'>
20
+ <h2 className='challenge-heading'>{t(heading)}</h2>
21
+ {isCompleted && <GreenPass />}
22
+ </div>
23
+ );
24
+ }
25
+
26
+ ChallengeHeading.displayName = 'ChallengeHeading';
27
+
28
+ export default ChallengeHeading;
github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/challenge-title.css ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .challenge-title-wrap {
2
+ text-align: center;
3
+ }
4
+
5
+ .challenge-title {
6
+ height: fit-content;
7
+ min-width: 25px;
8
+ margin: 20px 0px 15px;
9
+ padding: 0px 3px;
10
+ display: flex;
11
+ gap: 7px;
12
+ align-items: center;
13
+ justify-content: center;
14
+ overflow: hidden;
15
+ text-overflow: ellipsis;
16
+ max-height: fit-content;
17
+ white-space: pre-line;
18
+ flex-grow: 1;
19
+ flex-shrink: 1;
20
+ font-size: 16px;
21
+ }
22
+
23
+ .challenge-title-breadcrumbs {
24
+ font-size: 16px;
25
+ border: 1px solid var(--quaternary-background);
26
+ text-align: center;
27
+ }
28
+
29
+ .challenge-title-breadcrumbs ol {
30
+ display: flex;
31
+ justify-content: space-around;
32
+ list-style-type: none;
33
+ margin-bottom: 0;
34
+ padding-inline-start: 0;
35
+ width: 100%;
36
+ }
37
+
38
+ .challenge-title-breadcrumbs ol a {
39
+ width: 100%;
40
+ text-decoration: none;
41
+ overflow: hidden;
42
+ text-overflow: ellipsis;
43
+ display: block;
44
+ padding: 0 3px;
45
+ }
46
+
47
+ .challenge-title-breadcrumbs ol a:focus {
48
+ background-color: inherit;
49
+ }
50
+
51
+ .challenge-title-breadcrumbs ol a:hover {
52
+ background-color: inherit;
53
+ text-decoration: underline;
54
+ }
55
+
56
+ .breadcrumb-left,
57
+ .breadcrumb-right {
58
+ text-decoration: none;
59
+ display: inline-flex;
60
+ align-items: center;
61
+ justify-content: center;
62
+ text-overflow: ellipsis;
63
+ white-space: nowrap;
64
+ flex-grow: 1;
65
+ flex-shrink: 2;
66
+ padding: 0;
67
+ }
68
+
69
+ .breadcrumb-left {
70
+ min-width: 3rem;
71
+ background-color: var(--quaternary-background);
72
+ margin-inline-end: 0.57rem;
73
+ }
74
+
75
+ .breadcrumb-left:after {
76
+ background-color: var(--secondary-background);
77
+ content: '';
78
+ border-top: calc(1.375rem / 2) solid transparent;
79
+ border-bottom: calc(1.2rem / 2) solid transparent;
80
+ border-inline-start: calc(1.1rem / 2) solid var(--quaternary-background);
81
+ height: 100%;
82
+ margin-inline-start: 3px;
83
+ }
84
+
85
+ .breadcrumb-right {
86
+ min-width: 50px;
87
+ }
88
+
89
+ .breadcrumb-rule {
90
+ margin: 5px -10px;
91
+ }
92
+
93
+ .challenge-title h1 {
94
+ font-size: 1.1rem;
95
+ line-height: 1.42857143;
96
+ margin: 0;
97
+ display: inline;
98
+ }
99
+
100
+ .title-translation-cta {
101
+ display: flex;
102
+ flex-direction: row;
103
+ justify-content: space-around;
104
+ font-size: 16px;
105
+ height: 25px;
106
+ text-decoration: none;
107
+ color: var(--highlight-color);
108
+ background-color: var(--highlight-background);
109
+ margin-bottom: 10px;
110
+ }
111
+
112
+ .title-translation-cta:hover,
113
+ .title-translation-cta:focus {
114
+ text-decoration: none;
115
+ color: var(--highlight-background);
116
+ background-color: var(--highlight-color);
117
+ }
github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/challenge-title.test.tsx ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React from 'react';
2
+ import { render, screen } from '@testing-library/react';
3
+ import { describe, it, expect, vi } from 'vitest';
4
+
5
+ import ChallengeTitle from './challenge-title';
6
+
7
+ vi.mock('i18next', () => ({
8
+ default: {
9
+ t: (key: string) =>
10
+ ({
11
+ 'links:help-translate-link-url': 'https://example.com/help-translate',
12
+ 'misc.translation-pending': 'Help us translate'
13
+ })[key] ?? key
14
+ }
15
+ }));
16
+
17
+ const baseProps = {
18
+ children: 'What Role Does HTML Play on the Web?',
19
+ isCompleted: false,
20
+ translationPending: false
21
+ };
22
+
23
+ describe('<ChallengeTitle/>', () => {
24
+ it('renders the challenge title without a completion icon', () => {
25
+ render(<ChallengeTitle {...baseProps} />);
26
+
27
+ expect(
28
+ screen.getByRole('heading', {
29
+ level: 1,
30
+ name: 'What Role Does HTML Play on the Web?'
31
+ })
32
+ ).toBeInTheDocument();
33
+ expect(screen.queryByTestId('green-pass')).not.toBeInTheDocument();
34
+ });
35
+
36
+ it('renders the completion icon when the challenge is completed', () => {
37
+ render(<ChallengeTitle {...baseProps} isCompleted={true} />);
38
+
39
+ expect(screen.getByTestId('green-pass')).toBeInTheDocument();
40
+ });
41
+
42
+ it('renders the translation link when translation is pending', () => {
43
+ render(<ChallengeTitle {...baseProps} translationPending={true} />);
44
+
45
+ expect(
46
+ screen.getByRole('link', { name: 'Help us translate' })
47
+ ).toHaveAttribute('href', 'https://example.com/help-translate');
48
+ });
49
+
50
+ it('does not render the translation link when translation is not pending', () => {
51
+ render(<ChallengeTitle {...baseProps} />);
52
+
53
+ expect(
54
+ screen.queryByRole('link', { name: 'Help us translate' })
55
+ ).not.toBeInTheDocument();
56
+ });
57
+ });
github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/challenge-title.tsx ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import i18next from 'i18next';
2
+ import React from 'react';
3
+ import GreenPass from '../../../assets/icons/green-pass';
4
+ import { Link } from '../../../components/helpers/index';
5
+
6
+ import './challenge-title.css';
7
+
8
+ interface ChallengeTitleProps {
9
+ children: string;
10
+ isCompleted: boolean;
11
+ translationPending?: boolean;
12
+ }
13
+
14
+ function ChallengeTitle({
15
+ children,
16
+ isCompleted,
17
+ translationPending
18
+ }: ChallengeTitleProps): JSX.Element {
19
+ return (
20
+ <div className='challenge-title-wrap'>
21
+ {translationPending && (
22
+ <Link
23
+ className='title-translation-cta'
24
+ to={i18next.t('links:help-translate-link-url')}
25
+ >
26
+ {i18next.t('misc.translation-pending')}
27
+ </Link>
28
+ )}
29
+ <div className='challenge-title'>
30
+ <h1 id='content-start' data-playwright-test-label='challenge-title'>
31
+ {children}
32
+ </h1>
33
+ {isCompleted && <GreenPass />}
34
+ </div>
35
+ </div>
36
+ );
37
+ }
38
+
39
+ ChallengeTitle.displayName = 'ChallengeTitle';
40
+
41
+ export default ChallengeTitle;
github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/challenge-transcript.css ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .challenge-transcript-heading {
2
+ cursor: pointer;
3
+ font-weight: bold;
4
+ margin-top: 1.5em;
5
+ }
6
+
7
+ .challenge-transcript .transcript-dialogue {
8
+ border: 1px solid var(--secondary-color);
9
+ }
10
+
11
+ .challenge-transcript .transcript-dialogue p {
12
+ margin: 0;
13
+ padding: 6px 13px;
14
+ text-align: start;
15
+ }
16
+
17
+ .challenge-transcript .transcript-dialogue p:nth-child(odd) {
18
+ background-color: var(--tertiary-background);
19
+ }
github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/challenge-transcript.test.tsx ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React from 'react';
2
+ import { render, screen, fireEvent } from '@testing-library/react';
3
+ import store from 'store';
4
+ import { describe, it, expect, vi, afterEach } from 'vitest';
5
+ import ChallengeTranscript from './challenge-transcript';
6
+
7
+ const baseProps = {
8
+ transcript: 'Sample transcript text',
9
+ shouldPersistExpanded: false
10
+ };
11
+
12
+ describe('<ChallengeTranscript />', () => {
13
+ afterEach(() => {
14
+ store.clearAll();
15
+ });
16
+
17
+ it('renders the transcript heading', () => {
18
+ render(<ChallengeTranscript {...baseProps} />);
19
+ expect(screen.getByText('learn.transcript')).toBeVisible();
20
+ });
21
+
22
+ it('renders collapsed by default', () => {
23
+ render(<ChallengeTranscript {...baseProps} />);
24
+ expect(screen.getByTestId('challenge-transcript')).not.toHaveAttribute(
25
+ 'open'
26
+ );
27
+ expect(screen.getByText('Sample transcript text')).not.toBeVisible();
28
+ });
29
+
30
+ it("renders collapsed when localstorage 'fcc-transcript-expanded = false'", () => {
31
+ store.set('fcc-transcript-expanded', false);
32
+ render(<ChallengeTranscript {...baseProps} />);
33
+ expect(screen.getByTestId('challenge-transcript')).not.toHaveAttribute(
34
+ 'open'
35
+ );
36
+ expect(screen.getByText('Sample transcript text')).not.toBeVisible();
37
+ });
38
+
39
+ it("renders expanded when 'fcc-transcript-expanded = true' and shouldPersistExpanded = true", () => {
40
+ store.set('fcc-transcript-expanded', true);
41
+ render(<ChallengeTranscript {...baseProps} shouldPersistExpanded={true} />);
42
+ expect(screen.getByTestId('challenge-transcript')).toHaveAttribute('open');
43
+ expect(screen.getByText('Sample transcript text')).toBeVisible();
44
+ });
45
+
46
+ it('writes to localstorage when shouldPersistExpanded = true', () => {
47
+ const setSpy = vi.spyOn(store, 'set');
48
+ render(<ChallengeTranscript {...baseProps} shouldPersistExpanded={true} />);
49
+ fireEvent.click(screen.getByText('learn.transcript'));
50
+ expect(setSpy).toHaveBeenCalledWith('fcc-transcript-expanded', true);
51
+ setSpy.mockRestore();
52
+ });
53
+
54
+ it('does not write to localstorage when shouldPersistExpanded = false', () => {
55
+ const setSpy = vi.spyOn(store, 'set');
56
+ render(<ChallengeTranscript {...baseProps} />);
57
+ fireEvent.click(screen.getByText('learn.transcript'));
58
+ expect(setSpy).not.toHaveBeenCalled();
59
+ setSpy.mockRestore();
60
+ });
61
+
62
+ it('should render the transcript as paragraphs when isDialogue is true', () => {
63
+ store.set('fcc-transcript-expanded', true);
64
+
65
+ render(
66
+ <ChallengeTranscript
67
+ {...baseProps}
68
+ transcript={'<p><b>Alice</b>: Hello</p><p><b>Bob</b>: World</p>'}
69
+ shouldPersistExpanded={true}
70
+ isDialogue={true}
71
+ />
72
+ );
73
+
74
+ /* eslint-disable testing-library/no-node-access */
75
+ const aliceB = screen.getByText('Alice');
76
+ expect(aliceB).toBeVisible();
77
+ expect(aliceB.tagName).toBe('B');
78
+
79
+ const aliceP = aliceB.parentElement;
80
+ expect(aliceP?.tagName).toBe('P');
81
+ expect(aliceP?.textContent).toBe('Alice: Hello');
82
+
83
+ const bobB = screen.getByText('Bob');
84
+ expect(bobB).toBeVisible();
85
+ expect(bobB.tagName).toBe('B');
86
+
87
+ const bobP = bobB.parentElement;
88
+ expect(bobP?.tagName).toBe('P');
89
+ expect(bobP?.textContent).toBe('Bob: World');
90
+ /* eslint-enable testing-library/no-node-access */
91
+ });
92
+
93
+ it('should render the transcript with PrismFormatted when isDialogue is false', () => {
94
+ store.set('fcc-transcript-expanded', true);
95
+
96
+ render(
97
+ <ChallengeTranscript
98
+ {...baseProps}
99
+ transcript='<pre><code class="language-js">console.log("hi")</code></pre>'
100
+ shouldPersistExpanded={true}
101
+ isDialogue={false}
102
+ />
103
+ );
104
+
105
+ const preElement = screen.getByRole('region');
106
+ expect(preElement).toBeVisible();
107
+ expect(preElement.tagName).toBe('PRE');
108
+
109
+ // eslint-disable-next-line testing-library/no-node-access
110
+ const codeElement = preElement.querySelector('code');
111
+ expect(codeElement).toBeInTheDocument();
112
+ expect(preElement).toHaveTextContent('console.log("hi")');
113
+ });
114
+ });
github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/challenge-transcript.tsx ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useState } from 'react';
2
+ import { useTranslation } from 'react-i18next';
3
+ import { Spacer } from '@freecodecamp/ui';
4
+ import store from 'store';
5
+
6
+ import PrismFormatted from './prism-formatted';
7
+ import { getChallengeContentLangProps } from '../../../utils/challenge-content-lang';
8
+ import './challenge-transcript.css';
9
+
10
+ interface ChallengeTranscriptProps {
11
+ transcript: string;
12
+ shouldPersistExpanded?: boolean;
13
+ isDialogue?: boolean;
14
+ superBlock?: string;
15
+ }
16
+
17
+ function ChallengeTranscript({
18
+ transcript,
19
+ shouldPersistExpanded,
20
+ isDialogue,
21
+ superBlock
22
+ }: ChallengeTranscriptProps): JSX.Element {
23
+ const { t } = useTranslation();
24
+
25
+ // default to collapsed
26
+ const [isOpen, setIsOpen] = useState(() =>
27
+ shouldPersistExpanded
28
+ ? ((store.get('fcc-transcript-expanded') as boolean | null) ?? false)
29
+ : false
30
+ );
31
+
32
+ function toggleExpandedState(e: React.MouseEvent<HTMLDetailsElement>) {
33
+ e.preventDefault();
34
+ if (shouldPersistExpanded) {
35
+ store.set('fcc-transcript-expanded', !isOpen);
36
+ }
37
+ setIsOpen(!isOpen);
38
+ }
39
+
40
+ return (
41
+ <>
42
+ <details
43
+ data-testid='challenge-transcript'
44
+ className='challenge-transcript'
45
+ open={isOpen}
46
+ >
47
+ <summary
48
+ onClick={toggleExpandedState}
49
+ aria-expanded={isOpen}
50
+ className='challenge-transcript-heading'
51
+ >
52
+ {t('learn.transcript')}
53
+ </summary>
54
+ <Spacer size='m' />
55
+ {isDialogue ? (
56
+ <div
57
+ className='transcript-dialogue'
58
+ dangerouslySetInnerHTML={{ __html: transcript }}
59
+ {...getChallengeContentLangProps(superBlock)}
60
+ />
61
+ ) : (
62
+ <PrismFormatted
63
+ className='line-numbers'
64
+ text={transcript}
65
+ {...getChallengeContentLangProps(superBlock)}
66
+ />
67
+ )}
68
+ </details>
69
+ <Spacer size='m' />
70
+ </>
71
+ );
72
+ }
73
+
74
+ ChallengeTranscript.displayName = 'ChallengeTranscript';
75
+
76
+ export default ChallengeTranscript;
github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/completion-modal.css ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .completion-success-icon {
2
+ width: 200px;
3
+ height: 200px;
4
+ transform: scale(1.5);
5
+ opacity: 0;
6
+ animation: success-icon-animation 150ms linear 100ms forwards;
7
+ }
8
+
9
+ @keyframes success-icon-animation {
10
+ 100% {
11
+ opacity: 1;
12
+ transform: scale(1);
13
+ }
14
+ }
15
+
16
+ .completion-block-details {
17
+ display: flex;
18
+ flex-direction: column;
19
+ align-items: center;
20
+ align-self: center;
21
+ justify-content: space-between;
22
+ width: 100%;
23
+ gap: 0.5rem;
24
+ }
25
+
26
+ .completion-block-name {
27
+ font-weight: 700;
28
+ font-size: 1rem;
29
+ margin-bottom: 4px;
30
+ }
31
+
32
+ .completion-block-meta {
33
+ color: var(--quaternary-color);
34
+ font-size: 0.8rem;
35
+ margin-top: 5px;
36
+ }
37
+
38
+ .completion-block-details .completion-block-name {
39
+ font-size: 1.2rem;
40
+ }
41
+
42
+ .completion-block-details .completion-block-meta {
43
+ font-size: 1rem;
44
+ }
45
+
46
+ .progress-bar-wrap {
47
+ width: 100%;
48
+ position: relative;
49
+ border: 1px solid var(--quaternary-color);
50
+ }
51
+
52
+ .progress-header {
53
+ display: flex;
54
+ flex-direction: row;
55
+ justify-content: space-between;
56
+ width: 100%;
57
+ font-size: 0.9rem;
58
+ }
59
+
60
+ .progress-bar-background {
61
+ width: 100%;
62
+ height: 10px;
63
+ color: var(--primary-color);
64
+ background-color: var(--quaternary-background);
65
+ display: flex;
66
+ align-items: center;
67
+ justify-content: center;
68
+ position: absolute;
69
+
70
+ top: 0;
71
+ left: 0;
72
+ }
73
+
74
+ .progress-bar-percent {
75
+ height: 10px;
76
+ overflow: hidden;
77
+ position: relative;
78
+ background-color: var(--primary-color);
79
+ transition: width 0ms linear;
80
+ }
81
+
82
+ /* The maximum width of login button is 500px, which is set in global.css.
83
+ An override is needed as 500px is not enough to allow the button to span the modal width. */
84
+ .completion-modal-login-btn .signup-btn {
85
+ max-width: 100%;
86
+ }
87
+
88
+ .completion-modal-body {
89
+ display: flex;
90
+ flex-direction: column;
91
+ align-items: center;
92
+ }
93
+
94
+ @media screen and (max-width: 991px) {
95
+ .progress-bar-wrap,
96
+ .progress-bar-background {
97
+ height: 10px;
98
+ }
99
+
100
+ .completion-success-icon {
101
+ width: 160px;
102
+ height: 160px;
103
+ }
104
+
105
+ .completion-message {
106
+ font-weight: 600;
107
+ font-size: 1.2rem;
108
+ }
109
+
110
+ .completion-block-name {
111
+ font-size: 1rem;
112
+ }
113
+ }
github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/completion-modal.test.tsx ADDED
@@ -0,0 +1,390 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React from 'react';
2
+ import type { TFunction } from 'i18next';
3
+ import { runSaga } from 'redux-saga';
4
+ import { describe, test, it, expect, beforeEach, vi, type Mock } from 'vitest';
5
+ import { fireEvent, render, screen } from '../../../../utils/test-utils';
6
+
7
+ import { getCompletedPercentage } from '../../../utils/get-completion-percentage';
8
+ import { fireConfetti } from '../../../utils/fire-confetti';
9
+ import { createStore } from '../../../redux/create-store';
10
+ import { executeChallengeSaga } from '../redux/execute-challenge-saga';
11
+ import {
12
+ challengeDataSelector,
13
+ challengeMetaSelector,
14
+ challengeTestsSelector,
15
+ isBuildEnabledSelector,
16
+ isBlockNewlyCompletedSelector,
17
+ currentBlockIdsSelector
18
+ } from '../redux/selectors';
19
+ import { completedChallengesIdsSelector } from '../../../redux/selectors';
20
+ import { curriculumData } from '../../../services/curriculum-data';
21
+ import { getTestRunner } from '../utils/build';
22
+ import ConnectedCompletionModal, {
23
+ combineFileData,
24
+ CompletionModal
25
+ } from './completion-modal';
26
+ import { mockCurriculumData } from '../utils/__fixtures__/curriculum-data';
27
+ import { useStaticQuery } from 'gatsby';
28
+ import { ChallengeNode, SuperBlockStructure } from '../../../redux/prop-types';
29
+ vi.mock('../../../analytics');
30
+ vi.mock('../../../utils/fire-confetti');
31
+ vi.mock('../../../components/Progress', () => ({
32
+ default: () => <div data-testid='progress-bar-container' />
33
+ }));
34
+ vi.mock('../../../components/Header/components/login', () => ({
35
+ default: ({ children }: { children?: React.ReactNode }) => (
36
+ <a href='/learn'>{children}</a>
37
+ )
38
+ }));
39
+ vi.mock('../redux/selectors');
40
+ vi.mock('../../../redux/selectors');
41
+ vi.mock('../utils/build');
42
+ const mockSubmitChallenge = vi.hoisted(() => vi.fn());
43
+ vi.mock('../utils/fetch-all-curriculum-data', () => ({
44
+ useSubmit: () => mockSubmitChallenge
45
+ }));
46
+ vi.mock('../../../utils/get-words');
47
+ vi.mock('@freecodecamp/challenge-builder/build');
48
+ const mockFireConfetti = fireConfetti as Mock;
49
+ const mockTestRunner = vi.fn().mockReturnValue({ pass: true });
50
+ const mockBuildEnabledSelector = isBuildEnabledSelector as Mock;
51
+ const mockChallengeTestsSelector = challengeTestsSelector as Mock;
52
+ const mockChallengeMetaSelector = challengeMetaSelector as Mock;
53
+ const mockChallengeDataSelector = challengeDataSelector as Mock;
54
+ const mockIsBlockNewlyCompletedSelector = isBlockNewlyCompletedSelector as Mock;
55
+ const mockCurrentBlockIdsSelector = vi.mocked(currentBlockIdsSelector);
56
+ const mockCompletedChallengesIdsSelector =
57
+ completedChallengesIdsSelector as unknown as Mock;
58
+ const mockGetTestRunner = getTestRunner as Mock;
59
+ mockBuildEnabledSelector.mockReturnValue(true);
60
+ mockChallengeTestsSelector.mockReturnValue([
61
+ { text: 'Test 1', testString: 'mock test code' }
62
+ ]);
63
+ mockChallengeMetaSelector.mockReturnValue({
64
+ challengeType: 'mock_challenge_type'
65
+ });
66
+ mockChallengeDataSelector.mockReturnValue({
67
+ challengeFiles: ['mock_challenge_files']
68
+ });
69
+ mockGetTestRunner.mockReturnValue(mockTestRunner);
70
+
71
+ const completedChallengesIds = ['1', '3', '5'];
72
+ const currentBlockIds = ['1', '3', '5', '7'];
73
+ const id = '7';
74
+ const fakeCompletedChallengesIds = ['1', '3', '5', '7', '8'];
75
+ const t = ((key: string) => key) as TFunction;
76
+
77
+ function renderCompletionModal(
78
+ props: Partial<React.ComponentProps<typeof CompletionModal>> = {}
79
+ ) {
80
+ return render(
81
+ <CompletionModal
82
+ challengeFiles={[]}
83
+ close={vi.fn()}
84
+ completedChallengesIds={[]}
85
+ dashedName='mock-challenge'
86
+ id='mock-id'
87
+ isOpen={true}
88
+ isSignedIn={true}
89
+ isSubmitting={false}
90
+ message='Great job'
91
+ t={t}
92
+ {...props}
93
+ />,
94
+ createStore()
95
+ );
96
+ }
97
+
98
+ describe('<CompletionModal />', () => {
99
+ beforeEach(() => {
100
+ mockSubmitChallenge.mockClear();
101
+ vi.stubGlobal(
102
+ 'ResizeObserver',
103
+ class ResizeObserver {
104
+ observe = vi.fn();
105
+ unobserve = vi.fn();
106
+ disconnect = vi.fn();
107
+ }
108
+ );
109
+ vi.spyOn(window.navigator, 'userAgent', 'get').mockReturnValue('Linux');
110
+ Object.defineProperty(window, 'innerWidth', {
111
+ configurable: true,
112
+ value: 1200
113
+ });
114
+ vi.mocked(useStaticQuery).mockReturnValue(mockCurriculumData);
115
+ // Initialize curriculum data singleton for tests
116
+ const structuresMap: Record<string, SuperBlockStructure> = {};
117
+ mockCurriculumData.allSuperBlockStructure.nodes.forEach(node => {
118
+ structuresMap[node.superBlock] = node as SuperBlockStructure;
119
+ });
120
+ curriculumData.initialize({
121
+ challengeNodes: mockCurriculumData.allChallengeNode
122
+ .nodes as unknown as ChallengeNode[],
123
+ certificateNodes: mockCurriculumData.allCertificateNode.nodes,
124
+ superBlockStructures: structuresMap
125
+ });
126
+ });
127
+
128
+ describe('rendering', () => {
129
+ it('renders the signed-out completion state', () => {
130
+ renderCompletionModal({ isSignedIn: false });
131
+
132
+ expect(
133
+ screen.getByRole('heading', { name: 'Great job' })
134
+ ).toBeInTheDocument();
135
+ expect(screen.getByRole('button', { name: 'Close' })).toBeInTheDocument();
136
+ expect(
137
+ screen.getByTestId('fcc-completion-success-icon')
138
+ ).toBeInTheDocument();
139
+ expect(screen.getByTestId('progress-bar-container')).toBeInTheDocument();
140
+ expect(
141
+ screen.getByRole('link', { name: 'learn.sign-in-save' })
142
+ ).toHaveAttribute('href', '/learn');
143
+ expect(
144
+ screen.getByRole('button', { name: 'buttons.go-to-next-ctrl' })
145
+ ).toBeInTheDocument();
146
+ });
147
+
148
+ it('renders the signed-in completion state', () => {
149
+ renderCompletionModal();
150
+
151
+ expect(
152
+ screen.queryByRole('link', { name: 'learn.sign-in-save' })
153
+ ).not.toBeInTheDocument();
154
+ expect(
155
+ screen.getByRole('button', { name: 'buttons.submit-and-go-ctrl' })
156
+ ).toBeInTheDocument();
157
+ });
158
+
159
+ it('uses mobile button text when signed out on small screens', () => {
160
+ Object.defineProperty(window, 'innerWidth', {
161
+ configurable: true,
162
+ value: 320
163
+ });
164
+
165
+ renderCompletionModal({ isSignedIn: false });
166
+
167
+ expect(
168
+ screen.getByRole('button', { name: 'buttons.go-to-next' })
169
+ ).toBeInTheDocument();
170
+ });
171
+
172
+ it('uses Command button text on macOS desktops', () => {
173
+ vi.spyOn(window.navigator, 'userAgent', 'get').mockReturnValue('Mac OS');
174
+
175
+ renderCompletionModal();
176
+
177
+ expect(
178
+ screen.getByRole('button', { name: 'buttons.submit-and-go-cmd' })
179
+ ).toBeInTheDocument();
180
+ });
181
+
182
+ it('uses mobile button text on small screens', () => {
183
+ Object.defineProperty(window, 'innerWidth', {
184
+ configurable: true,
185
+ value: 320
186
+ });
187
+
188
+ renderCompletionModal();
189
+
190
+ expect(
191
+ screen.getByRole('button', { name: 'buttons.submit-and-go' })
192
+ ).toBeInTheDocument();
193
+ });
194
+
195
+ it('closes when the close button is clicked', () => {
196
+ const close = vi.fn();
197
+ renderCompletionModal({ close });
198
+
199
+ fireEvent.click(screen.getByRole('button', { name: 'Close' }));
200
+
201
+ expect(close).toHaveBeenCalled();
202
+ });
203
+
204
+ it('submits when the submit button is clicked', () => {
205
+ renderCompletionModal();
206
+
207
+ fireEvent.click(
208
+ screen.getByRole('button', { name: 'buttons.submit-and-go-ctrl' })
209
+ );
210
+
211
+ expect(mockSubmitChallenge).toHaveBeenCalled();
212
+ });
213
+
214
+ it('submits when the keyboard shortcut is pressed', () => {
215
+ renderCompletionModal();
216
+
217
+ fireEvent.keyDown(screen.getByRole('dialog'), {
218
+ ctrlKey: true,
219
+ key: 'Enter'
220
+ });
221
+
222
+ expect(mockSubmitChallenge).toHaveBeenCalled();
223
+ });
224
+ });
225
+
226
+ describe('fireConfetti', () => {
227
+ beforeEach(() => {
228
+ mockFireConfetti.mockClear();
229
+ });
230
+ test('should fire when block is completed and challenge data exists', async () => {
231
+ const payload = { showCompletionModal: true };
232
+ const challengeId = 'bd7158d8c442eddfaeb5bd18';
233
+ const blockIds = ['step1', 'step2', 'step3', challengeId];
234
+ const store = createStore({
235
+ challenge: {
236
+ modal: { completion: true },
237
+ challengeMeta: {
238
+ id: challengeId,
239
+ certification: 'responsive-web-design'
240
+ }
241
+ }
242
+ });
243
+ mockIsBlockNewlyCompletedSelector.mockReturnValue(true);
244
+ mockChallengeMetaSelector.mockReturnValue({
245
+ id: challengeId,
246
+ isLastChallengeInBlock: true,
247
+ challengeType: 'mock_challenge_type'
248
+ });
249
+ mockCurrentBlockIdsSelector.mockReturnValue(blockIds);
250
+ mockCompletedChallengesIdsSelector.mockReturnValue(['step1', 'step2']);
251
+ // Curriculum data is initialized in beforeEach
252
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
253
+ // @ts-ignore
254
+ await runSaga(store, executeChallengeSaga, { payload }).done;
255
+ expect(mockFireConfetti).toHaveBeenCalledTimes(1);
256
+ });
257
+ test('should not fire when challenge data is empty (saga guard)', async () => {
258
+ const payload = { showCompletionModal: true };
259
+ const challengeId = 'bd7158d8c442eddfaeb5bd18';
260
+ const store = createStore({
261
+ challenge: {
262
+ modal: { completion: true },
263
+ challengeMeta: {
264
+ id: challengeId,
265
+ certification: 'responsive-web-design'
266
+ }
267
+ }
268
+ });
269
+ mockIsBlockNewlyCompletedSelector.mockReturnValue(true);
270
+ mockChallengeMetaSelector.mockReturnValue({
271
+ id: challengeId,
272
+ isLastChallengeInBlock: true,
273
+ challengeType: 'mock_challenge_type'
274
+ });
275
+ // Reset curriculum data to empty state to test the guard
276
+ curriculumData.initialize({
277
+ certificateNodes: [],
278
+ challengeNodes: [],
279
+ superBlockStructures: {}
280
+ });
281
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
282
+ // @ts-ignore
283
+ await runSaga(store, executeChallengeSaga, { payload }).done;
284
+ expect(mockFireConfetti).toHaveBeenCalledTimes(0);
285
+ });
286
+ test('should not fire when block is not completed', async () => {
287
+ const payload = { showCompletionModal: true };
288
+ const store = createStore({
289
+ challenge: {
290
+ modal: { completion: true },
291
+ challengeMeta: {
292
+ id: 'bd7158d8c442eddfaeb5bd18',
293
+ certification: 'responsive-web-design' // Make sure the certification matches
294
+ }
295
+ }
296
+ });
297
+ mockIsBlockNewlyCompletedSelector.mockReturnValue(false);
298
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
299
+ // @ts-ignore
300
+ await runSaga(store, executeChallengeSaga, { payload }).done;
301
+ expect(mockFireConfetti).toHaveBeenCalledTimes(0);
302
+ });
303
+ test('should not fire if certification project has been completed', () => {
304
+ const store = createStore({
305
+ challenge: {
306
+ modal: { completion: true },
307
+ challengeMeta: {
308
+ // Build a Tribute Page's id:
309
+ id: 'bd7158d8c442eddfaeb5bd18'
310
+ }
311
+ }
312
+ });
313
+ render(<ConnectedCompletionModal />, store);
314
+
315
+ expect(mockFireConfetti).toHaveBeenCalledTimes(0);
316
+ });
317
+ test('should NOT fire if the challenge is not a project', () => {
318
+ const store = createStore({
319
+ challenge: {
320
+ modal: { completion: true },
321
+ challengeMeta: {
322
+ // id from learn-advanced-array-methods-by-building-a-statistics-calculator:
323
+ id: '6352e79d15aae30fac58f48e'
324
+ }
325
+ }
326
+ });
327
+
328
+ render(<ConnectedCompletionModal />, store);
329
+
330
+ expect(mockFireConfetti).toHaveBeenCalledTimes(0);
331
+ });
332
+ });
333
+
334
+ describe('getCompletedPercentage', () => {
335
+ it('returns 25 if one out of four challenges are complete', () => {
336
+ expect(
337
+ getCompletedPercentage([], currentBlockIds, currentBlockIds[1])
338
+ ).toBe(25);
339
+ });
340
+
341
+ it('returns 75 if three out of four challenges are complete', () => {
342
+ expect(
343
+ getCompletedPercentage(
344
+ completedChallengesIds,
345
+ currentBlockIds,
346
+ completedChallengesIds[0]
347
+ )
348
+ ).toBe(75);
349
+ });
350
+
351
+ it('returns 100 if all challenges have been completed', () => {
352
+ expect(
353
+ getCompletedPercentage(completedChallengesIds, currentBlockIds, id)
354
+ ).toBe(100);
355
+ });
356
+
357
+ it('returns 100 if more challenges have been complete than exist', () => {
358
+ expect(
359
+ getCompletedPercentage(fakeCompletedChallengesIds, currentBlockIds, id)
360
+ ).toBe(100);
361
+ });
362
+ });
363
+
364
+ describe('File Download Content', () => {
365
+ it('Should label each section appropriately', () => {
366
+ const indexHtml = {
367
+ name: 'index',
368
+ ext: 'html',
369
+ contents: 'some html elements'
370
+ };
371
+ const stylesCSS = {
372
+ name: 'styles',
373
+ ext: 'css',
374
+ contents: 'some css styles'
375
+ };
376
+ const scriptJS = {
377
+ name: 'script',
378
+ ext: 'js',
379
+ contents: 'some javascript'
380
+ };
381
+ const result = combineFileData([indexHtml, stylesCSS, scriptJS]);
382
+ expect(result).toContain('** start of index.html **');
383
+ expect(result).toContain('** end of index.html **');
384
+ expect(result).toContain('** start of styles.css **');
385
+ expect(result).toContain('** end of styles.css **');
386
+ expect(result).toContain('** start of script.js **');
387
+ expect(result).toContain('** end of script.js **');
388
+ });
389
+ });
390
+ });
github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/completion-modal.tsx ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useEffect, useCallback, useState } from 'react';
2
+ import type { TFunction } from 'i18next';
3
+ import { withTranslation } from 'react-i18next';
4
+ import { connect } from 'react-redux';
5
+ import { createSelector } from 'reselect';
6
+ import { Button, Modal, Spacer } from '@freecodecamp/ui';
7
+
8
+ import Login from '../../../components/Header/components/login';
9
+ import {
10
+ isSignedInSelector,
11
+ completedChallengesIdsSelector
12
+ } from '../../../redux/selectors';
13
+ import { ChallengeFiles } from '../../../redux/prop-types';
14
+ import { closeModal } from '../redux/actions';
15
+ import {
16
+ isCompletionModalOpenSelector,
17
+ successMessageSelector,
18
+ challengeFilesSelector,
19
+ challengeMetaSelector,
20
+ isSubmittingSelector
21
+ } from '../redux/selectors';
22
+ import Progress from '../../../components/Progress';
23
+ import GreenPass from '../../../assets/icons/green-pass';
24
+ import { MAX_MOBILE_WIDTH } from '../../../../config/misc';
25
+ import './completion-modal.css';
26
+ import callGA from '../../../analytics/call-ga';
27
+ import { useSubmit } from '../utils/fetch-all-curriculum-data';
28
+
29
+ const mapStateToProps = createSelector(
30
+ challengeFilesSelector,
31
+ challengeMetaSelector,
32
+ completedChallengesIdsSelector,
33
+ isCompletionModalOpenSelector,
34
+ isSignedInSelector,
35
+ successMessageSelector,
36
+ isSubmittingSelector,
37
+ (
38
+ challengeFiles: ChallengeFiles,
39
+ {
40
+ dashedName,
41
+ id
42
+ }: {
43
+ dashedName: string;
44
+ id: string;
45
+ },
46
+ completedChallengesIds: string[],
47
+ isOpen: boolean,
48
+ isSignedIn: boolean,
49
+ message: string,
50
+ isSubmitting: boolean
51
+ ) => ({
52
+ challengeFiles,
53
+ id,
54
+ dashedName,
55
+ completedChallengesIds,
56
+ isOpen,
57
+ isSignedIn,
58
+ message,
59
+ isSubmitting
60
+ })
61
+ );
62
+
63
+ const mapDispatchToProps = {
64
+ close: () => closeModal('completion')
65
+ };
66
+
67
+ type StateProps = ReturnType<typeof mapStateToProps>;
68
+
69
+ interface CompletionModalProps extends StateProps {
70
+ close: () => void;
71
+ t: TFunction;
72
+ }
73
+
74
+ interface DownloadableChallengeFile {
75
+ name: string;
76
+ ext: string;
77
+ contents: string;
78
+ }
79
+
80
+ export function CompletionModal({
81
+ challengeFiles,
82
+ close,
83
+ dashedName,
84
+ isOpen,
85
+ isSignedIn,
86
+ isSubmitting,
87
+ message,
88
+ t
89
+ }: CompletionModalProps): JSX.Element {
90
+ const [downloadURL, setDownloadURL] = useState<string>();
91
+ const submitChallenge = useSubmit();
92
+ // We can't useMemo here, because it does not guarantee that the URL object
93
+ // will be revoked when the dependencies change.
94
+ useEffect(() => {
95
+ // downloadURL is not in the dependency array because it should only change
96
+ // if the challengeFiles change. It is in the useEffect so that we cannot
97
+ // leak URL objects.
98
+ if (downloadURL) URL.revokeObjectURL(downloadURL);
99
+ if (challengeFiles?.length) {
100
+ const allFileContents = combineFileData(challengeFiles);
101
+ const blob = new Blob([allFileContents], { type: 'text/json' });
102
+ setDownloadURL(URL.createObjectURL(blob));
103
+ }
104
+ // eslint-disable-next-line react-hooks/exhaustive-deps
105
+ }, [challengeFiles]);
106
+
107
+ useEffect(() => {
108
+ return () => {
109
+ close();
110
+ };
111
+ }, [close]);
112
+
113
+ useEffect(() => {
114
+ if (isOpen) {
115
+ callGA({ event: 'pageview', pagePath: '/completion-modal' });
116
+ }
117
+ }, [isOpen]);
118
+
119
+ const handleKeypress = useCallback(
120
+ (e: React.KeyboardEvent) => {
121
+ if (e.key === 'Escape') {
122
+ e.stopPropagation();
123
+ close();
124
+ }
125
+ if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) {
126
+ e.preventDefault();
127
+ // Since Hotkeys also listens to Ctrl + Enter we have to stop this event
128
+ // getting to it.
129
+ e.stopPropagation();
130
+ submitChallenge();
131
+ }
132
+ },
133
+ [close, submitChallenge]
134
+ );
135
+
136
+ const isMacOS = navigator.userAgent.includes('Mac OS');
137
+
138
+ const isDesktop = window.innerWidth > MAX_MOBILE_WIDTH;
139
+
140
+ let buttonText;
141
+ if (isDesktop) {
142
+ if (isMacOS) {
143
+ buttonText = isSignedIn
144
+ ? t('buttons.submit-and-go-cmd')
145
+ : t('buttons.go-to-next-cmd');
146
+ } else {
147
+ buttonText = isSignedIn
148
+ ? t('buttons.submit-and-go-ctrl')
149
+ : t('buttons.go-to-next-ctrl');
150
+ }
151
+ } else {
152
+ buttonText = isSignedIn
153
+ ? t('buttons.submit-and-go')
154
+ : t('buttons.go-to-next');
155
+ }
156
+
157
+ return (
158
+ <Modal
159
+ onClose={close}
160
+ open={!!isOpen}
161
+ size='large'
162
+ onKeyDown={isOpen ? handleKeypress : undefined}
163
+ >
164
+ <Modal.Header closeButtonClassNames='close'>{message}</Modal.Header>
165
+ <Modal.Body className='completion-modal-body'>
166
+ <GreenPass
167
+ className='completion-success-icon'
168
+ data-testid='fcc-completion-success-icon'
169
+ data-playwright-test-label='completion-success-icon'
170
+ />
171
+ <div className='completion-block-details'>
172
+ <Progress />
173
+ </div>
174
+ </Modal.Body>
175
+ <Modal.Footer>
176
+ {isSignedIn ? null : (
177
+ <div className='completion-modal-login-btn'>
178
+ <Login block={true}>{t('learn.sign-in-save')}</Login>
179
+ <Spacer size='xxs' />
180
+ </div>
181
+ )}
182
+ <Button
183
+ block={true}
184
+ size='large'
185
+ variant='primary'
186
+ disabled={isSubmitting}
187
+ onClick={() => submitChallenge()}
188
+ >
189
+ {buttonText}
190
+ </Button>
191
+ <Spacer size='xxs' />
192
+ {downloadURL ? (
193
+ <Button
194
+ block={true}
195
+ size='large'
196
+ variant='primary'
197
+ download={`${dashedName}.txt`}
198
+ href={downloadURL}
199
+ >
200
+ {t('learn.download-solution')}
201
+ </Button>
202
+ ) : null}
203
+ </Modal.Footer>
204
+ </Modal>
205
+ );
206
+ }
207
+
208
+ CompletionModal.displayName = 'CompletionModal';
209
+
210
+ export default connect(
211
+ mapStateToProps,
212
+ mapDispatchToProps
213
+ )(withTranslation()(CompletionModal));
214
+
215
+ export function combineFileData(challengeFiles: DownloadableChallengeFile[]) {
216
+ return challengeFiles.reduce<string>(function (
217
+ allFiles: string,
218
+ currentFile: DownloadableChallengeFile
219
+ ) {
220
+ const beforeText = `** start of ${currentFile.name + '.' + currentFile.ext} **\n\n`;
221
+ const afterText = `\n\n** end of ${currentFile.name + '.' + currentFile.ext} **\n\n`;
222
+ allFiles +=
223
+ challengeFiles.length > 0
224
+ ? `${beforeText}${currentFile.contents}${afterText}`
225
+ : currentFile.contents;
226
+ return allFiles;
227
+ }, '');
228
+ }
github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/custom-monaco-editor.css ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ .monaco-editor-wrapper {
2
+ padding-block-start: 8px;
3
+ flex: 1;
4
+ }
5
+
6
+ .monaco-editor .line-numbers {
7
+ color: #858591 !important;
8
+ font-size: 12px;
9
+ }
github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/custom-monaco-editor.tsx ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React from 'react';
2
+ import Loadable from '@loadable/component';
3
+ import type * as monacoEditor from 'monaco-editor/esm/vs/editor/editor.api.js';
4
+ import { useActiveCode, useSandpack } from '@codesandbox/sandpack-react';
5
+ import './custom-monaco-editor.css';
6
+
7
+ const MonacoEditor = Loadable(() => import('react-monaco-editor'));
8
+
9
+ const CustomMonacoEditor = () => {
10
+ const { code, updateCode } = useActiveCode();
11
+ const { sandpack } = useSandpack();
12
+
13
+ const getLanguage = (filePath: string): string => {
14
+ const extension = filePath.split('.').pop();
15
+
16
+ switch (extension) {
17
+ case 'js':
18
+ case 'jsx':
19
+ return 'javascript';
20
+ case 'ts':
21
+ case 'tsx':
22
+ return 'typescript';
23
+ case 'html':
24
+ return 'html';
25
+ case 'css':
26
+ return 'css';
27
+ default:
28
+ return 'plaintext';
29
+ }
30
+ };
31
+ // theme
32
+ const FCC_DARK_CUSTOM: monacoEditor.editor.IStandaloneThemeData = {
33
+ base: 'vs-dark',
34
+ inherit: true,
35
+ rules: [
36
+ { token: 'comment', foreground: '858591', fontStyle: 'italic' },
37
+ { token: 'keyword', foreground: 'dbb8ff' },
38
+ { token: 'tag', foreground: 'f07178' },
39
+ { token: 'punctuation', foreground: '99c9ff' },
40
+ { token: 'definition', foreground: 'ffffff' },
41
+ { token: 'property', foreground: '99c9ff' },
42
+ { token: 'static', foreground: 'f78c6c' },
43
+ { token: 'string', foreground: 'acd157' },
44
+ { token: 'number', foreground: 'f78c6c' },
45
+ { token: 'variable', foreground: 'ffffff' },
46
+ { token: 'type', foreground: 'dbb8ff' },
47
+ { token: 'function', foreground: 'ffffff' },
48
+ { token: 'identifier', foreground: 'ffffff' },
49
+ { token: 'regexp', foreground: 'acd157' },
50
+ { token: 'delimiter', foreground: 'ffffff' },
51
+ { token: 'attribute.name', foreground: '99c9ff' },
52
+ { token: 'attribute.value', foreground: 'acd157' },
53
+ { token: 'annotation', foreground: 'dbb8ff' },
54
+ { token: 'constant', foreground: 'f78c6c' },
55
+ { token: 'class', foreground: 'dbb8ff' },
56
+ { token: 'interface', foreground: 'dbb9ff' },
57
+ { token: 'namespace', foreground: 'dbb8ff' },
58
+ { token: 'enum', foreground: 'dbb8ff' },
59
+ { token: 'operator', foreground: 'ffffff' }
60
+ ],
61
+ colors: {
62
+ 'editor.background': '#0a0a23', // surface1
63
+ 'editor.foreground': '#ffffff', // base (plain syntax)
64
+ 'editorCursor.foreground': '#ffffff',
65
+ 'editor.selectionBackground': '#3b3b4f',
66
+ 'editor.lineHighlightBackground': '#3b3b4f', // surface3
67
+ 'editorBracketMatch.border': '#dbb8ff'
68
+ }
69
+ };
70
+
71
+ const handleEditor = (monaco: typeof monacoEditor) => {
72
+ monaco.editor.defineTheme('fcc-dark', FCC_DARK_CUSTOM);
73
+ };
74
+
75
+ return (
76
+ <div className='monaco-editor-wrapper'>
77
+ <MonacoEditor
78
+ width='100%'
79
+ height='100%'
80
+ language={getLanguage(sandpack.activeFile)}
81
+ theme='fcc-dark'
82
+ editorWillMount={handleEditor}
83
+ key={sandpack.activeFile}
84
+ defaultValue={code}
85
+ onChange={value => {
86
+ updateCode(value || '');
87
+ }}
88
+ options={{
89
+ lineNumbersMinChars: 2,
90
+ minimap: { enabled: false },
91
+ scrollBeyondLastLine: false,
92
+ automaticLayout: true
93
+ }}
94
+ />
95
+ </div>
96
+ );
97
+ };
98
+
99
+ CustomMonacoEditor.displayname = 'CustomMonacoEditor';
100
+
101
+ export default CustomMonacoEditor;
github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/daily-challenge-bread-crumb.test.tsx ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React from 'react';
2
+ import { render, screen } from '@testing-library/react';
3
+ import { describe, expect, it, vi } from 'vitest';
4
+
5
+ import DailyChallengeBreadCrumb from './daily-challenge-bread-crumb';
6
+
7
+ vi.mock('i18next', () => ({
8
+ default: {
9
+ t: (key: string) => key
10
+ }
11
+ }));
12
+
13
+ describe('<DailyChallengeBreadCrumb />', () => {
14
+ it('renders nothing when there is no param', () => {
15
+ const { container } = render(<DailyChallengeBreadCrumb />);
16
+ expect(container).toBeEmptyDOMElement();
17
+ });
18
+
19
+ it('renders nothing for an invalid param', () => {
20
+ const { container } = render(
21
+ <DailyChallengeBreadCrumb dailyChallengeParam='not-a-date' />
22
+ );
23
+ expect(container).toBeEmptyDOMElement();
24
+ });
25
+
26
+ it('renders nothing for a shape-valid but semantically invalid month-day', () => {
27
+ const { container } = render(
28
+ <DailyChallengeBreadCrumb dailyChallengeParam='13-45' />
29
+ );
30
+ expect(container).toBeEmptyDOMElement();
31
+ });
32
+
33
+ it('shows only the month and day for a full "yyyy-MM-dd" date, with no year', () => {
34
+ render(<DailyChallengeBreadCrumb dailyChallengeParam='2026-07-15' />);
35
+
36
+ expect(
37
+ screen.getByRole('navigation', { name: 'aria.breadcrumb-nav' })
38
+ ).toBeInTheDocument();
39
+ expect(screen.getByText('July 15')).toBeInTheDocument();
40
+ expect(screen.queryByText('2026')).not.toBeInTheDocument();
41
+ });
42
+
43
+ it('shows only the month and day for a year-agnostic "MM-DD" param', () => {
44
+ render(<DailyChallengeBreadCrumb dailyChallengeParam='07-15' />);
45
+
46
+ expect(screen.getByText('July 15')).toBeInTheDocument();
47
+ });
48
+ });
github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/daily-challenge-bread-crumb.tsx ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import i18next from 'i18next';
2
+ import React from 'react';
3
+ import { useTranslation } from 'react-i18next';
4
+ import { Link } from '../../../components/helpers/index';
5
+
6
+ import './challenge-title.css';
7
+ import {
8
+ isValidDateOrMonthDayString,
9
+ formatDisplayDate
10
+ } from '../../../components/daily-coding-challenge/helpers';
11
+
12
+ function DailyChallengeBreadCrumb({
13
+ dailyChallengeParam
14
+ }: {
15
+ dailyChallengeParam?: string;
16
+ }): JSX.Element | null {
17
+ const { t } = useTranslation();
18
+
19
+ return dailyChallengeParam &&
20
+ isValidDateOrMonthDayString(dailyChallengeParam) ? (
21
+ <nav
22
+ className='challenge-title-breadcrumbs'
23
+ aria-label={t('aria.breadcrumb-nav')}
24
+ >
25
+ <ol data-playwright-test-label='breadcrumb-desktop'>
26
+ <li className='breadcrumb-left'>
27
+ <Link to={`/learn/daily-coding-challenge/archive`}>
28
+ <span>{i18next.t(`intro:daily-coding-challenge.title`)}</span>
29
+ </Link>
30
+ </li>
31
+ <li className='breadcrumb-right'>
32
+ <Link to={`/learn/daily-coding-challenge/archive`}>
33
+ {formatDisplayDate(dailyChallengeParam)}
34
+ </Link>
35
+ </li>
36
+ </ol>
37
+ </nav>
38
+ ) : null;
39
+ }
40
+
41
+ DailyChallengeBreadCrumb.displayName = 'DailyChallengeBreadCrumb';
42
+
43
+ export default DailyChallengeBreadCrumb;
github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/fill-in-the-blanks.test.tsx ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React from 'react';
2
+ import { render, screen } from '@testing-library/react';
3
+ import userEvent from '@testing-library/user-event';
4
+ import { describe, expect, it, vi } from 'vitest';
5
+
6
+ import type { FillInTheBlank } from '../../../redux/prop-types';
7
+ import FillInTheBlanks from './fill-in-the-blanks';
8
+
9
+ const fillInTheBlank = {
10
+ sentence: '<p>Is BLANK your book? No, BLANK is my book.</p>',
11
+ blanks: [
12
+ { answer: 'this', feedback: null, audioId: null },
13
+ {
14
+ answer: 'that',
15
+ feedback: '<p>Use <code>that</code> for something further away.</p>',
16
+ audioId: null
17
+ }
18
+ ]
19
+ } satisfies FillInTheBlank;
20
+
21
+ type FillInTheBlanksProps = React.ComponentProps<typeof FillInTheBlanks>;
22
+
23
+ const defaultProps = {
24
+ fillInTheBlank,
25
+ answersCorrect: [null, null],
26
+ showFeedback: false,
27
+ feedback: null,
28
+ showWrong: false,
29
+ handleInputChange: vi.fn()
30
+ } satisfies FillInTheBlanksProps;
31
+
32
+ function renderFillInTheBlanks(overrides: Partial<FillInTheBlanksProps> = {}) {
33
+ const props = { ...defaultProps, ...overrides };
34
+
35
+ render(<FillInTheBlanks {...props} />);
36
+ }
37
+
38
+ describe('<FillInTheBlanks />', () => {
39
+ it('marks incorrect blanks and shows feedback', () => {
40
+ renderFillInTheBlanks({
41
+ answersCorrect: [true, false],
42
+ showWrong: true,
43
+ showFeedback: true,
44
+ feedback: fillInTheBlank.blanks[1].feedback
45
+ });
46
+
47
+ expect(screen.getByText('learn.wrong-answer')).toBeInTheDocument();
48
+ expect(screen.getByText('this')).toHaveClass('correct-blank-answer');
49
+ expect(screen.getByText(/for something further away/)).toBeInTheDocument();
50
+
51
+ const blanks = screen.getAllByRole('textbox', {
52
+ name: 'learn.fill-in-the-blank.blank'
53
+ });
54
+ expect(blanks).toHaveLength(1);
55
+ expect(blanks[0]).toHaveAttribute('aria-invalid', 'true');
56
+ });
57
+
58
+ it('renders every blank as text when every answer is correct', () => {
59
+ renderFillInTheBlanks({
60
+ answersCorrect: [true, true]
61
+ });
62
+
63
+ expect(screen.queryByText('learn.wrong-answer')).not.toBeInTheDocument();
64
+ expect(
65
+ screen.queryByRole('textbox', {
66
+ name: 'learn.fill-in-the-blank.blank'
67
+ })
68
+ ).not.toBeInTheDocument();
69
+ expect(screen.getByText('this')).toHaveClass('correct-blank-answer');
70
+ expect(screen.getByText('that')).toHaveClass('correct-blank-answer');
71
+ });
72
+
73
+ it('calls the input change handler with the blank index and value', async () => {
74
+ const user = userEvent.setup();
75
+ const handleInputChange = vi.fn();
76
+ renderFillInTheBlanks({ handleInputChange });
77
+
78
+ await user.type(
79
+ screen.getAllByRole('textbox', {
80
+ name: 'learn.fill-in-the-blank.blank'
81
+ })[1],
82
+ 'that'
83
+ );
84
+
85
+ expect(handleInputChange).toHaveBeenLastCalledWith(1, 'that');
86
+ });
87
+ });
github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/fill-in-the-blanks.tsx ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React from 'react';
2
+ import { useTranslation } from 'react-i18next';
3
+ import { Spacer } from '@freecodecamp/ui';
4
+
5
+ import { parseBlanks, parseAnswer } from '../fill-in-the-blank/parse-blanks';
6
+ import PrismFormatted from '../components/prism-formatted';
7
+ import { getChallengeContentLangProps } from '../../../utils/challenge-content-lang';
8
+ import {
9
+ FillInTheBlankInputType,
10
+ FillInTheBlank
11
+ } from '../../../redux/prop-types';
12
+ import ChallengeHeading from './challenge-heading';
13
+ import PinyinToHanziInput from './pinyin-to-hanzi-input';
14
+ import PinyinToneInput from './pinyin-tone-input';
15
+
16
+ type FillInTheBlankProps = {
17
+ fillInTheBlank: FillInTheBlank;
18
+ inputType?: FillInTheBlankInputType;
19
+ answersCorrect: (boolean | null)[];
20
+ showFeedback: boolean;
21
+ feedback: string | null;
22
+ showWrong: boolean;
23
+ handleInputChange: (inputIndex: number, value: string) => void;
24
+ superBlock?: string;
25
+ };
26
+
27
+ const AnswerText = ({ answer }: { answer: string }) => {
28
+ const parsedAnswer = parseAnswer(answer);
29
+
30
+ if (typeof parsedAnswer === 'string') {
31
+ return <span className='correct-blank-answer'>{parsedAnswer}</span>;
32
+ }
33
+
34
+ return (
35
+ <ruby className='correct-blank-answer'>
36
+ {parsedAnswer.hanzi}
37
+ <rp>(</rp>
38
+ <rt>{parsedAnswer.pinyin}</rt>
39
+ <rp>)</rp>
40
+ </ruby>
41
+ );
42
+ };
43
+
44
+ type BlankInputProps = {
45
+ blankIndex: number;
46
+ answer: string;
47
+ isCorrect: boolean | null;
48
+ className: string;
49
+ onChange: (index: number, value: string) => void;
50
+ ariaLabel: string;
51
+ inputType?: 'pinyin-to-hanzi' | 'pinyin-tone';
52
+ };
53
+
54
+ const BlankInput = ({
55
+ blankIndex,
56
+ answer,
57
+ isCorrect,
58
+ className,
59
+ onChange,
60
+ ariaLabel,
61
+ inputType
62
+ }: BlankInputProps) => {
63
+ const parsedAnswer = parseAnswer(answer);
64
+ const answerLength =
65
+ typeof parsedAnswer === 'string'
66
+ ? parsedAnswer.length
67
+ : parsedAnswer.pinyin.length;
68
+
69
+ if (inputType === 'pinyin-to-hanzi' && typeof parsedAnswer === 'object') {
70
+ return (
71
+ <PinyinToHanziInput
72
+ index={blankIndex}
73
+ expectedAnswer={parsedAnswer}
74
+ isCorrect={isCorrect}
75
+ onChange={onChange}
76
+ className={className}
77
+ maxLength={answerLength + 3}
78
+ size={answerLength}
79
+ ariaLabel={ariaLabel}
80
+ />
81
+ );
82
+ } else if (inputType === 'pinyin-tone' && typeof parsedAnswer === 'string') {
83
+ return (
84
+ <PinyinToneInput
85
+ index={blankIndex}
86
+ isCorrect={isCorrect}
87
+ onChange={onChange}
88
+ className={className}
89
+ maxLength={answerLength + 3}
90
+ size={answerLength}
91
+ ariaLabel={ariaLabel}
92
+ />
93
+ );
94
+ }
95
+
96
+ // Default text input
97
+ return (
98
+ <input
99
+ type='text'
100
+ maxLength={answerLength + 3}
101
+ className={className}
102
+ onChange={e => onChange(blankIndex, e.target.value)}
103
+ size={answerLength}
104
+ autoComplete='off'
105
+ aria-label={ariaLabel}
106
+ {...(isCorrect === false ? { 'aria-invalid': 'true' } : {})}
107
+ />
108
+ );
109
+ };
110
+
111
+ function FillInTheBlanks({
112
+ fillInTheBlank: { sentence, blanks },
113
+ inputType,
114
+ answersCorrect,
115
+ showFeedback,
116
+ feedback,
117
+ showWrong,
118
+ handleInputChange,
119
+ superBlock
120
+ }: FillInTheBlankProps): JSX.Element {
121
+ const { t } = useTranslation();
122
+
123
+ const getInputClass = (index: number): string => {
124
+ let cls = 'fill-in-the-blank-input';
125
+
126
+ if (answersCorrect[index] === false) {
127
+ cls += ' incorrect-blank-answer';
128
+ }
129
+
130
+ return cls;
131
+ };
132
+
133
+ const paragraphs = parseBlanks(sentence);
134
+ const blankAnswers = blanks.map(b => b.answer);
135
+
136
+ const ariaInputDescription =
137
+ inputType === 'pinyin-to-hanzi'
138
+ ? t('aria.pinyin-to-hanzi-input-desc')
139
+ : inputType === 'pinyin-tone'
140
+ ? t('aria.pinyin-tone-input-desc')
141
+ : '';
142
+
143
+ return (
144
+ <>
145
+ <ChallengeHeading heading={t('learn.fill-in-the-blank.heading')} />
146
+ <Spacer size='xs' />
147
+ <p className='sr-only'>{ariaInputDescription}</p>
148
+ <div
149
+ className='fill-in-the-blank-wrap'
150
+ {...getChallengeContentLangProps(superBlock)}
151
+ >
152
+ {paragraphs.map((p, i) => (
153
+ // both keys, i and j, are stable between renders, since
154
+ // the paragraphs are static.
155
+ <p key={i}>
156
+ {p.map((node, j) => {
157
+ const { type, value } = node;
158
+
159
+ if (type === 'text') {
160
+ return value;
161
+ }
162
+
163
+ if (type === 'hanzi-pinyin') {
164
+ const { hanzi, pinyin } = value;
165
+ return (
166
+ <ruby key={j}>
167
+ {hanzi}
168
+ <rp>(</rp>
169
+ <rt>{pinyin}</rt>
170
+ <rp>)</rp>
171
+ </ruby>
172
+ );
173
+ }
174
+
175
+ // If a blank is answered correctly, render the answer as part of the sentence.
176
+ if (answersCorrect[value] === true) {
177
+ return <AnswerText key={j} answer={blankAnswers[value]} />;
178
+ }
179
+
180
+ return (
181
+ <BlankInput
182
+ key={j}
183
+ blankIndex={value}
184
+ answer={blankAnswers[value]}
185
+ isCorrect={answersCorrect[value]}
186
+ className={getInputClass(value)}
187
+ onChange={handleInputChange}
188
+ ariaLabel={t('learn.fill-in-the-blank.blank')}
189
+ inputType={inputType}
190
+ />
191
+ );
192
+ })}
193
+ </p>
194
+ ))}
195
+ </div>
196
+ <Spacer size='m' />
197
+ <div aria-live='polite'>
198
+ {showWrong && (
199
+ <div className='text-center'>
200
+ <span>{t('learn.wrong-answer')}</span>
201
+ <Spacer size='m' />
202
+ </div>
203
+ )}
204
+ {showFeedback && feedback && (
205
+ <PrismFormatted
206
+ text={feedback}
207
+ {...getChallengeContentLangProps(superBlock)}
208
+ />
209
+ )}
210
+ </div>
211
+ </>
212
+ );
213
+ }
214
+
215
+ FillInTheBlanks.displayName = 'FillInTheBlanks';
216
+
217
+ export default FillInTheBlanks;
github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/help-modal.css ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .help-form-legend {
2
+ color: var(--secondary-color);
3
+ border: 0;
4
+ font-size: 18px;
5
+ }
6
+
7
+ .checkbox-container {
8
+ display: flex;
9
+ width: 100%;
10
+ text-align: left;
11
+ }
12
+
13
+ .help-text-warning {
14
+ text-align: left;
15
+ }
github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/help-modal.test.tsx ADDED
@@ -0,0 +1,305 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React from 'react';
2
+ import { render, screen, within } from '@testing-library/react';
3
+ import userEvent from '@testing-library/user-event';
4
+ import { describe, it, expect, vi, beforeAll, afterEach } from 'vitest';
5
+ import i18n from '../../../../i18n/config-for-tests';
6
+ import translations from '../../../../i18n/locales/english/translations.json';
7
+ import { generateSearchLink, HelpModal } from './help-modal';
8
+
9
+ vi.unmock('react-i18next');
10
+
11
+ const validDescription =
12
+ 'Example text with enough characters to validate that the forum help form can be submitted.';
13
+
14
+ const createDefaultHelpModalProps = () => ({
15
+ closeHelpModal: vi.fn(),
16
+ createQuestion: vi.fn(),
17
+ isOpen: true,
18
+ challengeTitle: 'Write Your First C# Code',
19
+ challengeBlock: 'write-your-first-code-using-c-sharp',
20
+ superBlock: 'foundational-c-sharp-with-microsoft',
21
+ openVideoModal: vi.fn()
22
+ });
23
+
24
+ const renderHelpModal = (
25
+ props: Partial<React.ComponentProps<typeof HelpModal>> = {}
26
+ ) => {
27
+ const helpModalProps = {
28
+ ...createDefaultHelpModalProps(),
29
+ ...props
30
+ };
31
+
32
+ return {
33
+ ...render(<HelpModal {...helpModalProps} />),
34
+ helpModalProps
35
+ };
36
+ };
37
+
38
+ const openHelpForm = async () => {
39
+ await userEvent.click(
40
+ screen.getByRole('button', { name: translations.buttons['create-post'] })
41
+ );
42
+ };
43
+
44
+ const getDescriptionInput = () =>
45
+ screen.getByRole('textbox', {
46
+ name: /^Tell us what's happening:/
47
+ });
48
+
49
+ beforeAll(() => {
50
+ i18n.addResourceBundle('en', 'translations', translations, true, true);
51
+
52
+ type ResizeObserverMockInstance = {
53
+ observe: ResizeObserver['observe'];
54
+ unobserve: ResizeObserver['unobserve'];
55
+ disconnect: ResizeObserver['disconnect'];
56
+ };
57
+
58
+ Object.defineProperty(window, 'ResizeObserver', {
59
+ writable: true,
60
+ value: vi.fn(function (
61
+ this: ResizeObserverMockInstance,
62
+ _cb: ResizeObserverCallback
63
+ ) {
64
+ this.observe = vi.fn();
65
+ this.unobserve = vi.fn();
66
+ this.disconnect = vi.fn();
67
+ })
68
+ });
69
+ });
70
+
71
+ afterEach(() => {
72
+ vi.clearAllMocks();
73
+ });
74
+
75
+ describe('generateSearchLink', () => {
76
+ it("should return a link with search query containing block name and challenge title if the title includes 'step'", async () => {
77
+ await i18n.reloadResources('en', 'intro');
78
+ const link = generateSearchLink(
79
+ 'Step 10',
80
+ 'learn-basic-javascript-by-building-a-role-playing-game',
81
+ 'javascript-algorithms-and-data-structures-v8'
82
+ );
83
+
84
+ expect(link).toBe(
85
+ 'https://forum.freecodecamp.org/search?q=javascript-algorithms-and-data-structures-v8.blocks.learn-basic-javascript-by-building-a-role-playing-game.title%20-%20Step%2010%20in%3Atitle'
86
+ );
87
+ });
88
+
89
+ it("should return a link with search query containing block name and challenge title if the title includes 'task'", () => {
90
+ const link = generateSearchLink(
91
+ 'Task 10',
92
+ 'learn-greetings-in-your-first-day-at-the-office',
93
+ 'a2-english-for-developers'
94
+ );
95
+
96
+ expect(link).toBe(
97
+ 'https://forum.freecodecamp.org/search?q=a2-english-for-developers.blocks.learn-greetings-in-your-first-day-at-the-office.title%20-%20Task%2010%20in%3Atitle'
98
+ );
99
+ });
100
+
101
+ it("should return a link with search query containing only challenge title if the title does not include 'step' or 'task'", () => {
102
+ const link = generateSearchLink(
103
+ 'Perform Basic String Formatting in C#',
104
+ 'write-your-first-code-using-c-sharp',
105
+ 'foundational-c-sharp-with-microsoft'
106
+ );
107
+
108
+ expect(link).toBe(
109
+ 'https://forum.freecodecamp.org/search?q=foundational-c-sharp-with-microsoft.blocks.write-your-first-code-using-c-sharp.title%20-%20Perform%20Basic%20String%20Formatting%20in%20C%23%20in%3Atitle'
110
+ );
111
+ });
112
+ });
113
+
114
+ describe('<HelpModal />', () => {
115
+ it('renders the initial help options and warning copy', () => {
116
+ renderHelpModal();
117
+
118
+ const dialog = screen.getByRole('dialog', {
119
+ name: translations.buttons['get-help']
120
+ });
121
+
122
+ expect(dialog).toBeInTheDocument();
123
+ expect(
124
+ within(dialog).getByText(/If you've already tried the/)
125
+ ).toBeInTheDocument();
126
+ expect(
127
+ within(dialog).getByText(/Before making a new post/)
128
+ ).toBeInTheDocument();
129
+ expect(
130
+ within(dialog).getByRole('button', {
131
+ name: translations.buttons['create-post']
132
+ })
133
+ ).toBeInTheDocument();
134
+ expect(
135
+ within(dialog).getByRole('button', {
136
+ name: translations.buttons.cancel
137
+ })
138
+ ).toBeInTheDocument();
139
+ expect(
140
+ within(dialog).getByRole('button', {
141
+ name: translations.buttons.close
142
+ })
143
+ ).toBeInTheDocument();
144
+ });
145
+
146
+ it('renders a guide link and video button when video is available', async () => {
147
+ const { helpModalProps } = renderHelpModal({
148
+ guideUrl: 'https://forum.example.com/guide',
149
+ videoUrl: 'https://example.com/video'
150
+ });
151
+
152
+ const dialog = screen.getByRole('dialog', {
153
+ name: translations.buttons['get-help']
154
+ });
155
+
156
+ expect(
157
+ within(dialog).getByRole('link', {
158
+ name: translations.buttons['get-hint']
159
+ })
160
+ ).toHaveAttribute('href', 'https://forum.example.com/guide');
161
+
162
+ await userEvent.click(
163
+ within(dialog).getByRole('button', {
164
+ name: translations.buttons['watch-video']
165
+ })
166
+ );
167
+
168
+ expect(helpModalProps.openVideoModal).toHaveBeenCalledTimes(1);
169
+ expect(helpModalProps.closeHelpModal).toHaveBeenCalledTimes(1);
170
+ });
171
+
172
+ it('omits the video button when video is unavailable', () => {
173
+ renderHelpModal();
174
+
175
+ expect(
176
+ screen.queryByRole('button', {
177
+ name: translations.buttons['watch-video']
178
+ })
179
+ ).not.toBeInTheDocument();
180
+ });
181
+
182
+ it('closes from the cancel and header close buttons', async () => {
183
+ const { helpModalProps, unmount } = renderHelpModal();
184
+
185
+ await userEvent.click(
186
+ screen.getByRole('button', { name: translations.buttons.cancel })
187
+ );
188
+
189
+ expect(helpModalProps.closeHelpModal).toHaveBeenCalledTimes(1);
190
+
191
+ unmount();
192
+ const { helpModalProps: secondHelpModalProps } = renderHelpModal();
193
+
194
+ await userEvent.click(
195
+ screen.getByRole('button', { name: translations.buttons.close })
196
+ );
197
+
198
+ expect(secondHelpModalProps.closeHelpModal).toHaveBeenCalledTimes(1);
199
+ });
200
+
201
+ it('renders forum links with safe external-link attributes', () => {
202
+ renderHelpModal();
203
+
204
+ expect(
205
+ screen.getByRole('link', { name: 'Read-Search-Ask' })
206
+ ).toHaveAttribute('href', 'https://forum.freecodecamp.org/t/19514');
207
+ expect(
208
+ screen.getByRole('link', {
209
+ name: 'check if your question has already been answered on the forum'
210
+ })
211
+ ).toHaveAttribute(
212
+ 'href',
213
+ 'https://forum.freecodecamp.org/search?q=foundational-c-sharp-with-microsoft.blocks.write-your-first-code-using-c-sharp.title%20-%20Write%20Your%20First%20C%23%20Code%20in%3Atitle'
214
+ );
215
+
216
+ screen.getAllByRole('link').forEach(link => {
217
+ expect(link).toHaveAttribute('target', '_blank');
218
+ expect(link).toHaveAttribute('rel', 'noopener noreferrer');
219
+ });
220
+ });
221
+
222
+ it('keeps submit disabled until both confirmations are checked', async () => {
223
+ renderHelpModal();
224
+
225
+ await openHelpForm();
226
+
227
+ const rsaCheckbox = screen.getByRole('checkbox', {
228
+ name: translations.aria['rsa-checkbox']
229
+ });
230
+ const similarQuestionsCheckbox = screen.getByRole('checkbox', {
231
+ name: translations.aria['similar-questions-checkbox']
232
+ });
233
+ const descriptionInput = getDescriptionInput();
234
+ const submitButton = screen.getByRole('button', {
235
+ name: translations.buttons.submit
236
+ });
237
+
238
+ // paste is preferable since typing the whole description is slow (each
239
+ // keystroke triggers a re-render) and times the test out on loaded CI
240
+ // runners
241
+ await userEvent.click(descriptionInput);
242
+ await userEvent.paste(validDescription);
243
+
244
+ expect(submitButton).toHaveAttribute('aria-disabled', 'true');
245
+
246
+ await userEvent.click(rsaCheckbox);
247
+ expect(submitButton).toHaveAttribute('aria-disabled', 'true');
248
+
249
+ await userEvent.click(rsaCheckbox);
250
+ await userEvent.click(similarQuestionsCheckbox);
251
+ expect(submitButton).toHaveAttribute('aria-disabled', 'true');
252
+ });
253
+
254
+ it('keeps submit disabled when the description is too short', async () => {
255
+ renderHelpModal();
256
+
257
+ await openHelpForm();
258
+
259
+ await userEvent.click(
260
+ screen.getByRole('checkbox', {
261
+ name: translations.aria['rsa-checkbox']
262
+ })
263
+ );
264
+ await userEvent.click(
265
+ screen.getByRole('checkbox', {
266
+ name: translations.aria['similar-questions-checkbox']
267
+ })
268
+ );
269
+ await userEvent.type(getDescriptionInput(), 'Too short');
270
+
271
+ expect(
272
+ screen.getByRole('button', { name: translations.buttons.submit })
273
+ ).toHaveAttribute('aria-disabled', 'true');
274
+ });
275
+
276
+ it('submits a valid help request and closes the modal', async () => {
277
+ const { helpModalProps } = renderHelpModal();
278
+
279
+ await openHelpForm();
280
+
281
+ await userEvent.click(
282
+ screen.getByRole('checkbox', {
283
+ name: translations.aria['rsa-checkbox']
284
+ })
285
+ );
286
+ await userEvent.click(
287
+ screen.getByRole('checkbox', {
288
+ name: translations.aria['similar-questions-checkbox']
289
+ })
290
+ );
291
+ // paste is preferable since typing the whole description is slow (each
292
+ // keystroke triggers a re-render) and times the test out on loaded CI
293
+ // runners
294
+ await userEvent.click(getDescriptionInput());
295
+ await userEvent.paste(validDescription);
296
+ await userEvent.click(
297
+ screen.getByRole('button', { name: translations.buttons.submit })
298
+ );
299
+
300
+ expect(helpModalProps.createQuestion).toHaveBeenCalledWith(
301
+ validDescription
302
+ );
303
+ expect(helpModalProps.closeHelpModal).toHaveBeenCalledTimes(1);
304
+ });
305
+ });
github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/help-modal.tsx ADDED
@@ -0,0 +1,350 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useMemo, useState, useRef, useEffect } from 'react';
2
+ import { Trans, useTranslation } from 'react-i18next';
3
+ import { connect } from 'react-redux';
4
+ import { Dispatch, bindActionCreators } from 'redux';
5
+ import { Button, FormControl, Modal, Spacer } from '@freecodecamp/ui';
6
+
7
+ import { t } from 'i18next';
8
+ import envData from '../../../../config/env.json';
9
+ import { createQuestion, closeModal, openModal } from '../redux/actions';
10
+ import { isHelpModalOpenSelector } from '../redux/selectors';
11
+
12
+ import './help-modal.css';
13
+ import callGA from '../../../analytics/call-ga';
14
+
15
+ interface HelpModalProps {
16
+ closeHelpModal: () => void;
17
+ createQuestion: (description: string) => void;
18
+ isOpen?: boolean;
19
+ challengeTitle: string;
20
+ challengeBlock: string;
21
+ superBlock: string;
22
+ guideUrl?: string;
23
+ videoUrl?: string;
24
+ openVideoModal: () => void;
25
+ }
26
+
27
+ const { forumLocation } = envData;
28
+ const DESCRIPTION_MIN_CHARS = 50;
29
+ const DESCRIPTION_MAX_CHARS = 500;
30
+ const RSA = forumLocation + '/t/19514';
31
+
32
+ const mapStateToProps = (state: unknown) => ({
33
+ isOpen: isHelpModalOpenSelector(state) as boolean
34
+ });
35
+ const mapDispatchToProps = (dispatch: Dispatch) =>
36
+ bindActionCreators(
37
+ {
38
+ createQuestion,
39
+ closeHelpModal: () => closeModal('help'),
40
+ openVideoModal: () => openModal('video')
41
+ },
42
+ dispatch
43
+ );
44
+
45
+ export const generateSearchLink = (
46
+ title: string,
47
+ block: string,
48
+ superBlock: string
49
+ ) => {
50
+ const titleText = t(`intro:${superBlock}.blocks.${block}.title`);
51
+ const selector = 'in:title';
52
+ const query = encodeURIComponent(`${titleText} - ${title} ${selector}`);
53
+ const search = `${forumLocation}/search?q=${query}`;
54
+ return search;
55
+ };
56
+
57
+ interface CheckboxProps {
58
+ name: string;
59
+ i18nKey: string;
60
+ onChange: (event: React.ChangeEvent<HTMLInputElement>) => void;
61
+ value: boolean;
62
+ href: string;
63
+ label: string;
64
+ }
65
+
66
+ function Checkbox({
67
+ name,
68
+ i18nKey,
69
+ onChange,
70
+ value,
71
+ href,
72
+ label
73
+ }: CheckboxProps) {
74
+ const { t } = useTranslation();
75
+
76
+ return (
77
+ <div className='checkbox-container'>
78
+ <input
79
+ id={name}
80
+ name={name}
81
+ type='checkbox'
82
+ onChange={onChange}
83
+ checked={value}
84
+ required
85
+ // Instead of reusing the `i18nKey`, use a plain text version for label
86
+ // as input label should not contain interactive elements
87
+ aria-label={t(label)}
88
+ />
89
+
90
+ <span>
91
+ <Trans i18nKey={i18nKey}>
92
+ <a href={href} rel='noopener noreferrer' target='_blank'>
93
+ placeholder
94
+ <span className='sr-only'>{t('aria.opens-new-window')}</span>
95
+ </a>
96
+ </Trans>
97
+ </span>
98
+ </div>
99
+ );
100
+ }
101
+
102
+ export function HelpModal({
103
+ closeHelpModal,
104
+ createQuestion,
105
+ isOpen,
106
+ challengeBlock,
107
+ superBlock,
108
+ challengeTitle,
109
+ guideUrl,
110
+ videoUrl,
111
+ openVideoModal
112
+ }: HelpModalProps): JSX.Element {
113
+ const { t } = useTranslation();
114
+ const [showHelpForm, setShowHelpForm] = useState(false);
115
+ const [description, setDescription] = useState('');
116
+ const [readSearchCheckbox, setReadSearchCheckbox] = useState(false);
117
+ const [similarQuestionsCheckbox, setSimilarQuestionsCheckbox] =
118
+ useState(false);
119
+
120
+ const formRef = useRef<HTMLFormElement>(null);
121
+
122
+ useEffect(() => {
123
+ if (showHelpForm) {
124
+ formRef.current?.querySelector('input')?.focus();
125
+ }
126
+ }, [showHelpForm]);
127
+
128
+ const canSubmitForm = useMemo(() => {
129
+ return (
130
+ description.length >= DESCRIPTION_MIN_CHARS &&
131
+ readSearchCheckbox &&
132
+ similarQuestionsCheckbox
133
+ );
134
+ }, [description, readSearchCheckbox, similarQuestionsCheckbox]);
135
+
136
+ const resetFormValues = () => {
137
+ setDescription('');
138
+ setReadSearchCheckbox(false);
139
+ setSimilarQuestionsCheckbox(false);
140
+ };
141
+
142
+ const handleClose = () => {
143
+ closeHelpModal();
144
+ setShowHelpForm(false);
145
+ resetFormValues();
146
+ };
147
+
148
+ const handleOpenVideo = () => {
149
+ openVideoModal();
150
+ handleClose();
151
+ };
152
+
153
+ const handleSubmit = (event: React.FormEvent) => {
154
+ event.preventDefault();
155
+
156
+ if (!canSubmitForm) {
157
+ return;
158
+ }
159
+
160
+ setShowHelpForm(false);
161
+ resetFormValues();
162
+ createQuestion(description);
163
+ closeHelpModal();
164
+ };
165
+
166
+ const hintUrl = guideUrl
167
+ ? guideUrl
168
+ : generateSearchLink(challengeTitle, challengeBlock, superBlock);
169
+
170
+ if (isOpen) {
171
+ callGA({ event: 'pageview', pagePath: '/help-modal' });
172
+ }
173
+ return (
174
+ <Modal onClose={handleClose} open={!!isOpen}>
175
+ <Modal.Header closeButtonClassNames='close'>
176
+ {t('buttons.get-help')}
177
+ </Modal.Header>
178
+ <Modal.Body>
179
+ {showHelpForm ? (
180
+ <form onSubmit={handleSubmit} ref={formRef}>
181
+ <fieldset>
182
+ <legend className='help-form-legend'>
183
+ {t('learn.must-confirm-statements')}
184
+ </legend>
185
+
186
+ <Checkbox
187
+ name='read-search-ask-checkbox'
188
+ i18nKey='learn.read-search-ask-checkbox'
189
+ label='aria.rsa-checkbox'
190
+ onChange={event => setReadSearchCheckbox(event.target.checked)}
191
+ value={readSearchCheckbox}
192
+ href={RSA}
193
+ />
194
+
195
+ <Spacer size='xs' />
196
+
197
+ <Checkbox
198
+ name='similar-questions-checkbox'
199
+ i18nKey='learn.similar-questions-checkbox'
200
+ label='aria.similar-questions-checkbox'
201
+ onChange={event =>
202
+ setSimilarQuestionsCheckbox(event.target.checked)
203
+ }
204
+ value={similarQuestionsCheckbox}
205
+ href={generateSearchLink(
206
+ challengeTitle,
207
+ challengeBlock,
208
+ superBlock
209
+ )}
210
+ />
211
+ </fieldset>
212
+
213
+ <Spacer size='s' />
214
+
215
+ <label htmlFor='help-modal-form-description'>
216
+ {t('forum-help.whats-happening')}
217
+ <span className='sr-only'>{t('learn.min-50-max-500')}</span>
218
+ </label>
219
+
220
+ <FormControl
221
+ id='help-modal-form-description'
222
+ name='description'
223
+ onChange={(event: React.ChangeEvent<HTMLInputElement>) => {
224
+ setDescription(event.target.value);
225
+ }}
226
+ componentClass='textarea'
227
+ rows={5}
228
+ value={description}
229
+ placeholder={t('forum-help.describe')}
230
+ minLength={DESCRIPTION_MIN_CHARS}
231
+ maxLength={DESCRIPTION_MAX_CHARS}
232
+ required
233
+ />
234
+
235
+ <Spacer size='s' />
236
+
237
+ {description.length < DESCRIPTION_MIN_CHARS ? (
238
+ <p>
239
+ {t('learn.minimum-characters', {
240
+ characters: DESCRIPTION_MIN_CHARS - description.length
241
+ })}
242
+ </p>
243
+ ) : (
244
+ <p>
245
+ {t('learn.characters-left', {
246
+ characters: DESCRIPTION_MAX_CHARS - description.length
247
+ })}
248
+ </p>
249
+ )}
250
+
251
+ <Spacer size='xxs' />
252
+
253
+ <Button
254
+ block={true}
255
+ size='large'
256
+ variant='primary'
257
+ type='submit'
258
+ disabled={!canSubmitForm}
259
+ >
260
+ {t('buttons.submit')}
261
+ </Button>
262
+ <Spacer size='xxs' />
263
+ <Button
264
+ block={true}
265
+ size='large'
266
+ variant='primary'
267
+ onClick={handleClose}
268
+ >
269
+ {t('buttons.cancel')}
270
+ </Button>
271
+ </form>
272
+ ) : (
273
+ <>
274
+ <div className='help-text-warning'>
275
+ <p>
276
+ <Trans i18nKey='learn.tried-rsa'>
277
+ <a href={RSA} rel='noopener noreferrer' target='_blank'>
278
+ placeholder
279
+ </a>
280
+ </Trans>
281
+ </p>
282
+ <p>
283
+ <Trans i18nKey='learn.rsa-forum'>
284
+ <a
285
+ href={generateSearchLink(
286
+ challengeTitle,
287
+ challengeBlock,
288
+ superBlock
289
+ )}
290
+ rel='noopener noreferrer'
291
+ target='_blank'
292
+ >
293
+ placeholder
294
+ </a>
295
+ placeholder
296
+ </Trans>
297
+ </p>
298
+ </div>
299
+ <Button
300
+ block={true}
301
+ size='large'
302
+ variant='primary'
303
+ href={hintUrl}
304
+ target='_blank'
305
+ rel='noopener noreferrer'
306
+ >
307
+ {t('buttons.get-hint')}
308
+ </Button>
309
+ <Spacer size='xxs' />
310
+ {videoUrl && (
311
+ <>
312
+ <Button
313
+ block={true}
314
+ size='large'
315
+ variant='primary'
316
+ onClick={handleOpenVideo}
317
+ data-playwright-test-label='watch-a-video-modal-button'
318
+ >
319
+ {t('buttons.watch-video')}
320
+ </Button>
321
+ <Spacer size='xxs' />
322
+ </>
323
+ )}
324
+ <Button
325
+ block={true}
326
+ size='large'
327
+ variant='primary'
328
+ onClick={() => setShowHelpForm(true)}
329
+ >
330
+ {t('buttons.create-post')}
331
+ </Button>
332
+ <Spacer size='xxs' />
333
+ <Button
334
+ block={true}
335
+ size='large'
336
+ variant='primary'
337
+ onClick={handleClose}
338
+ >
339
+ {t('buttons.cancel')}
340
+ </Button>
341
+ </>
342
+ )}
343
+ </Modal.Body>
344
+ </Modal>
345
+ );
346
+ }
347
+
348
+ HelpModal.displayName = 'HelpModal';
349
+
350
+ export default connect(mapStateToProps, mapDispatchToProps)(HelpModal);