diff --git a/.gitattributes b/.gitattributes index f3408b4a8a8532909643b18ab392734aff0ff0e5..72139abd49c12f7b1cc6ff8f5505f6322a304eb6 100644 --- a/.gitattributes +++ b/.gitattributes @@ -59,3 +59,7 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text *.mp4 filter=lfs diff=lfs merge=lfs -text *.webm filter=lfs diff=lfs merge=lfs -text code_syntax_dataset_1GB.csv filter=lfs diff=lfs merge=lfs -text +github_code/freeCodeCamp__freeCodeCamp/client/static/fonts/noto-sans-japanese/NotoSansJP-Black.woff filter=lfs diff=lfs merge=lfs -text +github_code/freeCodeCamp__freeCodeCamp/client/static/fonts/noto-sans-japanese/NotoSansJP-Bold.woff filter=lfs diff=lfs merge=lfs -text +github_code/freeCodeCamp__freeCodeCamp/client/static/fonts/noto-sans-japanese/NotoSansJP-Light.woff filter=lfs diff=lfs merge=lfs -text +github_code/freeCodeCamp__freeCodeCamp/client/static/fonts/noto-sans-japanese/NotoSansJP-Regular.woff filter=lfs diff=lfs merge=lfs -text diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/classic/mobile-layout.test.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/classic/mobile-layout.test.tsx new file mode 100644 index 0000000000000000000000000000000000000000..013e53f63d183f924308b79d571aac375f39b2b0 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/classic/mobile-layout.test.tsx @@ -0,0 +1,145 @@ +import React from 'react'; +import { render, screen, fireEvent } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { describe, it, expect, vi } from 'vitest'; +import { MobileLayout } from './mobile-layout'; + +vi.mock('i18next', () => ({ + default: { + t: (key: string) => key + } +})); + +vi.mock('../components/independent-lower-jaw', () => ({ + default: () =>
+})); + +const mockProps = { + editor:
Editor
, + hasEditableBoundaries: false, + hasPreview: false, + instructions:
Instructions
, + notes: '', + preview:
Preview
, + onPreviewResize: vi.fn(), + windowTitle: 'Test Title', + showPreviewPortal: false, + showPreviewPane: false, + removePortalWindow: vi.fn(), + setShowPreviewPortal: vi.fn(), + setShowPreviewPane: vi.fn(), + portalWindow: null, + updateUsingKeyboardInTablist: vi.fn(), + testOutput:
Test Output
, + usesMultifileEditor: false, + usesTerminal: false +}; + +const renderMobileLayout = ( + props: Partial> = {} +) => render(); + +describe('', () => { + it('renders instructions, code, console, preview, portal controls, and the lower jaw when preview is available', () => { + renderMobileLayout({ + hasPreview: true, + showPreviewPane: true + }); + + expect(screen.getByRole('tablist')).toBeInTheDocument(); + expect( + screen.getByRole('tab', { name: 'learn.editor-tabs.instructions' }) + ).toBeInTheDocument(); + expect( + screen.getByRole('tab', { name: 'learn.editor-tabs.code' }) + ).toBeInTheDocument(); + expect( + screen.getByRole('tab', { name: 'learn.editor-tabs.console' }) + ).toBeInTheDocument(); + expect( + screen.getByRole('tab', { name: 'learn.editor-tabs.preview' }) + ).toBeInTheDocument(); + expect( + screen.getByRole('button', { name: 'aria.move-preview-to-new-window' }) + ).toBeInTheDocument(); + expect(screen.getByTestId('independent-lower-jaw')).toBeInTheDocument(); + }); + + it('renders instructions, code, console, and the lower jaw when preview is unavailable', () => { + renderMobileLayout({ + hasPreview: false + }); + + expect(screen.getByRole('tablist')).toBeInTheDocument(); + expect( + screen.getByRole('tab', { name: 'learn.editor-tabs.instructions' }) + ).toBeInTheDocument(); + expect( + screen.getByRole('tab', { name: 'learn.editor-tabs.code' }) + ).toBeInTheDocument(); + expect( + screen.getByRole('tab', { name: 'learn.editor-tabs.console' }) + ).toBeInTheDocument(); + expect( + screen.queryByRole('tab', { name: 'learn.editor-tabs.preview' }) + ).not.toBeInTheDocument(); + expect( + screen.queryByRole('button', { name: 'aria.move-preview-to-new-window' }) + ).not.toBeInTheDocument(); + expect(screen.getByTestId('independent-lower-jaw')).toBeInTheDocument(); + }); + + it('renders the lower jaw for challenges with editable boundaries', () => { + renderMobileLayout({ hasEditableBoundaries: true }); + + expect(screen.getByTestId('independent-lower-jaw')).toBeInTheDocument(); + }); + + it('should render language selector when isDailyCodingChallenge is true', () => { + renderMobileLayout({ + isDailyCodingChallenge: true, + dailyCodingChallengeLanguage: 'javascript' + }); + expect(screen.getByText('JS')).toBeInTheDocument(); + }); + + it('should not render language selector when isDailyCodingChallenge is false', () => { + renderMobileLayout({ isDailyCodingChallenge: false }); + expect(screen.queryByText('JS')).not.toBeInTheDocument(); + expect(screen.queryByText('PY')).not.toBeInTheDocument(); + }); + + it('should call setDailyCodingChallengeLanguage when a language is selected', () => { + const setDailyCodingChallengeLanguage = vi.fn(); + renderMobileLayout({ + isDailyCodingChallenge: true, + dailyCodingChallengeLanguage: 'javascript', + setDailyCodingChallengeLanguage + }); + + // Open dropdown + fireEvent.click(screen.getByText('JS')); + + // Click Python option + fireEvent.click(screen.getByText('Python')); + + expect(setDailyCodingChallengeLanguage).toHaveBeenCalledWith('python'); + }); + + it('renders notes in the notes tab for multifile editor challenges', async () => { + const user = userEvent.setup(); + render( + + ); + + await user.click( + screen.getByRole('tab', { name: 'learn.editor-tabs.notes' }) + ); + + expect(screen.getByText('This is a test note')).toBeVisible(); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/classic/mobile-layout.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/classic/mobile-layout.tsx new file mode 100644 index 0000000000000000000000000000000000000000..28fefdca09b48ecf42daff4009637c8bb4ddd9b3 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/classic/mobile-layout.tsx @@ -0,0 +1,343 @@ +import i18next from 'i18next'; +import React, { Component } from 'react'; +import { faWindowRestore } from '@fortawesome/free-solid-svg-icons'; +import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; +import { createSelector } from 'reselect'; +import { connect } from 'react-redux'; +import store from 'store'; +import { + Tabs, + TabsContent, + TabsTrigger, + TabsList, + Dropdown, + MenuItem +} from '@freecodecamp/ui'; +import { DailyCodingChallengeLanguages } from '../../../redux/prop-types'; + +import { + removePortalWindow, + setShowPreviewPortal, + setShowPreviewPane +} from '../redux/actions'; +import { + portalWindowSelector, + showPreviewPortalSelector, + showPreviewPaneSelector +} from '../redux/selectors'; +import { isRtlLanguage } from '../../../utils/is-rtl-language'; +import PreviewPortal from '../components/preview-portal'; +import Notes from '../components/notes'; +import IndependentLowerJaw from '../components/independent-lower-jaw'; +import EditorTabs from './editor-tabs'; + +interface MobileLayoutProps { + editor: JSX.Element | null; + hasEditableBoundaries: boolean; + hasPreview: boolean; + instructions: JSX.Element; + isDailyCodingChallenge?: boolean; + dailyCodingChallengeLanguage?: DailyCodingChallengeLanguages; + setDailyCodingChallengeLanguage?: ( + language: DailyCodingChallengeLanguages + ) => void; + notes: string; + preview: JSX.Element; + onPreviewResize: () => void; + windowTitle: string; + showPreviewPortal: boolean; + showPreviewPane: boolean; + removePortalWindow: () => void; + setShowPreviewPortal: (arg: boolean) => void; + setShowPreviewPane: (arg: boolean) => void; + portalWindow: null | Window; + updateUsingKeyboardInTablist: (arg0: boolean) => void; + testOutput: JSX.Element; + usesMultifileEditor: boolean; + usesTerminal: boolean; +} + +const tabs = { + editor: 'editor', + preview: 'preview', + console: 'console', + notes: 'notes', + instructions: 'instructions' +} as const; + +type Tab = keyof typeof tabs; + +interface MobileLayoutState { + currentTab: Tab; +} + +const mapDispatchToProps = { + removePortalWindow, + setShowPreviewPortal, + setShowPreviewPane +}; + +const mapStateToProps = createSelector( + showPreviewPortalSelector, + showPreviewPaneSelector, + portalWindowSelector, + + ( + showPreviewPortal: boolean, + showPreviewPane: boolean, + portalWindow: null | Window + ) => ({ + showPreviewPortal, + showPreviewPane, + portalWindow + }) +); + +export class MobileLayout extends Component< + MobileLayoutProps, + MobileLayoutState +> { + static displayName: string; + + state: MobileLayoutState = { + currentTab: this.props.hasEditableBoundaries + ? tabs.editor + : tabs.instructions + }; + + switchTab = (tab: string): void => { + this.setState({ + currentTab: tab as Tab + }); + }; + + handleKeyDown = (): void => this.props.updateUsingKeyboardInTablist(true); + + handleClick = (): void => this.props.updateUsingKeyboardInTablist(false); + + render(): JSX.Element { + const { currentTab } = this.state; + const { + hasEditableBoundaries, + instructions, + editor, + testOutput, + hasPreview, + notes, + preview, + onPreviewResize, + showPreviewPane, + showPreviewPortal, + removePortalWindow, + setShowPreviewPane, + setShowPreviewPortal, + portalWindow, + windowTitle, + usesMultifileEditor, + usesTerminal, + isDailyCodingChallenge, + dailyCodingChallengeLanguage, + setDailyCodingChallengeLanguage + } = this.props; + + const handleLanguageChange = ( + language: DailyCodingChallengeLanguages + ): void => { + store.set('dailyCodingChallengeLanguage', language); + if (setDailyCodingChallengeLanguage) { + setDailyCodingChallengeLanguage(language); + } + }; + + const displayPreviewPane = hasPreview && showPreviewPane; + const displayPreviewPortal = hasPreview && showPreviewPortal; + + const togglePane = (pane: string): void => { + if (pane === 'showPreviewPane') { + if (!showPreviewPane && showPreviewPortal) { + setShowPreviewPortal(false); + } + setShowPreviewPane(!showPreviewPane); + portalWindow?.close(); + removePortalWindow(); + } else if (pane === 'showPreviewPortal') { + if (!showPreviewPortal && showPreviewPane) { + setShowPreviewPane(false); + } + setShowPreviewPortal(!showPreviewPortal); + if (showPreviewPortal) { + portalWindow?.close(); + removePortalWindow(); + } + } else { + setShowPreviewPane(true); + setShowPreviewPortal(false); + } + }; + + // sets screen reader text for the portal button + function getPortalBtnSrText() { + // preview open in main window + let portalBtnSrText = i18next.t('aria.move-preview-to-new-window'); + + // preview open in external window + if (showPreviewPortal && !showPreviewPane) { + portalBtnSrText = i18next.t('aria.close-external-preview-window'); + } + + return portalBtnSrText; + } + + const previewTriggerText = + usesTerminal == false + ? 'learn.editor-tabs.preview' + : 'learn.editor-tabs.terminal'; + + // Unlike the desktop layout the mobile version does not have an ActionRow, + // but still needs a way to switch between the different tabs. + return ( + <> + + + {isDailyCodingChallenge && ( + + + {dailyCodingChallengeLanguage === 'javascript' + ? 'JS' + : 'PY'}{' '} + + + handleLanguageChange('javascript')}> + JavaScript + + handleLanguageChange('python')}> + Python + + + + )} + {!hasEditableBoundaries && ( + + {i18next.t('learn.editor-tabs.instructions')} + + )} + + {i18next.t('learn.editor-tabs.code')} + + {!!notes && usesMultifileEditor && ( + + {i18next.t('learn.editor-tabs.notes')} + + )} + + {i18next.t('learn.editor-tabs.console')} + + {hasPreview && ( + + {i18next.t(previewTriggerText)} + + )} + + + + {usesMultifileEditor && } + {editor} + + {!hasEditableBoundaries && ( + + {instructions} + + )} + + {testOutput} + + {!!notes && usesMultifileEditor && ( + + + + )} + {hasPreview && ( + +
+ +
+ {displayPreviewPane && preview} + {showPreviewPortal && ( +

+ {i18next.t('learn.preview-external-window')} +

+ )} +
+ )} + + {hasPreview && this.state.currentTab !== 'preview' && ( +
+ +
+ )} +
+ {displayPreviewPortal && ( + + {preview} + + )} + + ); + } +} + +MobileLayout.displayName = 'MobileLayout'; + +export default connect(mapStateToProps, mapDispatchToProps)(MobileLayout); diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/classic/multifile-editor.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/classic/multifile-editor.tsx new file mode 100644 index 0000000000000000000000000000000000000000..de6881ff26dbd3930f15b4ab4250f5ef9ce9dacb --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/classic/multifile-editor.tsx @@ -0,0 +1,173 @@ +import React, { useRef } from 'react'; +import { connect } from 'react-redux'; +import { ReflexContainer, ReflexElement, ReflexSplitter } from 'react-reflex'; +import { createSelector } from 'reselect'; +import { isDonationModalOpenSelector } from '../../../redux/selectors'; +import { + canFocusEditorSelector, + visibleEditorsSelector +} from '../redux/selectors'; +import { getTargetEditor } from '../utils/get-target-editor'; +import { isRtlLanguage } from '../../../utils/is-rtl-language'; +import './editor.css'; +import Editor, { type EditorProps } from './editor'; + +export type VisibleEditors = { + indexhtml?: boolean; + indexjsx?: boolean; + stylescss?: boolean; + scriptjs?: boolean; + indexts?: boolean; + indextsx?: boolean; + mainpy?: boolean; + tsconfigjson?: boolean; +}; +type MultifileEditorProps = Pick< + EditorProps, + | 'usesMultifileEditor' + | 'showProjectPreview' + | 'title' + | 'resizeProps' + | 'isUsingKeyboardInTablist' + | 'isMobileLayout' + | 'initialTests' + | 'editorRef' + | 'containerRef' + | 'block' + | 'superBlock' + | 'challengeFiles' + | 'description' + // We use dimensions to trigger a re-render of the editor + | 'dimensions' +> & { + visibleEditors: VisibleEditors; +}; + +const mapStateToProps = createSelector( + visibleEditorsSelector, + canFocusEditorSelector, + isDonationModalOpenSelector, + (visibleEditors: VisibleEditors, canFocus: boolean, open) => ({ + visibleEditors, + canFocus: open ? false : canFocus + }) +); + +const MultifileEditor = (props: MultifileEditorProps) => { + const { + block, + superBlock, + challengeFiles, + containerRef, + description, + editorRef, + initialTests, + isMobileLayout, + isUsingKeyboardInTablist, + resizeProps, + title, + visibleEditors: { + stylescss, + indexhtml, + scriptjs, + indexts, + indexjsx, + indextsx, + mainpy, + tsconfigjson + }, + usesMultifileEditor, + showProjectPreview + } = props; + // TODO: the tabs mess up the rendering (scroll doesn't work properly and + // the in-editor description) + + const reflexProps = { + propagateDimensions: true + }; + + const targetEditor = getTargetEditor(challengeFiles); + + // Only one editor should be focused and that should happen once, after it has + // been mounted. This ref allows the editors to coordinate, without having to + // resort to redux. + const canFocusOnMountRef = useRef(true); + + const editorKeys = []; + + // The order of the keys should match the order set by sortChallengeFiles + if (indexjsx) editorKeys.push('indexjsx'); + if (indextsx) editorKeys.push('indextsx'); + if (indexhtml) editorKeys.push('indexhtml'); + if (stylescss) editorKeys.push('stylescss'); + if (scriptjs) editorKeys.push('scriptjs'); + if (mainpy) editorKeys.push('mainpy'); + if (indexts) editorKeys.push('indexts'); + if (tsconfigjson) editorKeys.push('tsconfigjson'); + + const editorAndSplitterKeys = editorKeys.reduce((acc: string[] | [], key) => { + if (acc.length === 0) { + return [key]; + } else { + return [...acc, `${key}-splitter`, key]; + } + }, []); + + if (isRtlLanguage) { + editorAndSplitterKeys.reverse(); + } + + return ( + + + + {editorAndSplitterKeys.map(key => { + const isSplitter = key.endsWith('-splitter'); + if (isSplitter) { + return ( + + ); + } else { + return ( + + + + ); + } + })} + + + + ); +}; + +MultifileEditor.displayName = 'MultifileEditor'; + +export default connect(mapStateToProps)(MultifileEditor); diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/classic/react-types-license b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/classic/react-types-license new file mode 100644 index 0000000000000000000000000000000000000000..48ea6616b5b8581df3401872996cecf1f8b08a0d --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/classic/react-types-license @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/classic/react-types.json b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/classic/react-types.json new file mode 100644 index 0000000000000000000000000000000000000000..c4e908a4c0efb6c2eb96d60d942b5549b23001a8 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/classic/react-types.json @@ -0,0 +1,3 @@ +{ + "react-18": "// NOTE: Users of the `experimental` builds of React should add a reference\n// to 'react/experimental' in their project. See experimental.d.ts's top comment\n// for reference and documentation on how exactly to do it.\n\n/// \n\nimport * as CSS from \"csstype\";\nimport * as PropTypes from \"prop-types\";\n\ntype NativeAnimationEvent = AnimationEvent;\ntype NativeClipboardEvent = ClipboardEvent;\ntype NativeCompositionEvent = CompositionEvent;\ntype NativeDragEvent = DragEvent;\ntype NativeFocusEvent = FocusEvent;\ntype NativeInputEvent = InputEvent;\ntype NativeKeyboardEvent = KeyboardEvent;\ntype NativeMouseEvent = MouseEvent;\ntype NativeTouchEvent = TouchEvent;\ntype NativePointerEvent = PointerEvent;\ntype NativeTransitionEvent = TransitionEvent;\ntype NativeUIEvent = UIEvent;\ntype NativeWheelEvent = WheelEvent;\n\n/**\n * Used to represent DOM API's where users can either pass\n * true or false as a boolean or as its equivalent strings.\n */\ntype Booleanish = boolean | \"true\" | \"false\";\n\n/**\n * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/crossorigin MDN}\n */\ntype CrossOrigin = \"anonymous\" | \"use-credentials\" | \"\" | undefined;\n\ndeclare const UNDEFINED_VOID_ONLY: unique symbol;\n\n/**\n * The function returned from an effect passed to {@link React.useEffect useEffect},\n * which can be used to clean up the effect when the component unmounts.\n *\n * @see {@link https://react.dev/reference/react/useEffect React Docs}\n */\ntype Destructor = () => void | { [UNDEFINED_VOID_ONLY]: never };\ntype VoidOrUndefinedOnly = void | { [UNDEFINED_VOID_ONLY]: never };\n\n// eslint-disable-next-line @definitelytyped/export-just-namespace\nexport = React;\nexport as namespace React;\n\ndeclare namespace React {\n //\n // React Elements\n // ----------------------------------------------------------------------\n\n /**\n * Used to retrieve the possible components which accept a given set of props.\n *\n * Can be passed no type parameters to get a union of all possible components\n * and tags.\n *\n * Is a superset of {@link ComponentType}.\n *\n * @template P The props to match against. If not passed, defaults to any.\n * @template Tag An optional tag to match against. If not passed, attempts to match against all possible tags.\n *\n * @example\n *\n * ```tsx\n * // All components and tags (img, embed etc.)\n * // which accept `src`\n * type SrcComponents = ElementType<{ src: any }>;\n * ```\n *\n * @example\n *\n * ```tsx\n * // All components\n * type AllComponents = ElementType;\n * ```\n *\n * @example\n *\n * ```tsx\n * // All custom components which match `src`, and tags which\n * // match `src`, narrowed down to just `audio` and `embed`\n * type SrcComponents = ElementType<{ src: any }, 'audio' | 'embed'>;\n * ```\n */\n type ElementType

=\n | { [K in Tag]: P extends JSX.IntrinsicElements[K] ? K : never }[Tag]\n | ComponentType

;\n\n /**\n * Represents any user-defined component, either as a function or a class.\n *\n * Similar to {@link JSXElementConstructor}, but with extra properties like\n * {@link FunctionComponent.defaultProps defaultProps } and\n * {@link ComponentClass.contextTypes contextTypes}.\n *\n * @template P The props the component accepts.\n *\n * @see {@link ComponentClass}\n * @see {@link FunctionComponent}\n */\n type ComponentType

= ComponentClass

| FunctionComponent

;\n\n /**\n * Represents any user-defined component, either as a function or a class.\n *\n * Similar to {@link ComponentType}, but without extra properties like\n * {@link FunctionComponent.defaultProps defaultProps } and\n * {@link ComponentClass.contextTypes contextTypes}.\n *\n * @template P The props the component accepts.\n */\n type JSXElementConstructor

=\n | ((\n props: P,\n /**\n * @deprecated\n *\n * @see {@link https://legacy.reactjs.org/docs/legacy-context.html#referencing-context-in-stateless-function-components React Docs}\n */\n deprecatedLegacyContext?: any,\n ) => ReactNode)\n | (new(\n props: P,\n /**\n * @deprecated\n *\n * @see {@link https://legacy.reactjs.org/docs/legacy-context.html#referencing-context-in-lifecycle-methods React Docs}\n */\n deprecatedLegacyContext?: any,\n ) => Component);\n\n /**\n * A readonly ref container where {@link current} cannot be mutated.\n *\n * Created by {@link createRef}, or {@link useRef} when passed `null`.\n *\n * @template T The type of the ref's value.\n *\n * @example\n *\n * ```tsx\n * const ref = createRef();\n *\n * ref.current = document.createElement('div'); // Error\n * ```\n */\n interface RefObject {\n /**\n * The current value of the ref.\n */\n readonly current: T | null;\n }\n\n interface DO_NOT_USE_OR_YOU_WILL_BE_FIRED_CALLBACK_REF_RETURN_VALUES {\n }\n /**\n * A callback fired whenever the ref's value changes.\n *\n * @template T The type of the ref's value.\n *\n * @see {@link https://react.dev/reference/react-dom/components/common#ref-callback React Docs}\n *\n * @example\n *\n * ```tsx\n *

console.log(node)} />\n * ```\n */\n type RefCallback = {\n bivarianceHack(\n instance: T | null,\n ):\n | void\n | DO_NOT_USE_OR_YOU_WILL_BE_FIRED_CALLBACK_REF_RETURN_VALUES[\n keyof DO_NOT_USE_OR_YOU_WILL_BE_FIRED_CALLBACK_REF_RETURN_VALUES\n ];\n }[\"bivarianceHack\"];\n\n /**\n * A union type of all possible shapes for React refs.\n *\n * @see {@link RefCallback}\n * @see {@link RefObject}\n */\n\n type Ref = RefCallback | RefObject | null;\n /**\n * A legacy implementation of refs where you can pass a string to a ref prop.\n *\n * @see {@link https://react.dev/reference/react/Component#refs React Docs}\n *\n * @example\n *\n * ```tsx\n *
\n * ```\n */\n // TODO: Remove the string ref special case from `PropsWithRef` once we remove LegacyRef\n type LegacyRef = string | Ref;\n\n /**\n * Retrieves the type of the 'ref' prop for a given component type or tag name.\n *\n * @template C The component type.\n *\n * @example\n *\n * ```tsx\n * type MyComponentRef = React.ElementRef;\n * ```\n *\n * @example\n *\n * ```tsx\n * type DivRef = React.ElementRef<'div'>;\n * ```\n */\n type ElementRef<\n C extends\n | ForwardRefExoticComponent\n | { new(props: any): Component }\n | ((props: any, deprecatedLegacyContext?: any) => ReactNode)\n | keyof JSX.IntrinsicElements,\n > =\n // need to check first if `ref` is a valid prop for ts@3.0\n // otherwise it will infer `{}` instead of `never`\n \"ref\" extends keyof ComponentPropsWithRef\n ? NonNullable[\"ref\"]> extends RefAttributes<\n infer Instance\n >[\"ref\"] ? Instance\n : never\n : never;\n\n type ComponentState = any;\n\n /**\n * A value which uniquely identifies a node among items in an array.\n *\n * @see {@link https://react.dev/learn/rendering-lists#keeping-list-items-in-order-with-key React Docs}\n */\n type Key = string | number | bigint;\n\n /**\n * @internal The props any component can receive.\n * You don't have to add this type. All components automatically accept these props.\n * ```tsx\n * const Component = () =>
;\n * \n * ```\n *\n * WARNING: The implementation of a component will never have access to these attributes.\n * The following example would be incorrect usage because {@link Component} would never have access to `key`:\n * ```tsx\n * const Component = (props: React.Attributes) => props.key;\n * ```\n */\n interface Attributes {\n key?: Key | null | undefined;\n }\n /**\n * The props any component accepting refs can receive.\n * Class components, built-in browser components (e.g. `div`) and forwardRef components can receive refs and automatically accept these props.\n * ```tsx\n * const Component = forwardRef(() =>
);\n * console.log(current)} />\n * ```\n *\n * You only need this type if you manually author the types of props that need to be compatible with legacy refs.\n * ```tsx\n * interface Props extends React.RefAttributes {}\n * declare const Component: React.FunctionComponent;\n * ```\n *\n * Otherwise it's simpler to directly use {@link Ref} since you can safely use the\n * props type to describe to props that a consumer can pass to the component\n * as well as describing the props the implementation of a component \"sees\".\n * {@link RefAttributes} is generally not safe to describe both consumer and seen props.\n *\n * ```tsx\n * interface Props extends {\n * ref?: React.Ref | undefined;\n * }\n * declare const Component: React.FunctionComponent;\n * ```\n *\n * WARNING: The implementation of a component will not have access to the same type in versions of React supporting string refs.\n * The following example would be incorrect usage because {@link Component} would never have access to a `ref` with type `string`\n * ```tsx\n * const Component = (props: React.RefAttributes) => props.ref;\n * ```\n */\n interface RefAttributes extends Attributes {\n /**\n * Allows getting a ref to the component instance.\n * Once the component unmounts, React will set `ref.current` to `null`\n * (or call the ref with `null` if you passed a callback ref).\n *\n * @see {@link https://react.dev/learn/referencing-values-with-refs#refs-and-the-dom React Docs}\n */\n ref?: LegacyRef | undefined;\n }\n\n /**\n * Represents the built-in attributes available to class components.\n */\n interface ClassAttributes extends RefAttributes {\n }\n\n /**\n * Represents a JSX element.\n *\n * Where {@link ReactNode} represents everything that can be rendered, `ReactElement`\n * only represents JSX.\n *\n * @template P The type of the props object\n * @template T The type of the component or tag\n *\n * @example\n *\n * ```tsx\n * const element: ReactElement =
;\n * ```\n */\n interface ReactElement<\n P = any,\n T extends string | JSXElementConstructor = string | JSXElementConstructor,\n > {\n type: T;\n props: P;\n key: string | null;\n }\n\n /**\n * @deprecated\n */\n interface ReactComponentElement<\n T extends keyof JSX.IntrinsicElements | JSXElementConstructor,\n P = Pick, Exclude, \"key\" | \"ref\">>,\n > extends ReactElement> {}\n\n interface FunctionComponentElement

extends ReactElement> {\n ref?: (\"ref\" extends keyof P ? P extends { ref?: infer R | undefined } ? R : never : never) | undefined;\n }\n\n type CElement> = ComponentElement;\n interface ComponentElement> extends ReactElement> {\n ref?: LegacyRef | undefined;\n }\n\n /**\n * @deprecated Use {@link ComponentElement} instead.\n */\n type ClassicElement

= CElement>;\n\n // string fallback for custom web-components\n interface DOMElement

| SVGAttributes, T extends Element>\n extends ReactElement\n {\n ref: LegacyRef;\n }\n\n // ReactHTML for ReactHTMLElement\n interface ReactHTMLElement extends DetailedReactHTMLElement, T> {}\n\n interface DetailedReactHTMLElement

, T extends HTMLElement> extends DOMElement {\n type: keyof ReactHTML;\n }\n\n // ReactSVG for ReactSVGElement\n interface ReactSVGElement extends DOMElement, SVGElement> {\n type: keyof ReactSVG;\n }\n\n interface ReactPortal extends ReactElement {\n children: ReactNode;\n }\n\n //\n // Factories\n // ----------------------------------------------------------------------\n\n /** @deprecated */\n type Factory

= (props?: Attributes & P, ...children: ReactNode[]) => ReactElement

;\n\n /** @deprecated */\n type SFCFactory

= FunctionComponentFactory

;\n\n /** @deprecated */\n type FunctionComponentFactory

= (\n props?: Attributes & P,\n ...children: ReactNode[]\n ) => FunctionComponentElement

;\n\n /** @deprecated */\n type ComponentFactory> = (\n props?: ClassAttributes & P,\n ...children: ReactNode[]\n ) => CElement;\n\n /** @deprecated */\n type CFactory> = ComponentFactory;\n /** @deprecated */\n type ClassicFactory

= CFactory>;\n\n /** @deprecated */\n type DOMFactory

, T extends Element> = (\n props?: ClassAttributes & P | null,\n ...children: ReactNode[]\n ) => DOMElement;\n\n /** @deprecated */\n interface HTMLFactory extends DetailedHTMLFactory, T> {}\n\n /** @deprecated */\n interface DetailedHTMLFactory

, T extends HTMLElement> extends DOMFactory {\n (props?: ClassAttributes & P | null, ...children: ReactNode[]): DetailedReactHTMLElement;\n }\n\n /** @deprecated */\n interface SVGFactory extends DOMFactory, SVGElement> {\n (\n props?: ClassAttributes & SVGAttributes | null,\n ...children: ReactNode[]\n ): ReactSVGElement;\n }\n\n /**\n * @deprecated - This type is not relevant when using React. Inline the type instead to make the intent clear.\n */\n type ReactText = string | number;\n /**\n * @deprecated - This type is not relevant when using React. Inline the type instead to make the intent clear.\n */\n type ReactChild = ReactElement | string | number;\n\n /**\n * @deprecated Use either `ReactNode[]` if you need an array or `Iterable` if its passed to a host component.\n */\n interface ReactNodeArray extends ReadonlyArray {}\n /**\n * WARNING: Not related to `React.Fragment`.\n * @deprecated This type is not relevant when using React. Inline the type instead to make the intent clear.\n */\n type ReactFragment = Iterable;\n\n /**\n * Different release channels declare additional types of ReactNode this particular release channel accepts.\n * App or library types should never augment this interface.\n */\n interface DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_REACT_NODES {}\n\n /**\n * Represents all of the things React can render.\n *\n * Where {@link ReactElement} only represents JSX, `ReactNode` represents everything that can be rendered.\n *\n * @see {@link https://react-typescript-cheatsheet.netlify.app/docs/react-types/reactnode/ React TypeScript Cheatsheet}\n *\n * @example\n *\n * ```tsx\n * // Typing children\n * type Props = { children: ReactNode }\n *\n * const Component = ({ children }: Props) =>

{children}
\n *\n * hello\n * ```\n *\n * @example\n *\n * ```tsx\n * // Typing a custom element\n * type Props = { customElement: ReactNode }\n *\n * const Component = ({ customElement }: Props) =>
{customElement}
\n *\n * hello
} />\n * ```\n */\n // non-thenables need to be kept in sync with AwaitedReactNode\n type ReactNode =\n | ReactElement\n | string\n | number\n | Iterable\n | ReactPortal\n | boolean\n | null\n | undefined\n | DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_REACT_NODES[\n keyof DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_REACT_NODES\n ];\n\n //\n // Top Level API\n // ----------------------------------------------------------------------\n\n // DOM Elements\n /** @deprecated */\n function createFactory(\n type: keyof ReactHTML,\n ): HTMLFactory;\n /** @deprecated */\n function createFactory(\n type: keyof ReactSVG,\n ): SVGFactory;\n /** @deprecated */\n function createFactory

, T extends Element>(\n type: string,\n ): DOMFactory;\n\n // Custom components\n /** @deprecated */\n function createFactory

(type: FunctionComponent

): FunctionComponentFactory

;\n /** @deprecated */\n function createFactory, C extends ComponentClass

>(\n type: ClassType,\n ): CFactory;\n /** @deprecated */\n function createFactory

(type: ComponentClass

): Factory

;\n\n // DOM Elements\n // TODO: generalize this to everything in `keyof ReactHTML`, not just \"input\"\n function createElement(\n type: \"input\",\n props?: InputHTMLAttributes & ClassAttributes | null,\n ...children: ReactNode[]\n ): DetailedReactHTMLElement, HTMLInputElement>;\n function createElement

, T extends HTMLElement>(\n type: keyof ReactHTML,\n props?: ClassAttributes & P | null,\n ...children: ReactNode[]\n ): DetailedReactHTMLElement;\n function createElement

, T extends SVGElement>(\n type: keyof ReactSVG,\n props?: ClassAttributes & P | null,\n ...children: ReactNode[]\n ): ReactSVGElement;\n function createElement

, T extends Element>(\n type: string,\n props?: ClassAttributes & P | null,\n ...children: ReactNode[]\n ): DOMElement;\n\n // Custom components\n\n function createElement

(\n type: FunctionComponent

,\n props?: Attributes & P | null,\n ...children: ReactNode[]\n ): FunctionComponentElement

;\n function createElement

, C extends ComponentClass

>(\n type: ClassType,\n props?: ClassAttributes & P | null,\n ...children: ReactNode[]\n ): CElement;\n function createElement

(\n type: FunctionComponent

| ComponentClass

| string,\n props?: Attributes & P | null,\n ...children: ReactNode[]\n ): ReactElement

;\n\n // DOM Elements\n // ReactHTMLElement\n function cloneElement

, T extends HTMLElement>(\n element: DetailedReactHTMLElement,\n props?: P,\n ...children: ReactNode[]\n ): DetailedReactHTMLElement;\n // ReactHTMLElement, less specific\n function cloneElement

, T extends HTMLElement>(\n element: ReactHTMLElement,\n props?: P,\n ...children: ReactNode[]\n ): ReactHTMLElement;\n // SVGElement\n function cloneElement

, T extends SVGElement>(\n element: ReactSVGElement,\n props?: P,\n ...children: ReactNode[]\n ): ReactSVGElement;\n // DOM Element (has to be the last, because type checking stops at first overload that fits)\n function cloneElement

, T extends Element>(\n element: DOMElement,\n props?: DOMAttributes & P,\n ...children: ReactNode[]\n ): DOMElement;\n\n // Custom components\n function cloneElement

(\n element: FunctionComponentElement

,\n props?: Partial

& Attributes,\n ...children: ReactNode[]\n ): FunctionComponentElement

;\n function cloneElement>(\n element: CElement,\n props?: Partial

& ClassAttributes,\n ...children: ReactNode[]\n ): CElement;\n function cloneElement

(\n element: ReactElement

,\n props?: Partial

& Attributes,\n ...children: ReactNode[]\n ): ReactElement

;\n\n /**\n * Describes the props accepted by a Context {@link Provider}.\n *\n * @template T The type of the value the context provides.\n */\n interface ProviderProps {\n value: T;\n children?: ReactNode | undefined;\n }\n\n /**\n * Describes the props accepted by a Context {@link Consumer}.\n *\n * @template T The type of the value the context provides.\n */\n interface ConsumerProps {\n children: (value: T) => ReactNode;\n }\n\n /**\n * An object masquerading as a component. These are created by functions\n * like {@link forwardRef}, {@link memo}, and {@link createContext}.\n *\n * In order to make TypeScript work, we pretend that they are normal\n * components.\n *\n * But they are, in fact, not callable - instead, they are objects which\n * are treated specially by the renderer.\n *\n * @template P The props the component accepts.\n */\n interface ExoticComponent

{\n (props: P): ReactNode;\n readonly $$typeof: symbol;\n }\n\n /**\n * An {@link ExoticComponent} with a `displayName` property applied to it.\n *\n * @template P The props the component accepts.\n */\n interface NamedExoticComponent

extends ExoticComponent

{\n /**\n * Used in debugging messages. You might want to set it\n * explicitly if you want to display a different name for\n * debugging purposes.\n *\n * @see {@link https://legacy.reactjs.org/docs/react-component.html#displayname Legacy React Docs}\n */\n displayName?: string | undefined;\n }\n\n /**\n * An {@link ExoticComponent} with a `propTypes` property applied to it.\n *\n * @template P The props the component accepts.\n */\n interface ProviderExoticComponent

extends ExoticComponent

{\n propTypes?: WeakValidationMap

| undefined;\n }\n\n /**\n * Used to retrieve the type of a context object from a {@link Context}.\n *\n * @template C The context object.\n *\n * @example\n *\n * ```tsx\n * import { createContext } from 'react';\n *\n * const MyContext = createContext({ foo: 'bar' });\n *\n * type ContextType = ContextType;\n * // ContextType = { foo: string }\n * ```\n */\n type ContextType> = C extends Context ? T : never;\n\n /**\n * Wraps your components to specify the value of this context for all components inside.\n *\n * @see {@link https://react.dev/reference/react/createContext#provider React Docs}\n *\n * @example\n *\n * ```tsx\n * import { createContext } from 'react';\n *\n * const ThemeContext = createContext('light');\n *\n * function App() {\n * return (\n * \n * \n * \n * );\n * }\n * ```\n */\n type Provider = ProviderExoticComponent>;\n\n /**\n * The old way to read context, before {@link useContext} existed.\n *\n * @see {@link https://react.dev/reference/react/createContext#consumer React Docs}\n *\n * @example\n *\n * ```tsx\n * import { UserContext } from './user-context';\n *\n * function Avatar() {\n * return (\n * \n * {user => {user.name}}\n * \n * );\n * }\n * ```\n */\n type Consumer = ExoticComponent>;\n\n /**\n * Context lets components pass information deep down without explicitly\n * passing props.\n *\n * Created from {@link createContext}\n *\n * @see {@link https://react.dev/learn/passing-data-deeply-with-context React Docs}\n * @see {@link https://react-typescript-cheatsheet.netlify.app/docs/basic/getting-started/context/ React TypeScript Cheatsheet}\n *\n * @example\n *\n * ```tsx\n * import { createContext } from 'react';\n *\n * const ThemeContext = createContext('light');\n * ```\n */\n interface Context {\n Provider: Provider;\n Consumer: Consumer;\n /**\n * Used in debugging messages. You might want to set it\n * explicitly if you want to display a different name for\n * debugging purposes.\n *\n * @see {@link https://legacy.reactjs.org/docs/react-component.html#displayname Legacy React Docs}\n */\n displayName?: string | undefined;\n }\n\n /**\n * Lets you create a {@link Context} that components can provide or read.\n *\n * @param defaultValue The value you want the context to have when there is no matching\n * {@link Provider} in the tree above the component reading the context. This is meant\n * as a \"last resort\" fallback.\n *\n * @see {@link https://react.dev/reference/react/createContext#reference React Docs}\n * @see {@link https://react-typescript-cheatsheet.netlify.app/docs/basic/getting-started/context/ React TypeScript Cheatsheet}\n *\n * @example\n *\n * ```tsx\n * import { createContext } from 'react';\n *\n * const ThemeContext = createContext('light');\n * ```\n */\n function createContext(\n // If you thought this should be optional, see\n // https://github.com/DefinitelyTyped/DefinitelyTyped/pull/24509#issuecomment-382213106\n defaultValue: T,\n ): Context;\n\n function isValidElement

(object: {} | null | undefined): object is ReactElement

;\n\n /**\n * Maintainer's note: Sync with {@link ReactChildren} until {@link ReactChildren} is removed.\n */\n const Children: {\n map(\n children: C | readonly C[],\n fn: (child: C, index: number) => T,\n ): C extends null | undefined ? C : Array>;\n forEach(children: C | readonly C[], fn: (child: C, index: number) => void): void;\n count(children: any): number;\n only(children: C): C extends any[] ? never : C;\n toArray(children: ReactNode | ReactNode[]): Array>;\n };\n /**\n * Lets you group elements without a wrapper node.\n *\n * @see {@link https://react.dev/reference/react/Fragment React Docs}\n *\n * @example\n *\n * ```tsx\n * import { Fragment } from 'react';\n *\n * \n * Hello\n * World\n * \n * ```\n *\n * @example\n *\n * ```tsx\n * // Using the <> shorthand syntax:\n *\n * <>\n * Hello\n * World\n * \n * ```\n */\n const Fragment: ExoticComponent<{ children?: ReactNode | undefined }>;\n\n /**\n * Lets you find common bugs in your components early during development.\n *\n * @see {@link https://react.dev/reference/react/StrictMode React Docs}\n *\n * @example\n *\n * ```tsx\n * import { StrictMode } from 'react';\n *\n * \n * \n * \n * ```\n */\n const StrictMode: ExoticComponent<{ children?: ReactNode | undefined }>;\n\n /**\n * The props accepted by {@link Suspense}.\n *\n * @see {@link https://react.dev/reference/react/Suspense React Docs}\n */\n interface SuspenseProps {\n children?: ReactNode | undefined;\n\n /** A fallback react tree to show when a Suspense child (like React.lazy) suspends */\n fallback?: ReactNode;\n\n /**\n * A name for this Suspense boundary for instrumentation purposes.\n * The name will help identify this boundary in React DevTools.\n */\n name?: string | undefined;\n }\n\n /**\n * Lets you display a fallback until its children have finished loading.\n *\n * @see {@link https://react.dev/reference/react/Suspense React Docs}\n *\n * @example\n *\n * ```tsx\n * import { Suspense } from 'react';\n *\n * }>\n * \n * \n * ```\n */\n const Suspense: ExoticComponent;\n const version: string;\n\n /**\n * The callback passed to {@link ProfilerProps.onRender}.\n *\n * @see {@link https://react.dev/reference/react/Profiler#onrender-callback React Docs}\n */\n type ProfilerOnRenderCallback = (\n /**\n * The string id prop of the {@link Profiler} tree that has just committed. This lets\n * you identify which part of the tree was committed if you are using multiple\n * profilers.\n *\n * @see {@link https://react.dev/reference/react/Profiler#onrender-callback React Docs}\n */\n id: string,\n /**\n * This lets you know whether the tree has just been mounted for the first time\n * or re-rendered due to a change in props, state, or hooks.\n *\n * @see {@link https://react.dev/reference/react/Profiler#onrender-callback React Docs}\n */\n phase: \"mount\" | \"update\" | \"nested-update\",\n /**\n * The number of milliseconds spent rendering the {@link Profiler} and its descendants\n * for the current update. This indicates how well the subtree makes use of\n * memoization (e.g. {@link memo} and {@link useMemo}). Ideally this value should decrease\n * significantly after the initial mount as many of the descendants will only need to\n * re-render if their specific props change.\n *\n * @see {@link https://react.dev/reference/react/Profiler#onrender-callback React Docs}\n */\n actualDuration: number,\n /**\n * The number of milliseconds estimating how much time it would take to re-render the entire\n * {@link Profiler} subtree without any optimizations. It is calculated by summing up the most\n * recent render durations of each component in the tree. This value estimates a worst-case\n * cost of rendering (e.g. the initial mount or a tree with no memoization). Compare\n * {@link actualDuration} against it to see if memoization is working.\n *\n * @see {@link https://react.dev/reference/react/Profiler#onrender-callback React Docs}\n */\n baseDuration: number,\n /**\n * A numeric timestamp for when React began rendering the current update.\n *\n * @see {@link https://react.dev/reference/react/Profiler#onrender-callback React Docs}\n */\n startTime: number,\n /**\n * A numeric timestamp for when React committed the current update. This value is shared\n * between all profilers in a commit, enabling them to be grouped if desirable.\n *\n * @see {@link https://react.dev/reference/react/Profiler#onrender-callback React Docs}\n */\n commitTime: number,\n ) => void;\n\n /**\n * The props accepted by {@link Profiler}.\n *\n * @see {@link https://react.dev/reference/react/Profiler React Docs}\n */\n interface ProfilerProps {\n children?: ReactNode | undefined;\n id: string;\n onRender: ProfilerOnRenderCallback;\n }\n\n /**\n * Lets you measure rendering performance of a React tree programmatically.\n *\n * @see {@link https://react.dev/reference/react/Profiler#onrender-callback React Docs}\n *\n * @example\n *\n * ```tsx\n * \n * \n * \n * ```\n */\n const Profiler: ExoticComponent;\n\n //\n // Component API\n // ----------------------------------------------------------------------\n\n type ReactInstance = Component | Element;\n\n // Base component for plain JS classes\n interface Component

extends ComponentLifecycle {}\n class Component {\n /**\n * If set, `this.context` will be set at runtime to the current value of the given Context.\n *\n * @example\n *\n * ```ts\n * type MyContext = number\n * const Ctx = React.createContext(0)\n *\n * class Foo extends React.Component {\n * static contextType = Ctx\n * context!: React.ContextType\n * render () {\n * return <>My context's value: {this.context};\n * }\n * }\n * ```\n *\n * @see {@link https://react.dev/reference/react/Component#static-contexttype}\n */\n static contextType?: Context | undefined;\n\n /**\n * If using the new style context, re-declare this in your class to be the\n * `React.ContextType` of your `static contextType`.\n * Should be used with type annotation or static contextType.\n *\n * @example\n * ```ts\n * static contextType = MyContext\n * // For TS pre-3.7:\n * context!: React.ContextType\n * // For TS 3.7 and above:\n * declare context: React.ContextType\n * ```\n *\n * @see {@link https://react.dev/reference/react/Component#context React Docs}\n */\n context: unknown;\n\n constructor(props: P);\n /**\n * @deprecated\n * @see {@link https://legacy.reactjs.org/docs/legacy-context.html React Docs}\n */\n constructor(props: P, context: any);\n\n // We MUST keep setState() as a unified signature because it allows proper checking of the method return type.\n // See: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/18365#issuecomment-351013257\n // Also, the ` | S` allows intellisense to not be dumbisense\n setState(\n state: ((prevState: Readonly, props: Readonly

) => Pick | S | null) | (Pick | S | null),\n callback?: () => void,\n ): void;\n\n forceUpdate(callback?: () => void): void;\n render(): ReactNode;\n\n readonly props: Readonly

;\n state: Readonly;\n /**\n * @deprecated\n *\n * @see {@link https://legacy.reactjs.org/docs/refs-and-the-dom.html#legacy-api-string-refs Legacy React Docs}\n */\n refs: {\n [key: string]: ReactInstance;\n };\n }\n\n class PureComponent

extends Component {}\n\n /**\n * @deprecated Use `ClassicComponent` from `create-react-class`\n *\n * @see {@link https://legacy.reactjs.org/docs/react-without-es6.html Legacy React Docs}\n * @see {@link https://www.npmjs.com/package/create-react-class `create-react-class` on npm}\n */\n interface ClassicComponent

extends Component {\n replaceState(nextState: S, callback?: () => void): void;\n isMounted(): boolean;\n getInitialState?(): S;\n }\n\n interface ChildContextProvider {\n getChildContext(): CC;\n }\n\n //\n // Class Interfaces\n // ----------------------------------------------------------------------\n\n /**\n * Represents the type of a function component. Can optionally\n * receive a type argument that represents the props the component\n * receives.\n *\n * @template P The props the component accepts.\n * @see {@link https://react-typescript-cheatsheet.netlify.app/docs/basic/getting-started/function_components React TypeScript Cheatsheet}\n * @alias for {@link FunctionComponent}\n *\n * @example\n *\n * ```tsx\n * // With props:\n * type Props = { name: string }\n *\n * const MyComponent: FC = (props) => {\n * return

{props.name}
\n * }\n * ```\n *\n * @example\n *\n * ```tsx\n * // Without props:\n * const MyComponentWithoutProps: FC = () => {\n * return
MyComponentWithoutProps
\n * }\n * ```\n */\n type FC

= FunctionComponent

;\n\n /**\n * Represents the type of a function component. Can optionally\n * receive a type argument that represents the props the component\n * accepts.\n *\n * @template P The props the component accepts.\n * @see {@link https://react-typescript-cheatsheet.netlify.app/docs/basic/getting-started/function_components React TypeScript Cheatsheet}\n *\n * @example\n *\n * ```tsx\n * // With props:\n * type Props = { name: string }\n *\n * const MyComponent: FunctionComponent = (props) => {\n * return

{props.name}
\n * }\n * ```\n *\n * @example\n *\n * ```tsx\n * // Without props:\n * const MyComponentWithoutProps: FunctionComponent = () => {\n * return
MyComponentWithoutProps
\n * }\n * ```\n */\n interface FunctionComponent

{\n (\n props: P,\n /**\n * @deprecated\n *\n * @see {@link https://legacy.reactjs.org/docs/legacy-context.html#referencing-context-in-lifecycle-methods React Docs}\n */\n deprecatedLegacyContext?: any,\n ): ReactNode;\n /**\n * Used to declare the types of the props accepted by the\n * component. These types will be checked during rendering\n * and in development only.\n *\n * We recommend using TypeScript instead of checking prop\n * types at runtime.\n *\n * @see {@link https://react.dev/reference/react/Component#static-proptypes React Docs}\n */\n propTypes?: WeakValidationMap

| undefined;\n /**\n * @deprecated\n *\n * Lets you specify which legacy context is consumed by\n * this component.\n *\n * @see {@link https://legacy.reactjs.org/docs/legacy-context.html Legacy React Docs}\n */\n contextTypes?: ValidationMap | undefined;\n /**\n * Used to define default values for the props accepted by\n * the component.\n *\n * @see {@link https://react.dev/reference/react/Component#static-defaultprops React Docs}\n *\n * @example\n *\n * ```tsx\n * type Props = { name?: string }\n *\n * const MyComponent: FC = (props) => {\n * return

{props.name}
\n * }\n *\n * MyComponent.defaultProps = {\n * name: 'John Doe'\n * }\n * ```\n *\n * @deprecated Use {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#default_value|default values for destructuring assignments instead}.\n */\n defaultProps?: Partial

| undefined;\n /**\n * Used in debugging messages. You might want to set it\n * explicitly if you want to display a different name for\n * debugging purposes.\n *\n * @see {@link https://legacy.reactjs.org/docs/react-component.html#displayname Legacy React Docs}\n *\n * @example\n *\n * ```tsx\n *\n * const MyComponent: FC = () => {\n * return

Hello!
\n * }\n *\n * MyComponent.displayName = 'MyAwesomeComponent'\n * ```\n */\n displayName?: string | undefined;\n }\n\n /**\n * @deprecated - Equivalent to {@link React.FunctionComponent}.\n *\n * @see {@link React.FunctionComponent}\n * @alias {@link VoidFunctionComponent}\n */\n type VFC

= VoidFunctionComponent

;\n\n /**\n * @deprecated - Equivalent to {@link React.FunctionComponent}.\n *\n * @see {@link React.FunctionComponent}\n */\n interface VoidFunctionComponent

{\n (\n props: P,\n /**\n * @deprecated\n *\n * @see {@link https://legacy.reactjs.org/docs/legacy-context.html#referencing-context-in-lifecycle-methods React Docs}\n */\n deprecatedLegacyContext?: any,\n ): ReactNode;\n propTypes?: WeakValidationMap

| undefined;\n contextTypes?: ValidationMap | undefined;\n /**\n * @deprecated Use {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#default_value|default values for destructuring assignments instead}.\n */\n defaultProps?: Partial

| undefined;\n displayName?: string | undefined;\n }\n\n /**\n * The type of the ref received by a {@link ForwardRefRenderFunction}.\n *\n * @see {@link ForwardRefRenderFunction}\n */\n type ForwardedRef = ((instance: T | null) => void) | MutableRefObject | null;\n\n /**\n * The type of the function passed to {@link forwardRef}. This is considered different\n * to a normal {@link FunctionComponent} because it receives an additional argument,\n *\n * @param props Props passed to the component, if any.\n * @param ref A ref forwarded to the component of type {@link ForwardedRef}.\n *\n * @template T The type of the forwarded ref.\n * @template P The type of the props the component accepts.\n *\n * @see {@link https://react-typescript-cheatsheet.netlify.app/docs/basic/getting-started/forward_and_create_ref/ React TypeScript Cheatsheet}\n * @see {@link forwardRef}\n */\n interface ForwardRefRenderFunction {\n (props: P, ref: ForwardedRef): ReactNode;\n /**\n * Used in debugging messages. You might want to set it\n * explicitly if you want to display a different name for\n * debugging purposes.\n *\n * Will show `ForwardRef(${Component.displayName || Component.name})`\n * in devtools by default, but can be given its own specific name.\n *\n * @see {@link https://legacy.reactjs.org/docs/react-component.html#displayname Legacy React Docs}\n */\n displayName?: string | undefined;\n /**\n * defaultProps are not supported on render functions passed to forwardRef.\n *\n * @see {@link https://github.com/microsoft/TypeScript/issues/36826 linked GitHub issue} for context\n * @see {@link https://react.dev/reference/react/Component#static-defaultprops React Docs}\n */\n defaultProps?: never | undefined;\n /**\n * propTypes are not supported on render functions passed to forwardRef.\n *\n * @see {@link https://github.com/microsoft/TypeScript/issues/36826 linked GitHub issue} for context\n * @see {@link https://react.dev/reference/react/Component#static-proptypes React Docs}\n */\n propTypes?: never | undefined;\n }\n\n /**\n * Represents a component class in React.\n *\n * @template P The props the component accepts.\n * @template S The internal state of the component.\n */\n interface ComponentClass

extends StaticLifecycle {\n new(\n props: P,\n /**\n * @deprecated\n *\n * @see {@link https://legacy.reactjs.org/docs/legacy-context.html#referencing-context-in-lifecycle-methods React Docs}\n */\n deprecatedLegacyContext?: any,\n ): Component;\n /**\n * Used to declare the types of the props accepted by the\n * component. These types will be checked during rendering\n * and in development only.\n *\n * We recommend using TypeScript instead of checking prop\n * types at runtime.\n *\n * @see {@link https://react.dev/reference/react/Component#static-proptypes React Docs}\n */\n propTypes?: WeakValidationMap

| undefined;\n contextType?: Context | undefined;\n /**\n * @deprecated use {@link ComponentClass.contextType} instead\n *\n * Lets you specify which legacy context is consumed by\n * this component.\n *\n * @see {@link https://legacy.reactjs.org/docs/legacy-context.html Legacy React Docs}\n */\n contextTypes?: ValidationMap | undefined;\n /**\n * @deprecated\n *\n * @see {@link https://legacy.reactjs.org/docs/legacy-context.html#how-to-use-context Legacy React Docs}\n */\n childContextTypes?: ValidationMap | undefined;\n /**\n * Used to define default values for the props accepted by\n * the component.\n *\n * @see {@link https://react.dev/reference/react/Component#static-defaultprops React Docs}\n */\n defaultProps?: Partial

| undefined;\n /**\n * Used in debugging messages. You might want to set it\n * explicitly if you want to display a different name for\n * debugging purposes.\n *\n * @see {@link https://legacy.reactjs.org/docs/react-component.html#displayname Legacy React Docs}\n */\n displayName?: string | undefined;\n }\n\n /**\n * @deprecated Use `ClassicComponentClass` from `create-react-class`\n *\n * @see {@link https://legacy.reactjs.org/docs/react-without-es6.html Legacy React Docs}\n * @see {@link https://www.npmjs.com/package/create-react-class `create-react-class` on npm}\n */\n interface ClassicComponentClass

extends ComponentClass

{\n new(props: P, deprecatedLegacyContext?: any): ClassicComponent;\n getDefaultProps?(): P;\n }\n\n /**\n * Used in {@link createElement} and {@link createFactory} to represent\n * a class.\n *\n * An intersection type is used to infer multiple type parameters from\n * a single argument, which is useful for many top-level API defs.\n * See {@link https://github.com/Microsoft/TypeScript/issues/7234 this GitHub issue}\n * for more info.\n */\n type ClassType, C extends ComponentClass

> =\n & C\n & (new(props: P, deprecatedLegacyContext?: any) => T);\n\n //\n // Component Specs and Lifecycle\n // ----------------------------------------------------------------------\n\n // This should actually be something like `Lifecycle | DeprecatedLifecycle`,\n // as React will _not_ call the deprecated lifecycle methods if any of the new lifecycle\n // methods are present.\n interface ComponentLifecycle extends NewLifecycle, DeprecatedLifecycle {\n /**\n * Called immediately after a component is mounted. Setting state here will trigger re-rendering.\n */\n componentDidMount?(): void;\n /**\n * Called to determine whether the change in props and state should trigger a re-render.\n *\n * `Component` always returns true.\n * `PureComponent` implements a shallow comparison on props and state and returns true if any\n * props or states have changed.\n *\n * If false is returned, {@link Component.render}, `componentWillUpdate`\n * and `componentDidUpdate` will not be called.\n */\n shouldComponentUpdate?(nextProps: Readonly

, nextState: Readonly, nextContext: any): boolean;\n /**\n * Called immediately before a component is destroyed. Perform any necessary cleanup in this method, such as\n * cancelled network requests, or cleaning up any DOM elements created in `componentDidMount`.\n */\n componentWillUnmount?(): void;\n /**\n * Catches exceptions generated in descendant components. Unhandled exceptions will cause\n * the entire component tree to unmount.\n */\n componentDidCatch?(error: Error, errorInfo: ErrorInfo): void;\n }\n\n // Unfortunately, we have no way of declaring that the component constructor must implement this\n interface StaticLifecycle {\n getDerivedStateFromProps?: GetDerivedStateFromProps | undefined;\n getDerivedStateFromError?: GetDerivedStateFromError | undefined;\n }\n\n type GetDerivedStateFromProps =\n /**\n * Returns an update to a component's state based on its new props and old state.\n *\n * Note: its presence prevents any of the deprecated lifecycle methods from being invoked\n */\n (nextProps: Readonly

, prevState: S) => Partial | null;\n\n type GetDerivedStateFromError =\n /**\n * This lifecycle is invoked after an error has been thrown by a descendant component.\n * It receives the error that was thrown as a parameter and should return a value to update state.\n *\n * Note: its presence prevents any of the deprecated lifecycle methods from being invoked\n */\n (error: any) => Partial | null;\n\n // This should be \"infer SS\" but can't use it yet\n interface NewLifecycle {\n /**\n * Runs before React applies the result of {@link Component.render render} to the document, and\n * returns an object to be given to {@link componentDidUpdate}. Useful for saving\n * things such as scroll position before {@link Component.render render} causes changes to it.\n *\n * Note: the presence of this method prevents any of the deprecated\n * lifecycle events from running.\n */\n getSnapshotBeforeUpdate?(prevProps: Readonly

, prevState: Readonly): SS | null;\n /**\n * Called immediately after updating occurs. Not called for the initial render.\n *\n * The snapshot is only present if {@link getSnapshotBeforeUpdate} is present and returns non-null.\n */\n componentDidUpdate?(prevProps: Readonly

, prevState: Readonly, snapshot?: SS): void;\n }\n\n interface DeprecatedLifecycle {\n /**\n * Called immediately before mounting occurs, and before {@link Component.render}.\n * Avoid introducing any side-effects or subscriptions in this method.\n *\n * Note: the presence of {@link NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate}\n * or {@link StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps} prevents\n * this from being invoked.\n *\n * @deprecated 16.3, use {@link ComponentLifecycle.componentDidMount componentDidMount} or the constructor instead; will stop working in React 17\n * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#initializing-state}\n * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#gradual-migration-path}\n */\n componentWillMount?(): void;\n /**\n * Called immediately before mounting occurs, and before {@link Component.render}.\n * Avoid introducing any side-effects or subscriptions in this method.\n *\n * This method will not stop working in React 17.\n *\n * Note: the presence of {@link NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate}\n * or {@link StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps} prevents\n * this from being invoked.\n *\n * @deprecated 16.3, use {@link ComponentLifecycle.componentDidMount componentDidMount} or the constructor instead\n * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#initializing-state}\n * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#gradual-migration-path}\n */\n UNSAFE_componentWillMount?(): void;\n /**\n * Called when the component may be receiving new props.\n * React may call this even if props have not changed, so be sure to compare new and existing\n * props if you only want to handle changes.\n *\n * Calling {@link Component.setState} generally does not trigger this method.\n *\n * Note: the presence of {@link NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate}\n * or {@link StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps} prevents\n * this from being invoked.\n *\n * @deprecated 16.3, use static {@link StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps} instead; will stop working in React 17\n * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#updating-state-based-on-props}\n * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#gradual-migration-path}\n */\n componentWillReceiveProps?(nextProps: Readonly

, nextContext: any): void;\n /**\n * Called when the component may be receiving new props.\n * React may call this even if props have not changed, so be sure to compare new and existing\n * props if you only want to handle changes.\n *\n * Calling {@link Component.setState} generally does not trigger this method.\n *\n * This method will not stop working in React 17.\n *\n * Note: the presence of {@link NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate}\n * or {@link StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps} prevents\n * this from being invoked.\n *\n * @deprecated 16.3, use static {@link StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps} instead\n * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#updating-state-based-on-props}\n * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#gradual-migration-path}\n */\n UNSAFE_componentWillReceiveProps?(nextProps: Readonly

, nextContext: any): void;\n /**\n * Called immediately before rendering when new props or state is received. Not called for the initial render.\n *\n * Note: You cannot call {@link Component.setState} here.\n *\n * Note: the presence of {@link NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate}\n * or {@link StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps} prevents\n * this from being invoked.\n *\n * @deprecated 16.3, use getSnapshotBeforeUpdate instead; will stop working in React 17\n * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#reading-dom-properties-before-an-update}\n * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#gradual-migration-path}\n */\n componentWillUpdate?(nextProps: Readonly

, nextState: Readonly, nextContext: any): void;\n /**\n * Called immediately before rendering when new props or state is received. Not called for the initial render.\n *\n * Note: You cannot call {@link Component.setState} here.\n *\n * This method will not stop working in React 17.\n *\n * Note: the presence of {@link NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate}\n * or {@link StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps} prevents\n * this from being invoked.\n *\n * @deprecated 16.3, use getSnapshotBeforeUpdate instead\n * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#reading-dom-properties-before-an-update}\n * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#gradual-migration-path}\n */\n UNSAFE_componentWillUpdate?(nextProps: Readonly

, nextState: Readonly, nextContext: any): void;\n }\n\n /**\n * @deprecated\n *\n * @see {@link https://legacy.reactjs.org/blog/2016/07/13/mixins-considered-harmful.html Mixins Considered Harmful}\n */\n interface Mixin extends ComponentLifecycle {\n mixins?: Array> | undefined;\n statics?: {\n [key: string]: any;\n } | undefined;\n\n displayName?: string | undefined;\n propTypes?: ValidationMap | undefined;\n contextTypes?: ValidationMap | undefined;\n childContextTypes?: ValidationMap | undefined;\n\n getDefaultProps?(): P;\n getInitialState?(): S;\n }\n\n /**\n * @deprecated\n *\n * @see {@link https://legacy.reactjs.org/blog/2016/07/13/mixins-considered-harmful.html Mixins Considered Harmful}\n */\n interface ComponentSpec extends Mixin {\n render(): ReactNode;\n\n [propertyName: string]: any;\n }\n\n function createRef(): RefObject;\n\n /**\n * The type of the component returned from {@link forwardRef}.\n *\n * @template P The props the component accepts, if any.\n *\n * @see {@link ExoticComponent}\n */\n interface ForwardRefExoticComponent

extends NamedExoticComponent

{\n /**\n * @deprecated Use {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#default_value|default values for destructuring assignments instead}.\n */\n defaultProps?: Partial

| undefined;\n propTypes?: WeakValidationMap

| undefined;\n }\n\n /**\n * Lets your component expose a DOM node to a parent component\n * using a ref.\n *\n * @see {@link https://react.dev/reference/react/forwardRef React Docs}\n * @see {@link https://react-typescript-cheatsheet.netlify.app/docs/basic/getting-started/forward_and_create_ref/ React TypeScript Cheatsheet}\n *\n * @param render See the {@link ForwardRefRenderFunction}.\n *\n * @template T The type of the DOM node.\n * @template P The props the component accepts, if any.\n *\n * @example\n *\n * ```tsx\n * interface Props {\n * children?: ReactNode;\n * type: \"submit\" | \"button\";\n * }\n *\n * export const FancyButton = forwardRef((props, ref) => (\n * \n * ));\n * ```\n */\n function forwardRef(\n render: ForwardRefRenderFunction>,\n ): ForwardRefExoticComponent & RefAttributes>;\n\n /**\n * Omits the 'ref' attribute from the given props object.\n *\n * @template P The props object type.\n */\n type PropsWithoutRef

=\n // Omit would not be sufficient for this. We'd like to avoid unnecessary mapping and need a distributive conditional to support unions.\n // see: https://www.typescriptlang.org/docs/handbook/2/conditional-types.html#distributive-conditional-types\n // https://github.com/Microsoft/TypeScript/issues/28339\n P extends any ? (\"ref\" extends keyof P ? Omit : P) : P;\n /** Ensures that the props do not include string ref, which cannot be forwarded */\n type PropsWithRef

=\n // Note: String refs can be forwarded. We can't fix this bug without breaking a bunch of libraries now though.\n // Just \"P extends { ref?: infer R }\" looks sufficient, but R will infer as {} if P is {}.\n \"ref\" extends keyof P\n ? P extends { ref?: infer R | undefined }\n ? string extends R ? PropsWithoutRef

& { ref?: Exclude | undefined }\n : P\n : P\n : P;\n\n type PropsWithChildren

= P & { children?: ReactNode | undefined };\n\n /**\n * Used to retrieve the props a component accepts. Can either be passed a string,\n * indicating a DOM element (e.g. 'div', 'span', etc.) or the type of a React\n * component.\n *\n * It's usually better to use {@link ComponentPropsWithRef} or {@link ComponentPropsWithoutRef}\n * instead of this type, as they let you be explicit about whether or not to include\n * the `ref` prop.\n *\n * @see {@link https://react-typescript-cheatsheet.netlify.app/docs/react-types/componentprops/ React TypeScript Cheatsheet}\n *\n * @example\n *\n * ```tsx\n * // Retrieves the props an 'input' element accepts\n * type InputProps = React.ComponentProps<'input'>;\n * ```\n *\n * @example\n *\n * ```tsx\n * const MyComponent = (props: { foo: number, bar: string }) =>

;\n *\n * // Retrieves the props 'MyComponent' accepts\n * type MyComponentProps = React.ComponentProps;\n * ```\n */\n type ComponentProps> = T extends\n JSXElementConstructor ? P\n : T extends keyof JSX.IntrinsicElements ? JSX.IntrinsicElements[T]\n : {};\n\n /**\n * Used to retrieve the props a component accepts with its ref. Can either be\n * passed a string, indicating a DOM element (e.g. 'div', 'span', etc.) or the\n * type of a React component.\n *\n * @see {@link https://react-typescript-cheatsheet.netlify.app/docs/react-types/componentprops/ React TypeScript Cheatsheet}\n *\n * @example\n *\n * ```tsx\n * // Retrieves the props an 'input' element accepts\n * type InputProps = React.ComponentPropsWithRef<'input'>;\n * ```\n *\n * @example\n *\n * ```tsx\n * const MyComponent = (props: { foo: number, bar: string }) =>
;\n *\n * // Retrieves the props 'MyComponent' accepts\n * type MyComponentPropsWithRef = React.ComponentPropsWithRef;\n * ```\n */\n type ComponentPropsWithRef = T extends (new(props: infer P) => Component)\n ? PropsWithoutRef

& RefAttributes>\n : PropsWithRef>;\n /**\n * Used to retrieve the props a custom component accepts with its ref.\n *\n * Unlike {@link ComponentPropsWithRef}, this only works with custom\n * components, i.e. components you define yourself. This is to improve\n * type-checking performance.\n *\n * @example\n *\n * ```tsx\n * const MyComponent = (props: { foo: number, bar: string }) =>

;\n *\n * // Retrieves the props 'MyComponent' accepts\n * type MyComponentPropsWithRef = React.CustomComponentPropsWithRef;\n * ```\n */\n type CustomComponentPropsWithRef = T extends (new(props: infer P) => Component)\n ? (PropsWithoutRef

& RefAttributes>)\n : T extends ((props: infer P, legacyContext?: any) => ReactNode) ? PropsWithRef

\n : never;\n\n /**\n * Used to retrieve the props a component accepts without its ref. Can either be\n * passed a string, indicating a DOM element (e.g. 'div', 'span', etc.) or the\n * type of a React component.\n *\n * @see {@link https://react-typescript-cheatsheet.netlify.app/docs/react-types/componentprops/ React TypeScript Cheatsheet}\n *\n * @example\n *\n * ```tsx\n * // Retrieves the props an 'input' element accepts\n * type InputProps = React.ComponentPropsWithoutRef<'input'>;\n * ```\n *\n * @example\n *\n * ```tsx\n * const MyComponent = (props: { foo: number, bar: string }) =>

;\n *\n * // Retrieves the props 'MyComponent' accepts\n * type MyComponentPropsWithoutRef = React.ComponentPropsWithoutRef;\n * ```\n */\n type ComponentPropsWithoutRef = PropsWithoutRef>;\n\n type ComponentRef = T extends NamedExoticComponent<\n ComponentPropsWithoutRef & RefAttributes\n > ? Method\n : ComponentPropsWithRef extends RefAttributes ? Method\n : never;\n\n // will show `Memo(${Component.displayName || Component.name})` in devtools by default,\n // but can be given its own specific name\n type MemoExoticComponent> = NamedExoticComponent> & {\n readonly type: T;\n };\n\n /**\n * Lets you skip re-rendering a component when its props are unchanged.\n *\n * @see {@link https://react.dev/reference/react/memo React Docs}\n *\n * @param Component The component to memoize.\n * @param propsAreEqual A function that will be used to determine if the props have changed.\n *\n * @example\n *\n * ```tsx\n * import { memo } from 'react';\n *\n * const SomeComponent = memo(function SomeComponent(props: { foo: string }) {\n * // ...\n * });\n * ```\n */\n function memo

(\n Component: FunctionComponent

,\n propsAreEqual?: (prevProps: Readonly

, nextProps: Readonly

) => boolean,\n ): NamedExoticComponent

;\n function memo>(\n Component: T,\n propsAreEqual?: (prevProps: Readonly>, nextProps: Readonly>) => boolean,\n ): MemoExoticComponent;\n\n interface LazyExoticComponent>\n extends ExoticComponent>\n {\n readonly _result: T;\n }\n\n /**\n * Lets you defer loading a component’s code until it is rendered for the first time.\n *\n * @see {@link https://react.dev/reference/react/lazy React Docs}\n *\n * @param load A function that returns a `Promise` or another thenable (a `Promise`-like object with a\n * then method). React will not call `load` until the first time you attempt to render the returned\n * component. After React first calls load, it will wait for it to resolve, and then render the\n * resolved value’s `.default` as a React component. Both the returned `Promise` and the `Promise`’s\n * resolved value will be cached, so React will not call load more than once. If the `Promise` rejects,\n * React will throw the rejection reason for the nearest Error Boundary to handle.\n *\n * @example\n *\n * ```tsx\n * import { lazy } from 'react';\n *\n * const MarkdownPreview = lazy(() => import('./MarkdownPreview.js'));\n * ```\n */\n function lazy>(\n load: () => Promise<{ default: T }>,\n ): LazyExoticComponent;\n\n //\n // React Hooks\n // ----------------------------------------------------------------------\n\n /**\n * The instruction passed to a {@link Dispatch} function in {@link useState}\n * to tell React what the next value of the {@link useState} should be.\n *\n * Often found wrapped in {@link Dispatch}.\n *\n * @template S The type of the state.\n *\n * @example\n *\n * ```tsx\n * // This return type correctly represents the type of\n * // `setCount` in the example below.\n * const useCustomState = (): Dispatch> => {\n * const [count, setCount] = useState(0);\n *\n * return setCount;\n * }\n * ```\n */\n type SetStateAction = S | ((prevState: S) => S);\n\n /**\n * A function that can be used to update the state of a {@link useState}\n * or {@link useReducer} hook.\n */\n type Dispatch = (value: A) => void;\n /**\n * A {@link Dispatch} function can sometimes be called without any arguments.\n */\n type DispatchWithoutAction = () => void;\n // Unlike redux, the actions _can_ be anything\n type Reducer = (prevState: S, action: A) => S;\n // If useReducer accepts a reducer without action, dispatch may be called without any parameters.\n type ReducerWithoutAction = (prevState: S) => S;\n // types used to try and prevent the compiler from reducing S\n // to a supertype common with the second argument to useReducer()\n type ReducerState> = R extends Reducer ? S : never;\n type ReducerAction> = R extends Reducer ? A : never;\n // The identity check is done with the SameValue algorithm (Object.is), which is stricter than ===\n type ReducerStateWithoutAction> = R extends ReducerWithoutAction ? S\n : never;\n type DependencyList = readonly unknown[];\n\n // NOTE: callbacks are _only_ allowed to return either void, or a destructor.\n type EffectCallback = () => void | Destructor;\n\n interface MutableRefObject {\n current: T;\n }\n\n // This will technically work if you give a Consumer or Provider but it's deprecated and warns\n /**\n * Accepts a context object (the value returned from `React.createContext`) and returns the current\n * context value, as given by the nearest context provider for the given context.\n *\n * @version 16.8.0\n * @see {@link https://react.dev/reference/react/useContext}\n */\n function useContext(context: Context /*, (not public API) observedBits?: number|boolean */): T;\n /**\n * Returns a stateful value, and a function to update it.\n *\n * @version 16.8.0\n * @see {@link https://react.dev/reference/react/useState}\n */\n function useState(initialState: S | (() => S)): [S, Dispatch>];\n // convenience overload when first argument is omitted\n /**\n * Returns a stateful value, and a function to update it.\n *\n * @version 16.8.0\n * @see {@link https://react.dev/reference/react/useState}\n */\n function useState(): [S | undefined, Dispatch>];\n /**\n * An alternative to `useState`.\n *\n * `useReducer` is usually preferable to `useState` when you have complex state logic that involves\n * multiple sub-values. It also lets you optimize performance for components that trigger deep\n * updates because you can pass `dispatch` down instead of callbacks.\n *\n * @version 16.8.0\n * @see {@link https://react.dev/reference/react/useReducer}\n */\n // overload where dispatch could accept 0 arguments.\n function useReducer, I>(\n reducer: R,\n initializerArg: I,\n initializer: (arg: I) => ReducerStateWithoutAction,\n ): [ReducerStateWithoutAction, DispatchWithoutAction];\n /**\n * An alternative to `useState`.\n *\n * `useReducer` is usually preferable to `useState` when you have complex state logic that involves\n * multiple sub-values. It also lets you optimize performance for components that trigger deep\n * updates because you can pass `dispatch` down instead of callbacks.\n *\n * @version 16.8.0\n * @see {@link https://react.dev/reference/react/useReducer}\n */\n // overload where dispatch could accept 0 arguments.\n function useReducer>(\n reducer: R,\n initializerArg: ReducerStateWithoutAction,\n initializer?: undefined,\n ): [ReducerStateWithoutAction, DispatchWithoutAction];\n /**\n * An alternative to `useState`.\n *\n * `useReducer` is usually preferable to `useState` when you have complex state logic that involves\n * multiple sub-values. It also lets you optimize performance for components that trigger deep\n * updates because you can pass `dispatch` down instead of callbacks.\n *\n * @version 16.8.0\n * @see {@link https://react.dev/reference/react/useReducer}\n */\n // overload where \"I\" may be a subset of ReducerState; used to provide autocompletion.\n // If \"I\" matches ReducerState exactly then the last overload will allow initializer to be omitted.\n // the last overload effectively behaves as if the identity function (x => x) is the initializer.\n function useReducer, I>(\n reducer: R,\n initializerArg: I & ReducerState,\n initializer: (arg: I & ReducerState) => ReducerState,\n ): [ReducerState, Dispatch>];\n /**\n * An alternative to `useState`.\n *\n * `useReducer` is usually preferable to `useState` when you have complex state logic that involves\n * multiple sub-values. It also lets you optimize performance for components that trigger deep\n * updates because you can pass `dispatch` down instead of callbacks.\n *\n * @version 16.8.0\n * @see {@link https://react.dev/reference/react/useReducer}\n */\n // overload for free \"I\"; all goes as long as initializer converts it into \"ReducerState\".\n function useReducer, I>(\n reducer: R,\n initializerArg: I,\n initializer: (arg: I) => ReducerState,\n ): [ReducerState, Dispatch>];\n /**\n * An alternative to `useState`.\n *\n * `useReducer` is usually preferable to `useState` when you have complex state logic that involves\n * multiple sub-values. It also lets you optimize performance for components that trigger deep\n * updates because you can pass `dispatch` down instead of callbacks.\n *\n * @version 16.8.0\n * @see {@link https://react.dev/reference/react/useReducer}\n */\n\n // I'm not sure if I keep this 2-ary or if I make it (2,3)-ary; it's currently (2,3)-ary.\n // The Flow types do have an overload for 3-ary invocation with undefined initializer.\n\n // NOTE: without the ReducerState indirection, TypeScript would reduce S to be the most common\n // supertype between the reducer's return type and the initialState (or the initializer's return type),\n // which would prevent autocompletion from ever working.\n\n // TODO: double-check if this weird overload logic is necessary. It is possible it's either a bug\n // in older versions, or a regression in newer versions of the typescript completion service.\n function useReducer>(\n reducer: R,\n initialState: ReducerState,\n initializer?: undefined,\n ): [ReducerState, Dispatch>];\n /**\n * `useRef` returns a mutable ref object whose `.current` property is initialized to the passed argument\n * (`initialValue`). The returned object will persist for the full lifetime of the component.\n *\n * Note that `useRef()` is useful for more than the `ref` attribute. It’s handy for keeping any mutable\n * value around similar to how you’d use instance fields in classes.\n *\n * @version 16.8.0\n * @see {@link https://react.dev/reference/react/useRef}\n */\n function useRef(initialValue: T): MutableRefObject;\n // convenience overload for refs given as a ref prop as they typically start with a null value\n /**\n * `useRef` returns a mutable ref object whose `.current` property is initialized to the passed argument\n * (`initialValue`). The returned object will persist for the full lifetime of the component.\n *\n * Note that `useRef()` is useful for more than the `ref` attribute. It’s handy for keeping any mutable\n * value around similar to how you’d use instance fields in classes.\n *\n * Usage note: if you need the result of useRef to be directly mutable, include `| null` in the type\n * of the generic argument.\n *\n * @version 16.8.0\n * @see {@link https://react.dev/reference/react/useRef}\n */\n function useRef(initialValue: T | null): RefObject;\n // convenience overload for potentially undefined initialValue / call with 0 arguments\n // has a default to stop it from defaulting to {} instead\n /**\n * `useRef` returns a mutable ref object whose `.current` property is initialized to the passed argument\n * (`initialValue`). The returned object will persist for the full lifetime of the component.\n *\n * Note that `useRef()` is useful for more than the `ref` attribute. It’s handy for keeping any mutable\n * value around similar to how you’d use instance fields in classes.\n *\n * @version 16.8.0\n * @see {@link https://react.dev/reference/react/useRef}\n */\n function useRef(initialValue?: undefined): MutableRefObject;\n /**\n * The signature is identical to `useEffect`, but it fires synchronously after all DOM mutations.\n * Use this to read layout from the DOM and synchronously re-render. Updates scheduled inside\n * `useLayoutEffect` will be flushed synchronously, before the browser has a chance to paint.\n *\n * Prefer the standard `useEffect` when possible to avoid blocking visual updates.\n *\n * If you’re migrating code from a class component, `useLayoutEffect` fires in the same phase as\n * `componentDidMount` and `componentDidUpdate`.\n *\n * @version 16.8.0\n * @see {@link https://react.dev/reference/react/useLayoutEffect}\n */\n function useLayoutEffect(effect: EffectCallback, deps?: DependencyList): void;\n /**\n * Accepts a function that contains imperative, possibly effectful code.\n *\n * @param effect Imperative function that can return a cleanup function\n * @param deps If present, effect will only activate if the values in the list change.\n *\n * @version 16.8.0\n * @see {@link https://react.dev/reference/react/useEffect}\n */\n function useEffect(effect: EffectCallback, deps?: DependencyList): void;\n // NOTE: this does not accept strings, but this will have to be fixed by removing strings from type Ref\n /**\n * `useImperativeHandle` customizes the instance value that is exposed to parent components when using\n * `ref`. As always, imperative code using refs should be avoided in most cases.\n *\n * `useImperativeHandle` should be used with `React.forwardRef`.\n *\n * @version 16.8.0\n * @see {@link https://react.dev/reference/react/useImperativeHandle}\n */\n function useImperativeHandle(ref: Ref | undefined, init: () => R, deps?: DependencyList): void;\n // I made 'inputs' required here and in useMemo as there's no point to memoizing without the memoization key\n // useCallback(X) is identical to just using X, useMemo(() => Y) is identical to just using Y.\n /**\n * `useCallback` will return a memoized version of the callback that only changes if one of the `inputs`\n * has changed.\n *\n * @version 16.8.0\n * @see {@link https://react.dev/reference/react/useCallback}\n */\n // A specific function type would not trigger implicit any.\n // See https://github.com/DefinitelyTyped/DefinitelyTyped/issues/52873#issuecomment-845806435 for a comparison between `Function` and more specific types.\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n function useCallback(callback: T, deps: DependencyList): T;\n /**\n * `useMemo` will only recompute the memoized value when one of the `deps` has changed.\n *\n * @version 16.8.0\n * @see {@link https://react.dev/reference/react/useMemo}\n */\n // allow undefined, but don't make it optional as that is very likely a mistake\n function useMemo(factory: () => T, deps: DependencyList): T;\n /**\n * `useDebugValue` can be used to display a label for custom hooks in React DevTools.\n *\n * NOTE: We don’t recommend adding debug values to every custom hook.\n * It’s most valuable for custom hooks that are part of shared libraries.\n *\n * @version 16.8.0\n * @see {@link https://react.dev/reference/react/useDebugValue}\n */\n // the name of the custom hook is itself derived from the function name at runtime:\n // it's just the function name without the \"use\" prefix.\n function useDebugValue(value: T, format?: (value: T) => any): void;\n\n // must be synchronous\n export type TransitionFunction = () => VoidOrUndefinedOnly;\n // strange definition to allow vscode to show documentation on the invocation\n export interface TransitionStartFunction {\n /**\n * State updates caused inside the callback are allowed to be deferred.\n *\n * **If some state update causes a component to suspend, that state update should be wrapped in a transition.**\n *\n * @param callback A _synchronous_ function which causes state updates that can be deferred.\n */\n (callback: TransitionFunction): void;\n }\n\n /**\n * Returns a deferred version of the value that may “lag behind” it.\n *\n * This is commonly used to keep the interface responsive when you have something that renders immediately\n * based on user input and something that needs to wait for a data fetch.\n *\n * A good example of this is a text input.\n *\n * @param value The value that is going to be deferred\n *\n * @see {@link https://react.dev/reference/react/useDeferredValue}\n */\n export function useDeferredValue(value: T): T;\n\n /**\n * Allows components to avoid undesirable loading states by waiting for content to load\n * before transitioning to the next screen. It also allows components to defer slower,\n * data fetching updates until subsequent renders so that more crucial updates can be\n * rendered immediately.\n *\n * The `useTransition` hook returns two values in an array.\n *\n * The first is a boolean, React’s way of informing us whether we’re waiting for the transition to finish.\n * The second is a function that takes a callback. We can use it to tell React which state we want to defer.\n *\n * **If some state update causes a component to suspend, that state update should be wrapped in a transition.**\n *\n * @see {@link https://react.dev/reference/react/useTransition}\n */\n export function useTransition(): [boolean, TransitionStartFunction];\n\n /**\n * Similar to `useTransition` but allows uses where hooks are not available.\n *\n * @param callback A _synchronous_ function which causes state updates that can be deferred.\n */\n export function startTransition(scope: TransitionFunction): void;\n\n /**\n * Wrap any code rendering and triggering updates to your components into `act()` calls.\n *\n * Ensures that the behavior in your tests matches what happens in the browser\n * more closely by executing pending `useEffect`s before returning. This also\n * reduces the amount of re-renders done.\n *\n * @param callback A synchronous, void callback that will execute as a single, complete React commit.\n *\n * @see https://reactjs.org/blog/2019/02/06/react-v16.8.0.html#testing-hooks\n */\n // While act does always return Thenable, if a void function is passed, we pretend the return value is also void to not trigger dangling Promise lint rules.\n export function act(callback: () => VoidOrUndefinedOnly): void;\n export function act(callback: () => T | Promise): Promise;\n\n export function useId(): string;\n\n /**\n * @param effect Imperative function that can return a cleanup function\n * @param deps If present, effect will only activate if the values in the list change.\n *\n * @see {@link https://github.com/facebook/react/pull/21913}\n */\n export function useInsertionEffect(effect: EffectCallback, deps?: DependencyList): void;\n\n /**\n * @param subscribe\n * @param getSnapshot\n *\n * @see {@link https://github.com/reactwg/react-18/discussions/86}\n */\n // keep in sync with `useSyncExternalStore` from `use-sync-external-store`\n export function useSyncExternalStore(\n subscribe: (onStoreChange: () => void) => () => void,\n getSnapshot: () => Snapshot,\n getServerSnapshot?: () => Snapshot,\n ): Snapshot;\n\n //\n // Event System\n // ----------------------------------------------------------------------\n // TODO: change any to unknown when moving to TS v3\n interface BaseSyntheticEvent {\n nativeEvent: E;\n currentTarget: C;\n target: T;\n bubbles: boolean;\n cancelable: boolean;\n defaultPrevented: boolean;\n eventPhase: number;\n isTrusted: boolean;\n preventDefault(): void;\n isDefaultPrevented(): boolean;\n stopPropagation(): void;\n isPropagationStopped(): boolean;\n persist(): void;\n timeStamp: number;\n type: string;\n }\n\n /**\n * currentTarget - a reference to the element on which the event listener is registered.\n *\n * target - a reference to the element from which the event was originally dispatched.\n * This might be a child element to the element on which the event listener is registered.\n * If you thought this should be `EventTarget & T`, see https://github.com/DefinitelyTyped/DefinitelyTyped/issues/11508#issuecomment-256045682\n */\n interface SyntheticEvent extends BaseSyntheticEvent {}\n\n interface ClipboardEvent extends SyntheticEvent {\n clipboardData: DataTransfer;\n }\n\n interface CompositionEvent extends SyntheticEvent {\n data: string;\n }\n\n interface DragEvent extends MouseEvent {\n dataTransfer: DataTransfer;\n }\n\n interface PointerEvent extends MouseEvent {\n pointerId: number;\n pressure: number;\n tangentialPressure: number;\n tiltX: number;\n tiltY: number;\n twist: number;\n width: number;\n height: number;\n pointerType: \"mouse\" | \"pen\" | \"touch\";\n isPrimary: boolean;\n }\n\n interface FocusEvent extends SyntheticEvent {\n relatedTarget: (EventTarget & RelatedTarget) | null;\n target: EventTarget & Target;\n }\n\n interface FormEvent extends SyntheticEvent {\n }\n\n interface InvalidEvent extends SyntheticEvent {\n target: EventTarget & T;\n }\n\n interface ChangeEvent extends SyntheticEvent {\n target: EventTarget & T;\n }\n\n interface InputEvent extends SyntheticEvent {\n data: string;\n }\n\n export type ModifierKey =\n | \"Alt\"\n | \"AltGraph\"\n | \"CapsLock\"\n | \"Control\"\n | \"Fn\"\n | \"FnLock\"\n | \"Hyper\"\n | \"Meta\"\n | \"NumLock\"\n | \"ScrollLock\"\n | \"Shift\"\n | \"Super\"\n | \"Symbol\"\n | \"SymbolLock\";\n\n interface KeyboardEvent extends UIEvent {\n altKey: boolean;\n /** @deprecated */\n charCode: number;\n ctrlKey: boolean;\n code: string;\n /**\n * See [DOM Level 3 Events spec](https://www.w3.org/TR/uievents-key/#keys-modifier). for a list of valid (case-sensitive) arguments to this method.\n */\n getModifierState(key: ModifierKey): boolean;\n /**\n * See the [DOM Level 3 Events spec](https://www.w3.org/TR/uievents-key/#named-key-attribute-values). for possible values\n */\n key: string;\n /** @deprecated */\n keyCode: number;\n locale: string;\n location: number;\n metaKey: boolean;\n repeat: boolean;\n shiftKey: boolean;\n /** @deprecated */\n which: number;\n }\n\n interface MouseEvent extends UIEvent {\n altKey: boolean;\n button: number;\n buttons: number;\n clientX: number;\n clientY: number;\n ctrlKey: boolean;\n /**\n * See [DOM Level 3 Events spec](https://www.w3.org/TR/uievents-key/#keys-modifier). for a list of valid (case-sensitive) arguments to this method.\n */\n getModifierState(key: ModifierKey): boolean;\n metaKey: boolean;\n movementX: number;\n movementY: number;\n pageX: number;\n pageY: number;\n relatedTarget: EventTarget | null;\n screenX: number;\n screenY: number;\n shiftKey: boolean;\n }\n\n interface TouchEvent extends UIEvent {\n altKey: boolean;\n changedTouches: TouchList;\n ctrlKey: boolean;\n /**\n * See [DOM Level 3 Events spec](https://www.w3.org/TR/uievents-key/#keys-modifier). for a list of valid (case-sensitive) arguments to this method.\n */\n getModifierState(key: ModifierKey): boolean;\n metaKey: boolean;\n shiftKey: boolean;\n targetTouches: TouchList;\n touches: TouchList;\n }\n\n interface UIEvent extends SyntheticEvent {\n detail: number;\n view: AbstractView;\n }\n\n interface WheelEvent extends MouseEvent {\n deltaMode: number;\n deltaX: number;\n deltaY: number;\n deltaZ: number;\n }\n\n interface AnimationEvent extends SyntheticEvent {\n animationName: string;\n elapsedTime: number;\n pseudoElement: string;\n }\n\n interface TransitionEvent extends SyntheticEvent {\n elapsedTime: number;\n propertyName: string;\n pseudoElement: string;\n }\n\n //\n // Event Handler Types\n // ----------------------------------------------------------------------\n\n type EventHandler> = { bivarianceHack(event: E): void }[\"bivarianceHack\"];\n\n type ReactEventHandler = EventHandler>;\n\n type ClipboardEventHandler = EventHandler>;\n type CompositionEventHandler = EventHandler>;\n type DragEventHandler = EventHandler>;\n type FocusEventHandler = EventHandler>;\n type FormEventHandler = EventHandler>;\n type ChangeEventHandler = EventHandler>;\n type InputEventHandler = EventHandler>;\n type KeyboardEventHandler = EventHandler>;\n type MouseEventHandler = EventHandler>;\n type TouchEventHandler = EventHandler>;\n type PointerEventHandler = EventHandler>;\n type UIEventHandler = EventHandler>;\n type WheelEventHandler = EventHandler>;\n type AnimationEventHandler = EventHandler>;\n type TransitionEventHandler = EventHandler>;\n\n //\n // Props / DOM Attributes\n // ----------------------------------------------------------------------\n\n interface HTMLProps extends AllHTMLAttributes, ClassAttributes {\n }\n\n type DetailedHTMLProps, T> = ClassAttributes & E;\n\n interface SVGProps extends SVGAttributes, ClassAttributes {\n }\n\n interface SVGLineElementAttributes extends SVGProps {}\n interface SVGTextElementAttributes extends SVGProps {}\n\n interface DOMAttributes {\n children?: ReactNode | undefined;\n dangerouslySetInnerHTML?: {\n // Should be InnerHTML['innerHTML'].\n // But unfortunately we're mixing renderer-specific type declarations.\n __html: string | TrustedHTML;\n } | undefined;\n\n // Clipboard Events\n onCopy?: ClipboardEventHandler | undefined;\n onCopyCapture?: ClipboardEventHandler | undefined;\n onCut?: ClipboardEventHandler | undefined;\n onCutCapture?: ClipboardEventHandler | undefined;\n onPaste?: ClipboardEventHandler | undefined;\n onPasteCapture?: ClipboardEventHandler | undefined;\n\n // Composition Events\n onCompositionEnd?: CompositionEventHandler | undefined;\n onCompositionEndCapture?: CompositionEventHandler | undefined;\n onCompositionStart?: CompositionEventHandler | undefined;\n onCompositionStartCapture?: CompositionEventHandler | undefined;\n onCompositionUpdate?: CompositionEventHandler | undefined;\n onCompositionUpdateCapture?: CompositionEventHandler | undefined;\n\n // Focus Events\n onFocus?: FocusEventHandler | undefined;\n onFocusCapture?: FocusEventHandler | undefined;\n onBlur?: FocusEventHandler | undefined;\n onBlurCapture?: FocusEventHandler | undefined;\n\n // Form Events\n onChange?: FormEventHandler | undefined;\n onChangeCapture?: FormEventHandler | undefined;\n onBeforeInput?: InputEventHandler | undefined;\n onBeforeInputCapture?: FormEventHandler | undefined;\n onInput?: FormEventHandler | undefined;\n onInputCapture?: FormEventHandler | undefined;\n onReset?: FormEventHandler | undefined;\n onResetCapture?: FormEventHandler | undefined;\n onSubmit?: FormEventHandler | undefined;\n onSubmitCapture?: FormEventHandler | undefined;\n onInvalid?: FormEventHandler | undefined;\n onInvalidCapture?: FormEventHandler | undefined;\n\n // Image Events\n onLoad?: ReactEventHandler | undefined;\n onLoadCapture?: ReactEventHandler | undefined;\n onError?: ReactEventHandler | undefined; // also a Media Event\n onErrorCapture?: ReactEventHandler | undefined; // also a Media Event\n\n // Keyboard Events\n onKeyDown?: KeyboardEventHandler | undefined;\n onKeyDownCapture?: KeyboardEventHandler | undefined;\n /** @deprecated Use `onKeyUp` or `onKeyDown` instead */\n onKeyPress?: KeyboardEventHandler | undefined;\n /** @deprecated Use `onKeyUpCapture` or `onKeyDownCapture` instead */\n onKeyPressCapture?: KeyboardEventHandler | undefined;\n onKeyUp?: KeyboardEventHandler | undefined;\n onKeyUpCapture?: KeyboardEventHandler | undefined;\n\n // Media Events\n onAbort?: ReactEventHandler | undefined;\n onAbortCapture?: ReactEventHandler | undefined;\n onCanPlay?: ReactEventHandler | undefined;\n onCanPlayCapture?: ReactEventHandler | undefined;\n onCanPlayThrough?: ReactEventHandler | undefined;\n onCanPlayThroughCapture?: ReactEventHandler | undefined;\n onDurationChange?: ReactEventHandler | undefined;\n onDurationChangeCapture?: ReactEventHandler | undefined;\n onEmptied?: ReactEventHandler | undefined;\n onEmptiedCapture?: ReactEventHandler | undefined;\n onEncrypted?: ReactEventHandler | undefined;\n onEncryptedCapture?: ReactEventHandler | undefined;\n onEnded?: ReactEventHandler | undefined;\n onEndedCapture?: ReactEventHandler | undefined;\n onLoadedData?: ReactEventHandler | undefined;\n onLoadedDataCapture?: ReactEventHandler | undefined;\n onLoadedMetadata?: ReactEventHandler | undefined;\n onLoadedMetadataCapture?: ReactEventHandler | undefined;\n onLoadStart?: ReactEventHandler | undefined;\n onLoadStartCapture?: ReactEventHandler | undefined;\n onPause?: ReactEventHandler | undefined;\n onPauseCapture?: ReactEventHandler | undefined;\n onPlay?: ReactEventHandler | undefined;\n onPlayCapture?: ReactEventHandler | undefined;\n onPlaying?: ReactEventHandler | undefined;\n onPlayingCapture?: ReactEventHandler | undefined;\n onProgress?: ReactEventHandler | undefined;\n onProgressCapture?: ReactEventHandler | undefined;\n onRateChange?: ReactEventHandler | undefined;\n onRateChangeCapture?: ReactEventHandler | undefined;\n onSeeked?: ReactEventHandler | undefined;\n onSeekedCapture?: ReactEventHandler | undefined;\n onSeeking?: ReactEventHandler | undefined;\n onSeekingCapture?: ReactEventHandler | undefined;\n onStalled?: ReactEventHandler | undefined;\n onStalledCapture?: ReactEventHandler | undefined;\n onSuspend?: ReactEventHandler | undefined;\n onSuspendCapture?: ReactEventHandler | undefined;\n onTimeUpdate?: ReactEventHandler | undefined;\n onTimeUpdateCapture?: ReactEventHandler | undefined;\n onVolumeChange?: ReactEventHandler | undefined;\n onVolumeChangeCapture?: ReactEventHandler | undefined;\n onWaiting?: ReactEventHandler | undefined;\n onWaitingCapture?: ReactEventHandler | undefined;\n\n // MouseEvents\n onAuxClick?: MouseEventHandler | undefined;\n onAuxClickCapture?: MouseEventHandler | undefined;\n onClick?: MouseEventHandler | undefined;\n onClickCapture?: MouseEventHandler | undefined;\n onContextMenu?: MouseEventHandler | undefined;\n onContextMenuCapture?: MouseEventHandler | undefined;\n onDoubleClick?: MouseEventHandler | undefined;\n onDoubleClickCapture?: MouseEventHandler | undefined;\n onDrag?: DragEventHandler | undefined;\n onDragCapture?: DragEventHandler | undefined;\n onDragEnd?: DragEventHandler | undefined;\n onDragEndCapture?: DragEventHandler | undefined;\n onDragEnter?: DragEventHandler | undefined;\n onDragEnterCapture?: DragEventHandler | undefined;\n onDragExit?: DragEventHandler | undefined;\n onDragExitCapture?: DragEventHandler | undefined;\n onDragLeave?: DragEventHandler | undefined;\n onDragLeaveCapture?: DragEventHandler | undefined;\n onDragOver?: DragEventHandler | undefined;\n onDragOverCapture?: DragEventHandler | undefined;\n onDragStart?: DragEventHandler | undefined;\n onDragStartCapture?: DragEventHandler | undefined;\n onDrop?: DragEventHandler | undefined;\n onDropCapture?: DragEventHandler | undefined;\n onMouseDown?: MouseEventHandler | undefined;\n onMouseDownCapture?: MouseEventHandler | undefined;\n onMouseEnter?: MouseEventHandler | undefined;\n onMouseLeave?: MouseEventHandler | undefined;\n onMouseMove?: MouseEventHandler | undefined;\n onMouseMoveCapture?: MouseEventHandler | undefined;\n onMouseOut?: MouseEventHandler | undefined;\n onMouseOutCapture?: MouseEventHandler | undefined;\n onMouseOver?: MouseEventHandler | undefined;\n onMouseOverCapture?: MouseEventHandler | undefined;\n onMouseUp?: MouseEventHandler | undefined;\n onMouseUpCapture?: MouseEventHandler | undefined;\n\n // Selection Events\n onSelect?: ReactEventHandler | undefined;\n onSelectCapture?: ReactEventHandler | undefined;\n\n // Touch Events\n onTouchCancel?: TouchEventHandler | undefined;\n onTouchCancelCapture?: TouchEventHandler | undefined;\n onTouchEnd?: TouchEventHandler | undefined;\n onTouchEndCapture?: TouchEventHandler | undefined;\n onTouchMove?: TouchEventHandler | undefined;\n onTouchMoveCapture?: TouchEventHandler | undefined;\n onTouchStart?: TouchEventHandler | undefined;\n onTouchStartCapture?: TouchEventHandler | undefined;\n\n // Pointer Events\n onPointerDown?: PointerEventHandler | undefined;\n onPointerDownCapture?: PointerEventHandler | undefined;\n onPointerMove?: PointerEventHandler | undefined;\n onPointerMoveCapture?: PointerEventHandler | undefined;\n onPointerUp?: PointerEventHandler | undefined;\n onPointerUpCapture?: PointerEventHandler | undefined;\n onPointerCancel?: PointerEventHandler | undefined;\n onPointerCancelCapture?: PointerEventHandler | undefined;\n onPointerEnter?: PointerEventHandler | undefined;\n onPointerLeave?: PointerEventHandler | undefined;\n onPointerOver?: PointerEventHandler | undefined;\n onPointerOverCapture?: PointerEventHandler | undefined;\n onPointerOut?: PointerEventHandler | undefined;\n onPointerOutCapture?: PointerEventHandler | undefined;\n onGotPointerCapture?: PointerEventHandler | undefined;\n onGotPointerCaptureCapture?: PointerEventHandler | undefined;\n onLostPointerCapture?: PointerEventHandler | undefined;\n onLostPointerCaptureCapture?: PointerEventHandler | undefined;\n\n // UI Events\n onScroll?: UIEventHandler | undefined;\n onScrollCapture?: UIEventHandler | undefined;\n\n // Wheel Events\n onWheel?: WheelEventHandler | undefined;\n onWheelCapture?: WheelEventHandler | undefined;\n\n // Animation Events\n onAnimationStart?: AnimationEventHandler | undefined;\n onAnimationStartCapture?: AnimationEventHandler | undefined;\n onAnimationEnd?: AnimationEventHandler | undefined;\n onAnimationEndCapture?: AnimationEventHandler | undefined;\n onAnimationIteration?: AnimationEventHandler | undefined;\n onAnimationIterationCapture?: AnimationEventHandler | undefined;\n\n // Transition Events\n onTransitionEnd?: TransitionEventHandler | undefined;\n onTransitionEndCapture?: TransitionEventHandler | undefined;\n }\n\n export interface CSSProperties extends CSS.Properties {\n /**\n * The index signature was removed to enable closed typing for style\n * using CSSType. You're able to use type assertion or module augmentation\n * to add properties or an index signature of your own.\n *\n * For examples and more information, visit:\n * https://github.com/frenic/csstype#what-should-i-do-when-i-get-type-errors\n */\n }\n\n // All the WAI-ARIA 1.1 attributes from https://www.w3.org/TR/wai-aria-1.1/\n interface AriaAttributes {\n /** Identifies the currently active element when DOM focus is on a composite widget, textbox, group, or application. */\n \"aria-activedescendant\"?: string | undefined;\n /** Indicates whether assistive technologies will present all, or only parts of, the changed region based on the change notifications defined by the aria-relevant attribute. */\n \"aria-atomic\"?: Booleanish | undefined;\n /**\n * Indicates whether inputting text could trigger display of one or more predictions of the user's intended value for an input and specifies how predictions would be\n * presented if they are made.\n */\n \"aria-autocomplete\"?: \"none\" | \"inline\" | \"list\" | \"both\" | undefined;\n /** Indicates an element is being modified and that assistive technologies MAY want to wait until the modifications are complete before exposing them to the user. */\n /**\n * Defines a string value that labels the current element, which is intended to be converted into Braille.\n * @see aria-label.\n */\n \"aria-braillelabel\"?: string | undefined;\n /**\n * Defines a human-readable, author-localized abbreviated description for the role of an element, which is intended to be converted into Braille.\n * @see aria-roledescription.\n */\n \"aria-brailleroledescription\"?: string | undefined;\n \"aria-busy\"?: Booleanish | undefined;\n /**\n * Indicates the current \"checked\" state of checkboxes, radio buttons, and other widgets.\n * @see aria-pressed @see aria-selected.\n */\n \"aria-checked\"?: boolean | \"false\" | \"mixed\" | \"true\" | undefined;\n /**\n * Defines the total number of columns in a table, grid, or treegrid.\n * @see aria-colindex.\n */\n \"aria-colcount\"?: number | undefined;\n /**\n * Defines an element's column index or position with respect to the total number of columns within a table, grid, or treegrid.\n * @see aria-colcount @see aria-colspan.\n */\n \"aria-colindex\"?: number | undefined;\n /**\n * Defines a human readable text alternative of aria-colindex.\n * @see aria-rowindextext.\n */\n \"aria-colindextext\"?: string | undefined;\n /**\n * Defines the number of columns spanned by a cell or gridcell within a table, grid, or treegrid.\n * @see aria-colindex @see aria-rowspan.\n */\n \"aria-colspan\"?: number | undefined;\n /**\n * Identifies the element (or elements) whose contents or presence are controlled by the current element.\n * @see aria-owns.\n */\n \"aria-controls\"?: string | undefined;\n /** Indicates the element that represents the current item within a container or set of related elements. */\n \"aria-current\"?: boolean | \"false\" | \"true\" | \"page\" | \"step\" | \"location\" | \"date\" | \"time\" | undefined;\n /**\n * Identifies the element (or elements) that describes the object.\n * @see aria-labelledby\n */\n \"aria-describedby\"?: string | undefined;\n /**\n * Defines a string value that describes or annotates the current element.\n * @see related aria-describedby.\n */\n \"aria-description\"?: string | undefined;\n /**\n * Identifies the element that provides a detailed, extended description for the object.\n * @see aria-describedby.\n */\n \"aria-details\"?: string | undefined;\n /**\n * Indicates that the element is perceivable but disabled, so it is not editable or otherwise operable.\n * @see aria-hidden @see aria-readonly.\n */\n \"aria-disabled\"?: Booleanish | undefined;\n /**\n * Indicates what functions can be performed when a dragged object is released on the drop target.\n * @deprecated in ARIA 1.1\n */\n \"aria-dropeffect\"?: \"none\" | \"copy\" | \"execute\" | \"link\" | \"move\" | \"popup\" | undefined;\n /**\n * Identifies the element that provides an error message for the object.\n * @see aria-invalid @see aria-describedby.\n */\n \"aria-errormessage\"?: string | undefined;\n /** Indicates whether the element, or another grouping element it controls, is currently expanded or collapsed. */\n \"aria-expanded\"?: Booleanish | undefined;\n /**\n * Identifies the next element (or elements) in an alternate reading order of content which, at the user's discretion,\n * allows assistive technology to override the general default of reading in document source order.\n */\n \"aria-flowto\"?: string | undefined;\n /**\n * Indicates an element's \"grabbed\" state in a drag-and-drop operation.\n * @deprecated in ARIA 1.1\n */\n \"aria-grabbed\"?: Booleanish | undefined;\n /** Indicates the availability and type of interactive popup element, such as menu or dialog, that can be triggered by an element. */\n \"aria-haspopup\"?: boolean | \"false\" | \"true\" | \"menu\" | \"listbox\" | \"tree\" | \"grid\" | \"dialog\" | undefined;\n /**\n * Indicates whether the element is exposed to an accessibility API.\n * @see aria-disabled.\n */\n \"aria-hidden\"?: Booleanish | undefined;\n /**\n * Indicates the entered value does not conform to the format expected by the application.\n * @see aria-errormessage.\n */\n \"aria-invalid\"?: boolean | \"false\" | \"true\" | \"grammar\" | \"spelling\" | undefined;\n /** Indicates keyboard shortcuts that an author has implemented to activate or give focus to an element. */\n \"aria-keyshortcuts\"?: string | undefined;\n /**\n * Defines a string value that labels the current element.\n * @see aria-labelledby.\n */\n \"aria-label\"?: string | undefined;\n /**\n * Identifies the element (or elements) that labels the current element.\n * @see aria-describedby.\n */\n \"aria-labelledby\"?: string | undefined;\n /** Defines the hierarchical level of an element within a structure. */\n \"aria-level\"?: number | undefined;\n /** Indicates that an element will be updated, and describes the types of updates the user agents, assistive technologies, and user can expect from the live region. */\n \"aria-live\"?: \"off\" | \"assertive\" | \"polite\" | undefined;\n /** Indicates whether an element is modal when displayed. */\n \"aria-modal\"?: Booleanish | undefined;\n /** Indicates whether a text box accepts multiple lines of input or only a single line. */\n \"aria-multiline\"?: Booleanish | undefined;\n /** Indicates that the user may select more than one item from the current selectable descendants. */\n \"aria-multiselectable\"?: Booleanish | undefined;\n /** Indicates whether the element's orientation is horizontal, vertical, or unknown/ambiguous. */\n \"aria-orientation\"?: \"horizontal\" | \"vertical\" | undefined;\n /**\n * Identifies an element (or elements) in order to define a visual, functional, or contextual parent/child relationship\n * between DOM elements where the DOM hierarchy cannot be used to represent the relationship.\n * @see aria-controls.\n */\n \"aria-owns\"?: string | undefined;\n /**\n * Defines a short hint (a word or short phrase) intended to aid the user with data entry when the control has no value.\n * A hint could be a sample value or a brief description of the expected format.\n */\n \"aria-placeholder\"?: string | undefined;\n /**\n * Defines an element's number or position in the current set of listitems or treeitems. Not required if all elements in the set are present in the DOM.\n * @see aria-setsize.\n */\n \"aria-posinset\"?: number | undefined;\n /**\n * Indicates the current \"pressed\" state of toggle buttons.\n * @see aria-checked @see aria-selected.\n */\n \"aria-pressed\"?: boolean | \"false\" | \"mixed\" | \"true\" | undefined;\n /**\n * Indicates that the element is not editable, but is otherwise operable.\n * @see aria-disabled.\n */\n \"aria-readonly\"?: Booleanish | undefined;\n /**\n * Indicates what notifications the user agent will trigger when the accessibility tree within a live region is modified.\n * @see aria-atomic.\n */\n \"aria-relevant\"?:\n | \"additions\"\n | \"additions removals\"\n | \"additions text\"\n | \"all\"\n | \"removals\"\n | \"removals additions\"\n | \"removals text\"\n | \"text\"\n | \"text additions\"\n | \"text removals\"\n | undefined;\n /** Indicates that user input is required on the element before a form may be submitted. */\n \"aria-required\"?: Booleanish | undefined;\n /** Defines a human-readable, author-localized description for the role of an element. */\n \"aria-roledescription\"?: string | undefined;\n /**\n * Defines the total number of rows in a table, grid, or treegrid.\n * @see aria-rowindex.\n */\n \"aria-rowcount\"?: number | undefined;\n /**\n * Defines an element's row index or position with respect to the total number of rows within a table, grid, or treegrid.\n * @see aria-rowcount @see aria-rowspan.\n */\n \"aria-rowindex\"?: number | undefined;\n /**\n * Defines a human readable text alternative of aria-rowindex.\n * @see aria-colindextext.\n */\n \"aria-rowindextext\"?: string | undefined;\n /**\n * Defines the number of rows spanned by a cell or gridcell within a table, grid, or treegrid.\n * @see aria-rowindex @see aria-colspan.\n */\n \"aria-rowspan\"?: number | undefined;\n /**\n * Indicates the current \"selected\" state of various widgets.\n * @see aria-checked @see aria-pressed.\n */\n \"aria-selected\"?: Booleanish | undefined;\n /**\n * Defines the number of items in the current set of listitems or treeitems. Not required if all elements in the set are present in the DOM.\n * @see aria-posinset.\n */\n \"aria-setsize\"?: number | undefined;\n /** Indicates if items in a table or grid are sorted in ascending or descending order. */\n \"aria-sort\"?: \"none\" | \"ascending\" | \"descending\" | \"other\" | undefined;\n /** Defines the maximum allowed value for a range widget. */\n \"aria-valuemax\"?: number | undefined;\n /** Defines the minimum allowed value for a range widget. */\n \"aria-valuemin\"?: number | undefined;\n /**\n * Defines the current value for a range widget.\n * @see aria-valuetext.\n */\n \"aria-valuenow\"?: number | undefined;\n /** Defines the human readable text alternative of aria-valuenow for a range widget. */\n \"aria-valuetext\"?: string | undefined;\n }\n\n // All the WAI-ARIA 1.1 role attribute values from https://www.w3.org/TR/wai-aria-1.1/#role_definitions\n type AriaRole =\n | \"alert\"\n | \"alertdialog\"\n | \"application\"\n | \"article\"\n | \"banner\"\n | \"button\"\n | \"cell\"\n | \"checkbox\"\n | \"columnheader\"\n | \"combobox\"\n | \"complementary\"\n | \"contentinfo\"\n | \"definition\"\n | \"dialog\"\n | \"directory\"\n | \"document\"\n | \"feed\"\n | \"figure\"\n | \"form\"\n | \"grid\"\n | \"gridcell\"\n | \"group\"\n | \"heading\"\n | \"img\"\n | \"link\"\n | \"list\"\n | \"listbox\"\n | \"listitem\"\n | \"log\"\n | \"main\"\n | \"marquee\"\n | \"math\"\n | \"menu\"\n | \"menubar\"\n | \"menuitem\"\n | \"menuitemcheckbox\"\n | \"menuitemradio\"\n | \"navigation\"\n | \"none\"\n | \"note\"\n | \"option\"\n | \"presentation\"\n | \"progressbar\"\n | \"radio\"\n | \"radiogroup\"\n | \"region\"\n | \"row\"\n | \"rowgroup\"\n | \"rowheader\"\n | \"scrollbar\"\n | \"search\"\n | \"searchbox\"\n | \"separator\"\n | \"slider\"\n | \"spinbutton\"\n | \"status\"\n | \"switch\"\n | \"tab\"\n | \"table\"\n | \"tablist\"\n | \"tabpanel\"\n | \"term\"\n | \"textbox\"\n | \"timer\"\n | \"toolbar\"\n | \"tooltip\"\n | \"tree\"\n | \"treegrid\"\n | \"treeitem\"\n | (string & {});\n\n interface HTMLAttributes extends AriaAttributes, DOMAttributes {\n // React-specific Attributes\n defaultChecked?: boolean | undefined;\n defaultValue?: string | number | readonly string[] | undefined;\n suppressContentEditableWarning?: boolean | undefined;\n suppressHydrationWarning?: boolean | undefined;\n\n // Standard HTML Attributes\n accessKey?: string | undefined;\n autoCapitalize?: \"off\" | \"none\" | \"on\" | \"sentences\" | \"words\" | \"characters\" | undefined | (string & {});\n autoFocus?: boolean | undefined;\n className?: string | undefined;\n contentEditable?: Booleanish | \"inherit\" | \"plaintext-only\" | undefined;\n contextMenu?: string | undefined;\n dir?: string | undefined;\n draggable?: Booleanish | undefined;\n enterKeyHint?: \"enter\" | \"done\" | \"go\" | \"next\" | \"previous\" | \"search\" | \"send\" | undefined;\n hidden?: boolean | undefined;\n id?: string | undefined;\n lang?: string | undefined;\n nonce?: string | undefined;\n slot?: string | undefined;\n spellCheck?: Booleanish | undefined;\n style?: CSSProperties | undefined;\n tabIndex?: number | undefined;\n title?: string | undefined;\n translate?: \"yes\" | \"no\" | undefined;\n\n // Unknown\n radioGroup?: string | undefined; // , \n\n // WAI-ARIA\n role?: AriaRole | undefined;\n\n // RDFa Attributes\n about?: string | undefined;\n content?: string | undefined;\n datatype?: string | undefined;\n inlist?: any;\n prefix?: string | undefined;\n property?: string | undefined;\n rel?: string | undefined;\n resource?: string | undefined;\n rev?: string | undefined;\n typeof?: string | undefined;\n vocab?: string | undefined;\n\n // Non-standard Attributes\n autoCorrect?: string | undefined;\n autoSave?: string | undefined;\n color?: string | undefined;\n itemProp?: string | undefined;\n itemScope?: boolean | undefined;\n itemType?: string | undefined;\n itemID?: string | undefined;\n itemRef?: string | undefined;\n results?: number | undefined;\n security?: string | undefined;\n unselectable?: \"on\" | \"off\" | undefined;\n\n // Living Standard\n /**\n * Hints at the type of data that might be entered by the user while editing the element or its contents\n * @see {@link https://html.spec.whatwg.org/multipage/interaction.html#input-modalities:-the-inputmode-attribute}\n */\n inputMode?: \"none\" | \"text\" | \"tel\" | \"url\" | \"email\" | \"numeric\" | \"decimal\" | \"search\" | undefined;\n /**\n * Specify that a standard HTML element should behave like a defined custom built-in element\n * @see {@link https://html.spec.whatwg.org/multipage/custom-elements.html#attr-is}\n */\n is?: string | undefined;\n /**\n * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/exportparts}\n */\n exportparts?: string | undefined;\n /**\n * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/part}\n */\n part?: string | undefined;\n }\n\n /**\n * For internal usage only.\n * Different release channels declare additional types of ReactNode this particular release channel accepts.\n * App or library types should never augment this interface.\n */\n interface DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_FORM_ACTIONS {}\n\n interface AllHTMLAttributes extends HTMLAttributes {\n // Standard HTML Attributes\n accept?: string | undefined;\n acceptCharset?: string | undefined;\n action?:\n | string\n | undefined\n | DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_FORM_ACTIONS[\n keyof DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_FORM_ACTIONS\n ];\n allowFullScreen?: boolean | undefined;\n allowTransparency?: boolean | undefined;\n alt?: string | undefined;\n as?: string | undefined;\n async?: boolean | undefined;\n autoComplete?: string | undefined;\n autoPlay?: boolean | undefined;\n capture?: boolean | \"user\" | \"environment\" | undefined;\n cellPadding?: number | string | undefined;\n cellSpacing?: number | string | undefined;\n charSet?: string | undefined;\n challenge?: string | undefined;\n checked?: boolean | undefined;\n cite?: string | undefined;\n classID?: string | undefined;\n cols?: number | undefined;\n colSpan?: number | undefined;\n controls?: boolean | undefined;\n coords?: string | undefined;\n crossOrigin?: CrossOrigin;\n data?: string | undefined;\n dateTime?: string | undefined;\n default?: boolean | undefined;\n defer?: boolean | undefined;\n disabled?: boolean | undefined;\n download?: any;\n encType?: string | undefined;\n form?: string | undefined;\n formAction?:\n | string\n | undefined\n | DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_FORM_ACTIONS[\n keyof DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_FORM_ACTIONS\n ];\n formEncType?: string | undefined;\n formMethod?: string | undefined;\n formNoValidate?: boolean | undefined;\n formTarget?: string | undefined;\n frameBorder?: number | string | undefined;\n headers?: string | undefined;\n height?: number | string | undefined;\n high?: number | undefined;\n href?: string | undefined;\n hrefLang?: string | undefined;\n htmlFor?: string | undefined;\n httpEquiv?: string | undefined;\n integrity?: string | undefined;\n keyParams?: string | undefined;\n keyType?: string | undefined;\n kind?: string | undefined;\n label?: string | undefined;\n list?: string | undefined;\n loop?: boolean | undefined;\n low?: number | undefined;\n manifest?: string | undefined;\n marginHeight?: number | undefined;\n marginWidth?: number | undefined;\n max?: number | string | undefined;\n maxLength?: number | undefined;\n media?: string | undefined;\n mediaGroup?: string | undefined;\n method?: string | undefined;\n min?: number | string | undefined;\n minLength?: number | undefined;\n multiple?: boolean | undefined;\n muted?: boolean | undefined;\n name?: string | undefined;\n noValidate?: boolean | undefined;\n open?: boolean | undefined;\n optimum?: number | undefined;\n pattern?: string | undefined;\n placeholder?: string | undefined;\n playsInline?: boolean | undefined;\n poster?: string | undefined;\n preload?: string | undefined;\n readOnly?: boolean | undefined;\n required?: boolean | undefined;\n reversed?: boolean | undefined;\n rows?: number | undefined;\n rowSpan?: number | undefined;\n sandbox?: string | undefined;\n scope?: string | undefined;\n scoped?: boolean | undefined;\n scrolling?: string | undefined;\n seamless?: boolean | undefined;\n selected?: boolean | undefined;\n shape?: string | undefined;\n size?: number | undefined;\n sizes?: string | undefined;\n span?: number | undefined;\n src?: string | undefined;\n srcDoc?: string | undefined;\n srcLang?: string | undefined;\n srcSet?: string | undefined;\n start?: number | undefined;\n step?: number | string | undefined;\n summary?: string | undefined;\n target?: string | undefined;\n type?: string | undefined;\n useMap?: string | undefined;\n value?: string | readonly string[] | number | undefined;\n width?: number | string | undefined;\n wmode?: string | undefined;\n wrap?: string | undefined;\n }\n\n type HTMLAttributeReferrerPolicy =\n | \"\"\n | \"no-referrer\"\n | \"no-referrer-when-downgrade\"\n | \"origin\"\n | \"origin-when-cross-origin\"\n | \"same-origin\"\n | \"strict-origin\"\n | \"strict-origin-when-cross-origin\"\n | \"unsafe-url\";\n\n type HTMLAttributeAnchorTarget =\n | \"_self\"\n | \"_blank\"\n | \"_parent\"\n | \"_top\"\n | (string & {});\n\n interface AnchorHTMLAttributes extends HTMLAttributes {\n download?: any;\n href?: string | undefined;\n hrefLang?: string | undefined;\n media?: string | undefined;\n ping?: string | undefined;\n target?: HTMLAttributeAnchorTarget | undefined;\n type?: string | undefined;\n referrerPolicy?: HTMLAttributeReferrerPolicy | undefined;\n }\n\n interface AudioHTMLAttributes extends MediaHTMLAttributes {}\n\n interface AreaHTMLAttributes extends HTMLAttributes {\n alt?: string | undefined;\n coords?: string | undefined;\n download?: any;\n href?: string | undefined;\n hrefLang?: string | undefined;\n media?: string | undefined;\n referrerPolicy?: HTMLAttributeReferrerPolicy | undefined;\n shape?: string | undefined;\n target?: string | undefined;\n }\n\n interface BaseHTMLAttributes extends HTMLAttributes {\n href?: string | undefined;\n target?: string | undefined;\n }\n\n interface BlockquoteHTMLAttributes extends HTMLAttributes {\n cite?: string | undefined;\n }\n\n interface ButtonHTMLAttributes extends HTMLAttributes {\n disabled?: boolean | undefined;\n form?: string | undefined;\n formAction?:\n | string\n | DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_FORM_ACTIONS[\n keyof DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_FORM_ACTIONS\n ]\n | undefined;\n formEncType?: string | undefined;\n formMethod?: string | undefined;\n formNoValidate?: boolean | undefined;\n formTarget?: string | undefined;\n name?: string | undefined;\n type?: \"submit\" | \"reset\" | \"button\" | undefined;\n value?: string | readonly string[] | number | undefined;\n }\n\n interface CanvasHTMLAttributes extends HTMLAttributes {\n height?: number | string | undefined;\n width?: number | string | undefined;\n }\n\n interface ColHTMLAttributes extends HTMLAttributes {\n span?: number | undefined;\n width?: number | string | undefined;\n }\n\n interface ColgroupHTMLAttributes extends HTMLAttributes {\n span?: number | undefined;\n }\n\n interface DataHTMLAttributes extends HTMLAttributes {\n value?: string | readonly string[] | number | undefined;\n }\n\n interface DetailsHTMLAttributes extends HTMLAttributes {\n open?: boolean | undefined;\n onToggle?: ReactEventHandler | undefined;\n name?: string | undefined;\n }\n\n interface DelHTMLAttributes extends HTMLAttributes {\n cite?: string | undefined;\n dateTime?: string | undefined;\n }\n\n interface DialogHTMLAttributes extends HTMLAttributes {\n closedby?: \"any\" | \"closerequest\" | \"none\" | undefined;\n onCancel?: ReactEventHandler | undefined;\n onClose?: ReactEventHandler | undefined;\n open?: boolean | undefined;\n }\n\n interface EmbedHTMLAttributes extends HTMLAttributes {\n height?: number | string | undefined;\n src?: string | undefined;\n type?: string | undefined;\n width?: number | string | undefined;\n }\n\n interface FieldsetHTMLAttributes extends HTMLAttributes {\n disabled?: boolean | undefined;\n form?: string | undefined;\n name?: string | undefined;\n }\n\n interface FormHTMLAttributes extends HTMLAttributes {\n acceptCharset?: string | undefined;\n action?:\n | string\n | undefined\n | DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_FORM_ACTIONS[\n keyof DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_FORM_ACTIONS\n ];\n autoComplete?: string | undefined;\n encType?: string | undefined;\n method?: string | undefined;\n name?: string | undefined;\n noValidate?: boolean | undefined;\n target?: string | undefined;\n }\n\n interface HtmlHTMLAttributes extends HTMLAttributes {\n manifest?: string | undefined;\n }\n\n interface IframeHTMLAttributes extends HTMLAttributes {\n allow?: string | undefined;\n allowFullScreen?: boolean | undefined;\n allowTransparency?: boolean | undefined;\n /** @deprecated */\n frameBorder?: number | string | undefined;\n height?: number | string | undefined;\n loading?: \"eager\" | \"lazy\" | undefined;\n /** @deprecated */\n marginHeight?: number | undefined;\n /** @deprecated */\n marginWidth?: number | undefined;\n name?: string | undefined;\n referrerPolicy?: HTMLAttributeReferrerPolicy | undefined;\n sandbox?: string | undefined;\n /** @deprecated */\n scrolling?: string | undefined;\n seamless?: boolean | undefined;\n src?: string | undefined;\n srcDoc?: string | undefined;\n width?: number | string | undefined;\n }\n\n interface ImgHTMLAttributes extends HTMLAttributes {\n alt?: string | undefined;\n crossOrigin?: CrossOrigin;\n decoding?: \"async\" | \"auto\" | \"sync\" | undefined;\n fetchPriority?: \"high\" | \"low\" | \"auto\";\n height?: number | string | undefined;\n loading?: \"eager\" | \"lazy\" | undefined;\n referrerPolicy?: HTMLAttributeReferrerPolicy | undefined;\n sizes?: string | undefined;\n src?: string | undefined;\n srcSet?: string | undefined;\n useMap?: string | undefined;\n width?: number | string | undefined;\n }\n\n interface InsHTMLAttributes extends HTMLAttributes {\n cite?: string | undefined;\n dateTime?: string | undefined;\n }\n\n type HTMLInputTypeAttribute =\n | \"button\"\n | \"checkbox\"\n | \"color\"\n | \"date\"\n | \"datetime-local\"\n | \"email\"\n | \"file\"\n | \"hidden\"\n | \"image\"\n | \"month\"\n | \"number\"\n | \"password\"\n | \"radio\"\n | \"range\"\n | \"reset\"\n | \"search\"\n | \"submit\"\n | \"tel\"\n | \"text\"\n | \"time\"\n | \"url\"\n | \"week\"\n | (string & {});\n\n type AutoFillAddressKind = \"billing\" | \"shipping\";\n type AutoFillBase = \"\" | \"off\" | \"on\";\n type AutoFillContactField =\n | \"email\"\n | \"tel\"\n | \"tel-area-code\"\n | \"tel-country-code\"\n | \"tel-extension\"\n | \"tel-local\"\n | \"tel-local-prefix\"\n | \"tel-local-suffix\"\n | \"tel-national\";\n type AutoFillContactKind = \"home\" | \"mobile\" | \"work\";\n type AutoFillCredentialField = \"webauthn\";\n type AutoFillNormalField =\n | \"additional-name\"\n | \"address-level1\"\n | \"address-level2\"\n | \"address-level3\"\n | \"address-level4\"\n | \"address-line1\"\n | \"address-line2\"\n | \"address-line3\"\n | \"bday-day\"\n | \"bday-month\"\n | \"bday-year\"\n | \"cc-csc\"\n | \"cc-exp\"\n | \"cc-exp-month\"\n | \"cc-exp-year\"\n | \"cc-family-name\"\n | \"cc-given-name\"\n | \"cc-name\"\n | \"cc-number\"\n | \"cc-type\"\n | \"country\"\n | \"country-name\"\n | \"current-password\"\n | \"family-name\"\n | \"given-name\"\n | \"honorific-prefix\"\n | \"honorific-suffix\"\n | \"name\"\n | \"new-password\"\n | \"one-time-code\"\n | \"organization\"\n | \"postal-code\"\n | \"street-address\"\n | \"transaction-amount\"\n | \"transaction-currency\"\n | \"username\";\n type OptionalPrefixToken = `${T} ` | \"\";\n type OptionalPostfixToken = ` ${T}` | \"\";\n type AutoFillField = AutoFillNormalField | `${OptionalPrefixToken}${AutoFillContactField}`;\n type AutoFillSection = `section-${string}`;\n type AutoFill =\n | AutoFillBase\n | `${OptionalPrefixToken}${OptionalPrefixToken<\n AutoFillAddressKind\n >}${AutoFillField}${OptionalPostfixToken}`;\n type HTMLInputAutoCompleteAttribute = AutoFill | (string & {});\n\n interface InputHTMLAttributes extends HTMLAttributes {\n accept?: string | undefined;\n alt?: string | undefined;\n autoComplete?: HTMLInputAutoCompleteAttribute | undefined;\n capture?: boolean | \"user\" | \"environment\" | undefined; // https://www.w3.org/TR/html-media-capture/#the-capture-attribute\n checked?: boolean | undefined;\n disabled?: boolean | undefined;\n form?: string | undefined;\n formAction?:\n | string\n | DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_FORM_ACTIONS[\n keyof DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_FORM_ACTIONS\n ]\n | undefined;\n formEncType?: string | undefined;\n formMethod?: string | undefined;\n formNoValidate?: boolean | undefined;\n formTarget?: string | undefined;\n height?: number | string | undefined;\n list?: string | undefined;\n max?: number | string | undefined;\n maxLength?: number | undefined;\n min?: number | string | undefined;\n minLength?: number | undefined;\n multiple?: boolean | undefined;\n name?: string | undefined;\n pattern?: string | undefined;\n placeholder?: string | undefined;\n readOnly?: boolean | undefined;\n required?: boolean | undefined;\n size?: number | undefined;\n src?: string | undefined;\n step?: number | string | undefined;\n type?: HTMLInputTypeAttribute | undefined;\n value?: string | readonly string[] | number | undefined;\n width?: number | string | undefined;\n\n onChange?: ChangeEventHandler | undefined;\n }\n\n interface KeygenHTMLAttributes extends HTMLAttributes {\n challenge?: string | undefined;\n disabled?: boolean | undefined;\n form?: string | undefined;\n keyType?: string | undefined;\n keyParams?: string | undefined;\n name?: string | undefined;\n }\n\n interface LabelHTMLAttributes extends HTMLAttributes {\n form?: string | undefined;\n htmlFor?: string | undefined;\n }\n\n interface LiHTMLAttributes extends HTMLAttributes {\n value?: string | readonly string[] | number | undefined;\n }\n\n interface LinkHTMLAttributes extends HTMLAttributes {\n as?: string | undefined;\n blocking?: \"render\" | (string & {}) | undefined;\n crossOrigin?: CrossOrigin;\n fetchPriority?: \"high\" | \"low\" | \"auto\";\n href?: string | undefined;\n hrefLang?: string | undefined;\n integrity?: string | undefined;\n media?: string | undefined;\n imageSrcSet?: string | undefined;\n imageSizes?: string | undefined;\n referrerPolicy?: HTMLAttributeReferrerPolicy | undefined;\n sizes?: string | undefined;\n type?: string | undefined;\n charSet?: string | undefined;\n }\n\n interface MapHTMLAttributes extends HTMLAttributes {\n name?: string | undefined;\n }\n\n interface MenuHTMLAttributes extends HTMLAttributes {\n type?: string | undefined;\n }\n\n interface MediaHTMLAttributes extends HTMLAttributes {\n autoPlay?: boolean | undefined;\n controls?: boolean | undefined;\n controlsList?: string | undefined;\n crossOrigin?: CrossOrigin;\n loop?: boolean | undefined;\n mediaGroup?: string | undefined;\n muted?: boolean | undefined;\n playsInline?: boolean | undefined;\n preload?: string | undefined;\n src?: string | undefined;\n }\n\n interface MetaHTMLAttributes extends HTMLAttributes {\n charSet?: string | undefined;\n content?: string | undefined;\n httpEquiv?: string | undefined;\n media?: string | undefined;\n name?: string | undefined;\n }\n\n interface MeterHTMLAttributes extends HTMLAttributes {\n form?: string | undefined;\n high?: number | undefined;\n low?: number | undefined;\n max?: number | string | undefined;\n min?: number | string | undefined;\n optimum?: number | undefined;\n value?: string | readonly string[] | number | undefined;\n }\n\n interface QuoteHTMLAttributes extends HTMLAttributes {\n cite?: string | undefined;\n }\n\n interface ObjectHTMLAttributes extends HTMLAttributes {\n classID?: string | undefined;\n data?: string | undefined;\n form?: string | undefined;\n height?: number | string | undefined;\n name?: string | undefined;\n type?: string | undefined;\n useMap?: string | undefined;\n width?: number | string | undefined;\n wmode?: string | undefined;\n }\n\n interface OlHTMLAttributes extends HTMLAttributes {\n reversed?: boolean | undefined;\n start?: number | undefined;\n type?: \"1\" | \"a\" | \"A\" | \"i\" | \"I\" | undefined;\n }\n\n interface OptgroupHTMLAttributes extends HTMLAttributes {\n disabled?: boolean | undefined;\n label?: string | undefined;\n }\n\n interface OptionHTMLAttributes extends HTMLAttributes {\n disabled?: boolean | undefined;\n label?: string | undefined;\n selected?: boolean | undefined;\n value?: string | readonly string[] | number | undefined;\n }\n\n interface OutputHTMLAttributes extends HTMLAttributes {\n form?: string | undefined;\n htmlFor?: string | undefined;\n name?: string | undefined;\n }\n\n interface ParamHTMLAttributes extends HTMLAttributes {\n name?: string | undefined;\n value?: string | readonly string[] | number | undefined;\n }\n\n interface ProgressHTMLAttributes extends HTMLAttributes {\n max?: number | string | undefined;\n value?: string | readonly string[] | number | undefined;\n }\n\n interface SlotHTMLAttributes extends HTMLAttributes {\n name?: string | undefined;\n }\n\n interface ScriptHTMLAttributes extends HTMLAttributes {\n async?: boolean | undefined;\n blocking?: \"render\" | (string & {}) | undefined;\n /** @deprecated */\n charSet?: string | undefined;\n crossOrigin?: CrossOrigin;\n defer?: boolean | undefined;\n integrity?: string | undefined;\n noModule?: boolean | undefined;\n referrerPolicy?: HTMLAttributeReferrerPolicy | undefined;\n src?: string | undefined;\n type?: string | undefined;\n }\n\n interface SelectHTMLAttributes extends HTMLAttributes {\n autoComplete?: string | undefined;\n disabled?: boolean | undefined;\n form?: string | undefined;\n multiple?: boolean | undefined;\n name?: string | undefined;\n required?: boolean | undefined;\n size?: number | undefined;\n value?: string | readonly string[] | number | undefined;\n onChange?: ChangeEventHandler | undefined;\n }\n\n interface SourceHTMLAttributes extends HTMLAttributes {\n height?: number | string | undefined;\n media?: string | undefined;\n sizes?: string | undefined;\n src?: string | undefined;\n srcSet?: string | undefined;\n type?: string | undefined;\n width?: number | string | undefined;\n }\n\n interface StyleHTMLAttributes extends HTMLAttributes {\n blocking?: \"render\" | (string & {}) | undefined;\n media?: string | undefined;\n scoped?: boolean | undefined;\n type?: string | undefined;\n }\n\n interface TableHTMLAttributes extends HTMLAttributes {\n align?: \"left\" | \"center\" | \"right\" | undefined;\n bgcolor?: string | undefined;\n border?: number | undefined;\n cellPadding?: number | string | undefined;\n cellSpacing?: number | string | undefined;\n frame?: boolean | undefined;\n rules?: \"none\" | \"groups\" | \"rows\" | \"columns\" | \"all\" | undefined;\n summary?: string | undefined;\n width?: number | string | undefined;\n }\n\n interface TextareaHTMLAttributes extends HTMLAttributes {\n autoComplete?: string | undefined;\n cols?: number | undefined;\n dirName?: string | undefined;\n disabled?: boolean | undefined;\n form?: string | undefined;\n maxLength?: number | undefined;\n minLength?: number | undefined;\n name?: string | undefined;\n placeholder?: string | undefined;\n readOnly?: boolean | undefined;\n required?: boolean | undefined;\n rows?: number | undefined;\n value?: string | readonly string[] | number | undefined;\n wrap?: string | undefined;\n\n onChange?: ChangeEventHandler | undefined;\n }\n\n interface TdHTMLAttributes extends HTMLAttributes {\n align?: \"left\" | \"center\" | \"right\" | \"justify\" | \"char\" | undefined;\n colSpan?: number | undefined;\n headers?: string | undefined;\n rowSpan?: number | undefined;\n scope?: string | undefined;\n abbr?: string | undefined;\n height?: number | string | undefined;\n width?: number | string | undefined;\n valign?: \"top\" | \"middle\" | \"bottom\" | \"baseline\" | undefined;\n }\n\n interface ThHTMLAttributes extends HTMLAttributes {\n align?: \"left\" | \"center\" | \"right\" | \"justify\" | \"char\" | undefined;\n colSpan?: number | undefined;\n headers?: string | undefined;\n rowSpan?: number | undefined;\n scope?: string | undefined;\n abbr?: string | undefined;\n }\n\n interface TimeHTMLAttributes extends HTMLAttributes {\n dateTime?: string | undefined;\n }\n\n interface TrackHTMLAttributes extends HTMLAttributes {\n default?: boolean | undefined;\n kind?: string | undefined;\n label?: string | undefined;\n src?: string | undefined;\n srcLang?: string | undefined;\n }\n\n interface VideoHTMLAttributes extends MediaHTMLAttributes {\n height?: number | string | undefined;\n playsInline?: boolean | undefined;\n poster?: string | undefined;\n width?: number | string | undefined;\n disablePictureInPicture?: boolean | undefined;\n disableRemotePlayback?: boolean | undefined;\n\n onResize?: ReactEventHandler | undefined;\n onResizeCapture?: ReactEventHandler | undefined;\n }\n\n // this list is \"complete\" in that it contains every SVG attribute\n // that React supports, but the types can be improved.\n // Full list here: https://facebook.github.io/react/docs/dom-elements.html\n //\n // The three broad type categories are (in order of restrictiveness):\n // - \"number | string\"\n // - \"string\"\n // - union of string literals\n interface SVGAttributes extends AriaAttributes, DOMAttributes {\n // React-specific Attributes\n suppressHydrationWarning?: boolean | undefined;\n\n // Attributes which also defined in HTMLAttributes\n // See comment in SVGDOMPropertyConfig.js\n className?: string | undefined;\n color?: string | undefined;\n height?: number | string | undefined;\n id?: string | undefined;\n lang?: string | undefined;\n max?: number | string | undefined;\n media?: string | undefined;\n method?: string | undefined;\n min?: number | string | undefined;\n name?: string | undefined;\n style?: CSSProperties | undefined;\n target?: string | undefined;\n type?: string | undefined;\n width?: number | string | undefined;\n\n // Other HTML properties supported by SVG elements in browsers\n role?: AriaRole | undefined;\n tabIndex?: number | undefined;\n crossOrigin?: CrossOrigin;\n\n // SVG Specific attributes\n accentHeight?: number | string | undefined;\n accumulate?: \"none\" | \"sum\" | undefined;\n additive?: \"replace\" | \"sum\" | undefined;\n alignmentBaseline?:\n | \"auto\"\n | \"baseline\"\n | \"before-edge\"\n | \"text-before-edge\"\n | \"middle\"\n | \"central\"\n | \"after-edge\"\n | \"text-after-edge\"\n | \"ideographic\"\n | \"alphabetic\"\n | \"hanging\"\n | \"mathematical\"\n | \"inherit\"\n | undefined;\n allowReorder?: \"no\" | \"yes\" | undefined;\n alphabetic?: number | string | undefined;\n amplitude?: number | string | undefined;\n arabicForm?: \"initial\" | \"medial\" | \"terminal\" | \"isolated\" | undefined;\n ascent?: number | string | undefined;\n attributeName?: string | undefined;\n attributeType?: string | undefined;\n autoReverse?: Booleanish | undefined;\n azimuth?: number | string | undefined;\n baseFrequency?: number | string | undefined;\n baselineShift?: number | string | undefined;\n baseProfile?: number | string | undefined;\n bbox?: number | string | undefined;\n begin?: number | string | undefined;\n bias?: number | string | undefined;\n by?: number | string | undefined;\n calcMode?: number | string | undefined;\n capHeight?: number | string | undefined;\n clip?: number | string | undefined;\n clipPath?: string | undefined;\n clipPathUnits?: number | string | undefined;\n clipRule?: number | string | undefined;\n colorInterpolation?: number | string | undefined;\n colorInterpolationFilters?: \"auto\" | \"sRGB\" | \"linearRGB\" | \"inherit\" | undefined;\n colorProfile?: number | string | undefined;\n colorRendering?: number | string | undefined;\n contentScriptType?: number | string | undefined;\n contentStyleType?: number | string | undefined;\n cursor?: number | string | undefined;\n cx?: number | string | undefined;\n cy?: number | string | undefined;\n d?: string | undefined;\n decelerate?: number | string | undefined;\n descent?: number | string | undefined;\n diffuseConstant?: number | string | undefined;\n direction?: number | string | undefined;\n display?: number | string | undefined;\n divisor?: number | string | undefined;\n dominantBaseline?:\n | \"auto\"\n | \"use-script\"\n | \"no-change\"\n | \"reset-size\"\n | \"ideographic\"\n | \"alphabetic\"\n | \"hanging\"\n | \"mathematical\"\n | \"central\"\n | \"middle\"\n | \"text-after-edge\"\n | \"text-before-edge\"\n | \"inherit\"\n | undefined;\n dur?: number | string | undefined;\n dx?: number | string | undefined;\n dy?: number | string | undefined;\n edgeMode?: number | string | undefined;\n elevation?: number | string | undefined;\n enableBackground?: number | string | undefined;\n end?: number | string | undefined;\n exponent?: number | string | undefined;\n externalResourcesRequired?: Booleanish | undefined;\n fill?: string | undefined;\n fillOpacity?: number | string | undefined;\n fillRule?: \"nonzero\" | \"evenodd\" | \"inherit\" | undefined;\n filter?: string | undefined;\n filterRes?: number | string | undefined;\n filterUnits?: number | string | undefined;\n floodColor?: number | string | undefined;\n floodOpacity?: number | string | undefined;\n focusable?: Booleanish | \"auto\" | undefined;\n fontFamily?: string | undefined;\n fontSize?: number | string | undefined;\n fontSizeAdjust?: number | string | undefined;\n fontStretch?: number | string | undefined;\n fontStyle?: number | string | undefined;\n fontVariant?: number | string | undefined;\n fontWeight?: number | string | undefined;\n format?: number | string | undefined;\n fr?: number | string | undefined;\n from?: number | string | undefined;\n fx?: number | string | undefined;\n fy?: number | string | undefined;\n g1?: number | string | undefined;\n g2?: number | string | undefined;\n glyphName?: number | string | undefined;\n glyphOrientationHorizontal?: number | string | undefined;\n glyphOrientationVertical?: number | string | undefined;\n glyphRef?: number | string | undefined;\n gradientTransform?: string | undefined;\n gradientUnits?: string | undefined;\n hanging?: number | string | undefined;\n horizAdvX?: number | string | undefined;\n horizOriginX?: number | string | undefined;\n href?: string | undefined;\n ideographic?: number | string | undefined;\n imageRendering?: number | string | undefined;\n in2?: number | string | undefined;\n in?: string | undefined;\n intercept?: number | string | undefined;\n k1?: number | string | undefined;\n k2?: number | string | undefined;\n k3?: number | string | undefined;\n k4?: number | string | undefined;\n k?: number | string | undefined;\n kernelMatrix?: number | string | undefined;\n kernelUnitLength?: number | string | undefined;\n kerning?: number | string | undefined;\n keyPoints?: number | string | undefined;\n keySplines?: number | string | undefined;\n keyTimes?: number | string | undefined;\n lengthAdjust?: number | string | undefined;\n letterSpacing?: number | string | undefined;\n lightingColor?: number | string | undefined;\n limitingConeAngle?: number | string | undefined;\n local?: number | string | undefined;\n markerEnd?: string | undefined;\n markerHeight?: number | string | undefined;\n markerMid?: string | undefined;\n markerStart?: string | undefined;\n markerUnits?: number | string | undefined;\n markerWidth?: number | string | undefined;\n mask?: string | undefined;\n maskContentUnits?: number | string | undefined;\n maskUnits?: number | string | undefined;\n mathematical?: number | string | undefined;\n mode?: number | string | undefined;\n numOctaves?: number | string | undefined;\n offset?: number | string | undefined;\n opacity?: number | string | undefined;\n operator?: number | string | undefined;\n order?: number | string | undefined;\n orient?: number | string | undefined;\n orientation?: number | string | undefined;\n origin?: number | string | undefined;\n overflow?: number | string | undefined;\n overlinePosition?: number | string | undefined;\n overlineThickness?: number | string | undefined;\n paintOrder?: number | string | undefined;\n panose1?: number | string | undefined;\n path?: string | undefined;\n pathLength?: number | string | undefined;\n patternContentUnits?: string | undefined;\n patternTransform?: number | string | undefined;\n patternUnits?: string | undefined;\n pointerEvents?: number | string | undefined;\n points?: string | undefined;\n pointsAtX?: number | string | undefined;\n pointsAtY?: number | string | undefined;\n pointsAtZ?: number | string | undefined;\n preserveAlpha?: Booleanish | undefined;\n preserveAspectRatio?: string | undefined;\n primitiveUnits?: number | string | undefined;\n r?: number | string | undefined;\n radius?: number | string | undefined;\n refX?: number | string | undefined;\n refY?: number | string | undefined;\n renderingIntent?: number | string | undefined;\n repeatCount?: number | string | undefined;\n repeatDur?: number | string | undefined;\n requiredExtensions?: number | string | undefined;\n requiredFeatures?: number | string | undefined;\n restart?: number | string | undefined;\n result?: string | undefined;\n rotate?: number | string | undefined;\n rx?: number | string | undefined;\n ry?: number | string | undefined;\n scale?: number | string | undefined;\n seed?: number | string | undefined;\n shapeRendering?: number | string | undefined;\n slope?: number | string | undefined;\n spacing?: number | string | undefined;\n specularConstant?: number | string | undefined;\n specularExponent?: number | string | undefined;\n speed?: number | string | undefined;\n spreadMethod?: string | undefined;\n startOffset?: number | string | undefined;\n stdDeviation?: number | string | undefined;\n stemh?: number | string | undefined;\n stemv?: number | string | undefined;\n stitchTiles?: number | string | undefined;\n stopColor?: string | undefined;\n stopOpacity?: number | string | undefined;\n strikethroughPosition?: number | string | undefined;\n strikethroughThickness?: number | string | undefined;\n string?: number | string | undefined;\n stroke?: string | undefined;\n strokeDasharray?: string | number | undefined;\n strokeDashoffset?: string | number | undefined;\n strokeLinecap?: \"butt\" | \"round\" | \"square\" | \"inherit\" | undefined;\n strokeLinejoin?: \"miter\" | \"round\" | \"bevel\" | \"inherit\" | undefined;\n strokeMiterlimit?: number | string | undefined;\n strokeOpacity?: number | string | undefined;\n strokeWidth?: number | string | undefined;\n surfaceScale?: number | string | undefined;\n systemLanguage?: number | string | undefined;\n tableValues?: number | string | undefined;\n targetX?: number | string | undefined;\n targetY?: number | string | undefined;\n textAnchor?: \"start\" | \"middle\" | \"end\" | \"inherit\" | undefined;\n textDecoration?: number | string | undefined;\n textLength?: number | string | undefined;\n textRendering?: number | string | undefined;\n to?: number | string | undefined;\n transform?: string | undefined;\n transformOrigin?: string | undefined;\n u1?: number | string | undefined;\n u2?: number | string | undefined;\n underlinePosition?: number | string | undefined;\n underlineThickness?: number | string | undefined;\n unicode?: number | string | undefined;\n unicodeBidi?: number | string | undefined;\n unicodeRange?: number | string | undefined;\n unitsPerEm?: number | string | undefined;\n vAlphabetic?: number | string | undefined;\n values?: string | undefined;\n vectorEffect?: number | string | undefined;\n version?: string | undefined;\n vertAdvY?: number | string | undefined;\n vertOriginX?: number | string | undefined;\n vertOriginY?: number | string | undefined;\n vHanging?: number | string | undefined;\n vIdeographic?: number | string | undefined;\n viewBox?: string | undefined;\n viewTarget?: number | string | undefined;\n visibility?: number | string | undefined;\n vMathematical?: number | string | undefined;\n widths?: number | string | undefined;\n wordSpacing?: number | string | undefined;\n writingMode?: number | string | undefined;\n x1?: number | string | undefined;\n x2?: number | string | undefined;\n x?: number | string | undefined;\n xChannelSelector?: string | undefined;\n xHeight?: number | string | undefined;\n xlinkActuate?: string | undefined;\n xlinkArcrole?: string | undefined;\n xlinkHref?: string | undefined;\n xlinkRole?: string | undefined;\n xlinkShow?: string | undefined;\n xlinkTitle?: string | undefined;\n xlinkType?: string | undefined;\n xmlBase?: string | undefined;\n xmlLang?: string | undefined;\n xmlns?: string | undefined;\n xmlnsXlink?: string | undefined;\n xmlSpace?: string | undefined;\n y1?: number | string | undefined;\n y2?: number | string | undefined;\n y?: number | string | undefined;\n yChannelSelector?: string | undefined;\n z?: number | string | undefined;\n zoomAndPan?: string | undefined;\n }\n\n interface WebViewHTMLAttributes extends HTMLAttributes {\n allowFullScreen?: boolean | undefined;\n allowpopups?: boolean | undefined;\n autosize?: boolean | undefined;\n blinkfeatures?: string | undefined;\n disableblinkfeatures?: string | undefined;\n disableguestresize?: boolean | undefined;\n disablewebsecurity?: boolean | undefined;\n guestinstance?: string | undefined;\n httpreferrer?: string | undefined;\n nodeintegration?: boolean | undefined;\n partition?: string | undefined;\n plugins?: boolean | undefined;\n preload?: string | undefined;\n src?: string | undefined;\n useragent?: string | undefined;\n webpreferences?: string | undefined;\n }\n\n //\n // React.DOM\n // ----------------------------------------------------------------------\n\n /* deprecated */\n interface ReactHTML {\n a: DetailedHTMLFactory, HTMLAnchorElement>;\n abbr: DetailedHTMLFactory, HTMLElement>;\n address: DetailedHTMLFactory, HTMLElement>;\n area: DetailedHTMLFactory, HTMLAreaElement>;\n article: DetailedHTMLFactory, HTMLElement>;\n aside: DetailedHTMLFactory, HTMLElement>;\n audio: DetailedHTMLFactory, HTMLAudioElement>;\n b: DetailedHTMLFactory, HTMLElement>;\n base: DetailedHTMLFactory, HTMLBaseElement>;\n bdi: DetailedHTMLFactory, HTMLElement>;\n bdo: DetailedHTMLFactory, HTMLElement>;\n big: DetailedHTMLFactory, HTMLElement>;\n blockquote: DetailedHTMLFactory, HTMLQuoteElement>;\n body: DetailedHTMLFactory, HTMLBodyElement>;\n br: DetailedHTMLFactory, HTMLBRElement>;\n button: DetailedHTMLFactory, HTMLButtonElement>;\n canvas: DetailedHTMLFactory, HTMLCanvasElement>;\n caption: DetailedHTMLFactory, HTMLElement>;\n center: DetailedHTMLFactory, HTMLElement>;\n cite: DetailedHTMLFactory, HTMLElement>;\n code: DetailedHTMLFactory, HTMLElement>;\n col: DetailedHTMLFactory, HTMLTableColElement>;\n colgroup: DetailedHTMLFactory, HTMLTableColElement>;\n data: DetailedHTMLFactory, HTMLDataElement>;\n datalist: DetailedHTMLFactory, HTMLDataListElement>;\n dd: DetailedHTMLFactory, HTMLElement>;\n del: DetailedHTMLFactory, HTMLModElement>;\n details: DetailedHTMLFactory, HTMLDetailsElement>;\n dfn: DetailedHTMLFactory, HTMLElement>;\n dialog: DetailedHTMLFactory, HTMLDialogElement>;\n div: DetailedHTMLFactory, HTMLDivElement>;\n dl: DetailedHTMLFactory, HTMLDListElement>;\n dt: DetailedHTMLFactory, HTMLElement>;\n em: DetailedHTMLFactory, HTMLElement>;\n embed: DetailedHTMLFactory, HTMLEmbedElement>;\n fieldset: DetailedHTMLFactory, HTMLFieldSetElement>;\n figcaption: DetailedHTMLFactory, HTMLElement>;\n figure: DetailedHTMLFactory, HTMLElement>;\n footer: DetailedHTMLFactory, HTMLElement>;\n form: DetailedHTMLFactory, HTMLFormElement>;\n h1: DetailedHTMLFactory, HTMLHeadingElement>;\n h2: DetailedHTMLFactory, HTMLHeadingElement>;\n h3: DetailedHTMLFactory, HTMLHeadingElement>;\n h4: DetailedHTMLFactory, HTMLHeadingElement>;\n h5: DetailedHTMLFactory, HTMLHeadingElement>;\n h6: DetailedHTMLFactory, HTMLHeadingElement>;\n head: DetailedHTMLFactory, HTMLHeadElement>;\n header: DetailedHTMLFactory, HTMLElement>;\n hgroup: DetailedHTMLFactory, HTMLElement>;\n hr: DetailedHTMLFactory, HTMLHRElement>;\n html: DetailedHTMLFactory, HTMLHtmlElement>;\n i: DetailedHTMLFactory, HTMLElement>;\n iframe: DetailedHTMLFactory, HTMLIFrameElement>;\n img: DetailedHTMLFactory, HTMLImageElement>;\n input: DetailedHTMLFactory, HTMLInputElement>;\n ins: DetailedHTMLFactory, HTMLModElement>;\n kbd: DetailedHTMLFactory, HTMLElement>;\n keygen: DetailedHTMLFactory, HTMLElement>;\n label: DetailedHTMLFactory, HTMLLabelElement>;\n legend: DetailedHTMLFactory, HTMLLegendElement>;\n li: DetailedHTMLFactory, HTMLLIElement>;\n link: DetailedHTMLFactory, HTMLLinkElement>;\n main: DetailedHTMLFactory, HTMLElement>;\n map: DetailedHTMLFactory, HTMLMapElement>;\n mark: DetailedHTMLFactory, HTMLElement>;\n menu: DetailedHTMLFactory, HTMLElement>;\n menuitem: DetailedHTMLFactory, HTMLElement>;\n meta: DetailedHTMLFactory, HTMLMetaElement>;\n meter: DetailedHTMLFactory, HTMLMeterElement>;\n nav: DetailedHTMLFactory, HTMLElement>;\n noscript: DetailedHTMLFactory, HTMLElement>;\n object: DetailedHTMLFactory, HTMLObjectElement>;\n ol: DetailedHTMLFactory, HTMLOListElement>;\n optgroup: DetailedHTMLFactory, HTMLOptGroupElement>;\n option: DetailedHTMLFactory, HTMLOptionElement>;\n output: DetailedHTMLFactory, HTMLOutputElement>;\n p: DetailedHTMLFactory, HTMLParagraphElement>;\n param: DetailedHTMLFactory, HTMLParamElement>;\n picture: DetailedHTMLFactory, HTMLElement>;\n pre: DetailedHTMLFactory, HTMLPreElement>;\n progress: DetailedHTMLFactory, HTMLProgressElement>;\n q: DetailedHTMLFactory, HTMLQuoteElement>;\n rp: DetailedHTMLFactory, HTMLElement>;\n rt: DetailedHTMLFactory, HTMLElement>;\n ruby: DetailedHTMLFactory, HTMLElement>;\n s: DetailedHTMLFactory, HTMLElement>;\n samp: DetailedHTMLFactory, HTMLElement>;\n search: DetailedHTMLFactory, HTMLElement>;\n slot: DetailedHTMLFactory, HTMLSlotElement>;\n script: DetailedHTMLFactory, HTMLScriptElement>;\n section: DetailedHTMLFactory, HTMLElement>;\n select: DetailedHTMLFactory, HTMLSelectElement>;\n small: DetailedHTMLFactory, HTMLElement>;\n source: DetailedHTMLFactory, HTMLSourceElement>;\n span: DetailedHTMLFactory, HTMLSpanElement>;\n strong: DetailedHTMLFactory, HTMLElement>;\n style: DetailedHTMLFactory, HTMLStyleElement>;\n sub: DetailedHTMLFactory, HTMLElement>;\n summary: DetailedHTMLFactory, HTMLElement>;\n sup: DetailedHTMLFactory, HTMLElement>;\n table: DetailedHTMLFactory, HTMLTableElement>;\n template: DetailedHTMLFactory, HTMLTemplateElement>;\n tbody: DetailedHTMLFactory, HTMLTableSectionElement>;\n td: DetailedHTMLFactory, HTMLTableDataCellElement>;\n textarea: DetailedHTMLFactory, HTMLTextAreaElement>;\n tfoot: DetailedHTMLFactory, HTMLTableSectionElement>;\n th: DetailedHTMLFactory, HTMLTableHeaderCellElement>;\n thead: DetailedHTMLFactory, HTMLTableSectionElement>;\n time: DetailedHTMLFactory, HTMLTimeElement>;\n title: DetailedHTMLFactory, HTMLTitleElement>;\n tr: DetailedHTMLFactory, HTMLTableRowElement>;\n track: DetailedHTMLFactory, HTMLTrackElement>;\n u: DetailedHTMLFactory, HTMLElement>;\n ul: DetailedHTMLFactory, HTMLUListElement>;\n \"var\": DetailedHTMLFactory, HTMLElement>;\n video: DetailedHTMLFactory, HTMLVideoElement>;\n wbr: DetailedHTMLFactory, HTMLElement>;\n webview: DetailedHTMLFactory, HTMLWebViewElement>;\n }\n\n /* deprecated */\n interface ReactSVG {\n animate: SVGFactory;\n circle: SVGFactory;\n clipPath: SVGFactory;\n defs: SVGFactory;\n desc: SVGFactory;\n ellipse: SVGFactory;\n feBlend: SVGFactory;\n feColorMatrix: SVGFactory;\n feComponentTransfer: SVGFactory;\n feComposite: SVGFactory;\n feConvolveMatrix: SVGFactory;\n feDiffuseLighting: SVGFactory;\n feDisplacementMap: SVGFactory;\n feDistantLight: SVGFactory;\n feDropShadow: SVGFactory;\n feFlood: SVGFactory;\n feFuncA: SVGFactory;\n feFuncB: SVGFactory;\n feFuncG: SVGFactory;\n feFuncR: SVGFactory;\n feGaussianBlur: SVGFactory;\n feImage: SVGFactory;\n feMerge: SVGFactory;\n feMergeNode: SVGFactory;\n feMorphology: SVGFactory;\n feOffset: SVGFactory;\n fePointLight: SVGFactory;\n feSpecularLighting: SVGFactory;\n feSpotLight: SVGFactory;\n feTile: SVGFactory;\n feTurbulence: SVGFactory;\n filter: SVGFactory;\n foreignObject: SVGFactory;\n g: SVGFactory;\n image: SVGFactory;\n line: SVGFactory;\n linearGradient: SVGFactory;\n marker: SVGFactory;\n mask: SVGFactory;\n metadata: SVGFactory;\n path: SVGFactory;\n pattern: SVGFactory;\n polygon: SVGFactory;\n polyline: SVGFactory;\n radialGradient: SVGFactory;\n rect: SVGFactory;\n stop: SVGFactory;\n svg: SVGFactory;\n switch: SVGFactory;\n symbol: SVGFactory;\n text: SVGFactory;\n textPath: SVGFactory;\n tspan: SVGFactory;\n use: SVGFactory;\n view: SVGFactory;\n }\n\n /* deprecated */\n interface ReactDOM extends ReactHTML, ReactSVG {}\n\n //\n // React.PropTypes\n // ----------------------------------------------------------------------\n\n /**\n * @deprecated Use `Validator` from the ´prop-types` instead.\n */\n type Validator = PropTypes.Validator;\n\n /**\n * @deprecated Use `Requireable` from the ´prop-types` instead.\n */\n type Requireable = PropTypes.Requireable;\n\n /**\n * @deprecated Use `ValidationMap` from the ´prop-types` instead.\n */\n type ValidationMap = PropTypes.ValidationMap;\n\n /**\n * @deprecated Use `WeakValidationMap` from the ´prop-types` instead.\n */\n type WeakValidationMap = {\n [K in keyof T]?: null extends T[K] ? Validator\n : undefined extends T[K] ? Validator\n : Validator;\n };\n\n /**\n * @deprecated Use `PropTypes.*` where `PropTypes` comes from `import * as PropTypes from 'prop-types'` instead.\n */\n interface ReactPropTypes {\n any: typeof PropTypes.any;\n array: typeof PropTypes.array;\n bool: typeof PropTypes.bool;\n func: typeof PropTypes.func;\n number: typeof PropTypes.number;\n object: typeof PropTypes.object;\n string: typeof PropTypes.string;\n node: typeof PropTypes.node;\n element: typeof PropTypes.element;\n instanceOf: typeof PropTypes.instanceOf;\n oneOf: typeof PropTypes.oneOf;\n oneOfType: typeof PropTypes.oneOfType;\n arrayOf: typeof PropTypes.arrayOf;\n objectOf: typeof PropTypes.objectOf;\n shape: typeof PropTypes.shape;\n exact: typeof PropTypes.exact;\n }\n\n //\n // React.Children\n // ----------------------------------------------------------------------\n\n /**\n * @deprecated - Use `typeof React.Children` instead.\n */\n // Sync with type of `const Children`.\n interface ReactChildren {\n map(\n children: C | readonly C[],\n fn: (child: C, index: number) => T,\n ): C extends null | undefined ? C : Array>;\n forEach(children: C | readonly C[], fn: (child: C, index: number) => void): void;\n count(children: any): number;\n only(children: C): C extends any[] ? never : C;\n toArray(children: ReactNode | ReactNode[]): Array>;\n }\n\n //\n // Browser Interfaces\n // https://github.com/nikeee/2048-typescript/blob/master/2048/js/touch.d.ts\n // ----------------------------------------------------------------------\n\n interface AbstractView {\n styleMedia: StyleMedia;\n document: Document;\n }\n\n interface Touch {\n identifier: number;\n target: EventTarget;\n screenX: number;\n screenY: number;\n clientX: number;\n clientY: number;\n pageX: number;\n pageY: number;\n }\n\n interface TouchList {\n [index: number]: Touch;\n length: number;\n item(index: number): Touch;\n identifiedTouch(identifier: number): Touch;\n }\n\n //\n // Error Interfaces\n // ----------------------------------------------------------------------\n interface ErrorInfo {\n /**\n * Captures which component contained the exception, and its ancestors.\n */\n componentStack?: string | null;\n digest?: string | null;\n }\n\n // Keep in sync with JSX namespace in ./jsx-runtime.d.ts and ./jsx-dev-runtime.d.ts\n namespace JSX {\n type ElementType = GlobalJSXElementType;\n interface Element extends GlobalJSXElement {}\n interface ElementClass extends GlobalJSXElementClass {}\n interface ElementAttributesProperty extends GlobalJSXElementAttributesProperty {}\n interface ElementChildrenAttribute extends GlobalJSXElementChildrenAttribute {}\n\n type LibraryManagedAttributes = GlobalJSXLibraryManagedAttributes;\n\n interface IntrinsicAttributes extends GlobalJSXIntrinsicAttributes {}\n interface IntrinsicClassAttributes extends GlobalJSXIntrinsicClassAttributes {}\n interface IntrinsicElements extends GlobalJSXIntrinsicElements {}\n }\n}\n\n// naked 'any' type in a conditional type will short circuit and union both the then/else branches\n// so boolean is only resolved for T = any\ntype IsExactlyAny = boolean extends (T extends never ? true : false) ? true : false;\n\ntype ExactlyAnyPropertyKeys = { [K in keyof T]: IsExactlyAny extends true ? K : never }[keyof T];\ntype NotExactlyAnyPropertyKeys = Exclude>;\n\n// Try to resolve ill-defined props like for JS users: props can be any, or sometimes objects with properties of type any\ntype MergePropTypes =\n // Distribute over P in case it is a union type\n P extends any\n // If props is type any, use propTypes definitions\n ? IsExactlyAny

extends true ? T\n // If declared props have indexed properties, ignore inferred props entirely as keyof gets widened\n : string extends keyof P ? P\n // Prefer declared types which are not exactly any\n :\n & Pick>\n // For props which are exactly any, use the type inferred from propTypes if present\n & Pick>>\n // Keep leftover props not specified in propTypes\n & Pick>\n : never;\n\ntype InexactPartial = { [K in keyof T]?: T[K] | undefined };\n\n// Any prop that has a default prop becomes optional, but its type is unchanged\n// Undeclared default props are augmented into the resulting allowable attributes\n// If declared props have indexed properties, ignore default props entirely as keyof gets widened\n// Wrap in an outer-level conditional type to allow distribution over props that are unions\ntype Defaultize = P extends any ? string extends keyof P ? P\n :\n & Pick>\n & InexactPartial>>\n & InexactPartial>>\n : never;\n\ntype ReactManagedAttributes = C extends { propTypes: infer T; defaultProps: infer D }\n ? Defaultize>, D>\n : C extends { propTypes: infer T } ? MergePropTypes>\n : C extends { defaultProps: infer D } ? Defaultize\n : P;\n\ndeclare global {\n /**\n * @deprecated Use `React.JSX` instead of the global `JSX` namespace.\n */\n namespace JSX {\n // We don't just alias React.ElementType because React.ElementType\n // historically does more than we need it to.\n // E.g. it also contains .propTypes and so TS also verifies the declared\n // props type does match the declared .propTypes.\n // But if libraries declared their .propTypes but not props type,\n // or they mismatch, you won't be able to use the class component\n // as a JSX.ElementType.\n // We could fix this everywhere but we're ultimately not interested in\n // .propTypes assignability so we might as well drop it entirely here to\n // reduce the work of the type-checker.\n // TODO: Check impact of making React.ElementType

= React.JSXElementConstructor

\n type ElementType = string | React.JSXElementConstructor;\n interface Element extends React.ReactElement {}\n interface ElementClass extends React.Component {\n render(): React.ReactNode;\n }\n interface ElementAttributesProperty {\n props: {};\n }\n interface ElementChildrenAttribute {\n children: {};\n }\n\n // We can't recurse forever because `type` can't be self-referential;\n // let's assume it's reasonable to do a single React.lazy() around a single React.memo() / vice-versa\n type LibraryManagedAttributes = C extends\n React.MemoExoticComponent | React.LazyExoticComponent\n ? T extends React.MemoExoticComponent | React.LazyExoticComponent\n ? ReactManagedAttributes\n : ReactManagedAttributes\n : ReactManagedAttributes;\n\n interface IntrinsicAttributes extends React.Attributes {}\n interface IntrinsicClassAttributes extends React.ClassAttributes {}\n\n interface IntrinsicElements {\n // HTML\n a: React.DetailedHTMLProps, HTMLAnchorElement>;\n abbr: React.DetailedHTMLProps, HTMLElement>;\n address: React.DetailedHTMLProps, HTMLElement>;\n area: React.DetailedHTMLProps, HTMLAreaElement>;\n article: React.DetailedHTMLProps, HTMLElement>;\n aside: React.DetailedHTMLProps, HTMLElement>;\n audio: React.DetailedHTMLProps, HTMLAudioElement>;\n b: React.DetailedHTMLProps, HTMLElement>;\n base: React.DetailedHTMLProps, HTMLBaseElement>;\n bdi: React.DetailedHTMLProps, HTMLElement>;\n bdo: React.DetailedHTMLProps, HTMLElement>;\n big: React.DetailedHTMLProps, HTMLElement>;\n blockquote: React.DetailedHTMLProps, HTMLQuoteElement>;\n body: React.DetailedHTMLProps, HTMLBodyElement>;\n br: React.DetailedHTMLProps, HTMLBRElement>;\n button: React.DetailedHTMLProps, HTMLButtonElement>;\n canvas: React.DetailedHTMLProps, HTMLCanvasElement>;\n caption: React.DetailedHTMLProps, HTMLElement>;\n center: React.DetailedHTMLProps, HTMLElement>;\n cite: React.DetailedHTMLProps, HTMLElement>;\n code: React.DetailedHTMLProps, HTMLElement>;\n col: React.DetailedHTMLProps, HTMLTableColElement>;\n colgroup: React.DetailedHTMLProps, HTMLTableColElement>;\n data: React.DetailedHTMLProps, HTMLDataElement>;\n datalist: React.DetailedHTMLProps, HTMLDataListElement>;\n dd: React.DetailedHTMLProps, HTMLElement>;\n del: React.DetailedHTMLProps, HTMLModElement>;\n details: React.DetailedHTMLProps, HTMLDetailsElement>;\n dfn: React.DetailedHTMLProps, HTMLElement>;\n dialog: React.DetailedHTMLProps, HTMLDialogElement>;\n div: React.DetailedHTMLProps, HTMLDivElement>;\n dl: React.DetailedHTMLProps, HTMLDListElement>;\n dt: React.DetailedHTMLProps, HTMLElement>;\n em: React.DetailedHTMLProps, HTMLElement>;\n embed: React.DetailedHTMLProps, HTMLEmbedElement>;\n fieldset: React.DetailedHTMLProps, HTMLFieldSetElement>;\n figcaption: React.DetailedHTMLProps, HTMLElement>;\n figure: React.DetailedHTMLProps, HTMLElement>;\n footer: React.DetailedHTMLProps, HTMLElement>;\n form: React.DetailedHTMLProps, HTMLFormElement>;\n h1: React.DetailedHTMLProps, HTMLHeadingElement>;\n h2: React.DetailedHTMLProps, HTMLHeadingElement>;\n h3: React.DetailedHTMLProps, HTMLHeadingElement>;\n h4: React.DetailedHTMLProps, HTMLHeadingElement>;\n h5: React.DetailedHTMLProps, HTMLHeadingElement>;\n h6: React.DetailedHTMLProps, HTMLHeadingElement>;\n head: React.DetailedHTMLProps, HTMLHeadElement>;\n header: React.DetailedHTMLProps, HTMLElement>;\n hgroup: React.DetailedHTMLProps, HTMLElement>;\n hr: React.DetailedHTMLProps, HTMLHRElement>;\n html: React.DetailedHTMLProps, HTMLHtmlElement>;\n i: React.DetailedHTMLProps, HTMLElement>;\n iframe: React.DetailedHTMLProps, HTMLIFrameElement>;\n img: React.DetailedHTMLProps, HTMLImageElement>;\n input: React.DetailedHTMLProps, HTMLInputElement>;\n ins: React.DetailedHTMLProps, HTMLModElement>;\n kbd: React.DetailedHTMLProps, HTMLElement>;\n keygen: React.DetailedHTMLProps, HTMLElement>;\n label: React.DetailedHTMLProps, HTMLLabelElement>;\n legend: React.DetailedHTMLProps, HTMLLegendElement>;\n li: React.DetailedHTMLProps, HTMLLIElement>;\n link: React.DetailedHTMLProps, HTMLLinkElement>;\n main: React.DetailedHTMLProps, HTMLElement>;\n map: React.DetailedHTMLProps, HTMLMapElement>;\n mark: React.DetailedHTMLProps, HTMLElement>;\n menu: React.DetailedHTMLProps, HTMLElement>;\n menuitem: React.DetailedHTMLProps, HTMLElement>;\n meta: React.DetailedHTMLProps, HTMLMetaElement>;\n meter: React.DetailedHTMLProps, HTMLMeterElement>;\n nav: React.DetailedHTMLProps, HTMLElement>;\n noindex: React.DetailedHTMLProps, HTMLElement>;\n noscript: React.DetailedHTMLProps, HTMLElement>;\n object: React.DetailedHTMLProps, HTMLObjectElement>;\n ol: React.DetailedHTMLProps, HTMLOListElement>;\n optgroup: React.DetailedHTMLProps, HTMLOptGroupElement>;\n option: React.DetailedHTMLProps, HTMLOptionElement>;\n output: React.DetailedHTMLProps, HTMLOutputElement>;\n p: React.DetailedHTMLProps, HTMLParagraphElement>;\n param: React.DetailedHTMLProps, HTMLParamElement>;\n picture: React.DetailedHTMLProps, HTMLElement>;\n pre: React.DetailedHTMLProps, HTMLPreElement>;\n progress: React.DetailedHTMLProps, HTMLProgressElement>;\n q: React.DetailedHTMLProps, HTMLQuoteElement>;\n rp: React.DetailedHTMLProps, HTMLElement>;\n rt: React.DetailedHTMLProps, HTMLElement>;\n ruby: React.DetailedHTMLProps, HTMLElement>;\n s: React.DetailedHTMLProps, HTMLElement>;\n samp: React.DetailedHTMLProps, HTMLElement>;\n search: React.DetailedHTMLProps, HTMLElement>;\n slot: React.DetailedHTMLProps, HTMLSlotElement>;\n script: React.DetailedHTMLProps, HTMLScriptElement>;\n section: React.DetailedHTMLProps, HTMLElement>;\n select: React.DetailedHTMLProps, HTMLSelectElement>;\n small: React.DetailedHTMLProps, HTMLElement>;\n source: React.DetailedHTMLProps, HTMLSourceElement>;\n span: React.DetailedHTMLProps, HTMLSpanElement>;\n strong: React.DetailedHTMLProps, HTMLElement>;\n style: React.DetailedHTMLProps, HTMLStyleElement>;\n sub: React.DetailedHTMLProps, HTMLElement>;\n summary: React.DetailedHTMLProps, HTMLElement>;\n sup: React.DetailedHTMLProps, HTMLElement>;\n table: React.DetailedHTMLProps, HTMLTableElement>;\n template: React.DetailedHTMLProps, HTMLTemplateElement>;\n tbody: React.DetailedHTMLProps, HTMLTableSectionElement>;\n td: React.DetailedHTMLProps, HTMLTableDataCellElement>;\n textarea: React.DetailedHTMLProps, HTMLTextAreaElement>;\n tfoot: React.DetailedHTMLProps, HTMLTableSectionElement>;\n th: React.DetailedHTMLProps, HTMLTableHeaderCellElement>;\n thead: React.DetailedHTMLProps, HTMLTableSectionElement>;\n time: React.DetailedHTMLProps, HTMLTimeElement>;\n title: React.DetailedHTMLProps, HTMLTitleElement>;\n tr: React.DetailedHTMLProps, HTMLTableRowElement>;\n track: React.DetailedHTMLProps, HTMLTrackElement>;\n u: React.DetailedHTMLProps, HTMLElement>;\n ul: React.DetailedHTMLProps, HTMLUListElement>;\n \"var\": React.DetailedHTMLProps, HTMLElement>;\n video: React.DetailedHTMLProps, HTMLVideoElement>;\n wbr: React.DetailedHTMLProps, HTMLElement>;\n webview: React.DetailedHTMLProps, HTMLWebViewElement>;\n\n // SVG\n svg: React.SVGProps;\n\n animate: React.SVGProps; // TODO: It is SVGAnimateElement but is not in TypeScript's lib.dom.d.ts for now.\n animateMotion: React.SVGProps;\n animateTransform: React.SVGProps; // TODO: It is SVGAnimateTransformElement but is not in TypeScript's lib.dom.d.ts for now.\n circle: React.SVGProps;\n clipPath: React.SVGProps;\n defs: React.SVGProps;\n desc: React.SVGProps;\n ellipse: React.SVGProps;\n feBlend: React.SVGProps;\n feColorMatrix: React.SVGProps;\n feComponentTransfer: React.SVGProps;\n feComposite: React.SVGProps;\n feConvolveMatrix: React.SVGProps;\n feDiffuseLighting: React.SVGProps;\n feDisplacementMap: React.SVGProps;\n feDistantLight: React.SVGProps;\n feDropShadow: React.SVGProps;\n feFlood: React.SVGProps;\n feFuncA: React.SVGProps;\n feFuncB: React.SVGProps;\n feFuncG: React.SVGProps;\n feFuncR: React.SVGProps;\n feGaussianBlur: React.SVGProps;\n feImage: React.SVGProps;\n feMerge: React.SVGProps;\n feMergeNode: React.SVGProps;\n feMorphology: React.SVGProps;\n feOffset: React.SVGProps;\n fePointLight: React.SVGProps;\n feSpecularLighting: React.SVGProps;\n feSpotLight: React.SVGProps;\n feTile: React.SVGProps;\n feTurbulence: React.SVGProps;\n filter: React.SVGProps;\n foreignObject: React.SVGProps;\n g: React.SVGProps;\n image: React.SVGProps;\n line: React.SVGLineElementAttributes;\n linearGradient: React.SVGProps;\n marker: React.SVGProps;\n mask: React.SVGProps;\n metadata: React.SVGProps;\n mpath: React.SVGProps;\n path: React.SVGProps;\n pattern: React.SVGProps;\n polygon: React.SVGProps;\n polyline: React.SVGProps;\n radialGradient: React.SVGProps;\n rect: React.SVGProps;\n set: React.SVGProps;\n stop: React.SVGProps;\n switch: React.SVGProps;\n symbol: React.SVGProps;\n text: React.SVGTextElementAttributes;\n textPath: React.SVGProps;\n tspan: React.SVGProps;\n use: React.SVGProps;\n view: React.SVGProps;\n }\n }\n}\n\n// React.JSX needs to point to global.JSX to keep global module augmentations intact.\n// But we can't access global.JSX so we need to create these aliases instead.\n// Once the global JSX namespace will be removed we replace React.JSX with the contents of global.JSX\ntype GlobalJSXElementType = JSX.ElementType;\ninterface GlobalJSXElement extends JSX.Element {}\ninterface GlobalJSXElementClass extends JSX.ElementClass {}\ninterface GlobalJSXElementAttributesProperty extends JSX.ElementAttributesProperty {}\ninterface GlobalJSXElementChildrenAttribute extends JSX.ElementChildrenAttribute {}\n\ntype GlobalJSXLibraryManagedAttributes = JSX.LibraryManagedAttributes;\n\ninterface GlobalJSXIntrinsicAttributes extends JSX.IntrinsicAttributes {}\ninterface GlobalJSXIntrinsicClassAttributes extends JSX.IntrinsicClassAttributes {}\n\ninterface GlobalJSXIntrinsicElements extends JSX.IntrinsicElements {}\n" +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/classic/saved-challenges.test.ts b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/classic/saved-challenges.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..5e1d648076a7b072da4ae71eebd03a4a3ff3a37f --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/classic/saved-challenges.test.ts @@ -0,0 +1,143 @@ +import { describe, it, expect } from 'vitest'; +import type { + ChallengeFile, + SavedChallengeFile +} from '../../../redux/prop-types'; +import { mergeChallengeFiles } from './saved-challenges'; + +const jsChallenge = { + contents: 'js contents', + fileKey: 'jsFileKey', + name: 'name', + ext: 'js' as const, + history: [], + seed: 'original js contents', + path: 'index.js' +}; + +const cssChallenge = { + contents: 'css contents', + fileKey: 'cssFileKey', + name: 'name', + ext: 'css' as const, + history: [], + seed: 'original css contents', + path: 'styles.css' +}; + +const htmlChallenge = { + contents: 'html contents', + fileKey: 'htmlFileKey', + name: 'name', + ext: 'html' as const, + history: [], + seed: 'original html contents', + path: 'index.html' +}; + +const savedJsChallenge: SavedChallengeFile = { + contents: 'saved js contents', + fileKey: 'jsFileKey', + name: 'name', + ext: 'js' as const +}; + +const savedCssChallenge: SavedChallengeFile = { + contents: 'saved css contents', + fileKey: 'cssFileKey', + name: 'name', + ext: 'css' as const +}; + +const savedHtmlChallenge: SavedChallengeFile = { + contents: 'saved html contents', + fileKey: 'htmlFileKey', + name: 'name', + ext: 'html' as const +}; + +describe('mergeChallengeFiles', () => { + it('should return files if savedChallengeFiles is undefined', () => { + const files: ChallengeFile[] = [htmlChallenge]; + const savedChallengeFiles = undefined; + + const result = mergeChallengeFiles(files, savedChallengeFiles); + + expect(result).toEqual(files); + }); + + it('should return an empty array if files is undefined', () => { + const files = undefined; + const savedChallengeFiles = [savedJsChallenge]; + + const result = mergeChallengeFiles(files, savedChallengeFiles); + + expect(result).toEqual([]); + }); + + it('should return files if savedChallengeFiles has a different length', () => { + const files: ChallengeFile[] = [cssChallenge]; + const savedChallengeFiles: SavedChallengeFile[] = [ + savedCssChallenge, + savedJsChallenge + ]; + + const result = mergeChallengeFiles(files, savedChallengeFiles); + + expect(result).toEqual(files); + }); + + it('should return files if the fileKey properties do not match', () => { + const files: ChallengeFile[] = [jsChallenge, cssChallenge]; + const savedChallengeFiles: SavedChallengeFile[] = [ + savedHtmlChallenge, + savedCssChallenge + ]; + + const result = mergeChallengeFiles(files, savedChallengeFiles); + + expect(result).toEqual(files); + }); + + it('should use the contents from the saved file', () => { + const files: ChallengeFile[] = [cssChallenge, htmlChallenge, jsChallenge]; + const savedChallengeFiles = [ + savedJsChallenge, + savedCssChallenge, + savedHtmlChallenge + ]; + + const result = mergeChallengeFiles(files, savedChallengeFiles); + + expect(result).toEqual([ + { + ...cssChallenge, + contents: savedCssChallenge.contents + }, + { + ...htmlChallenge, + contents: savedHtmlChallenge.contents + }, + { + ...jsChallenge, + contents: savedJsChallenge.contents + } + ]); + }); + + it('should not mutate the original files and savedChallengeFiles arrays', () => { + const files: ChallengeFile[] = [jsChallenge, cssChallenge]; + const savedChallengeFiles: SavedChallengeFile[] = [ + savedJsChallenge, + savedCssChallenge + ]; + + const filesCopy = JSON.parse(JSON.stringify(files)); + const savedFilesCopy = JSON.parse(JSON.stringify(savedChallengeFiles)); + + mergeChallengeFiles(files, savedChallengeFiles); + + expect(files).toEqual(filesCopy); + expect(savedChallengeFiles).toEqual(savedFilesCopy); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/classic/saved-challenges.ts b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/classic/saved-challenges.ts new file mode 100644 index 0000000000000000000000000000000000000000..12979be1fb9ef97efe7a1f6b7e14ed135d1ab258 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/classic/saved-challenges.ts @@ -0,0 +1,30 @@ +import { ChallengeFile, SavedChallengeFile } from '../../../redux/prop-types'; + +export function mergeChallengeFiles( + files?: ChallengeFile[] | null, + savedFiles?: SavedChallengeFile[] | null +): ChallengeFile[] { + if (!files) return []; + if (!savedFiles) return files; + if (files.length !== savedFiles.length) return files; + + const sortedChallengeFiles = files.toSorted((a, b) => + a.fileKey.localeCompare(b.fileKey) + ); + const sortedSavedChallengeFiles = savedFiles.toSorted((a, b) => + a.fileKey.localeCompare(b.fileKey) + ); + + const fileKeysMatch = sortedChallengeFiles.every( + (file, index) => file.fileKey === sortedSavedChallengeFiles[index].fileKey + ); + + if (!fileKeysMatch) return files; + + return sortedChallengeFiles.map((file, index) => ({ + ...file, + contents: sortedSavedChallengeFiles[index].contents, + editableRegionBoundaries: + sortedSavedChallengeFiles[index].editableRegionBoundaries + })); +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/classic/show.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/classic/show.tsx new file mode 100644 index 0000000000000000000000000000000000000000..3f6a94a67457fbcf0406d1add0a616c480b7d092 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/classic/show.tsx @@ -0,0 +1,593 @@ +import { graphql } from 'gatsby'; +import React, { useState, useEffect, useRef } from 'react'; +import Helmet from 'react-helmet'; +import { useTranslation } from 'react-i18next'; +import { connect } from 'react-redux'; +import { HandlerProps } from 'react-reflex'; +import { useMediaQuery } from 'react-responsive'; +import { bindActionCreators, Dispatch } from 'redux'; +import store from 'store'; +import { editor } from 'monaco-editor'; +import type { FitAddon } from '@xterm/addon-fit'; + +import { useFeature } from '@growthbook/growthbook-react'; +import { challengeTypes } from '@freecodecamp/shared/config/challenge-types'; +import LearnLayout from '../../../components/layouts/learn'; +import { MAX_MOBILE_WIDTH } from '../../../../config/misc'; + +import type { + ChallengeFiles, + ChallengeMeta, + ChallengeNode, + Hooks, + DailyCodingChallengeLanguages, + DailyCodingChallengeNode, + DailyCodingChallengePageContext, + PageContext, + ResizeProps, + SavedChallenge, + SavedChallengeFiles, + Test +} from '../../../redux/prop-types'; +import { isContained } from '../../../utils/is-contained'; +import ChallengeDescription from '../components/challenge-description'; +import Hotkeys from '../components/hotkeys'; +import ResetModal from '../components/reset-modal'; +import ChallengeTitle from '../components/challenge-title'; +import CompletionModal from '../components/completion-modal'; +import HelpModal from '../components/help-modal'; +import ShortcutsModal from '../components/shortcuts-modal'; +import MobileAppModal from '../components/mobile-app-modal'; +import Output from '../components/output'; +import Preview, { type PreviewProps } from '../components/preview'; +import ProjectPreviewModal from '../components/project-preview-modal'; +import SidePanel from '../components/side-panel'; +import VideoModal from '../components/video-modal'; +import { + cancelTests, + challengeMounted, + createFiles, + executeChallenge, + initConsole, + initTests, + initHooks, + initVisibleEditors, + previewMounted, + updateChallengeMeta, + openModal, + setEditorFocusability, + setIsAdvancing +} from '../redux/actions'; +import { + challengeFilesSelector, + consoleOutputSelector, + isChallengeCompletedSelector +} from '../redux/selectors'; +import { savedChallengesSelector } from '../../../redux/selectors'; +import { getGuideUrl } from '../utils'; +import { preloadPage } from '../../../../utils/gatsby/page-loading'; +import envData from '../../../../config/env.json'; +import { getChallengePaths } from '../utils/challenge-paths'; +import { challengeHasPreview, isJavaScriptChallenge } from '../utils/build'; +import { XtermTerminal } from './xterm'; +import MultifileEditor from './multifile-editor'; +import DesktopLayout from './desktop-layout'; +import MobileLayout from './mobile-layout'; +import { mergeChallengeFiles } from './saved-challenges'; + +import './classic.css'; +import '../components/test-frame.css'; + +const mapStateToProps = (state: unknown) => ({ + challengeFiles: challengeFilesSelector(state) as ChallengeFiles, + output: consoleOutputSelector(state) as string, + isChallengeCompleted: isChallengeCompletedSelector(state), + savedChallenges: savedChallengesSelector(state) as SavedChallenge[] +}); + +const mapDispatchToProps = (dispatch: Dispatch) => + bindActionCreators( + { + createFiles, + initConsole, + initTests, + initHooks, + initVisibleEditors, + updateChallengeMeta, + challengeMounted, + executeChallenge, + cancelTests, + previewMounted, + openModal, + setEditorFocusability, + setIsAdvancing + }, + dispatch + ); + +interface ShowClassicProps extends Pick { + cancelTests: () => void; + challengeMounted: (arg0: string) => void; + createFiles: (arg0: ChallengeFiles | SavedChallengeFiles) => void; + dailyCodingChallengeLanguage: DailyCodingChallengeLanguages; + data: { challengeNode: ChallengeNode | DailyCodingChallengeNode }; + executeChallenge: (options?: { showCompletionModal: boolean }) => void; + challengeFiles: ChallengeFiles; + initConsole: (arg0: string) => void; + initTests: (tests: Test[]) => void; + initHooks: (hooks?: Hooks) => void; + initVisibleEditors: () => void; + isChallengeCompleted: boolean; + isDailyCodingChallenge?: boolean; + output: string; + pageContext: PageContext | DailyCodingChallengePageContext; + updateChallengeMeta: (arg0: ChallengeMeta) => void; + openModal: (modal: string) => void; + setDailyCodingChallengeLanguage: ( + language: DailyCodingChallengeLanguages + ) => void; + setEditorFocusability: (canFocus: boolean) => void; + setIsAdvancing: (arg: boolean) => void; + savedChallenges: SavedChallenge[]; +} + +interface ReflexLayout { + codePane: { flex: number }; + editorPane: { flex: number }; + instructionPane: { flex: number }; + notesPane: { flex: number }; + previewPane: { flex: number }; + testsPane: { flex: number }; +} + +interface RenderEditorArgs { + isMobileLayout: boolean; + isUsingKeyboardInTablist: boolean; +} + +const REFLEX_LAYOUT = 'challenge-layout'; +const BASE_LAYOUT = { + codePane: { flex: 1 }, + editorPane: { flex: 1 }, + instructionPane: { flex: 1 }, + previewPane: { flex: 0.7 }, + notesPane: { flex: 0.7 }, + testsPane: { flex: 0.3 } +}; + +const StepPreview = ({ + dimensions, + disableIframe, + previewMounted, + challengeType, + xtermFitRef +}: Pick & { + challengeType: number; + xtermFitRef: React.MutableRefObject; + dimensions?: { width: number; height: number }; +}) => { + return challengeType === challengeTypes.python || + challengeType === challengeTypes.multifilePythonCertProject || + challengeType === challengeTypes.pyLab || + challengeType === challengeTypes.dailyChallengePy ? ( + + ) : ( + + ); +}; + +// The newline is important, because this text ends up in a `pre` element. +const defaultOutput = ` +/** +* Your test output will go here +*/`; + +function ShowClassic({ + challengeFiles, + data: { + challengeNode: { + challenge: { + challengeFiles: seedChallengeFiles, + block, + demoType, + title, + description, + instructions, + id, + hooks, + tests, + challengeType, + hasEditableBoundaries = false, + superBlock, + helpCategory, + forumTopicId, + usesMultifileEditor, + notes, + videoUrl, + translationPending, + saveSubmissionToDB + } + } + }, + pageContext: { + challengeMeta, + challengeMeta: { isFirstStep, nextChallengePath }, + projectPreview: { challengeData } + }, + createFiles, + cancelTests, + challengeMounted, + initConsole, + initTests, + initHooks, + initVisibleEditors, + dailyCodingChallengeLanguage, + isDailyCodingChallenge = false, + setDailyCodingChallengeLanguage, + updateChallengeMeta, + openModal, + setIsAdvancing, + savedChallenges, + isChallengeCompleted, + output, + executeChallenge, + previewMounted +}: ShowClassicProps) { + const { t } = useTranslation(); + const [resizing, setResizing] = useState(false); + const [usingKeyboardInTablist, setUsingKeyboardInTablist] = useState(false); + const containerRef = useRef(null); + const editorRef = useRef(); + const instructionsPanelRef = useRef(null); + const xtermFitRef = useRef(null); + const isMobile = useMediaQuery({ + query: `(max-width: ${MAX_MOBILE_WIDTH}px)` + }); + + const guideUrl = getGuideUrl({ forumTopicId, title, block, superBlock }); + + const blockNameTitle = `${t( + `intro:${superBlock}.blocks.${block}.title` + )}: ${title}`; + const windowTitle = `${blockNameTitle} | freeCodeCamp.org`; + const openConsole = isJavaScriptChallenge({ challengeType }); + const hasPreview = challengeHasPreview({ challengeType }); + const getLayoutState = () => { + const reflexLayout = store.get(REFLEX_LAYOUT) as ReflexLayout | null; + + // Check that the layout values stored are valid (exist in base layout). If + // not valid, it will fallback to the base layout values and be set on next + // user resize. + const isValidLayout = + reflexLayout && + isContained(Object.keys(BASE_LAYOUT), Object.keys(reflexLayout)); + + if (!isValidLayout) store.remove(REFLEX_LAYOUT); + + return isValidLayout ? reflexLayout : BASE_LAYOUT; + }; + + const onPreviewResize = () => xtermFitRef.current?.fit(); + + // layout: Holds the information of the panes sizes for desktop view + const [layout, setLayout] = useState(getLayoutState()); + + const onStopResize = (event: HandlerProps) => { + setResizing(false); + // 'name' is used to identify the Elements whose layout is stored. + const { name, flex } = event.component.props; + + // onStopResize can be called multiple times before the state changes, so + // we need an updater function to ensure all updates are applied. + setLayout(l => { + const newLayout = name ? { ...l, [name]: { flex } } : l; + store.set(REFLEX_LAYOUT, newLayout); + return newLayout; + }); + }; + + const setHtmlHeight = () => { + const vh = String(window.innerHeight - 1); + document.documentElement.style.height = vh + 'px'; + }; + const onResize = () => { + setResizing(true); + }; + const resizeProps: ResizeProps = { + onResize, + onStopResize + }; + + const updateUsingKeyboardInTablist = ( + usingKeyboardInTablist: boolean + ): void => { + setUsingKeyboardInTablist(usingKeyboardInTablist); + }; + + // AB testing Pre-fetch in the Spanish locale + const isPreFetchEnabled = useFeature('prefetch_ab_test').on; + + const showSidePanelTests = isMobile || !hasEditableBoundaries; + + // Show test + + useEffect(() => { + if ( + isPreFetchEnabled && + (envData as { clientLocale: string }).clientLocale === 'espanol' + ) { + preloadPage(nextChallengePath); + } + }, [nextChallengePath, isPreFetchEnabled]); + + useEffect(() => { + initializeComponent(title); + + window.addEventListener('resize', setHtmlHeight); + setHtmlHeight(); + + return () => { + createFiles([]); + cancelTests(); + window.removeEventListener('resize', setHtmlHeight); + }; + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [dailyCodingChallengeLanguage]); + + const initializeComponent = (title: string): void => { + initConsole(''); + + const savedChallenge = savedChallenges?.find(challenge => { + return challenge.id === challengeMeta.id; + }); + + createFiles( + mergeChallengeFiles(seedChallengeFiles, savedChallenge?.challengeFiles) + ); + + initTests(tests); + initHooks(hooks); + + initVisibleEditors(); + + // Typically, this kind of preview only appears on the first step of a + // project and is shown (once) automatically. In contrast, labs are more + // freeform, so the preview is shown on demand. + if (demoType === 'onLoad') openModal('projectPreview'); + const challengePaths = getChallengePaths({ + currentCurriculumPaths: challengeMeta + }); + + updateChallengeMeta({ + ...challengeMeta, + title, + challengeType, + helpCategory, + description, + ...challengePaths + }); + challengeMounted(challengeMeta.id); + setIsAdvancing(false); + }; + + const renderInstructionsPanel = ({ hasDemo }: { hasDemo: boolean }) => { + return ( + + } + challengeTitle={ + + {title} + + } + instructionsPanelRef={instructionsPanelRef} + hasDemo={hasDemo} + showSidePanelTests={showSidePanelTests} + /> + ); + }; + + const renderEditor = ({ + isMobileLayout, + isUsingKeyboardInTablist + }: RenderEditorArgs) => { + return ( + challengeFiles && ( + + ) + ); + }; + + const usesTerminal = + challengeType === challengeTypes.python || + challengeType === challengeTypes.multifilePythonCertProject || + challengeType === challengeTypes.pyLab || + challengeType === challengeTypes.dailyChallengePy; + + return ( + + + + {isMobile ? ( + + } + windowTitle={windowTitle} + testOutput={ + + } + updateUsingKeyboardInTablist={updateUsingKeyboardInTablist} + usesMultifileEditor={usesMultifileEditor} + usesTerminal={usesTerminal} + /> + ) : ( + + } + resizeProps={resizeProps} + testOutput={ + + } + windowTitle={windowTitle} + startWithConsoleShown={openConsole} + /> + )} + + + + + + + + + + ); +} + +ShowClassic.displayName = 'ShowClassic'; + +export default connect(mapStateToProps, mapDispatchToProps)(ShowClassic); + +export const query = graphql` + query ClassicChallenge($id: String!) { + challengeNode(id: { eq: $id }) { + challenge { + block + demoType + title + description + id + hasEditableBoundaries + instructions + notes + challengeType + helpCategory + videoUrl + superBlock + translationPending + forumTopicId + hooks { + beforeAll + beforeEach + afterEach + afterAll + } + fields { + slug + } + required { + link + src + } + usesMultifileEditor + challengeFiles { + fileKey + ext + name + contents + head + tail + editableRegionBoundaries + history + } + saveSubmissionToDB + tests { + text + testString + } + } + } + } +`; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/classic/xterm-original.css b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/classic/xterm-original.css new file mode 100644 index 0000000000000000000000000000000000000000..559a675775f73ec8a08e27ecc4ca3bcd8584216a --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/classic/xterm-original.css @@ -0,0 +1,231 @@ +/** + * Copyright (c) 2014 The xterm.js authors. All rights reserved. + * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License) + * https://github.com/chjj/term.js + * @license MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + * Originally forked from (with the author's permission): + * Fabrice Bellard's javascript vt100 for jslinux: + * http://bellard.org/jslinux/ + * Copyright (c) 2011 Fabrice Bellard + * The original design remains. The terminal itself + * has been extended to include xterm CSI codes, among + * other features. + */ + +/** + * Default styles for xterm.js + */ + +.xterm { + cursor: text; + position: relative; + user-select: none; + -ms-user-select: none; + -webkit-user-select: none; +} + +.xterm.focus, +.xterm:focus { + outline: none; +} + +.xterm .xterm-helpers { + position: absolute; + top: 0; + /** + * The z-index of the helpers must be higher than the canvases in order for + * IMEs to appear on top. + */ + z-index: 5; +} + +.xterm .xterm-helper-textarea { + padding: 0; + border: 0; + margin: 0; + /* Move textarea out of the screen to the far left, so that the cursor is not visible */ + position: absolute; + opacity: 0; + left: -9999em; + top: 0; + width: 0; + height: 0; + z-index: -5; + /** Prevent wrapping so the IME appears against the textarea at the correct position */ + white-space: nowrap; + overflow: hidden; + resize: none; +} + +.xterm .composition-view { + /* TODO: Composition position got messed up somewhere */ + background: #000; + color: #fff; + display: none; + position: absolute; + white-space: nowrap; + z-index: 1; +} + +.xterm .composition-view.active { + display: block; +} + +.xterm .xterm-viewport { + /* On OS X this is required in order for the scroll bar to appear fully opaque */ + background-color: #000; + overflow-y: scroll; + cursor: default; + position: absolute; + right: 0; + left: 0; + top: 0; + bottom: 0; +} + +.xterm .xterm-screen { + position: relative; +} + +.xterm .xterm-screen canvas { + position: absolute; + left: 0; + top: 0; +} + +.xterm .xterm-scroll-area { + visibility: hidden; +} + +.xterm-char-measure-element { + display: inline-block; + visibility: hidden; + position: absolute; + top: 0; + left: -9999em; + line-height: normal; +} + +.xterm.enable-mouse-events { + /* When mouse events are enabled (eg. tmux), revert to the standard pointer cursor */ + cursor: default; +} + +.xterm.xterm-cursor-pointer, +.xterm .xterm-cursor-pointer { + cursor: pointer; +} + +.xterm.column-select.focus { + /* Column selection mode */ + cursor: crosshair; +} + +.xterm .xterm-accessibility, +.xterm .xterm-message { + position: absolute; + left: 0; + top: 0; + bottom: 0; + right: 0; + z-index: 10; + color: transparent; + pointer-events: none; +} + +.xterm .live-region { + position: absolute; + left: -9999px; + width: 1px; + height: 1px; + overflow: hidden; +} + +.xterm-dim { + /* Dim should not apply to background, so the opacity of the foreground color is applied + * explicitly in the generated class and reset to 1 here */ + opacity: 1 !important; +} + +.xterm-underline-1 { + text-decoration: underline; +} +.xterm-underline-2 { + text-decoration: double underline; +} +.xterm-underline-3 { + text-decoration: wavy underline; +} +.xterm-underline-4 { + text-decoration: dotted underline; +} +.xterm-underline-5 { + text-decoration: dashed underline; +} + +.xterm-overline { + text-decoration: overline; +} + +.xterm-overline.xterm-underline-1 { + text-decoration: overline underline; +} +.xterm-overline.xterm-underline-2 { + text-decoration: overline double underline; +} +.xterm-overline.xterm-underline-3 { + text-decoration: overline wavy underline; +} +.xterm-overline.xterm-underline-4 { + text-decoration: overline dotted underline; +} +.xterm-overline.xterm-underline-5 { + text-decoration: overline dashed underline; +} + +.xterm-strikethrough { + text-decoration: line-through; +} + +.xterm-screen .xterm-decoration-container .xterm-decoration { + z-index: 6; + position: absolute; +} + +.xterm-screen + .xterm-decoration-container + .xterm-decoration.xterm-decoration-top-layer { + z-index: 7; +} + +.xterm-decoration-overview-ruler { + z-index: 8; + position: absolute; + top: 0; + right: 0; + pointer-events: none; +} + +.xterm-decoration-top { + z-index: 2; + position: relative; +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/classic/xterm.css b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/classic/xterm.css new file mode 100644 index 0000000000000000000000000000000000000000..82076de1836d6aec67e673b81a3d5665502727c8 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/classic/xterm.css @@ -0,0 +1,3 @@ +.xterm-screen { + height: 100vh !important; +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/classic/xterm.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/classic/xterm.tsx new file mode 100644 index 0000000000000000000000000000000000000000..e4290ac1d7c65182066baf1593d2177b61efe08d --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/classic/xterm.tsx @@ -0,0 +1,148 @@ +import React, { MutableRefObject, useEffect, useRef } from 'react'; +import type { FitAddon } from '@xterm/addon-fit'; +import type { IDisposable, Terminal } from '@xterm/xterm'; +import { useTranslation } from 'react-i18next'; + +import { registerTerminal } from '../utils/python-worker-handler'; +import './xterm.css'; +import './xterm-original.css'; + +const registerServiceWorker = async () => { + if ('serviceWorker' in navigator) { + try { + await navigator.serviceWorker.register('/python-input-sw.js'); + } catch (error) { + console.error(`Registration failed`); + console.error(error); + } + } +}; + +export const XtermTerminal = ({ + xtermFitRef, + dimensions +}: { + xtermFitRef: MutableRefObject; + dimensions?: { height: number; width: number }; +}) => { + const termContainerRef = useRef(null); + const { t } = useTranslation(); + + useEffect(() => { + void registerServiceWorker(); + + let term: Terminal | null; + + async function createTerminal() { + const disposables: IDisposable[] = []; + const { Terminal } = await import('@xterm/xterm'); + const { FitAddon } = await import('@xterm/addon-fit'); + + // Setting convertEol so that \n is converted to \r\n. Otherwise the terminal + // will interpret \n as line feed and just move the cursor to the next line. + // convertEol makes every \n a \r\n. + term = new Terminal({ convertEol: true }); + const fitAddon = new FitAddon(); + xtermFitRef.current = fitAddon; + term.loadAddon(fitAddon); + if (termContainerRef.current) term.open(termContainerRef.current); + fitAddon.fit(); + + // xterm does provide a11y support via the `screenReaderMode` option. + // However, the mode only works best if the user interacts with the terminal directly. + // Since we feed the content to xterm, it's better to control the output a11y ourselves. + const termContainerDiv = + termContainerRef.current?.querySelector('.xterm'); + const outputForScreenReader = document.createElement('div'); + + outputForScreenReader.setAttribute('role', 'region'); + outputForScreenReader.setAttribute( + 'aria-label', + t('aria.terminal-output') + ); + outputForScreenReader.classList.add('sr-only'); + termContainerDiv?.appendChild(outputForScreenReader); + + const print = (text?: string) => { + term?.writeln(`${text ?? ''}`); + outputForScreenReader.textContent = text ?? ''; + }; + + // TODO: prevent user from moving cursor outside the current input line and + // handle insertion and deletion properly. While backspace and delete don't + // seem to work, we can use "\x1b[0K" to clear from the cursor to the end. + // Also, we should not add special characters to the userinput string. + const input = (text?: string) => { + print(text); + let userinput = ''; + // Eslint is correct that this only gets assigned once, but we can't use + // const because the declaration (before keyListener is defined) and + // assignment (after keyListener is defined) must be separate. + // eslint-disable-next-line prefer-const + let disposable: IDisposable | undefined; + + const done = () => { + disposable?.dispose(); + navigator.serviceWorker.controller?.postMessage( + JSON.stringify({ + type: 'msg', + value: userinput + }) + ); + }; + + const keyListener = (key: string) => { + if (key === '\u007F' || key === '\b') { + // Backspace or delete key + term?.write('\b \b'); // Move cursor back, replace character with space, then move cursor back again + userinput = userinput.slice(0, -1); // Remove the last character from userinput + } + if (key == '\r') { + term?.write('\r\n'); + done(); + } else { + userinput += key; + term?.write(key); + } + }; + + disposable = term?.onData(keyListener); // Listen for key events and store the disposable + if (disposable) disposables.push(disposable); + }; + const reset = () => { + // Ironically, term.reset(), while synchronous, is not a reliable way to + // reset the terminal. It does not clear the input buffer, so old print + // statements can still appear. The \x1bc (ESC c) escape sequence triggers + // a full terminal reset, which is what we want. + term?.write('\x1bc'); + disposables.forEach(disposable => disposable.dispose()); + disposables.length = 0; + + outputForScreenReader.textContent = ''; + }; + registerTerminal({ print, input, reset }); + } + + void createTerminal(); + + return () => { + term?.dispose(); + }; + }, [xtermFitRef, t]); + + useEffect(() => { + if (xtermFitRef.current) xtermFitRef.current.fit(); + + // dimensions is an implicit dependency, since it's not directly used by the + // effect, but fitAddon.fit() needs to be called whenever the container size + // changes. + }, [xtermFitRef, dimensions]); + + return ( +

+ ); +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/codeally/codeally.css b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/codeally/codeally.css new file mode 100644 index 0000000000000000000000000000000000000000..267b81b54dae178df07350066fb2f548a25e3759 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/codeally/codeally.css @@ -0,0 +1,3 @@ +button[aria-described-by='codeally-cookie-warning'] { + font-size: 1.1rem; +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/codeally/codespaces-instructions.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/codeally/codespaces-instructions.tsx new file mode 100644 index 0000000000000000000000000000000000000000..4bc4f92f23c19f1479cafe965afca4e7b4f5ae35 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/codeally/codespaces-instructions.tsx @@ -0,0 +1,211 @@ +import React from 'react'; +import { Trans, useTranslation } from 'react-i18next'; +import { Spacer, Button, Callout } from '@freecodecamp/ui'; + +import { CodeAllyButton } from '../../../components/growth-book/codeally-button'; + +interface CodespacesInstructionsProps { + challengeType: number; + copyUrl: () => void; + copyUserToken: () => void; + generateUserToken: () => Promise; + isSignedIn: boolean; + title: string; + userToken: string | null; +} + +export function CodespacesInstructions({ + challengeType, + copyUrl, + copyUserToken, + generateUserToken, + isSignedIn, + title, + userToken +}: CodespacesInstructionsProps) { + const { t } = useTranslation(); + + function openCodespaces() { + const codespacesUrl = `https://codespaces.new/freeCodeCamp/rdb-alpha`; + + window.open(codespacesUrl, '_blank'); + } + + return ( +
+

{t('learn.codespaces.intro')}

+ +
    +
  1. + + + placeholder + + +
  2. + {isSignedIn && ( + <> + +

    {t('learn.local.sub-step-heading')}

    +
      +
    1. {t('learn.local.sub-step-1')}
    2. + + + +
    3. {t('learn.local.sub-step-2')}
    4. + + + +
    5. + + + Codespaces secrets page + + +
    6. +
    7. + + placeholder + +
    8. +
    9. + + placeholder + +
    10. + + + +
    11. + + placeholder + placeholder + +
    12. +
    13. + + placeholder + +
    14. +
    + + + )} +
  3. {t('learn.codespaces.step-2')}
  4. +
  5. + + +
  6. +
+
    +
  1. {t('learn.codespaces.step-3')}
  2. +
  3. + {t('learn.codespaces.step-4')} +
      +
    • {t('learn.codespaces.step-5')}
    • +
    • + + placeholder + +
    • +
    • + + placeholder + +
    • +
    • + + placeholder + +
    • +
    • {t('learn.local.step-6')}
    • +
    • {t('learn.local.step-7')}
    • + + + +
    • {t('learn.local.step-8')}
    • +
    +
  4. +
  5. {t('learn.codespaces.step-9')}
  6. +
+
+ ); +} + +interface CodespacesContinueAlertProps { + title: string; +} + +function CodespacesContinueAlert({ title }: CodespacesContinueAlertProps) { + const { t } = useTranslation(); + return ( + <> + + + + placeholder + + + + + + placeholder + + + + + + {t('learn.codespaces.reuse-tab-warning')} + + + ); +} + +interface CodespacesLogoutAlertProps { + course: string; +} + +function CodespacesLogoutAlert({ + course +}: CodespacesLogoutAlertProps): JSX.Element { + const { t } = useTranslation(); + + return ( + + {t('learn.codespaces.logout-warning', { course })} + + ); +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/codeally/local-instructions.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/codeally/local-instructions.tsx new file mode 100644 index 0000000000000000000000000000000000000000..c9ef8372b0df8370ea08d7a4d0e007701573b304 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/codeally/local-instructions.tsx @@ -0,0 +1,131 @@ +import React from 'react'; +import { Trans, useTranslation } from 'react-i18next'; +import { Spacer, Button } from '@freecodecamp/ui'; + +import { Link } from '../../../components/helpers'; +import RdbLocalLogoutAlert from './rdb-local-logout-alert'; + +interface LocalInstructionsProps { + copyUrl: () => void; + copyUserToken: () => void; + generateUserToken: () => Promise; + isSignedIn: boolean; + title: string; + userToken: string | null; +} + +export function LocalInstructions({ + copyUrl, + copyUserToken, + generateUserToken, + isSignedIn, + title, + userToken +}: LocalInstructionsProps) { + const { t } = useTranslation(); + + return ( +
+

{t('learn.local.intro')}

+
    +
  • + + Docker Engine + +
  • +
  • + + + placeholder + + + placeholder + + +
  • +
  • + + Git + +
  • +
+ +

{t('learn.local.heading')}

+
    +
  1. + + placeholder + +
  2. +
  3. + + placeholder + placeholder + placeholder + +
  4. + {isSignedIn && ( + <> + +

    {t('learn.local.sub-step-heading')}

    +
      +
    1. {t('learn.local.sub-step-1')}
    2. + + + +
    3. {t('learn.local.sub-step-2')}
    4. + + + +
    5. + + placeholder + placeholder + placeholder + +
    6. + + +
    + + + )} +
  5. + + placeholder + +
  6. +
  7. {t('learn.local.step-4')}
  8. +
  9. + + placeholder + +
  10. +
  11. {t('learn.local.step-6')}
  12. +
  13. {t('learn.local.step-7')}
  14. + + + +
  15. {t('learn.local.step-8')}
  16. +
  17. {t('learn.local.step-9')}
  18. +
+
+ ); +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/codeally/project-submit.test.ts b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/codeally/project-submit.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..57ef7269314a270622e49092df4985e0170eede2 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/codeally/project-submit.test.ts @@ -0,0 +1,37 @@ +import { describe, expect, test } from 'vitest'; + +import { isCodeAllyProjectCompleted } from './project-submit'; + +const challengeId = '5e601c775ac9d0ecd8b94aff'; + +describe('isCodeAllyProjectCompleted', () => { + test('returns false when the project has not been completed', () => { + expect( + isCodeAllyProjectCompleted({ + challengeId, + completedChallenges: [], + partiallyCompletedChallenges: [] + }) + ).toBe(false); + }); + + test('returns true when the project is partially completed', () => { + expect( + isCodeAllyProjectCompleted({ + challengeId, + completedChallenges: [], + partiallyCompletedChallenges: [{ id: challengeId }] + }) + ).toBe(true); + }); + + test('returns true when the project is completed', () => { + expect( + isCodeAllyProjectCompleted({ + challengeId, + completedChallenges: [{ id: challengeId }], + partiallyCompletedChallenges: [] + }) + ).toBe(true); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/codeally/project-submit.ts b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/codeally/project-submit.ts new file mode 100644 index 0000000000000000000000000000000000000000..f748ecddafcaffa736b8bc6cefc23b881c0d0a10 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/codeally/project-submit.ts @@ -0,0 +1,17 @@ +type ChallengeWithId = { + id: string; +}; + +export function isCodeAllyProjectCompleted({ + challengeId, + completedChallenges, + partiallyCompletedChallenges +}: { + challengeId: string; + completedChallenges: ChallengeWithId[]; + partiallyCompletedChallenges: ChallengeWithId[]; +}): boolean { + return [...partiallyCompletedChallenges, ...completedChallenges].some( + challenge => challenge.id === challengeId + ); +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/codeally/rdb-local-logout-alert.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/codeally/rdb-local-logout-alert.tsx new file mode 100644 index 0000000000000000000000000000000000000000..3a985871e7762943496641d13d5f149bcdb14f8f --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/codeally/rdb-local-logout-alert.tsx @@ -0,0 +1,21 @@ +import React from 'react'; +import { useTranslation } from 'react-i18next'; +import { Callout } from '@freecodecamp/ui'; + +interface RdbLocalLogoutAlertProps { + title: string; +} + +function RdbLocalLogoutAlert({ title }: RdbLocalLogoutAlertProps): JSX.Element { + const { t } = useTranslation(); + + return ( + + {t('learn.local.logout-warning', { course: title })} + + ); +} + +RdbLocalLogoutAlert.displayName = 'RdbLocalLogoutAlert'; + +export default RdbLocalLogoutAlert; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/codeally/rdb-step-1-instructions.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/codeally/rdb-step-1-instructions.tsx new file mode 100644 index 0000000000000000000000000000000000000000..a69f42eaddf70484d217fa11d917063d4732fb91 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/codeally/rdb-step-1-instructions.tsx @@ -0,0 +1,32 @@ +import React from 'react'; +import { useTranslation } from 'react-i18next'; +import { Spacer } from '@freecodecamp/ui'; + +import ChallengeHeading from '../components/challenge-heading'; +import PrismFormatted from '../components/prism-formatted'; + +interface RdbStep1InstructionsProps { + instructions: string; + isCompleted: boolean; +} + +function RdbStep1Instructions({ + instructions, + isCompleted +}: RdbStep1InstructionsProps): JSX.Element { + const { t } = useTranslation(); + + return ( + <> + + +
{t('learn.runs-in-vm')}
+ + + + ); +} + +RdbStep1Instructions.displayName = 'RdbStep1Instructions'; + +export default RdbStep1Instructions; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/codeally/rdb-step-2-instructions.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/codeally/rdb-step-2-instructions.tsx new file mode 100644 index 0000000000000000000000000000000000000000..77ade0efd065ba238895f26744374fe72ba83858 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/codeally/rdb-step-2-instructions.tsx @@ -0,0 +1,33 @@ +import React from 'react'; + +import { useTranslation } from 'react-i18next'; +import { Spacer } from '@freecodecamp/ui'; + +import ChallengeHeading from '../components/challenge-heading'; +import PrismFormatted from '../components/prism-formatted'; + +interface RdbStep2InstructionsProps { + notes: string; + isCompleted: boolean; +} + +function RdbStep2Instructions({ + isCompleted, + notes +}: RdbStep2InstructionsProps): JSX.Element { + const { t } = useTranslation(); + + return ( + <> + + +
{t('learn.submit-public-url')}
+ + + + ); +} + +RdbStep2Instructions.displayName = 'RdbStep2Instructions'; + +export default RdbStep2Instructions; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/codeally/show.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/codeally/show.tsx new file mode 100644 index 0000000000000000000000000000000000000000..b100bd020af1673ebbcc31772aef7bbcb5b7f000 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/codeally/show.tsx @@ -0,0 +1,399 @@ +// Package Utilities +import { graphql } from 'gatsby'; +import React, { Fragment, useEffect, useRef } from 'react'; +import Helmet from 'react-helmet'; +import type { TFunction } from 'i18next'; +import { withTranslation } from 'react-i18next'; +import { connect } from 'react-redux'; +import { bindActionCreators } from 'redux'; +import type { Dispatch } from 'redux'; +import { createSelector } from 'reselect'; +import { Container, Col, Row, Spacer } from '@freecodecamp/ui'; +import { useFeature } from '@growthbook/growthbook-react'; + +// Local Utilities +import LearnLayout from '../../../components/layouts/learn'; +import ChallengeTitle from '../components/challenge-title'; +import PrismFormatted from '../components/prism-formatted'; +import { challengeTypes } from '@freecodecamp/shared/config/challenge-types'; +import CompletionModal from '../components/completion-modal'; +import HelpModal from '../components/help-modal'; +import Hotkeys from '../components/hotkeys'; +import { updateUserToken } from '../../../redux/actions'; +import { + completedChallengesSelector, + partiallyCompletedChallengesSelector, + isSignedInSelector, + userTokenSelector +} from '../../../redux/selectors'; +import { + challengeMounted, + updateChallengeMeta, + openModal, + updateSolutionFormValues, + initTests +} from '../redux/actions'; +import { isChallengeCompletedSelector } from '../redux/selectors'; +import { createFlashMessage } from '../../../components/Flash/redux'; +import { + ChallengeNode, + ChallengeMeta, + CompletedChallenge, + Test +} from '../../../redux/prop-types'; +import ProjectToolPanel from '../projects/tool-panel'; +import { getChallengePaths } from '../utils/challenge-paths'; +import SolutionForm from '../projects/solution-form'; +import { FlashMessages } from '../../../components/Flash/redux/flash-messages'; +import { SuperBlocks } from '@freecodecamp/shared/config/curriculum'; +import { CodeAllyDown } from '../../../components/growth-book/codeally-down'; +import { postUserToken } from '../../../utils/ajax'; +import RdbStep1Instructions from './rdb-step-1-instructions'; +import RdbStep2Instructions from './rdb-step-2-instructions'; +import { LocalInstructions } from './local-instructions'; + +import './codeally.css'; +import { CodespacesInstructions } from './codespaces-instructions'; +import { isCodeAllyProjectCompleted } from './project-submit'; + +// Redux +const mapStateToProps = createSelector( + completedChallengesSelector, + isChallengeCompletedSelector, + isSignedInSelector, + partiallyCompletedChallengesSelector, + userTokenSelector, + ( + completedChallenges: CompletedChallenge[], + isChallengeCompleted: boolean, + isSignedIn: boolean, + partiallyCompletedChallenges: CompletedChallenge[], + userToken: string | null + ) => ({ + completedChallenges, + isChallengeCompleted, + isSignedIn, + partiallyCompletedChallenges, + userToken + }) +); + +const mapDispatchToProps = (dispatch: Dispatch) => + bindActionCreators( + { + challengeMounted, + createFlashMessage, + openCompletionModal: () => openModal('completion'), + initTests, + updateUserToken, + updateChallengeMeta, + updateSolutionFormValues + }, + dispatch + ); + +// Types +interface ShowCodeAllyProps { + challengeMounted: (arg0: string) => void; + completedChallenges: CompletedChallenge[]; + createFlashMessage: typeof createFlashMessage; + data: { challengeNode: ChallengeNode }; + initTests: (xs: Test[]) => void; + isChallengeCompleted: boolean; + isSignedIn: boolean; + openCompletionModal: () => void; + pageContext: { + challengeMeta: ChallengeMeta; + }; + partiallyCompletedChallenges: CompletedChallenge[]; + t: TFunction; + updateChallengeMeta: (arg0: ChallengeMeta) => void; + updateUserToken: (arg0: string) => void; + updateSolutionFormValues: () => void; + userToken: string | null; +} + +function ShowCodeAlly({ + completedChallenges, + data, + isChallengeCompleted, + isSignedIn, + partiallyCompletedChallenges, + t, + updateSolutionFormValues, + userToken, + updateUserToken, + createFlashMessage, + challengeMounted, + initTests, + pageContext: { challengeMeta }, + updateChallengeMeta, + openCompletionModal +}: ShowCodeAllyProps) { + const container = useRef(null); + + const { + challengeNode: { + challenge: { + block, + challengeType, + tests, + description, + helpCategory, + id: challengeId, + instructions, + notes, + superBlock, + title, + translationPending, + url + } + } + } = data; + const blockNameTitle = `${t( + `intro:${superBlock}.blocks.${block}.title` + )}: ${title}`; + const windowTitle = `${blockNameTitle} | freeCodeCamp.org`; + + const isPartiallyCompleted = partiallyCompletedChallenges.some( + challenge => challenge.id === challengeId + ); + + const isCompleted = completedChallenges.some( + challenge => challenge.id === challengeId + ); + + useEffect(() => { + initTests(tests); + const challengePaths = getChallengePaths({ + currentCurriculumPaths: challengeMeta + }); + updateChallengeMeta({ + ...challengeMeta, + title, + challengeType, + helpCategory, + description, + ...challengePaths + }); + challengeMounted(challengeMeta.id); + // hack to ensure the container is focused after the component mounts + // and Gatsby doesn't interfere with the focus. + requestAnimationFrame(() => container.current?.focus()); + // This effect should be run once on mount + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); + + const handleSubmit = ({ + showCompletionModal + }: { + showCompletionModal: boolean; + }) => { + if ( + !isCodeAllyProjectCompleted({ + challengeId, + completedChallenges, + partiallyCompletedChallenges + }) + ) { + createFlashMessage({ + type: 'danger', + message: FlashMessages.CompleteProjectFirst + }); + } else if (showCompletionModal) { + openCompletionModal(); + } + }; + + const rdbLocalInstructions = useFeature('rdb-local-instructions'); + const rdbCodespacesInstructions = useFeature('rdb-codespaces-instructions'); + + const coderoadTutorial = `https://raw.githubusercontent.com/${url}/main/tutorial.json`; + + async function generateUserToken() { + const createUserTokenResponse = await postUserToken(); + const { data = { userToken: null } } = createUserTokenResponse; + + if (data?.userToken) { + updateUserToken(data.userToken); + createFlashMessage({ + type: 'success', + message: FlashMessages.UserTokenGenerated + }); + } else { + createFlashMessage({ + type: 'danger', + message: FlashMessages.UserTokenGenerateError + }); + } + } + + function copyUserToken() { + navigator.clipboard.writeText(userToken ?? '').then( + () => { + createFlashMessage({ + type: 'success', + message: FlashMessages.UserTokenCopied + }); + }, + () => { + createFlashMessage({ + type: 'danger', + message: FlashMessages.UserTokenCopyError + }); + } + ); + } + + function copyUrl() { + navigator.clipboard.writeText(coderoadTutorial ?? '').then( + () => { + createFlashMessage({ + type: 'success', + message: FlashMessages.CourseUrlCopied + }); + }, + () => { + createFlashMessage({ + type: 'danger', + message: FlashMessages.CourseUrlCopyError + }); + } + ); + } + + const setups = [ + { + name: t('learn.codespaces.summary'), + component: CodespacesInstructions, + on: rdbCodespacesInstructions.on + }, + { + name: t('learn.local.summary'), + component: LocalInstructions, + on: rdbLocalInstructions.on + } + ]; + + const setupsToShow = setups.filter(setup => { + return setup.on; + }); + + return ( + + + + + + + + {superBlock === SuperBlocks.RelationalDb && } + + + {title} + + + + + + {setupsToShow.map(({ name, component: SetupComponent }, i) => ( + +
+ {name} + + +
+ +
+ ))} + + + {isSignedIn && challengeType === challengeTypes.codeAllyCert && ( + <> +
+ {t('learn.complete-both-steps')} +
+
+ + +
+ + + + + + )} + + +
+ + + + +
+
+
+
+ ); +} + +export default connect( + mapStateToProps, + mapDispatchToProps +)(withTranslation()(ShowCodeAlly)); + +// GraphQL +export const query = graphql` + query CodeAllyChallenge($id: String!) { + challengeNode(id: { eq: $id }) { + challenge { + block + challengeType + description + helpCategory + id + instructions + notes + superBlock + tests { + text + testString + } + title + translationPending + url + } + } + } +`; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/assignments.css b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/assignments.css new file mode 100644 index 0000000000000000000000000000000000000000..7e52d42aaa15cfbcd29f330daed58ca025495858 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/assignments.css @@ -0,0 +1,4 @@ +.assignments-not-complete { + text-align: center; + color: var(--danger-color); +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/assignments.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/assignments.tsx new file mode 100644 index 0000000000000000000000000000000000000000..4634856a71bc9a74d7a00d2d3776dac8702aaa35 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/assignments.tsx @@ -0,0 +1,68 @@ +import React from 'react'; +import { useTranslation } from 'react-i18next'; +import { Spacer } from '@freecodecamp/ui'; + +import ChallengeHeading from './challenge-heading'; +import PrismFormatted from './prism-formatted'; +import { getChallengeContentLangProps } from '../../../utils/challenge-content-lang'; + +import './assignments.css'; + +type AssignmentsProps = { + assignments: string[]; + allAssignmentsCompleted: boolean; + handleAssignmentChange: ( + event: React.ChangeEvent, + totalAssignments: number + ) => void; + superBlock?: string; +}; + +function Assignments({ + assignments, + allAssignmentsCompleted, + handleAssignmentChange, + superBlock +}: AssignmentsProps): JSX.Element { + const { t } = useTranslation(); + const contentLangProps = getChallengeContentLangProps(superBlock); + return ( + <> + +
+ {assignments.map((assignment, index) => ( + + ))} +
+ {!allAssignmentsCompleted && ( + <> + +
+ {t('learn.assignment-not-complete', { count: assignments.length })} +
+ + )} + + + ); +} + +Assignments.displayName = 'Assignments'; + +export default Assignments; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/bread-crumb.test.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/bread-crumb.test.tsx new file mode 100644 index 0000000000000000000000000000000000000000..0beeb48dd23a76ad56a308f964d2bc33a8ed3a1e --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/bread-crumb.test.tsx @@ -0,0 +1,39 @@ +import React from 'react'; +import { render, screen } from '@testing-library/react'; +import { describe, expect, test, vi } from 'vitest'; + +import BreadCrumb from './bread-crumb'; + +vi.mock('i18next', () => ({ + default: { + t: (key: string) => key + } +})); + +describe('', () => { + test('renders superblock and block links', () => { + render( + + ); + + expect( + screen.getByRole('navigation', { name: 'aria.breadcrumb-nav' }) + ).toBeInTheDocument(); + expect( + screen.getByRole('link', { + name: 'intro:responsive-web-design-v9.title' + }) + ).toHaveAttribute('href', '/learn/responsive-web-design-v9'); + expect( + screen.getByRole('link', { + name: 'intro:responsive-web-design-v9.blocks.workshop-cat-photo-app.title' + }) + ).toHaveAttribute( + 'href', + '/learn/responsive-web-design-v9/#workshop-cat-photo-app' + ); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/bread-crumb.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/bread-crumb.tsx new file mode 100644 index 0000000000000000000000000000000000000000..853eedc97e8ac44e510078891bfc444d58bfe452 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/bread-crumb.tsx @@ -0,0 +1,44 @@ +import i18next from 'i18next'; +import React from 'react'; +import { useTranslation } from 'react-i18next'; +import { Link } from '../../../components/helpers/index'; + +import './challenge-title.css'; + +interface BreadCrumbProps { + block: string; + superBlock: string; +} + +function BreadCrumb({ block, superBlock }: BreadCrumbProps): JSX.Element { + const { t } = useTranslation(); + return ( + + ); +} + +BreadCrumb.displayName = 'BreadCrumb'; + +export default BreadCrumb; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/challenge-description.css b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/challenge-description.css new file mode 100644 index 0000000000000000000000000000000000000000..789d00c5784fde5d21f5f53e826f7c5668fe8854 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/challenge-description.css @@ -0,0 +1,17 @@ +.challenge-instructions blockquote { + background-color: var(--tertiary-background); + color: var(--tertiary-color); + padding: 10px; + width: 100%; + margin: 0; + margin-bottom: 1.45rem; + font-size: 0.9rem; +} + +#description ol li a { + word-break: break-all; +} + +#description ol li { + line-height: 1.5; +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/challenge-description.test.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/challenge-description.test.tsx new file mode 100644 index 0000000000000000000000000000000000000000..0744dd208b6c53ddbcd914598bec07d0b80c4b2c --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/challenge-description.test.tsx @@ -0,0 +1,31 @@ +import React from 'react'; +import { render, screen } from '@testing-library/react'; +import { describe, expect, test } from 'vitest'; + +import ChallengeDescription from './challenge-description'; + +describe('', () => { + test('renders description links with their attributes', () => { + render( + + ); + + expect(screen.getByText(/View/)).toBeInTheDocument(); + expect( + screen.getByRole('link', { name: 'your achievements page' }) + ).toHaveAttribute( + 'href', + 'https://learn.microsoft.com/users/me/achievements#trophies-section' + ); + expect( + screen.getByRole('link', { name: 'your achievements page' }) + ).toHaveAttribute('target', '_blank'); + expect( + screen.getByRole('link', { name: 'your achievements page' }) + ).toHaveAttribute('rel', 'noreferrer'); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/challenge-description.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/challenge-description.tsx new file mode 100644 index 0000000000000000000000000000000000000000..87a47254b5544ff4ae4f3153f4c11074d90571b8 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/challenge-description.tsx @@ -0,0 +1,50 @@ +import React, { useEffect } from 'react'; +import { initializeMathJax, isMathJaxAllowed } from '../../../utils/math-jax'; +import PrismFormatted from './prism-formatted'; +import './challenge-description.css'; +import { generateGithubLink } from '../../../components/create-github-link'; +import { getChallengeContentLangProps } from '../../../utils/challenge-content-lang'; + +type Props = { + description?: string; + instructions?: string; + superBlock?: string; + challengeId: string; + block: string; +}; + +const ChallengeDescription = ({ + description, + instructions, + superBlock, + challengeId, + block +}: Props) => { + useEffect(() => { + if (superBlock && isMathJaxAllowed(superBlock)) { + initializeMathJax(); + } + }, [superBlock]); + + const githubLink = generateGithubLink(challengeId, block); + const contentLangProps = getChallengeContentLangProps(superBlock); + return ( +
+ {description && ( + + )} + {instructions && description &&
} + {instructions && ( + + )} +
+ ); +}; + +ChallengeDescription.displayName = 'ChallengeDescription'; + +export default ChallengeDescription; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/challenge-explanation.css b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/challenge-explanation.css new file mode 100644 index 0000000000000000000000000000000000000000..d81c7e6726e191a1c766252d5735baca448987ca --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/challenge-explanation.css @@ -0,0 +1,3 @@ +.challenge-summary { + cursor: pointer; +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/challenge-explanation.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/challenge-explanation.tsx new file mode 100644 index 0000000000000000000000000000000000000000..7fd05f0c51946d8159fe8a6f28c31e3ad5967202 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/challenge-explanation.tsx @@ -0,0 +1,41 @@ +import React from 'react'; +import { useTranslation } from 'react-i18next'; +import { Spacer } from '@freecodecamp/ui'; +import { SuperBlocks } from '@freecodecamp/shared/config/curriculum'; +import PrismFormatted from './prism-formatted'; +import { getChallengeContentLangProps } from '../../../utils/challenge-content-lang'; + +import './challenge-explanation.css'; + +interface ChallengeExplanationProps { + explanation: string; + superBlock: SuperBlocks; +} + +function ChallengeExplanation({ + explanation, + superBlock +}: ChallengeExplanationProps): JSX.Element { + const { t } = useTranslation(); + + return ( + <> +
+ + {t('learn.explanation')} + + + +
+ + + ); +} + +ChallengeExplanation.displayName = 'ChallengeExplanation'; + +export default ChallengeExplanation; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/challenge-heading.css b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/challenge-heading.css new file mode 100644 index 0000000000000000000000000000000000000000..c125527c5069f867f245d3b8e6e85f868871f7b2 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/challenge-heading.css @@ -0,0 +1,10 @@ +.challenge-heading-wrap { + display: flex; + gap: 7px; + align-items: center; + justify-content: center; +} + +.challenge-heading { + font-size: 16px; +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/challenge-heading.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/challenge-heading.tsx new file mode 100644 index 0000000000000000000000000000000000000000..8ecc2d357c988ced8ad4aead8b3d4cd353504a7c --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/challenge-heading.tsx @@ -0,0 +1,28 @@ +import React from 'react'; +import { useTranslation } from 'react-i18next'; +import GreenPass from '../../../assets/icons/green-pass'; + +import './challenge-heading.css'; + +interface ChallengeHeadingProps { + heading: string; + isCompleted?: boolean; +} + +function ChallengeHeading({ + heading, + isCompleted = false +}: ChallengeHeadingProps): JSX.Element { + const { t } = useTranslation(); + + return ( +
+

{t(heading)}

+ {isCompleted && } +
+ ); +} + +ChallengeHeading.displayName = 'ChallengeHeading'; + +export default ChallengeHeading; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/challenge-title.css b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/challenge-title.css new file mode 100644 index 0000000000000000000000000000000000000000..5478d3b9ba0c6725e6b9725577fa8b8dd0025991 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/challenge-title.css @@ -0,0 +1,117 @@ +.challenge-title-wrap { + text-align: center; +} + +.challenge-title { + height: fit-content; + min-width: 25px; + margin: 20px 0px 15px; + padding: 0px 3px; + display: flex; + gap: 7px; + align-items: center; + justify-content: center; + overflow: hidden; + text-overflow: ellipsis; + max-height: fit-content; + white-space: pre-line; + flex-grow: 1; + flex-shrink: 1; + font-size: 16px; +} + +.challenge-title-breadcrumbs { + font-size: 16px; + border: 1px solid var(--quaternary-background); + text-align: center; +} + +.challenge-title-breadcrumbs ol { + display: flex; + justify-content: space-around; + list-style-type: none; + margin-bottom: 0; + padding-inline-start: 0; + width: 100%; +} + +.challenge-title-breadcrumbs ol a { + width: 100%; + text-decoration: none; + overflow: hidden; + text-overflow: ellipsis; + display: block; + padding: 0 3px; +} + +.challenge-title-breadcrumbs ol a:focus { + background-color: inherit; +} + +.challenge-title-breadcrumbs ol a:hover { + background-color: inherit; + text-decoration: underline; +} + +.breadcrumb-left, +.breadcrumb-right { + text-decoration: none; + display: inline-flex; + align-items: center; + justify-content: center; + text-overflow: ellipsis; + white-space: nowrap; + flex-grow: 1; + flex-shrink: 2; + padding: 0; +} + +.breadcrumb-left { + min-width: 3rem; + background-color: var(--quaternary-background); + margin-inline-end: 0.57rem; +} + +.breadcrumb-left:after { + background-color: var(--secondary-background); + content: ''; + border-top: calc(1.375rem / 2) solid transparent; + border-bottom: calc(1.2rem / 2) solid transparent; + border-inline-start: calc(1.1rem / 2) solid var(--quaternary-background); + height: 100%; + margin-inline-start: 3px; +} + +.breadcrumb-right { + min-width: 50px; +} + +.breadcrumb-rule { + margin: 5px -10px; +} + +.challenge-title h1 { + font-size: 1.1rem; + line-height: 1.42857143; + margin: 0; + display: inline; +} + +.title-translation-cta { + display: flex; + flex-direction: row; + justify-content: space-around; + font-size: 16px; + height: 25px; + text-decoration: none; + color: var(--highlight-color); + background-color: var(--highlight-background); + margin-bottom: 10px; +} + +.title-translation-cta:hover, +.title-translation-cta:focus { + text-decoration: none; + color: var(--highlight-background); + background-color: var(--highlight-color); +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/challenge-title.test.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/challenge-title.test.tsx new file mode 100644 index 0000000000000000000000000000000000000000..8bfa573e94d59e1621eca624300444062ccbbaa7 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/challenge-title.test.tsx @@ -0,0 +1,57 @@ +import React from 'react'; +import { render, screen } from '@testing-library/react'; +import { describe, it, expect, vi } from 'vitest'; + +import ChallengeTitle from './challenge-title'; + +vi.mock('i18next', () => ({ + default: { + t: (key: string) => + ({ + 'links:help-translate-link-url': 'https://example.com/help-translate', + 'misc.translation-pending': 'Help us translate' + })[key] ?? key + } +})); + +const baseProps = { + children: 'What Role Does HTML Play on the Web?', + isCompleted: false, + translationPending: false +}; + +describe('', () => { + it('renders the challenge title without a completion icon', () => { + render(); + + expect( + screen.getByRole('heading', { + level: 1, + name: 'What Role Does HTML Play on the Web?' + }) + ).toBeInTheDocument(); + expect(screen.queryByTestId('green-pass')).not.toBeInTheDocument(); + }); + + it('renders the completion icon when the challenge is completed', () => { + render(); + + expect(screen.getByTestId('green-pass')).toBeInTheDocument(); + }); + + it('renders the translation link when translation is pending', () => { + render(); + + expect( + screen.getByRole('link', { name: 'Help us translate' }) + ).toHaveAttribute('href', 'https://example.com/help-translate'); + }); + + it('does not render the translation link when translation is not pending', () => { + render(); + + expect( + screen.queryByRole('link', { name: 'Help us translate' }) + ).not.toBeInTheDocument(); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/challenge-title.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/challenge-title.tsx new file mode 100644 index 0000000000000000000000000000000000000000..f22b35156215a989dec7cbd20923f9274df1e0f2 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/challenge-title.tsx @@ -0,0 +1,41 @@ +import i18next from 'i18next'; +import React from 'react'; +import GreenPass from '../../../assets/icons/green-pass'; +import { Link } from '../../../components/helpers/index'; + +import './challenge-title.css'; + +interface ChallengeTitleProps { + children: string; + isCompleted: boolean; + translationPending?: boolean; +} + +function ChallengeTitle({ + children, + isCompleted, + translationPending +}: ChallengeTitleProps): JSX.Element { + return ( +
+ {translationPending && ( + + {i18next.t('misc.translation-pending')} + + )} +
+

+ {children} +

+ {isCompleted && } +
+
+ ); +} + +ChallengeTitle.displayName = 'ChallengeTitle'; + +export default ChallengeTitle; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/challenge-transcript.css b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/challenge-transcript.css new file mode 100644 index 0000000000000000000000000000000000000000..9a747a80b287890980ed29d2bb8acffaf7beacf4 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/challenge-transcript.css @@ -0,0 +1,19 @@ +.challenge-transcript-heading { + cursor: pointer; + font-weight: bold; + margin-top: 1.5em; +} + +.challenge-transcript .transcript-dialogue { + border: 1px solid var(--secondary-color); +} + +.challenge-transcript .transcript-dialogue p { + margin: 0; + padding: 6px 13px; + text-align: start; +} + +.challenge-transcript .transcript-dialogue p:nth-child(odd) { + background-color: var(--tertiary-background); +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/challenge-transcript.test.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/challenge-transcript.test.tsx new file mode 100644 index 0000000000000000000000000000000000000000..53d3c9c1876e0cfb82f70ec2484b5bc32a9db415 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/challenge-transcript.test.tsx @@ -0,0 +1,114 @@ +import React from 'react'; +import { render, screen, fireEvent } from '@testing-library/react'; +import store from 'store'; +import { describe, it, expect, vi, afterEach } from 'vitest'; +import ChallengeTranscript from './challenge-transcript'; + +const baseProps = { + transcript: 'Sample transcript text', + shouldPersistExpanded: false +}; + +describe('', () => { + afterEach(() => { + store.clearAll(); + }); + + it('renders the transcript heading', () => { + render(); + expect(screen.getByText('learn.transcript')).toBeVisible(); + }); + + it('renders collapsed by default', () => { + render(); + expect(screen.getByTestId('challenge-transcript')).not.toHaveAttribute( + 'open' + ); + expect(screen.getByText('Sample transcript text')).not.toBeVisible(); + }); + + it("renders collapsed when localstorage 'fcc-transcript-expanded = false'", () => { + store.set('fcc-transcript-expanded', false); + render(); + expect(screen.getByTestId('challenge-transcript')).not.toHaveAttribute( + 'open' + ); + expect(screen.getByText('Sample transcript text')).not.toBeVisible(); + }); + + it("renders expanded when 'fcc-transcript-expanded = true' and shouldPersistExpanded = true", () => { + store.set('fcc-transcript-expanded', true); + render(); + expect(screen.getByTestId('challenge-transcript')).toHaveAttribute('open'); + expect(screen.getByText('Sample transcript text')).toBeVisible(); + }); + + it('writes to localstorage when shouldPersistExpanded = true', () => { + const setSpy = vi.spyOn(store, 'set'); + render(); + fireEvent.click(screen.getByText('learn.transcript')); + expect(setSpy).toHaveBeenCalledWith('fcc-transcript-expanded', true); + setSpy.mockRestore(); + }); + + it('does not write to localstorage when shouldPersistExpanded = false', () => { + const setSpy = vi.spyOn(store, 'set'); + render(); + fireEvent.click(screen.getByText('learn.transcript')); + expect(setSpy).not.toHaveBeenCalled(); + setSpy.mockRestore(); + }); + + it('should render the transcript as paragraphs when isDialogue is true', () => { + store.set('fcc-transcript-expanded', true); + + render( + Alice: Hello

Bob: World

'} + shouldPersistExpanded={true} + isDialogue={true} + /> + ); + + /* eslint-disable testing-library/no-node-access */ + const aliceB = screen.getByText('Alice'); + expect(aliceB).toBeVisible(); + expect(aliceB.tagName).toBe('B'); + + const aliceP = aliceB.parentElement; + expect(aliceP?.tagName).toBe('P'); + expect(aliceP?.textContent).toBe('Alice: Hello'); + + const bobB = screen.getByText('Bob'); + expect(bobB).toBeVisible(); + expect(bobB.tagName).toBe('B'); + + const bobP = bobB.parentElement; + expect(bobP?.tagName).toBe('P'); + expect(bobP?.textContent).toBe('Bob: World'); + /* eslint-enable testing-library/no-node-access */ + }); + + it('should render the transcript with PrismFormatted when isDialogue is false', () => { + store.set('fcc-transcript-expanded', true); + + render( + + ); + + const preElement = screen.getByRole('region'); + expect(preElement).toBeVisible(); + expect(preElement.tagName).toBe('PRE'); + + // eslint-disable-next-line testing-library/no-node-access + const codeElement = preElement.querySelector('code'); + expect(codeElement).toBeInTheDocument(); + expect(preElement).toHaveTextContent('console.log("hi")'); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/challenge-transcript.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/challenge-transcript.tsx new file mode 100644 index 0000000000000000000000000000000000000000..fe76fca641649bc0e44385aec552c7e03a7f04cf --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/challenge-transcript.tsx @@ -0,0 +1,76 @@ +import React, { useState } from 'react'; +import { useTranslation } from 'react-i18next'; +import { Spacer } from '@freecodecamp/ui'; +import store from 'store'; + +import PrismFormatted from './prism-formatted'; +import { getChallengeContentLangProps } from '../../../utils/challenge-content-lang'; +import './challenge-transcript.css'; + +interface ChallengeTranscriptProps { + transcript: string; + shouldPersistExpanded?: boolean; + isDialogue?: boolean; + superBlock?: string; +} + +function ChallengeTranscript({ + transcript, + shouldPersistExpanded, + isDialogue, + superBlock +}: ChallengeTranscriptProps): JSX.Element { + const { t } = useTranslation(); + + // default to collapsed + const [isOpen, setIsOpen] = useState(() => + shouldPersistExpanded + ? ((store.get('fcc-transcript-expanded') as boolean | null) ?? false) + : false + ); + + function toggleExpandedState(e: React.MouseEvent) { + e.preventDefault(); + if (shouldPersistExpanded) { + store.set('fcc-transcript-expanded', !isOpen); + } + setIsOpen(!isOpen); + } + + return ( + <> +
+ + {t('learn.transcript')} + + + {isDialogue ? ( +
+ ) : ( + + )} +
+ + + ); +} + +ChallengeTranscript.displayName = 'ChallengeTranscript'; + +export default ChallengeTranscript; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/completion-modal.css b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/completion-modal.css new file mode 100644 index 0000000000000000000000000000000000000000..ec73ab160318c1695235be9afd603554d0560762 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/completion-modal.css @@ -0,0 +1,113 @@ +.completion-success-icon { + width: 200px; + height: 200px; + transform: scale(1.5); + opacity: 0; + animation: success-icon-animation 150ms linear 100ms forwards; +} + +@keyframes success-icon-animation { + 100% { + opacity: 1; + transform: scale(1); + } +} + +.completion-block-details { + display: flex; + flex-direction: column; + align-items: center; + align-self: center; + justify-content: space-between; + width: 100%; + gap: 0.5rem; +} + +.completion-block-name { + font-weight: 700; + font-size: 1rem; + margin-bottom: 4px; +} + +.completion-block-meta { + color: var(--quaternary-color); + font-size: 0.8rem; + margin-top: 5px; +} + +.completion-block-details .completion-block-name { + font-size: 1.2rem; +} + +.completion-block-details .completion-block-meta { + font-size: 1rem; +} + +.progress-bar-wrap { + width: 100%; + position: relative; + border: 1px solid var(--quaternary-color); +} + +.progress-header { + display: flex; + flex-direction: row; + justify-content: space-between; + width: 100%; + font-size: 0.9rem; +} + +.progress-bar-background { + width: 100%; + height: 10px; + color: var(--primary-color); + background-color: var(--quaternary-background); + display: flex; + align-items: center; + justify-content: center; + position: absolute; + + top: 0; + left: 0; +} + +.progress-bar-percent { + height: 10px; + overflow: hidden; + position: relative; + background-color: var(--primary-color); + transition: width 0ms linear; +} + +/* The maximum width of login button is 500px, which is set in global.css. + An override is needed as 500px is not enough to allow the button to span the modal width. */ +.completion-modal-login-btn .signup-btn { + max-width: 100%; +} + +.completion-modal-body { + display: flex; + flex-direction: column; + align-items: center; +} + +@media screen and (max-width: 991px) { + .progress-bar-wrap, + .progress-bar-background { + height: 10px; + } + + .completion-success-icon { + width: 160px; + height: 160px; + } + + .completion-message { + font-weight: 600; + font-size: 1.2rem; + } + + .completion-block-name { + font-size: 1rem; + } +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/completion-modal.test.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/completion-modal.test.tsx new file mode 100644 index 0000000000000000000000000000000000000000..caf48a72dba3e9b89a3e950a29d176650d4e782d --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/completion-modal.test.tsx @@ -0,0 +1,390 @@ +import React from 'react'; +import type { TFunction } from 'i18next'; +import { runSaga } from 'redux-saga'; +import { describe, test, it, expect, beforeEach, vi, type Mock } from 'vitest'; +import { fireEvent, render, screen } from '../../../../utils/test-utils'; + +import { getCompletedPercentage } from '../../../utils/get-completion-percentage'; +import { fireConfetti } from '../../../utils/fire-confetti'; +import { createStore } from '../../../redux/create-store'; +import { executeChallengeSaga } from '../redux/execute-challenge-saga'; +import { + challengeDataSelector, + challengeMetaSelector, + challengeTestsSelector, + isBuildEnabledSelector, + isBlockNewlyCompletedSelector, + currentBlockIdsSelector +} from '../redux/selectors'; +import { completedChallengesIdsSelector } from '../../../redux/selectors'; +import { curriculumData } from '../../../services/curriculum-data'; +import { getTestRunner } from '../utils/build'; +import ConnectedCompletionModal, { + combineFileData, + CompletionModal +} from './completion-modal'; +import { mockCurriculumData } from '../utils/__fixtures__/curriculum-data'; +import { useStaticQuery } from 'gatsby'; +import { ChallengeNode, SuperBlockStructure } from '../../../redux/prop-types'; +vi.mock('../../../analytics'); +vi.mock('../../../utils/fire-confetti'); +vi.mock('../../../components/Progress', () => ({ + default: () =>
+})); +vi.mock('../../../components/Header/components/login', () => ({ + default: ({ children }: { children?: React.ReactNode }) => ( + {children} + ) +})); +vi.mock('../redux/selectors'); +vi.mock('../../../redux/selectors'); +vi.mock('../utils/build'); +const mockSubmitChallenge = vi.hoisted(() => vi.fn()); +vi.mock('../utils/fetch-all-curriculum-data', () => ({ + useSubmit: () => mockSubmitChallenge +})); +vi.mock('../../../utils/get-words'); +vi.mock('@freecodecamp/challenge-builder/build'); +const mockFireConfetti = fireConfetti as Mock; +const mockTestRunner = vi.fn().mockReturnValue({ pass: true }); +const mockBuildEnabledSelector = isBuildEnabledSelector as Mock; +const mockChallengeTestsSelector = challengeTestsSelector as Mock; +const mockChallengeMetaSelector = challengeMetaSelector as Mock; +const mockChallengeDataSelector = challengeDataSelector as Mock; +const mockIsBlockNewlyCompletedSelector = isBlockNewlyCompletedSelector as Mock; +const mockCurrentBlockIdsSelector = vi.mocked(currentBlockIdsSelector); +const mockCompletedChallengesIdsSelector = + completedChallengesIdsSelector as unknown as Mock; +const mockGetTestRunner = getTestRunner as Mock; +mockBuildEnabledSelector.mockReturnValue(true); +mockChallengeTestsSelector.mockReturnValue([ + { text: 'Test 1', testString: 'mock test code' } +]); +mockChallengeMetaSelector.mockReturnValue({ + challengeType: 'mock_challenge_type' +}); +mockChallengeDataSelector.mockReturnValue({ + challengeFiles: ['mock_challenge_files'] +}); +mockGetTestRunner.mockReturnValue(mockTestRunner); + +const completedChallengesIds = ['1', '3', '5']; +const currentBlockIds = ['1', '3', '5', '7']; +const id = '7'; +const fakeCompletedChallengesIds = ['1', '3', '5', '7', '8']; +const t = ((key: string) => key) as TFunction; + +function renderCompletionModal( + props: Partial> = {} +) { + return render( + , + createStore() + ); +} + +describe('', () => { + beforeEach(() => { + mockSubmitChallenge.mockClear(); + vi.stubGlobal( + 'ResizeObserver', + class ResizeObserver { + observe = vi.fn(); + unobserve = vi.fn(); + disconnect = vi.fn(); + } + ); + vi.spyOn(window.navigator, 'userAgent', 'get').mockReturnValue('Linux'); + Object.defineProperty(window, 'innerWidth', { + configurable: true, + value: 1200 + }); + vi.mocked(useStaticQuery).mockReturnValue(mockCurriculumData); + // Initialize curriculum data singleton for tests + const structuresMap: Record = {}; + mockCurriculumData.allSuperBlockStructure.nodes.forEach(node => { + structuresMap[node.superBlock] = node as SuperBlockStructure; + }); + curriculumData.initialize({ + challengeNodes: mockCurriculumData.allChallengeNode + .nodes as unknown as ChallengeNode[], + certificateNodes: mockCurriculumData.allCertificateNode.nodes, + superBlockStructures: structuresMap + }); + }); + + describe('rendering', () => { + it('renders the signed-out completion state', () => { + renderCompletionModal({ isSignedIn: false }); + + expect( + screen.getByRole('heading', { name: 'Great job' }) + ).toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Close' })).toBeInTheDocument(); + expect( + screen.getByTestId('fcc-completion-success-icon') + ).toBeInTheDocument(); + expect(screen.getByTestId('progress-bar-container')).toBeInTheDocument(); + expect( + screen.getByRole('link', { name: 'learn.sign-in-save' }) + ).toHaveAttribute('href', '/learn'); + expect( + screen.getByRole('button', { name: 'buttons.go-to-next-ctrl' }) + ).toBeInTheDocument(); + }); + + it('renders the signed-in completion state', () => { + renderCompletionModal(); + + expect( + screen.queryByRole('link', { name: 'learn.sign-in-save' }) + ).not.toBeInTheDocument(); + expect( + screen.getByRole('button', { name: 'buttons.submit-and-go-ctrl' }) + ).toBeInTheDocument(); + }); + + it('uses mobile button text when signed out on small screens', () => { + Object.defineProperty(window, 'innerWidth', { + configurable: true, + value: 320 + }); + + renderCompletionModal({ isSignedIn: false }); + + expect( + screen.getByRole('button', { name: 'buttons.go-to-next' }) + ).toBeInTheDocument(); + }); + + it('uses Command button text on macOS desktops', () => { + vi.spyOn(window.navigator, 'userAgent', 'get').mockReturnValue('Mac OS'); + + renderCompletionModal(); + + expect( + screen.getByRole('button', { name: 'buttons.submit-and-go-cmd' }) + ).toBeInTheDocument(); + }); + + it('uses mobile button text on small screens', () => { + Object.defineProperty(window, 'innerWidth', { + configurable: true, + value: 320 + }); + + renderCompletionModal(); + + expect( + screen.getByRole('button', { name: 'buttons.submit-and-go' }) + ).toBeInTheDocument(); + }); + + it('closes when the close button is clicked', () => { + const close = vi.fn(); + renderCompletionModal({ close }); + + fireEvent.click(screen.getByRole('button', { name: 'Close' })); + + expect(close).toHaveBeenCalled(); + }); + + it('submits when the submit button is clicked', () => { + renderCompletionModal(); + + fireEvent.click( + screen.getByRole('button', { name: 'buttons.submit-and-go-ctrl' }) + ); + + expect(mockSubmitChallenge).toHaveBeenCalled(); + }); + + it('submits when the keyboard shortcut is pressed', () => { + renderCompletionModal(); + + fireEvent.keyDown(screen.getByRole('dialog'), { + ctrlKey: true, + key: 'Enter' + }); + + expect(mockSubmitChallenge).toHaveBeenCalled(); + }); + }); + + describe('fireConfetti', () => { + beforeEach(() => { + mockFireConfetti.mockClear(); + }); + test('should fire when block is completed and challenge data exists', async () => { + const payload = { showCompletionModal: true }; + const challengeId = 'bd7158d8c442eddfaeb5bd18'; + const blockIds = ['step1', 'step2', 'step3', challengeId]; + const store = createStore({ + challenge: { + modal: { completion: true }, + challengeMeta: { + id: challengeId, + certification: 'responsive-web-design' + } + } + }); + mockIsBlockNewlyCompletedSelector.mockReturnValue(true); + mockChallengeMetaSelector.mockReturnValue({ + id: challengeId, + isLastChallengeInBlock: true, + challengeType: 'mock_challenge_type' + }); + mockCurrentBlockIdsSelector.mockReturnValue(blockIds); + mockCompletedChallengesIdsSelector.mockReturnValue(['step1', 'step2']); + // Curriculum data is initialized in beforeEach + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + await runSaga(store, executeChallengeSaga, { payload }).done; + expect(mockFireConfetti).toHaveBeenCalledTimes(1); + }); + test('should not fire when challenge data is empty (saga guard)', async () => { + const payload = { showCompletionModal: true }; + const challengeId = 'bd7158d8c442eddfaeb5bd18'; + const store = createStore({ + challenge: { + modal: { completion: true }, + challengeMeta: { + id: challengeId, + certification: 'responsive-web-design' + } + } + }); + mockIsBlockNewlyCompletedSelector.mockReturnValue(true); + mockChallengeMetaSelector.mockReturnValue({ + id: challengeId, + isLastChallengeInBlock: true, + challengeType: 'mock_challenge_type' + }); + // Reset curriculum data to empty state to test the guard + curriculumData.initialize({ + certificateNodes: [], + challengeNodes: [], + superBlockStructures: {} + }); + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + await runSaga(store, executeChallengeSaga, { payload }).done; + expect(mockFireConfetti).toHaveBeenCalledTimes(0); + }); + test('should not fire when block is not completed', async () => { + const payload = { showCompletionModal: true }; + const store = createStore({ + challenge: { + modal: { completion: true }, + challengeMeta: { + id: 'bd7158d8c442eddfaeb5bd18', + certification: 'responsive-web-design' // Make sure the certification matches + } + } + }); + mockIsBlockNewlyCompletedSelector.mockReturnValue(false); + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + await runSaga(store, executeChallengeSaga, { payload }).done; + expect(mockFireConfetti).toHaveBeenCalledTimes(0); + }); + test('should not fire if certification project has been completed', () => { + const store = createStore({ + challenge: { + modal: { completion: true }, + challengeMeta: { + // Build a Tribute Page's id: + id: 'bd7158d8c442eddfaeb5bd18' + } + } + }); + render(, store); + + expect(mockFireConfetti).toHaveBeenCalledTimes(0); + }); + test('should NOT fire if the challenge is not a project', () => { + const store = createStore({ + challenge: { + modal: { completion: true }, + challengeMeta: { + // id from learn-advanced-array-methods-by-building-a-statistics-calculator: + id: '6352e79d15aae30fac58f48e' + } + } + }); + + render(, store); + + expect(mockFireConfetti).toHaveBeenCalledTimes(0); + }); + }); + + describe('getCompletedPercentage', () => { + it('returns 25 if one out of four challenges are complete', () => { + expect( + getCompletedPercentage([], currentBlockIds, currentBlockIds[1]) + ).toBe(25); + }); + + it('returns 75 if three out of four challenges are complete', () => { + expect( + getCompletedPercentage( + completedChallengesIds, + currentBlockIds, + completedChallengesIds[0] + ) + ).toBe(75); + }); + + it('returns 100 if all challenges have been completed', () => { + expect( + getCompletedPercentage(completedChallengesIds, currentBlockIds, id) + ).toBe(100); + }); + + it('returns 100 if more challenges have been complete than exist', () => { + expect( + getCompletedPercentage(fakeCompletedChallengesIds, currentBlockIds, id) + ).toBe(100); + }); + }); + + describe('File Download Content', () => { + it('Should label each section appropriately', () => { + const indexHtml = { + name: 'index', + ext: 'html', + contents: 'some html elements' + }; + const stylesCSS = { + name: 'styles', + ext: 'css', + contents: 'some css styles' + }; + const scriptJS = { + name: 'script', + ext: 'js', + contents: 'some javascript' + }; + const result = combineFileData([indexHtml, stylesCSS, scriptJS]); + expect(result).toContain('** start of index.html **'); + expect(result).toContain('** end of index.html **'); + expect(result).toContain('** start of styles.css **'); + expect(result).toContain('** end of styles.css **'); + expect(result).toContain('** start of script.js **'); + expect(result).toContain('** end of script.js **'); + }); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/completion-modal.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/completion-modal.tsx new file mode 100644 index 0000000000000000000000000000000000000000..d8160e8e429e3d59ef1d3d6b30bee00f30049985 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/completion-modal.tsx @@ -0,0 +1,228 @@ +import React, { useEffect, useCallback, useState } from 'react'; +import type { TFunction } from 'i18next'; +import { withTranslation } from 'react-i18next'; +import { connect } from 'react-redux'; +import { createSelector } from 'reselect'; +import { Button, Modal, Spacer } from '@freecodecamp/ui'; + +import Login from '../../../components/Header/components/login'; +import { + isSignedInSelector, + completedChallengesIdsSelector +} from '../../../redux/selectors'; +import { ChallengeFiles } from '../../../redux/prop-types'; +import { closeModal } from '../redux/actions'; +import { + isCompletionModalOpenSelector, + successMessageSelector, + challengeFilesSelector, + challengeMetaSelector, + isSubmittingSelector +} from '../redux/selectors'; +import Progress from '../../../components/Progress'; +import GreenPass from '../../../assets/icons/green-pass'; +import { MAX_MOBILE_WIDTH } from '../../../../config/misc'; +import './completion-modal.css'; +import callGA from '../../../analytics/call-ga'; +import { useSubmit } from '../utils/fetch-all-curriculum-data'; + +const mapStateToProps = createSelector( + challengeFilesSelector, + challengeMetaSelector, + completedChallengesIdsSelector, + isCompletionModalOpenSelector, + isSignedInSelector, + successMessageSelector, + isSubmittingSelector, + ( + challengeFiles: ChallengeFiles, + { + dashedName, + id + }: { + dashedName: string; + id: string; + }, + completedChallengesIds: string[], + isOpen: boolean, + isSignedIn: boolean, + message: string, + isSubmitting: boolean + ) => ({ + challengeFiles, + id, + dashedName, + completedChallengesIds, + isOpen, + isSignedIn, + message, + isSubmitting + }) +); + +const mapDispatchToProps = { + close: () => closeModal('completion') +}; + +type StateProps = ReturnType; + +interface CompletionModalProps extends StateProps { + close: () => void; + t: TFunction; +} + +interface DownloadableChallengeFile { + name: string; + ext: string; + contents: string; +} + +export function CompletionModal({ + challengeFiles, + close, + dashedName, + isOpen, + isSignedIn, + isSubmitting, + message, + t +}: CompletionModalProps): JSX.Element { + const [downloadURL, setDownloadURL] = useState(); + const submitChallenge = useSubmit(); + // We can't useMemo here, because it does not guarantee that the URL object + // will be revoked when the dependencies change. + useEffect(() => { + // downloadURL is not in the dependency array because it should only change + // if the challengeFiles change. It is in the useEffect so that we cannot + // leak URL objects. + if (downloadURL) URL.revokeObjectURL(downloadURL); + if (challengeFiles?.length) { + const allFileContents = combineFileData(challengeFiles); + const blob = new Blob([allFileContents], { type: 'text/json' }); + setDownloadURL(URL.createObjectURL(blob)); + } + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [challengeFiles]); + + useEffect(() => { + return () => { + close(); + }; + }, [close]); + + useEffect(() => { + if (isOpen) { + callGA({ event: 'pageview', pagePath: '/completion-modal' }); + } + }, [isOpen]); + + const handleKeypress = useCallback( + (e: React.KeyboardEvent) => { + if (e.key === 'Escape') { + e.stopPropagation(); + close(); + } + if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) { + e.preventDefault(); + // Since Hotkeys also listens to Ctrl + Enter we have to stop this event + // getting to it. + e.stopPropagation(); + submitChallenge(); + } + }, + [close, submitChallenge] + ); + + const isMacOS = navigator.userAgent.includes('Mac OS'); + + const isDesktop = window.innerWidth > MAX_MOBILE_WIDTH; + + let buttonText; + if (isDesktop) { + if (isMacOS) { + buttonText = isSignedIn + ? t('buttons.submit-and-go-cmd') + : t('buttons.go-to-next-cmd'); + } else { + buttonText = isSignedIn + ? t('buttons.submit-and-go-ctrl') + : t('buttons.go-to-next-ctrl'); + } + } else { + buttonText = isSignedIn + ? t('buttons.submit-and-go') + : t('buttons.go-to-next'); + } + + return ( + + {message} + + +
+ +
+
+ + {isSignedIn ? null : ( +
+ {t('learn.sign-in-save')} + +
+ )} + + + {downloadURL ? ( + + ) : null} +
+
+ ); +} + +CompletionModal.displayName = 'CompletionModal'; + +export default connect( + mapStateToProps, + mapDispatchToProps +)(withTranslation()(CompletionModal)); + +export function combineFileData(challengeFiles: DownloadableChallengeFile[]) { + return challengeFiles.reduce(function ( + allFiles: string, + currentFile: DownloadableChallengeFile + ) { + const beforeText = `** start of ${currentFile.name + '.' + currentFile.ext} **\n\n`; + const afterText = `\n\n** end of ${currentFile.name + '.' + currentFile.ext} **\n\n`; + allFiles += + challengeFiles.length > 0 + ? `${beforeText}${currentFile.contents}${afterText}` + : currentFile.contents; + return allFiles; + }, ''); +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/custom-monaco-editor.css b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/custom-monaco-editor.css new file mode 100644 index 0000000000000000000000000000000000000000..c8fbd3231884ef25fb644820125a13f600120480 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/custom-monaco-editor.css @@ -0,0 +1,9 @@ +.monaco-editor-wrapper { + padding-block-start: 8px; + flex: 1; +} + +.monaco-editor .line-numbers { + color: #858591 !important; + font-size: 12px; +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/custom-monaco-editor.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/custom-monaco-editor.tsx new file mode 100644 index 0000000000000000000000000000000000000000..62724b8d9ce65de32e6d77c037f36691b4d28fa8 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/custom-monaco-editor.tsx @@ -0,0 +1,101 @@ +import React from 'react'; +import Loadable from '@loadable/component'; +import type * as monacoEditor from 'monaco-editor/esm/vs/editor/editor.api.js'; +import { useActiveCode, useSandpack } from '@codesandbox/sandpack-react'; +import './custom-monaco-editor.css'; + +const MonacoEditor = Loadable(() => import('react-monaco-editor')); + +const CustomMonacoEditor = () => { + const { code, updateCode } = useActiveCode(); + const { sandpack } = useSandpack(); + + const getLanguage = (filePath: string): string => { + const extension = filePath.split('.').pop(); + + switch (extension) { + case 'js': + case 'jsx': + return 'javascript'; + case 'ts': + case 'tsx': + return 'typescript'; + case 'html': + return 'html'; + case 'css': + return 'css'; + default: + return 'plaintext'; + } + }; + // theme + const FCC_DARK_CUSTOM: monacoEditor.editor.IStandaloneThemeData = { + base: 'vs-dark', + inherit: true, + rules: [ + { token: 'comment', foreground: '858591', fontStyle: 'italic' }, + { token: 'keyword', foreground: 'dbb8ff' }, + { token: 'tag', foreground: 'f07178' }, + { token: 'punctuation', foreground: '99c9ff' }, + { token: 'definition', foreground: 'ffffff' }, + { token: 'property', foreground: '99c9ff' }, + { token: 'static', foreground: 'f78c6c' }, + { token: 'string', foreground: 'acd157' }, + { token: 'number', foreground: 'f78c6c' }, + { token: 'variable', foreground: 'ffffff' }, + { token: 'type', foreground: 'dbb8ff' }, + { token: 'function', foreground: 'ffffff' }, + { token: 'identifier', foreground: 'ffffff' }, + { token: 'regexp', foreground: 'acd157' }, + { token: 'delimiter', foreground: 'ffffff' }, + { token: 'attribute.name', foreground: '99c9ff' }, + { token: 'attribute.value', foreground: 'acd157' }, + { token: 'annotation', foreground: 'dbb8ff' }, + { token: 'constant', foreground: 'f78c6c' }, + { token: 'class', foreground: 'dbb8ff' }, + { token: 'interface', foreground: 'dbb9ff' }, + { token: 'namespace', foreground: 'dbb8ff' }, + { token: 'enum', foreground: 'dbb8ff' }, + { token: 'operator', foreground: 'ffffff' } + ], + colors: { + 'editor.background': '#0a0a23', // surface1 + 'editor.foreground': '#ffffff', // base (plain syntax) + 'editorCursor.foreground': '#ffffff', + 'editor.selectionBackground': '#3b3b4f', + 'editor.lineHighlightBackground': '#3b3b4f', // surface3 + 'editorBracketMatch.border': '#dbb8ff' + } + }; + + const handleEditor = (monaco: typeof monacoEditor) => { + monaco.editor.defineTheme('fcc-dark', FCC_DARK_CUSTOM); + }; + + return ( +
+ { + updateCode(value || ''); + }} + options={{ + lineNumbersMinChars: 2, + minimap: { enabled: false }, + scrollBeyondLastLine: false, + automaticLayout: true + }} + /> +
+ ); +}; + +CustomMonacoEditor.displayname = 'CustomMonacoEditor'; + +export default CustomMonacoEditor; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/daily-challenge-bread-crumb.test.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/daily-challenge-bread-crumb.test.tsx new file mode 100644 index 0000000000000000000000000000000000000000..02e7a0397ff0e61b8edcd6311c09d2069af8c694 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/daily-challenge-bread-crumb.test.tsx @@ -0,0 +1,48 @@ +import React from 'react'; +import { render, screen } from '@testing-library/react'; +import { describe, expect, it, vi } from 'vitest'; + +import DailyChallengeBreadCrumb from './daily-challenge-bread-crumb'; + +vi.mock('i18next', () => ({ + default: { + t: (key: string) => key + } +})); + +describe('', () => { + it('renders nothing when there is no param', () => { + const { container } = render(); + expect(container).toBeEmptyDOMElement(); + }); + + it('renders nothing for an invalid param', () => { + const { container } = render( + + ); + expect(container).toBeEmptyDOMElement(); + }); + + it('renders nothing for a shape-valid but semantically invalid month-day', () => { + const { container } = render( + + ); + expect(container).toBeEmptyDOMElement(); + }); + + it('shows only the month and day for a full "yyyy-MM-dd" date, with no year', () => { + render(); + + expect( + screen.getByRole('navigation', { name: 'aria.breadcrumb-nav' }) + ).toBeInTheDocument(); + expect(screen.getByText('July 15')).toBeInTheDocument(); + expect(screen.queryByText('2026')).not.toBeInTheDocument(); + }); + + it('shows only the month and day for a year-agnostic "MM-DD" param', () => { + render(); + + expect(screen.getByText('July 15')).toBeInTheDocument(); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/daily-challenge-bread-crumb.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/daily-challenge-bread-crumb.tsx new file mode 100644 index 0000000000000000000000000000000000000000..945a927185b54858125dacec54f06c9fa8d214ff --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/daily-challenge-bread-crumb.tsx @@ -0,0 +1,43 @@ +import i18next from 'i18next'; +import React from 'react'; +import { useTranslation } from 'react-i18next'; +import { Link } from '../../../components/helpers/index'; + +import './challenge-title.css'; +import { + isValidDateOrMonthDayString, + formatDisplayDate +} from '../../../components/daily-coding-challenge/helpers'; + +function DailyChallengeBreadCrumb({ + dailyChallengeParam +}: { + dailyChallengeParam?: string; +}): JSX.Element | null { + const { t } = useTranslation(); + + return dailyChallengeParam && + isValidDateOrMonthDayString(dailyChallengeParam) ? ( + + ) : null; +} + +DailyChallengeBreadCrumb.displayName = 'DailyChallengeBreadCrumb'; + +export default DailyChallengeBreadCrumb; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/fill-in-the-blanks.test.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/fill-in-the-blanks.test.tsx new file mode 100644 index 0000000000000000000000000000000000000000..7214c11940bd149f24d35b9656c71f93923bb60a --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/fill-in-the-blanks.test.tsx @@ -0,0 +1,87 @@ +import React from 'react'; +import { render, screen } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { describe, expect, it, vi } from 'vitest'; + +import type { FillInTheBlank } from '../../../redux/prop-types'; +import FillInTheBlanks from './fill-in-the-blanks'; + +const fillInTheBlank = { + sentence: '

Is BLANK your book? No, BLANK is my book.

', + blanks: [ + { answer: 'this', feedback: null, audioId: null }, + { + answer: 'that', + feedback: '

Use that for something further away.

', + audioId: null + } + ] +} satisfies FillInTheBlank; + +type FillInTheBlanksProps = React.ComponentProps; + +const defaultProps = { + fillInTheBlank, + answersCorrect: [null, null], + showFeedback: false, + feedback: null, + showWrong: false, + handleInputChange: vi.fn() +} satisfies FillInTheBlanksProps; + +function renderFillInTheBlanks(overrides: Partial = {}) { + const props = { ...defaultProps, ...overrides }; + + render(); +} + +describe('', () => { + it('marks incorrect blanks and shows feedback', () => { + renderFillInTheBlanks({ + answersCorrect: [true, false], + showWrong: true, + showFeedback: true, + feedback: fillInTheBlank.blanks[1].feedback + }); + + expect(screen.getByText('learn.wrong-answer')).toBeInTheDocument(); + expect(screen.getByText('this')).toHaveClass('correct-blank-answer'); + expect(screen.getByText(/for something further away/)).toBeInTheDocument(); + + const blanks = screen.getAllByRole('textbox', { + name: 'learn.fill-in-the-blank.blank' + }); + expect(blanks).toHaveLength(1); + expect(blanks[0]).toHaveAttribute('aria-invalid', 'true'); + }); + + it('renders every blank as text when every answer is correct', () => { + renderFillInTheBlanks({ + answersCorrect: [true, true] + }); + + expect(screen.queryByText('learn.wrong-answer')).not.toBeInTheDocument(); + expect( + screen.queryByRole('textbox', { + name: 'learn.fill-in-the-blank.blank' + }) + ).not.toBeInTheDocument(); + expect(screen.getByText('this')).toHaveClass('correct-blank-answer'); + expect(screen.getByText('that')).toHaveClass('correct-blank-answer'); + }); + + it('calls the input change handler with the blank index and value', async () => { + const user = userEvent.setup(); + const handleInputChange = vi.fn(); + renderFillInTheBlanks({ handleInputChange }); + + await user.type( + screen.getAllByRole('textbox', { + name: 'learn.fill-in-the-blank.blank' + })[1], + 'that' + ); + + expect(handleInputChange).toHaveBeenLastCalledWith(1, 'that'); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/fill-in-the-blanks.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/fill-in-the-blanks.tsx new file mode 100644 index 0000000000000000000000000000000000000000..0c29a77f145bc47138bdc78b0a1f182a3e65c6a6 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/fill-in-the-blanks.tsx @@ -0,0 +1,217 @@ +import React from 'react'; +import { useTranslation } from 'react-i18next'; +import { Spacer } from '@freecodecamp/ui'; + +import { parseBlanks, parseAnswer } from '../fill-in-the-blank/parse-blanks'; +import PrismFormatted from '../components/prism-formatted'; +import { getChallengeContentLangProps } from '../../../utils/challenge-content-lang'; +import { + FillInTheBlankInputType, + FillInTheBlank +} from '../../../redux/prop-types'; +import ChallengeHeading from './challenge-heading'; +import PinyinToHanziInput from './pinyin-to-hanzi-input'; +import PinyinToneInput from './pinyin-tone-input'; + +type FillInTheBlankProps = { + fillInTheBlank: FillInTheBlank; + inputType?: FillInTheBlankInputType; + answersCorrect: (boolean | null)[]; + showFeedback: boolean; + feedback: string | null; + showWrong: boolean; + handleInputChange: (inputIndex: number, value: string) => void; + superBlock?: string; +}; + +const AnswerText = ({ answer }: { answer: string }) => { + const parsedAnswer = parseAnswer(answer); + + if (typeof parsedAnswer === 'string') { + return {parsedAnswer}; + } + + return ( + + {parsedAnswer.hanzi} + ( + {parsedAnswer.pinyin} + ) + + ); +}; + +type BlankInputProps = { + blankIndex: number; + answer: string; + isCorrect: boolean | null; + className: string; + onChange: (index: number, value: string) => void; + ariaLabel: string; + inputType?: 'pinyin-to-hanzi' | 'pinyin-tone'; +}; + +const BlankInput = ({ + blankIndex, + answer, + isCorrect, + className, + onChange, + ariaLabel, + inputType +}: BlankInputProps) => { + const parsedAnswer = parseAnswer(answer); + const answerLength = + typeof parsedAnswer === 'string' + ? parsedAnswer.length + : parsedAnswer.pinyin.length; + + if (inputType === 'pinyin-to-hanzi' && typeof parsedAnswer === 'object') { + return ( + + ); + } else if (inputType === 'pinyin-tone' && typeof parsedAnswer === 'string') { + return ( + + ); + } + + // Default text input + return ( + onChange(blankIndex, e.target.value)} + size={answerLength} + autoComplete='off' + aria-label={ariaLabel} + {...(isCorrect === false ? { 'aria-invalid': 'true' } : {})} + /> + ); +}; + +function FillInTheBlanks({ + fillInTheBlank: { sentence, blanks }, + inputType, + answersCorrect, + showFeedback, + feedback, + showWrong, + handleInputChange, + superBlock +}: FillInTheBlankProps): JSX.Element { + const { t } = useTranslation(); + + const getInputClass = (index: number): string => { + let cls = 'fill-in-the-blank-input'; + + if (answersCorrect[index] === false) { + cls += ' incorrect-blank-answer'; + } + + return cls; + }; + + const paragraphs = parseBlanks(sentence); + const blankAnswers = blanks.map(b => b.answer); + + const ariaInputDescription = + inputType === 'pinyin-to-hanzi' + ? t('aria.pinyin-to-hanzi-input-desc') + : inputType === 'pinyin-tone' + ? t('aria.pinyin-tone-input-desc') + : ''; + + return ( + <> + + +

{ariaInputDescription}

+
+ {paragraphs.map((p, i) => ( + // both keys, i and j, are stable between renders, since + // the paragraphs are static. +

+ {p.map((node, j) => { + const { type, value } = node; + + if (type === 'text') { + return value; + } + + if (type === 'hanzi-pinyin') { + const { hanzi, pinyin } = value; + return ( + + {hanzi} + ( + {pinyin} + ) + + ); + } + + // If a blank is answered correctly, render the answer as part of the sentence. + if (answersCorrect[value] === true) { + return ; + } + + return ( + + ); + })} +

+ ))} +
+ +
+ {showWrong && ( +
+ {t('learn.wrong-answer')} + +
+ )} + {showFeedback && feedback && ( + + )} +
+ + ); +} + +FillInTheBlanks.displayName = 'FillInTheBlanks'; + +export default FillInTheBlanks; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/help-modal.css b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/help-modal.css new file mode 100644 index 0000000000000000000000000000000000000000..83e321440170bb919a78eb558019c5287243e5a3 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/help-modal.css @@ -0,0 +1,15 @@ +.help-form-legend { + color: var(--secondary-color); + border: 0; + font-size: 18px; +} + +.checkbox-container { + display: flex; + width: 100%; + text-align: left; +} + +.help-text-warning { + text-align: left; +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/help-modal.test.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/help-modal.test.tsx new file mode 100644 index 0000000000000000000000000000000000000000..0dfd980a4fec983c08201e5c5f4cd09ec23b9cd1 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/help-modal.test.tsx @@ -0,0 +1,305 @@ +import React from 'react'; +import { render, screen, within } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { describe, it, expect, vi, beforeAll, afterEach } from 'vitest'; +import i18n from '../../../../i18n/config-for-tests'; +import translations from '../../../../i18n/locales/english/translations.json'; +import { generateSearchLink, HelpModal } from './help-modal'; + +vi.unmock('react-i18next'); + +const validDescription = + 'Example text with enough characters to validate that the forum help form can be submitted.'; + +const createDefaultHelpModalProps = () => ({ + closeHelpModal: vi.fn(), + createQuestion: vi.fn(), + isOpen: true, + challengeTitle: 'Write Your First C# Code', + challengeBlock: 'write-your-first-code-using-c-sharp', + superBlock: 'foundational-c-sharp-with-microsoft', + openVideoModal: vi.fn() +}); + +const renderHelpModal = ( + props: Partial> = {} +) => { + const helpModalProps = { + ...createDefaultHelpModalProps(), + ...props + }; + + return { + ...render(), + helpModalProps + }; +}; + +const openHelpForm = async () => { + await userEvent.click( + screen.getByRole('button', { name: translations.buttons['create-post'] }) + ); +}; + +const getDescriptionInput = () => + screen.getByRole('textbox', { + name: /^Tell us what's happening:/ + }); + +beforeAll(() => { + i18n.addResourceBundle('en', 'translations', translations, true, true); + + type ResizeObserverMockInstance = { + observe: ResizeObserver['observe']; + unobserve: ResizeObserver['unobserve']; + disconnect: ResizeObserver['disconnect']; + }; + + Object.defineProperty(window, 'ResizeObserver', { + writable: true, + value: vi.fn(function ( + this: ResizeObserverMockInstance, + _cb: ResizeObserverCallback + ) { + this.observe = vi.fn(); + this.unobserve = vi.fn(); + this.disconnect = vi.fn(); + }) + }); +}); + +afterEach(() => { + vi.clearAllMocks(); +}); + +describe('generateSearchLink', () => { + it("should return a link with search query containing block name and challenge title if the title includes 'step'", async () => { + await i18n.reloadResources('en', 'intro'); + const link = generateSearchLink( + 'Step 10', + 'learn-basic-javascript-by-building-a-role-playing-game', + 'javascript-algorithms-and-data-structures-v8' + ); + + expect(link).toBe( + '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' + ); + }); + + it("should return a link with search query containing block name and challenge title if the title includes 'task'", () => { + const link = generateSearchLink( + 'Task 10', + 'learn-greetings-in-your-first-day-at-the-office', + 'a2-english-for-developers' + ); + + expect(link).toBe( + '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' + ); + }); + + it("should return a link with search query containing only challenge title if the title does not include 'step' or 'task'", () => { + const link = generateSearchLink( + 'Perform Basic String Formatting in C#', + 'write-your-first-code-using-c-sharp', + 'foundational-c-sharp-with-microsoft' + ); + + expect(link).toBe( + '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' + ); + }); +}); + +describe('', () => { + it('renders the initial help options and warning copy', () => { + renderHelpModal(); + + const dialog = screen.getByRole('dialog', { + name: translations.buttons['get-help'] + }); + + expect(dialog).toBeInTheDocument(); + expect( + within(dialog).getByText(/If you've already tried the/) + ).toBeInTheDocument(); + expect( + within(dialog).getByText(/Before making a new post/) + ).toBeInTheDocument(); + expect( + within(dialog).getByRole('button', { + name: translations.buttons['create-post'] + }) + ).toBeInTheDocument(); + expect( + within(dialog).getByRole('button', { + name: translations.buttons.cancel + }) + ).toBeInTheDocument(); + expect( + within(dialog).getByRole('button', { + name: translations.buttons.close + }) + ).toBeInTheDocument(); + }); + + it('renders a guide link and video button when video is available', async () => { + const { helpModalProps } = renderHelpModal({ + guideUrl: 'https://forum.example.com/guide', + videoUrl: 'https://example.com/video' + }); + + const dialog = screen.getByRole('dialog', { + name: translations.buttons['get-help'] + }); + + expect( + within(dialog).getByRole('link', { + name: translations.buttons['get-hint'] + }) + ).toHaveAttribute('href', 'https://forum.example.com/guide'); + + await userEvent.click( + within(dialog).getByRole('button', { + name: translations.buttons['watch-video'] + }) + ); + + expect(helpModalProps.openVideoModal).toHaveBeenCalledTimes(1); + expect(helpModalProps.closeHelpModal).toHaveBeenCalledTimes(1); + }); + + it('omits the video button when video is unavailable', () => { + renderHelpModal(); + + expect( + screen.queryByRole('button', { + name: translations.buttons['watch-video'] + }) + ).not.toBeInTheDocument(); + }); + + it('closes from the cancel and header close buttons', async () => { + const { helpModalProps, unmount } = renderHelpModal(); + + await userEvent.click( + screen.getByRole('button', { name: translations.buttons.cancel }) + ); + + expect(helpModalProps.closeHelpModal).toHaveBeenCalledTimes(1); + + unmount(); + const { helpModalProps: secondHelpModalProps } = renderHelpModal(); + + await userEvent.click( + screen.getByRole('button', { name: translations.buttons.close }) + ); + + expect(secondHelpModalProps.closeHelpModal).toHaveBeenCalledTimes(1); + }); + + it('renders forum links with safe external-link attributes', () => { + renderHelpModal(); + + expect( + screen.getByRole('link', { name: 'Read-Search-Ask' }) + ).toHaveAttribute('href', 'https://forum.freecodecamp.org/t/19514'); + expect( + screen.getByRole('link', { + name: 'check if your question has already been answered on the forum' + }) + ).toHaveAttribute( + 'href', + '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' + ); + + screen.getAllByRole('link').forEach(link => { + expect(link).toHaveAttribute('target', '_blank'); + expect(link).toHaveAttribute('rel', 'noopener noreferrer'); + }); + }); + + it('keeps submit disabled until both confirmations are checked', async () => { + renderHelpModal(); + + await openHelpForm(); + + const rsaCheckbox = screen.getByRole('checkbox', { + name: translations.aria['rsa-checkbox'] + }); + const similarQuestionsCheckbox = screen.getByRole('checkbox', { + name: translations.aria['similar-questions-checkbox'] + }); + const descriptionInput = getDescriptionInput(); + const submitButton = screen.getByRole('button', { + name: translations.buttons.submit + }); + + // paste is preferable since typing the whole description is slow (each + // keystroke triggers a re-render) and times the test out on loaded CI + // runners + await userEvent.click(descriptionInput); + await userEvent.paste(validDescription); + + expect(submitButton).toHaveAttribute('aria-disabled', 'true'); + + await userEvent.click(rsaCheckbox); + expect(submitButton).toHaveAttribute('aria-disabled', 'true'); + + await userEvent.click(rsaCheckbox); + await userEvent.click(similarQuestionsCheckbox); + expect(submitButton).toHaveAttribute('aria-disabled', 'true'); + }); + + it('keeps submit disabled when the description is too short', async () => { + renderHelpModal(); + + await openHelpForm(); + + await userEvent.click( + screen.getByRole('checkbox', { + name: translations.aria['rsa-checkbox'] + }) + ); + await userEvent.click( + screen.getByRole('checkbox', { + name: translations.aria['similar-questions-checkbox'] + }) + ); + await userEvent.type(getDescriptionInput(), 'Too short'); + + expect( + screen.getByRole('button', { name: translations.buttons.submit }) + ).toHaveAttribute('aria-disabled', 'true'); + }); + + it('submits a valid help request and closes the modal', async () => { + const { helpModalProps } = renderHelpModal(); + + await openHelpForm(); + + await userEvent.click( + screen.getByRole('checkbox', { + name: translations.aria['rsa-checkbox'] + }) + ); + await userEvent.click( + screen.getByRole('checkbox', { + name: translations.aria['similar-questions-checkbox'] + }) + ); + // paste is preferable since typing the whole description is slow (each + // keystroke triggers a re-render) and times the test out on loaded CI + // runners + await userEvent.click(getDescriptionInput()); + await userEvent.paste(validDescription); + await userEvent.click( + screen.getByRole('button', { name: translations.buttons.submit }) + ); + + expect(helpModalProps.createQuestion).toHaveBeenCalledWith( + validDescription + ); + expect(helpModalProps.closeHelpModal).toHaveBeenCalledTimes(1); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/help-modal.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/help-modal.tsx new file mode 100644 index 0000000000000000000000000000000000000000..03fd717043282dd84a530b26600a89ecaa02c76d --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/help-modal.tsx @@ -0,0 +1,350 @@ +import React, { useMemo, useState, useRef, useEffect } from 'react'; +import { Trans, useTranslation } from 'react-i18next'; +import { connect } from 'react-redux'; +import { Dispatch, bindActionCreators } from 'redux'; +import { Button, FormControl, Modal, Spacer } from '@freecodecamp/ui'; + +import { t } from 'i18next'; +import envData from '../../../../config/env.json'; +import { createQuestion, closeModal, openModal } from '../redux/actions'; +import { isHelpModalOpenSelector } from '../redux/selectors'; + +import './help-modal.css'; +import callGA from '../../../analytics/call-ga'; + +interface HelpModalProps { + closeHelpModal: () => void; + createQuestion: (description: string) => void; + isOpen?: boolean; + challengeTitle: string; + challengeBlock: string; + superBlock: string; + guideUrl?: string; + videoUrl?: string; + openVideoModal: () => void; +} + +const { forumLocation } = envData; +const DESCRIPTION_MIN_CHARS = 50; +const DESCRIPTION_MAX_CHARS = 500; +const RSA = forumLocation + '/t/19514'; + +const mapStateToProps = (state: unknown) => ({ + isOpen: isHelpModalOpenSelector(state) as boolean +}); +const mapDispatchToProps = (dispatch: Dispatch) => + bindActionCreators( + { + createQuestion, + closeHelpModal: () => closeModal('help'), + openVideoModal: () => openModal('video') + }, + dispatch + ); + +export const generateSearchLink = ( + title: string, + block: string, + superBlock: string +) => { + const titleText = t(`intro:${superBlock}.blocks.${block}.title`); + const selector = 'in:title'; + const query = encodeURIComponent(`${titleText} - ${title} ${selector}`); + const search = `${forumLocation}/search?q=${query}`; + return search; +}; + +interface CheckboxProps { + name: string; + i18nKey: string; + onChange: (event: React.ChangeEvent) => void; + value: boolean; + href: string; + label: string; +} + +function Checkbox({ + name, + i18nKey, + onChange, + value, + href, + label +}: CheckboxProps) { + const { t } = useTranslation(); + + return ( + + ); +} + +export function HelpModal({ + closeHelpModal, + createQuestion, + isOpen, + challengeBlock, + superBlock, + challengeTitle, + guideUrl, + videoUrl, + openVideoModal +}: HelpModalProps): JSX.Element { + const { t } = useTranslation(); + const [showHelpForm, setShowHelpForm] = useState(false); + const [description, setDescription] = useState(''); + const [readSearchCheckbox, setReadSearchCheckbox] = useState(false); + const [similarQuestionsCheckbox, setSimilarQuestionsCheckbox] = + useState(false); + + const formRef = useRef(null); + + useEffect(() => { + if (showHelpForm) { + formRef.current?.querySelector('input')?.focus(); + } + }, [showHelpForm]); + + const canSubmitForm = useMemo(() => { + return ( + description.length >= DESCRIPTION_MIN_CHARS && + readSearchCheckbox && + similarQuestionsCheckbox + ); + }, [description, readSearchCheckbox, similarQuestionsCheckbox]); + + const resetFormValues = () => { + setDescription(''); + setReadSearchCheckbox(false); + setSimilarQuestionsCheckbox(false); + }; + + const handleClose = () => { + closeHelpModal(); + setShowHelpForm(false); + resetFormValues(); + }; + + const handleOpenVideo = () => { + openVideoModal(); + handleClose(); + }; + + const handleSubmit = (event: React.FormEvent) => { + event.preventDefault(); + + if (!canSubmitForm) { + return; + } + + setShowHelpForm(false); + resetFormValues(); + createQuestion(description); + closeHelpModal(); + }; + + const hintUrl = guideUrl + ? guideUrl + : generateSearchLink(challengeTitle, challengeBlock, superBlock); + + if (isOpen) { + callGA({ event: 'pageview', pagePath: '/help-modal' }); + } + return ( + + + {t('buttons.get-help')} + + + {showHelpForm ? ( +
+
+ + {t('learn.must-confirm-statements')} + + + setReadSearchCheckbox(event.target.checked)} + value={readSearchCheckbox} + href={RSA} + /> + + + + + setSimilarQuestionsCheckbox(event.target.checked) + } + value={similarQuestionsCheckbox} + href={generateSearchLink( + challengeTitle, + challengeBlock, + superBlock + )} + /> +
+ + + + + + ) => { + setDescription(event.target.value); + }} + componentClass='textarea' + rows={5} + value={description} + placeholder={t('forum-help.describe')} + minLength={DESCRIPTION_MIN_CHARS} + maxLength={DESCRIPTION_MAX_CHARS} + required + /> + + + + {description.length < DESCRIPTION_MIN_CHARS ? ( +

+ {t('learn.minimum-characters', { + characters: DESCRIPTION_MIN_CHARS - description.length + })} +

+ ) : ( +

+ {t('learn.characters-left', { + characters: DESCRIPTION_MAX_CHARS - description.length + })} +

+ )} + + + + + + + + ) : ( + <> +
+

+ + + placeholder + + +

+

+ + + placeholder + + placeholder + +

+
+ + + {videoUrl && ( + <> + + + + )} + + + + + )} +
+
+ ); +} + +HelpModal.displayName = 'HelpModal'; + +export default connect(mapStateToProps, mapDispatchToProps)(HelpModal); diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/hotkeys.css b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/hotkeys.css new file mode 100644 index 0000000000000000000000000000000000000000..4b181ae793976e7ce2cab4e8369f36d4cebb0783 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/hotkeys.css @@ -0,0 +1,4 @@ +/* hide the outline for the HotKeys component */ +div[tabindex='-1']:focus { + outline-color: transparent; +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/hotkeys.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/hotkeys.tsx new file mode 100644 index 0000000000000000000000000000000000000000..68c5e79edac4109c2f0cf673dce7eb7561e15bd2 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/hotkeys.tsx @@ -0,0 +1,241 @@ +import { navigate } from 'gatsby'; +import React from 'react'; +import { HotKeys, GlobalHotKeys } from 'react-hotkeys'; +import { connect } from 'react-redux'; +import { createSelector } from 'reselect'; + +import type { + ChallengeFiles, + Test, + ChallengeMeta, + User +} from '../../../redux/prop-types'; +import { userSelector } from '../../../redux/selectors'; +import { + setEditorFocusability, + openModal, + setIsAdvancing +} from '../redux/actions'; +import { + canFocusEditorSelector, + challengeFilesSelector, + challengeMetaSelector, + challengeTestsSelector, + isHelpModalOpenSelector, + isProjectPreviewModalOpenSelector, + isResetModalOpenSelector, + isShortcutsModalOpenSelector +} from '../redux/selectors'; +import './hotkeys.css'; +import { isProjectBased } from '../../../utils/curriculum-layout'; +import type { EditorProps } from '../classic/editor'; +import { useSubmit } from '../utils/fetch-all-curriculum-data'; + +const mapStateToProps = createSelector( + isHelpModalOpenSelector, + isResetModalOpenSelector, + isShortcutsModalOpenSelector, + isProjectPreviewModalOpenSelector, + canFocusEditorSelector, + challengeFilesSelector, + challengeTestsSelector, + userSelector, + challengeMetaSelector, + ( + isHelpModalOpen: boolean, + isResetModalOpen: boolean, + isShortcutsModalOpen: boolean, + isProjectPreviewModalOpen: boolean, + canFocusEditor: boolean, + challengeFiles: ChallengeFiles, + tests: Test[], + user: User | null, + { nextChallengePath, prevChallengePath }: ChallengeMeta + ) => ({ + isHelpModalOpen, + isResetModalOpen, + isShortcutsModalOpen, + isProjectPreviewModalOpen, + canFocusEditor, + challengeFiles, + tests, + keyboardShortcuts: !!user?.keyboardShortcuts, + nextChallengePath, + prevChallengePath + }) +); + +const mapDispatchToProps = { + setEditorFocusability, + openShortcutsModal: () => openModal('shortcuts'), + setIsAdvancing +}; + +export type HotkeysProps = Pick< + ChallengeMeta, + 'nextChallengePath' | 'prevChallengePath' +> & + Partial< + Pick< + EditorProps, + 'usesMultifileEditor' | 'editorRef' | 'challengeType' | 'executeChallenge' + > + > & + Pick< + EditorProps, + 'containerRef' | 'tests' | 'challengeFiles' | 'setEditorFocusability' + > & { + isHelpModalOpen?: boolean; + isResetModalOpen?: boolean; + isShortcutsModalOpen?: boolean; + isProjectPreviewModalOpen?: boolean; + canFocusEditor: boolean; + children: React.ReactElement; + instructionsPanelRef?: React.RefObject; + setEditorFocusability: (arg0: boolean) => void; + setIsAdvancing: (arg0: boolean) => void; + openShortcutsModal: () => void; + playScene?: () => void; + keyboardShortcuts: boolean; + }; + +function Hotkeys({ + canFocusEditor, + challengeType, + children, + instructionsPanelRef, + editorRef, + executeChallenge, + containerRef, + nextChallengePath, + prevChallengePath, + setEditorFocusability, + setIsAdvancing, + tests, + usesMultifileEditor, + openShortcutsModal, + playScene, + keyboardShortcuts, + isHelpModalOpen, + isResetModalOpen, + isShortcutsModalOpen, + isProjectPreviewModalOpen +}: HotkeysProps): JSX.Element { + const submitChallenge = useSubmit(); + + const isModalOpen = [ + isHelpModalOpen, + isResetModalOpen, + isShortcutsModalOpen, + isProjectPreviewModalOpen + ].some(Boolean); + + const keyMap = { + // The Modal component needs to listen to the 'Escape' keypress event + // in order to close itself when the key is press. + // Therefore, we don't want HotKeys to hijack the 'escape' event when a modal is open. + navigationMode: isModalOpen ? '' : 'escape', + executeChallenge: ['ctrl+enter', 'command+enter'], + focusEditor: 'e', + focusInstructionsPanel: 'r', + navigatePrev: ['p'], + navigateNext: ['n'], + showShortcuts: 'shift+/', + playScene: ['ctrl+space'] + }; + + const handlers = { + executeChallenge: (keyEvent?: KeyboardEvent) => { + // the 'enter' part of 'ctrl+enter' stops HotKeys from listening, so it + // needs to be prevented. + // TODO: 'enter' on its own also disables HotKeys, but default behaviour + // should not be prevented in that case. + keyEvent?.preventDefault(); + + if (!executeChallenge) return; + + const testsArePassing = tests.every(test => test.pass && !test.err); + + if ( + usesMultifileEditor && + typeof challengeType == 'number' && + !isProjectBased(challengeType) + ) { + if (testsArePassing) { + submitChallenge(); + } else { + executeChallenge(); + } + } else { + executeChallenge({ showCompletionModal: false }); + } + }, + ...(keyboardShortcuts + ? { + showShortcuts: (keyEvent?: KeyboardEvent) => { + if (keyEvent?.key === '?') { + openShortcutsModal(); + } + }, + focusEditor: (keyEvent?: KeyboardEvent) => { + keyEvent?.preventDefault(); + if (editorRef && editorRef.current) { + editorRef.current.focus(); + } + }, + focusInstructionsPanel: () => { + if (instructionsPanelRef && instructionsPanelRef.current) { + instructionsPanelRef.current.focus(); + } + }, + navigationMode: () => setEditorFocusability(false), + navigatePrev: () => { + if (!canFocusEditor) { + if (prevChallengePath) { + setIsAdvancing(true); + void navigate(prevChallengePath); + } else { + void navigate('/learn'); + } + } + }, + navigateNext: () => { + if (!canFocusEditor) { + if (nextChallengePath) { + setIsAdvancing(true); + void navigate(nextChallengePath); + } else { + void navigate('/learn'); + } + } + }, + playScene: () => { + if (!playScene) return; + playScene(); + } + } + : {}) + }; + // GlobalHotKeys is always mounted and tracks all keypresses. Without it, + // keyup events can be missed and react-hotkeys assumes that key is still + // being pressed. + // allowChanges is necessary if the handlers depend on props (in this case + // canFocusEditor) + return ( + + {children} + + + ); +} + +Hotkeys.displayName = 'Hotkeys'; + +export default connect(mapStateToProps, mapDispatchToProps)(Hotkeys); diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/independent-lower-jaw.css b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/independent-lower-jaw.css new file mode 100644 index 0000000000000000000000000000000000000000..74264b7be36a1c30faf056d02b6a07c69df7bf5d --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/independent-lower-jaw.css @@ -0,0 +1,240 @@ +.independent-lower-jaw { + width: 100%; + flex: 0 0 auto; + position: relative; + z-index: 101; +} + +.independent-lower-jaw .hint-container { + background-color: var(--background-quaternary); + display: flex; + flex-direction: column; + justify-content: space-between; + gap: 10px; + padding: 12px; + position: absolute; + bottom: 100%; + width: 97%; + left: 50%; + transform: translateX(-50%); + margin-bottom: 12px; + border: 1px solid var(--background-secondary); + opacity: 0; + animation: jaw-hint-fade-in 0.3s ease forwards; +} + +.independent-lower-jaw .hint-container .hint-header { + display: flex; + justify-content: space-between; + flex-direction: row; + margin-bottom: 10px; +} + +.independent-lower-jaw .hint-container .hint-header svg { + height: 1.4rem; + width: 1.4rem; +} + +.independent-lower-jaw .hint-body code { + white-space: pre-wrap; + overflow-wrap: anywhere; +} + +.independent-lower-jaw .hint-container .hint-body p:last-child { + margin-bottom: 0; +} + +@keyframes jaw-hint-fade-in { + from { + opacity: 0; + } + to { + opacity: 1; + } +} + +.independent-lower-jaw .btn-cta { + padding: 6px 12px; +} + +.independent-lower-jaw .buttons-row-container { + display: flex; + justify-content: space-between; + flex-direction: row; + background-color: var(--background-secondary); + border: var(--background-quaternary) 1px solid; + padding: 12px; +} + +.action-row-right { + display: flex; + flex-direction: row; + align-items: center; +} + +.independent-lower-jaw .hint-container button { + font-size: 1.5rem; + display: flex; + justify-content: center; + align-items: center; + border: 1px solid var(--quaternary-color); +} + +.independent-lower-jaw .action-row-right button { + height: 40px; + width: 40px; + display: flex; + justify-content: center; + align-items: center; + border: none; + margin-left: 10px; +} + +.independent-lower-jaw .tooltip { + position: relative; + display: inline-block; +} + +.independent-lower-jaw .socrates-feature-dot { + position: absolute; + top: -4px; + right: -4px; + width: 14px; + height: 14px; + border-radius: 50%; + background-color: var(--red80); + pointer-events: none; + animation: socrates-dot-pulse 2s ease-out infinite; +} + +@keyframes socrates-dot-pulse { + 0% { + box-shadow: 0 0 0 0 var(--red80); + } + + 70% { + box-shadow: 0 0 0 6px rgba(248, 33, 83, 0); + } + + 100% { + box-shadow: 0 0 0 0 rgba(248, 33, 83, 0); + } +} + +@media (prefers-reduced-motion: reduce) { + .independent-lower-jaw .socrates-feature-dot { + animation: none; + } +} + +/* Tooltip text */ +.independent-lower-jaw .tooltip .tooltiptext { + visibility: hidden; + opacity: 0; + background-color: var(--background-quaternary); + color: var(--foreground-primary); + border: 1px solid var(--foreground-secondary); + padding: 5px 10px; + font-size: 1rem; + text-align: center; + position: absolute; + width: max-content; + top: -60px; + z-index: 1; +} + +/* Show the tooltip text when you mouse over the tooltip container */ +.independent-lower-jaw .tooltip:hover .tooltiptext { + visibility: visible; + opacity: 1; + transition: opacity 0.5s ease 1s; +} + +/* .independent-lower-jaw */ + +.tooltiptext::after { + content: ''; + position: absolute; + display: block; + width: 0.5rem; + height: 0.5rem; + border-style: solid; + border-width: 0px 1px 1px 0px; + border-color: var(--color-border-primary); + transform: rotate(45deg); + bottom: -5px; + left: calc(50% - 0.25rem); + background-image: linear-gradient( + to top left, + var(--background-quaternary) 55%, + rgba(0, 0, 0, 0) 20% + ); +} + +.independent-lower-jaw .tooltip .tooltiptext.left-tooltip { + left: 0; +} + +.share-button-wrapper { + display: flex; + justify-content: end; + margin-top: 10px; + gap: 10px; +} + +.socrates-skeleton { + display: flex; + flex-direction: column; + gap: 8px; + padding: 8px 0; +} + +.skeleton-line { + height: 16px; + border-radius: 2px; +} + +.skeleton-line-1 { + background-color: var(--tertiary-background); + width: 100%; + animation: pulse-1 1.5s ease-in-out infinite; +} + +.skeleton-line-2 { + background-color: var(--tertiary-background); + width: 85%; + animation: pulse-2 1.5s ease-in-out infinite; +} + +@keyframes pulse-1 { + 0%, + 100% { + opacity: 1; + } + 50% { + opacity: 0.5; + } +} + +@keyframes pulse-2 { + 0% { + opacity: 0.5; + } + 50% { + opacity: 1; + } + 100% { + opacity: 0.5; + } +} + +.share-button-wrapper a { + border: 1px solid var(--quaternary-color); + padding: 2px 6px; +} + +.socrates-donation-cta { + border-top: 1px solid var(--background-secondary); + margin-top: 8px; + padding-top: 10px; +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/independent-lower-jaw.test.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/independent-lower-jaw.test.tsx new file mode 100644 index 0000000000000000000000000000000000000000..d9b3aa3730c75eb16ccfb2fe4656192b7cbe2a27 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/independent-lower-jaw.test.tsx @@ -0,0 +1,647 @@ +import React from 'react'; +import { screen, waitFor } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { useStaticQuery } from 'gatsby'; + +import type { ChallengeMeta, Test } from '../../../redux/prop-types'; +import { SuperBlocks } from '@freecodecamp/shared/config/curriculum'; +import callGA from '../../../analytics/call-ga'; +import { IndependentLowerJaw } from './independent-lower-jaw'; +import { createStore } from '../../../redux/create-store'; +import { mockCurriculumData } from '../utils/__fixtures__/curriculum-data'; +import { render } from '../../../../utils/test-utils'; + +vi.mock('../../../components/Progress'); +vi.mock('../../../analytics/call-ga', () => ({ + default: vi.fn() +})); + +let showSocratesFlag = true; +const envMock = vi.hoisted(() => ({ + clientLocale: 'english', + apiLocation: 'http://localhost:3000' +})); +vi.mock('../../../../config/env.json', () => ({ + get clientLocale() { + return envMock.clientLocale; + }, + get apiLocation() { + return envMock.apiLocation; + }, + get default() { + return envMock; + } +})); +vi.mock('@growthbook/growthbook-react', () => ({ + useFeature: () => ({ on: showSocratesFlag }) +})); +const mockSubmitChallenge = vi.hoisted(() => vi.fn()); +vi.mock('../utils/fetch-all-curriculum-data', () => ({ + useSubmit: () => mockSubmitChallenge +})); + +const baseChallengeMeta: ChallengeMeta = { + block: 'test-block', + id: 'test-challenge-id', + isFirstStep: false, + superBlock: SuperBlocks.RespWebDesignV9, + helpCategory: 'HTML-CSS', + disableLoopProtectTests: false, + disableLoopProtectPreview: false +}; + +const passingTests: Test[] = [{ pass: true, text: 'test', testString: 'test' }]; +const baseProps = { + openHelpModal: vi.fn(), + openResetModal: vi.fn(), + executeChallenge: vi.fn(), + submitChallenge: vi.fn(), + askSocrates: vi.fn(), + saveChallenge: vi.fn(), + attempts: 0, + tests: passingTests, + isDonating: false, + isSignedIn: true, + challengeMeta: baseChallengeMeta, + completedPercent: 100, + completedChallengeIds: ['id-1', 'test-challenge-id'], + currentBlockIds: ['id-1', 'test-challenge-id'], + hasSocratesAccess: false, + socratesHintState: { + hint: null, + isLoading: false, + error: null, + attempts: null, + limit: null + } +}; + +vi.mock('../../../utils/get-words'); + +const getLiveRegion = () => { + const region = screen.getByTestId('independent-lower-jaw-live-region'); + expect(region).toHaveAttribute('aria-live', 'polite'); + expect(region).toHaveAttribute('aria-atomic', 'true'); + return region; +}; + +describe('', () => { + beforeEach(() => { + showSocratesFlag = true; + envMock.clientLocale = 'english'; + localStorage.clear(); + vi.mocked(useStaticQuery).mockReturnValue(mockCurriculumData); + }); + + afterEach(() => { + vi.resetAllMocks(); + }); + + it('shows share buttons when the block is completed on the last step', () => { + render(, createStore()); + + expect(screen.getByTestId('share-on-x')).toBeInTheDocument(); + expect(screen.getByTestId('share-on-bluesky')).toBeInTheDocument(); + expect(screen.getByTestId('share-on-threads')).toBeInTheDocument(); + }); + + it('does not show share buttons when the block is not completed', () => { + render( + , + createStore() + ); + + expect(screen.queryByTestId('share-on-x')).not.toBeInTheDocument(); + }); + + it('does not show share buttons when it is not the last step', () => { + render( + , + createStore() + ); + + expect(screen.queryByTestId('share-on-x')).not.toBeInTheDocument(); + }); + + it('shows reset and help buttons by default', () => { + render(, createStore()); + + expect( + screen.getByRole('button', { name: 'buttons.reset' }) + ).toBeInTheDocument(); + expect( + screen.getByRole('button', { name: 'buttons.help' }) + ).toBeInTheDocument(); + }); + + it('opens the help modal when the help button is clicked', async () => { + const openHelpModal = vi.fn(); + + render( + , + createStore() + ); + + await userEvent.click(screen.getByRole('button', { name: 'buttons.help' })); + + expect(openHelpModal).toHaveBeenCalledTimes(1); + }); + + it('checks the challenge when the check button is clicked', async () => { + const executeChallenge = vi.fn(); + const failingTests: Test[] = [ + { pass: false, err: 'fail', text: 'test', testString: 'test' } + ]; + + render( + , + createStore() + ); + + await userEvent.click( + screen.getByRole('button', { name: 'buttons.check-code' }) + ); + + expect(executeChallenge).toHaveBeenCalled(); + }); + + it('opens the reset modal when the reset button is clicked', async () => { + const openResetModal = vi.fn(); + + render( + , + createStore() + ); + + await userEvent.click( + screen.getByRole('button', { name: 'buttons.reset' }) + ); + + expect(openResetModal).toHaveBeenCalled(); + }); + + it('saves the challenge when the save button is clicked', async () => { + const saveChallenge = vi.fn(); + + render( + , + createStore() + ); + + await userEvent.click(screen.getByRole('button', { name: 'buttons.save' })); + + expect(saveChallenge).toHaveBeenCalled(); + }); + + it('opens the reset modal when the revert button is clicked', async () => { + const openResetModal = vi.fn(); + + render( + , + createStore() + ); + + await userEvent.click( + screen.getByRole('button', { name: 'buttons.revert' }) + ); + + expect(openResetModal).toHaveBeenCalled(); + }); + + it('shows socrates button when hasSocratesAccess is true and flag is on', () => { + render( + , + createStore() + ); + + expect(screen.getByText('buttons.ask-socrates')).toBeInTheDocument(); + }); + + it('tracks CallSocrates analytics when ask socrates button is clicked', async () => { + render( + , + createStore() + ); + + await userEvent.click(screen.getByRole('button', { name: /ask-socrates/ })); + + expect(callGA).toHaveBeenCalledWith({ + event: 'call_socrates', + action: 'Socrates LowerJaw Button Click', + is_donating: false, + attempts: 2, + limit: 3, + optimized_request: null + }); + expect(baseProps.askSocrates).toHaveBeenCalled(); + }); + + it('tracks check code analytics when the check button is clicked', async () => { + render( + , + createStore() + ); + + await userEvent.click(screen.getByRole('button', { name: /check-code/ })); + + expect(callGA).toHaveBeenCalledWith({ + event: 'challenge_test_code_button_click' + }); + }); + + it('tracks submit code analytics when the submit button is clicked', async () => { + mockSubmitChallenge.mockClear(); + + render(, createStore()); + + await userEvent.click( + screen.getByRole('button', { name: /submit-continue/ }) + ); + + expect(callGA).toHaveBeenCalledWith({ + event: 'challenge_submit_button_click' + }); + expect(mockSubmitChallenge).toHaveBeenCalled(); + }); + + it('hides socrates button when show-socrates flag is off', () => { + showSocratesFlag = false; + + render( + , + createStore() + ); + + expect(screen.queryByText('buttons.ask-socrates')).not.toBeInTheDocument(); + }); + + it('hides socrates button when language is not english', () => { + envMock.clientLocale = 'espanol'; + + render( + , + createStore() + ); + + expect(screen.queryByText('buttons.ask-socrates')).not.toBeInTheDocument(); + }); + + it('hides socrates button when hasSocratesAccess is false', () => { + render( + , + createStore() + ); + + expect(screen.queryByText('buttons.ask-socrates')).not.toBeInTheDocument(); + }); + + it('displays usage counter when attempts and limit are set', async () => { + const failingTests: Test[] = [ + { pass: false, err: 'fail', text: 'test', testString: 'test' } + ]; + + render( + , + createStore() + ); + + // Click the socrates button to open the results panel + await userEvent.click(screen.getByRole('button', { name: /ask-socrates/ })); + + expect(screen.getByText(/2\/3/)).toBeInTheDocument(); + expect(screen.getByText(/learn\.hints-used-today/)).toBeInTheDocument(); + }); + + it('shows Socrates donation CTA when the daily limit is reached', async () => { + const failingTests: Test[] = [ + { pass: false, err: 'fail', text: 'test', testString: 'test' } + ]; + + render( + , + createStore() + ); + + await userEvent.click(screen.getByRole('button', { name: /ask-socrates/ })); + + expect(screen.getByTestId('socrates-donation-cta')).toBeInTheDocument(); + expect( + screen.getByText('learn.donor-socrates-benefit') + ).toBeInTheDocument(); + expect( + screen.getByRole('link', { name: /donate.become-supporter/ }) + ).toHaveAttribute('href', '/donate'); + }); + + it('tracks donation_related analytics when become supporter link is clicked', async () => { + const failingTests: Test[] = [ + { pass: false, err: 'fail', text: 'test', testString: 'test' } + ]; + + vi.mocked(callGA).mockClear(); + + render( + , + createStore() + ); + + await userEvent.click(screen.getByRole('button', { name: /ask-socrates/ })); + await userEvent.click( + screen.getByRole('link', { name: /donate.become-supporter/ }) + ); + + expect(callGA).toHaveBeenCalledWith({ + event: 'donation_related', + action: 'Socrates LowerJaw Become Supporter Click' + }); + }); + + it('hides Socrates donation CTA for supporters even when the limit is reached', async () => { + const failingTests: Test[] = [ + { pass: false, err: 'fail', text: 'test', testString: 'test' } + ]; + + render( + , + createStore() + ); + + await userEvent.click(screen.getByRole('button', { name: /ask-socrates/ })); + + expect( + screen.queryByTestId('socrates-donation-cta') + ).not.toBeInTheDocument(); + }); + + const twoFailedAttemptsProps = { + ...baseProps, + hasSocratesAccess: true, + attempts: 2, + tests: [ + { pass: false, err: 'fail', text: 'test', testString: 'test' } + ] as Test[], + completedPercent: 50, + completedChallengeIds: ['id-1'] + }; + + it('shows the Socrates feature-discovery dot after two failed checks', () => { + render(, createStore()); + + expect(screen.getByTestId('socrates-feature-dot')).toBeInTheDocument(); + }); + + it('does not show the dot before two failed checks', () => { + render( + , + createStore() + ); + + expect( + screen.queryByTestId('socrates-feature-dot') + ).not.toBeInTheDocument(); + }); + + it('does not show the dot when the challenge is complete', () => { + render( + , + createStore() + ); + + expect( + screen.queryByTestId('socrates-feature-dot') + ).not.toBeInTheDocument(); + }); + + it('hides the dot once the Socrates button is clicked and remembers it', async () => { + const { unmount } = render( + , + createStore() + ); + + expect(screen.getByTestId('socrates-feature-dot')).toBeInTheDocument(); + + await userEvent.click(screen.getByRole('button', { name: /ask-socrates/ })); + + expect( + screen.queryByTestId('socrates-feature-dot') + ).not.toBeInTheDocument(); + expect(localStorage.getItem('fcc-socrates-discovered')).toBe('true'); + + // The dismissal persists across remounts (e.g. other challenges). + unmount(); + render(, createStore()); + + expect( + screen.queryByTestId('socrates-feature-dot') + ).not.toBeInTheDocument(); + }); + + it('announces hint text through a live region', async () => { + const failingTests: Test[] = [ + { + pass: false, + err: 'Use <main> here.', + message: 'Use <main> here.', + text: 'test', + testString: 'test' + } + ]; + + render( + , + createStore() + ); + + expect(getLiveRegion()).toHaveTextContent(''); + + await waitFor(() => + expect(getLiveRegion()).toHaveTextContent('Use
here.') + ); + }); + + it('re-announces the same hint after each check attempt', async () => { + const firstFailingTests: Test[] = [ + { + pass: false, + err: 'Use <main> here.', + message: 'Use <main> here.', + text: 'test', + testString: 'test' + } + ]; + const thirdFailingTests: Test[] = [ + { + pass: false, + err: 'Use <main> here.', + message: 'Use <main> here.', + text: 'test', + testString: 'test' + } + ]; + const secondFailingTests: Test[] = [ + { + pass: false, + err: 'Use <main> here.', + message: 'Use <main> here.', + text: 'test', + testString: 'test' + } + ]; + + const { rerender } = render( + , + createStore() + ); + + expect(getLiveRegion()).toHaveTextContent(''); + + await waitFor(() => + expect(getLiveRegion()).toHaveTextContent('Use
here.') + ); + + rerender( + + ); + + expect(getLiveRegion()).toHaveTextContent(''); + + await waitFor(() => + expect(getLiveRegion()).toHaveTextContent('Use
here.') + ); + + rerender( + + ); + + expect(getLiveRegion()).toHaveTextContent(''); + + await waitFor(() => + expect(getLiveRegion()).toHaveTextContent('Use
here.') + ); + }); + + it('announces completion text through a hidden live region', async () => { + render(, createStore()); + + expect(getLiveRegion()).toHaveTextContent(''); + + await waitFor(() => + expect(getLiveRegion()).toHaveTextContent( + /learn\.congratulations-code-passes .* learn\.percent-complete/ + ) + ); + }); + + it('does not reset the completion live region on passing rerenders', async () => { + const firstPassingTests: Test[] = [ + { pass: true, text: 'test', testString: 'test' } + ]; + const secondPassingTests: Test[] = [ + { pass: true, text: 'test', testString: 'test' } + ]; + + const { rerender } = render( + , + createStore() + ); + + await waitFor(() => + expect(getLiveRegion()).toHaveTextContent( + /learn\.congratulations-code-passes .* learn\.percent-complete/ + ) + ); + + rerender(); + + expect(getLiveRegion()).toHaveTextContent( + /learn\.congratulations-code-passes .* learn\.percent-complete/ + ); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/independent-lower-jaw.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/independent-lower-jaw.tsx new file mode 100644 index 0000000000000000000000000000000000000000..e7a4b48896a62cf4a77aaf9d2f59db2b1b34a295 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/independent-lower-jaw.tsx @@ -0,0 +1,578 @@ +import React, { useState, useEffect } from 'react'; +import { connect } from 'react-redux'; +import { createSelector } from 'reselect'; +import { useTranslation } from 'react-i18next'; +import sanitizeHtml from 'sanitize-html'; +import { Button, Spacer } from '@freecodecamp/ui'; +import { useFeature } from '@growthbook/growthbook-react'; +import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; +import { + faClose, + faZap, + faSave, + faClockRotateLeft, + faRotateLeft +} from '@fortawesome/free-solid-svg-icons'; +import Progress from '../../../components/Progress'; +import { + completedChallengesIdsSelector, + isDonatingSelector, + isSignedInSelector, + isSocratesOnSelector +} from '../../../redux/selectors'; +import { ChallengeMeta, Test } from '../../../redux/prop-types'; +import { + attemptsSelector, + challengeMetaSelector, + challengeTestsSelector, + completedPercentageSelector, + currentBlockIdsSelector, + socratesHintStateSelector +} from '../redux/selectors'; +import envData from '../../../../config/env.json'; +import { openModal, executeChallenge, askSocrates } from '../redux/actions'; +import { saveChallenge } from '../../../redux/actions'; +import Help from '../../../assets/icons/help'; +import callGA from '../../../analytics/call-ga'; +import { Share } from '../../../components/share'; +import { useSubmit } from '../utils/fetch-all-curriculum-data'; + +import './independent-lower-jaw.css'; +import Socrates from '../../../assets/icons/socrates'; +import OutlineLightbulb from '../../../assets/icons/outline-lightbulb'; + +const SOCRATES_DISCOVERED_KEY = 'fcc-socrates-discovered'; + +type SocratesHintState = { + hint: null | string; + isLoading: boolean; + error: null | string; + attempts: null | number; + limit: null | number; +}; + +interface StatusAnnouncementProps { + message: string; +} + +const StatusAnnouncement = ({ + message +}: StatusAnnouncementProps): JSX.Element => { + const [announcement, setAnnouncement] = useState(''); + + useEffect(() => { + setAnnouncement(''); + + if (!message) return; + + const announceTimeout = window.setTimeout(() => { + setAnnouncement(message); + }, 100); + + return () => { + window.clearTimeout(announceTimeout); + }; + }, [message]); + + return ( + + {announcement} + + ); +}; + +const mapStateToProps = createSelector( + attemptsSelector, + challengeTestsSelector, + isDonatingSelector, + isSignedInSelector, + challengeMetaSelector, + completedPercentageSelector, + completedChallengesIdsSelector, + currentBlockIdsSelector, + socratesHintStateSelector, + isSocratesOnSelector, + ( + attempts: number, + tests: Test[], + isDonating: boolean, + isSignedIn: boolean, + challengeMeta: ChallengeMeta, + completedPercent: number, + completedChallengeIds: string[], + currentBlockIds: string[], + socratesHintState: SocratesHintState, + hasSocratesAccess: boolean + ) => ({ + attempts, + tests, + isDonating, + isSignedIn, + challengeMeta, + completedPercent, + completedChallengeIds, + currentBlockIds, + socratesHintState, + hasSocratesAccess + }) +); + +const mapDispatchToProps = { + openHelpModal: () => openModal('help'), + openResetModal: () => openModal('reset'), + askSocrates: () => askSocrates(), + executeChallenge, + saveChallenge +}; + +interface IndependentLowerJawProps { + openHelpModal: () => void; + openResetModal: () => void; + executeChallenge: () => void; + askSocrates: () => void; + saveChallenge: () => void; + attempts: number; + tests: Test[]; + isDonating: boolean; + isSignedIn: boolean; + challengeMeta: ChallengeMeta; + completedPercent: number; + completedChallengeIds: string[]; + currentBlockIds: string[]; + socratesHintState: SocratesHintState; + hasSocratesAccess: boolean; +} +export function IndependentLowerJaw({ + openHelpModal, + openResetModal, + askSocrates, + executeChallenge, + saveChallenge, + attempts, + tests, + isDonating, + isSignedIn, + challengeMeta, + completedPercent, + completedChallengeIds, + currentBlockIds, + socratesHintState, + hasSocratesAccess +}: IndependentLowerJawProps): JSX.Element { + const { t } = useTranslation(); + const { apiLocation, clientLocale } = envData; + const showSocratesFlag = + useFeature('show-socrates').on && clientLocale === 'english'; + const submitChallenge = useSubmit(); + const firstFailedTest = tests.find(test => !!test.err); + const hint = firstFailedTest?.message; + const sanitizedHint = React.useMemo( + () => + hint + ? sanitizeHtml(hint, { + allowedTags: ['b', 'i', 'em', 'strong', 'code', 'wbr'] + }) + : '', + [hint] + ); + const hintAnnouncement = React.useMemo( + () => + new DOMParser() + .parseFromString(sanitizedHint, 'text/html') + .body.textContent?.replace(/\s+/g, ' ') + .trim() ?? '', + [sanitizedHint] + ); + const [showHint, setShowHint] = React.useState(false); + const [showSocratesResults, setShowSocratesResults] = React.useState(false); + const [showSubmissionHint, setShowSubmissionHint] = React.useState(true); + const signInLinkRef = React.useRef(null); + const submitButtonRef = React.useRef(null); + const [wasCheckButtonClicked, setWasCheckButtonClicked] = + React.useState(false); + const [socratesDiscovered, setSocratesDiscovered] = React.useState(false); + + const isChallengeComplete = tests.every(test => test.pass); + // Feature-discovery nudge: after two failed checks on a challenge, flash a dot + // on the Socrates button until the learner clicks it for the first time. + const showSocratesDot = + hasSocratesAccess && + showSocratesFlag && + !socratesDiscovered && + attempts >= 2 && + !isChallengeComplete; + const hasBlockIds = currentBlockIds.length > 0; + const isLastStepInBlock = + hasBlockIds && + currentBlockIds[currentBlockIds.length - 1] === challengeMeta.id; + const isBlockCompletedByIds = + hasBlockIds && + currentBlockIds.every(challengeId => + completedChallengeIds.includes(challengeId) + ); + const hasCompletedPercent = Number.isFinite(completedPercent); + const isBlockCompleted = + isBlockCompletedByIds || (hasCompletedPercent && completedPercent === 100); + const showShareButton = + isChallengeComplete && isLastStepInBlock && isBlockCompleted; + const completionAnnouncement = [ + t('learn.congratulations-code-passes'), + hasCompletedPercent + ? `${t(`intro:${challengeMeta.superBlock}.blocks.${challengeMeta.block}.title`)} ${t('learn.percent-complete', { percent: completedPercent })}` + : null + ] + .filter(Boolean) + .join(' '); + + const liveAnnouncementMessage = + showHint && hint + ? hintAnnouncement + : isChallengeComplete && showSubmissionHint + ? completionAnnouncement + : ''; + + // Hint announcements need a fresh signal for every check attempt so the same + // failing message can be remounted and announced again. Completion only needs + // to announce when the challenge becomes complete, not on passing rerenders. + const liveAnnouncementSignal = + showHint && hint + ? attempts + : isChallengeComplete && showSubmissionHint + ? isChallengeComplete + : liveAnnouncementMessage; + + const liveAnnouncementKey = liveAnnouncementMessage + ? `${challengeMeta.id}-${String(liveAnnouncementSignal)}` + : `${challengeMeta.id}-idle`; + + React.useEffect(() => { + setShowHint(!!hint); + }, [hint, attempts]); + + // Read the feature-discovery flag client-side only to avoid an SSR/hydration + // mismatch. The dot can only appear after two client-side checks anyway. + React.useEffect(() => { + setSocratesDiscovered( + localStorage.getItem(SOCRATES_DISCOVERED_KEY) === 'true' + ); + }, []); + + React.useEffect(() => { + if (!isChallengeComplete || !wasCheckButtonClicked) return; + + const focusTarget = isSignedIn + ? submitButtonRef.current + : signInLinkRef.current; + focusTarget?.focus(); + setWasCheckButtonClicked(false); + }, [isChallengeComplete, isSignedIn, wasCheckButtonClicked]); + + const isMacOS = navigator.userAgent.includes('Mac OS'); + const showRevertButton = isSignedIn && challengeMeta.saveSubmissionToDB; + const shouldShowSocratesDonateCta = + !isDonating && + socratesHintState.attempts !== null && + socratesHintState.limit !== null && + socratesHintState.attempts >= socratesHintState.limit; + const checkButtonText = isMacOS + ? t('buttons.command-enter') + : t('buttons.ctrl-enter'); + + const askSocratesAttempt = () => { + if (!socratesDiscovered) { + localStorage.setItem(SOCRATES_DISCOVERED_KEY, 'true'); + setSocratesDiscovered(true); + } + + callGA({ + event: 'call_socrates', + action: 'Socrates LowerJaw Button Click', + is_donating: isDonating, + attempts: socratesHintState.attempts, + limit: socratesHintState.limit, + optimized_request: null + }); + + setShowSocratesResults(true); + setShowHint(false); + setShowSubmissionHint(false); + if (socratesHintState.isLoading) return; + askSocrates(); + }; + + const handleCheckButtonClick = () => { + callGA({ + event: 'challenge_test_code_button_click' + }); + setWasCheckButtonClicked(true); + setShowSocratesResults(false); + executeChallenge(); + }; + + const handleSubmitButtonClick = () => { + callGA({ + event: 'challenge_submit_button_click' + }); + submitChallenge(); + }; + + return ( +
+ + {showHint && hint && ( +
+
+ + +
+
+
+ )} + {showSocratesResults && ( +
+
+ + +
+ {socratesHintState.isLoading ? ( +
+
+
+
+ ) : ( +
+ )} + {socratesHintState.attempts !== null && + socratesHintState.limit !== null && ( +
+ {socratesHintState.attempts}/{socratesHintState.limit}{' '} + {t('learn.hints-used-today')} +
+ )} + {shouldShowSocratesDonateCta && ( + + )} +
+ )} + {isChallengeComplete && showSubmissionHint && ( +
+
+ + +
+ {t('learn.congratulations-code-passes')} +
+ +
+ {isSignedIn && showShareButton && ( +
+ +
+ )} + {!isSignedIn && ( + <> + + { + callGA({ + event: 'sign_in' + }); + }} + > + {t('learn.sign-in-save')} + + + )} +
+ )} + +
+
+ {isChallengeComplete ? ( + + ) : ( + + )} +
+
+ {hasSocratesAccess && showSocratesFlag && ( + + )} + {showRevertButton ? ( + <> + + + + ) : ( + + )} + +
+
+
+ ); +} + +IndependentLowerJaw.displayName = 'IndependentLowerJaw'; + +export default connect( + mapStateToProps, + mapDispatchToProps +)(IndependentLowerJaw); diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/interactive-editor.css b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/interactive-editor.css new file mode 100644 index 0000000000000000000000000000000000000000..9c5d60f5ed5b98fefe3c127dffcda35152864def --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/interactive-editor.css @@ -0,0 +1,65 @@ +.interactive-editor-wrapper { + margin-bottom: 1rem; + border-radius: 4px; +} + +.sp-cm .cm-gutters { + color: var(--gray-45); +} + +.sp-tabs .sp-tab-button { + color: var(--gray-10) !important; +} + +.sp-tabs .sp-tab-button[aria-selected='true'], +.sp-tabs .sp-tab-button:hover { + background-color: var(--gray-10); + color: var(--gray-90) !important; +} + +.sp-preview-actions .sp-button { + background-color: var(--gray-90); + color: var(--gray-10) !important; +} + +.sp-preview-actions .sp-button:hover { + background-color: var(--gray-10) !important; + color: var(--gray-90) !important; + border-color: var(--gray-90) !important; +} + +.interactive-layout { + display: flex; + flex-direction: row; /* Default for desktop: side-by-side */ + height: 450px; +} + +.interactive-editor-column { + flex: 1.5 !important; + height: 100% !important; +} + +.interactive-preview-column { + flex: 1 !important; + height: 100% !important; +} + +.sp-preview { + height: 100%; +} + +@media (max-width: 768px) { + .interactive-layout { + flex-direction: column; + height: auto !important; /* Allow the height to expand as content stacks */ + } + + .interactive-editor-column, + .interactive-preview-column { + width: 100%; + /* Override desktop flex value */ + flex: 0 0 auto !important; + /* Set a reasonable mobile height for the editor */ + height: 400px !important; + } +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/interactive-editor.test.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/interactive-editor.test.tsx new file mode 100644 index 0000000000000000000000000000000000000000..1d8a10dd3e0fb486e3a9c9aa58bee30997cc85f8 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/interactive-editor.test.tsx @@ -0,0 +1,35 @@ +import { render, screen } from '@testing-library/react'; +import React from 'react'; +import { describe, expect, it } from 'vitest'; + +import InteractiveEditor, { type InteractiveFile } from './interactive-editor'; + +const htmlFile: InteractiveFile = { + ext: 'html', + name: 'index', + contents: '

Hello

', + contentsHtml: '

Hello

' +}; + +const jsFile: InteractiveFile = { + ext: 'js', + name: 'script', + contents: 'console.log("Hello");', + contentsHtml: 'console.log("Hello");' +}; + +describe('', () => { + it('shows preview and console panels for HTML with JavaScript', () => { + render(); + + expect(screen.getByTestId('sp-preview')).toBeInTheDocument(); + expect(screen.getByTestId('sp-console')).toBeInTheDocument(); + }); + + it('shows only the console panel for JavaScript-only files', () => { + render(); + + expect(screen.getByTestId('sp-console')).toBeInTheDocument(); + expect(screen.queryByTestId('sp-preview')).not.toBeInTheDocument(); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/interactive-editor.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/interactive-editor.tsx new file mode 100644 index 0000000000000000000000000000000000000000..ebbd61639ff168dcf266fc40cdee693760c673ec --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/interactive-editor.tsx @@ -0,0 +1,131 @@ +import React, { useMemo } from 'react'; +import { + FileTabs, + SandpackConsole, + SandpackLayout, + SandpackPreview, + SandpackProvider, + SandpackStack +} from '@codesandbox/sandpack-react'; +import { freeCodeCampDark } from '@codesandbox/sandpack-themes'; +import './interactive-editor.css'; +import CustomMonacoEditor from './custom-monaco-editor'; + +export interface InteractiveFile { + ext: string; + name: string; + contents: string; + contentsHtml: string; + fileKey?: string; +} + +interface Props { + files: InteractiveFile[]; +} + +const InteractiveEditor = ({ files }: Props) => { + // Build Sandpack files object + // https://github.com/codesandbox/sandpack/tree/main/sandpack-react/src/templates + const spFiles = useMemo(() => { + const obj = {} as Record< + string, + { code: string; active?: boolean; hidden?: boolean } + >; + files.forEach(file => { + const ext = file.ext; + let path = ''; + if (ext === 'html') path = '/index.html'; + else if (ext === 'css') path = '/styles.css'; + else if (ext === 'js' || ext === 'ts') path = `/index.${ext}`; + else if (ext === 'py') + return; // python not supported in sandpack vanilla template + else if (ext === 'jsx') path = '/App.jsx'; + else if (ext === 'tsx') path = '/App.tsx'; + else path = `/index.${ext}`; + // TODO: Consider making active file first file in markdown + obj[path] = { code: file.contents, active: path === '/index.html' }; + }); + return obj; + }, [files]); + + function got(ext: string) { + return files.some(f => f.ext === ext); + } + + const hasHTML = got('html'); + const hasJavaScript = got('js') || got('ts') || got('jsx') || got('tsx'); + + const showConsole = hasJavaScript && hasHTML; + const layout = hasHTML ? 'preview' : 'console'; + const freeCodeCampDarkSyntax = { + ...freeCodeCampDark.syntax, + punctuation: '#ffff00', + definition: '#e2777a', + keyword: '#569cd6' + }; + + return ( +
+ + + + {files.length > 1 && } + + + + + {layout === 'preview' ? ( + showConsole ? ( + <> + + + + ) : ( + + ) + ) : ( + + )} + + + +
+ ); +}; + +InteractiveEditor.displayName = 'InteractiveEditor'; +export default InteractiveEditor; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/mobile-app-modal.test.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/mobile-app-modal.test.tsx new file mode 100644 index 0000000000000000000000000000000000000000..240ae3adcbe24d7e10d2b834ddaf5729bccda013 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/mobile-app-modal.test.tsx @@ -0,0 +1,184 @@ +import React from 'react'; +import { renderToString } from 'react-dom/server'; +import { render, screen, fireEvent, waitFor } from '@testing-library/react'; +import { + describe, + it, + expect, + beforeAll, + beforeEach, + afterEach, + vi, + type Mock +} from 'vitest'; +import store from 'store'; + +vi.mock('react-redux', () => ({ + useSelector: vi.fn().mockReturnValue(false) +})); + +import { useSelector } from 'react-redux'; +import MobileAppModal from './mobile-app-modal'; + +const mockUseSelector = useSelector as Mock; + +const MOBILE_SUPERBLOCK = 'responsive-web-design-v9'; +const NON_MOBILE_SUPERBLOCK = 'coding-interview-prep'; +const STORE_KEY = 'mobileAppModalDismissedAt'; +const THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1000; + +const ANDROID_UA = + 'Mozilla/5.0 (Linux; Android 13; Pixel 7) AppleWebKit/537.36'; +const IOS_UA = + 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15'; +const DESKTOP_UA = + 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36'; + +describe('MobileAppModal', () => { + beforeAll(() => { + // The Modal component uses `ResizeObserver` under the hood. + // However, this property is not available in JSDOM, so we need to manually add it to the window object. + // Ref: https://github.com/jsdom/jsdom/issues/3368 + type ResizeObserverMockInstance = { + observe: ResizeObserver['observe']; + unobserve: ResizeObserver['unobserve']; + disconnect: ResizeObserver['disconnect']; + }; + Object.defineProperty(window, 'ResizeObserver', { + writable: true, + value: vi.fn(function ( + this: ResizeObserverMockInstance, + _cb: ResizeObserverCallback + ) { + this.observe = vi.fn(); + this.unobserve = vi.fn(); + this.disconnect = vi.fn(); + }) + }); + }); + + beforeEach(() => { + mockUseSelector.mockReturnValue(false); // default: project preview closed + store.remove(STORE_KEY); + Object.defineProperty(navigator, 'userAgent', { + value: ANDROID_UA, + configurable: true + }); + }); + + afterEach(() => { + vi.clearAllMocks(); + store.remove(STORE_KEY); + }); + + it('renders the modal on mobile for a public superblock', () => { + render(); + expect(screen.getByRole('dialog')).toBeInTheDocument(); + }); + + it('does not render before mount', () => { + // useEffect does not run during server-side rendering, so the 'mounted' + // flag stays false and the component should produce no output. + expect( + renderToString() + ).toBe(''); + }); + + it('does not render on a desktop OS', () => { + Object.defineProperty(navigator, 'userAgent', { + value: DESKTOP_UA, + configurable: true + }); + render(); + expect(screen.queryByRole('dialog')).not.toBeInTheDocument(); + }); + + it('does not render for a non-public superblock', () => { + render(); + expect(screen.queryByRole('dialog')).not.toBeInTheDocument(); + }); + + it('does not render when the project preview is open', () => { + mockUseSelector.mockReturnValue(true); + render(); + expect(screen.queryByRole('dialog')).not.toBeInTheDocument(); + }); + + it('does not render when dismissed within 30 days', () => { + store.set(STORE_KEY, Date.now() - THIRTY_DAYS_MS + 1000); + render(); + expect(screen.queryByRole('dialog')).not.toBeInTheDocument(); + }); + + it('renders again after 30 days have passed', () => { + store.set(STORE_KEY, Date.now() - THIRTY_DAYS_MS - 1000); + render(); + expect(screen.getByRole('dialog')).toBeInTheDocument(); + }); + + it('displays the correct modal content', () => { + render(); + const dialog = screen.getByRole('dialog'); + expect(dialog).toHaveTextContent('mobile-app-modal.heading'); + expect(dialog).toHaveTextContent('mobile-app-modal.body'); + }); + + it('closes the modal without persisting when X is clicked', async () => { + render(); + fireEvent.click(screen.getByText('Close')); + + await waitFor(() => { + expect(screen.queryByRole('dialog')).not.toBeInTheDocument(); + }); + + expect(store.get(STORE_KEY)).toBeUndefined(); + }); + + it('closes the modal without persisting when the store link is clicked', async () => { + render(); + fireEvent.click(screen.getByRole('link')); + + await waitFor(() => { + expect(screen.queryByRole('dialog')).not.toBeInTheDocument(); + }); + + expect(store.get(STORE_KEY)).toBeUndefined(); + }); + + it('closes the modal and stores a timestamp when "do not show" is clicked', async () => { + render(); + fireEvent.click(screen.getByText('mobile-app-modal.do-not-show')); + + await waitFor(() => { + expect(screen.queryByRole('dialog')).not.toBeInTheDocument(); + }); + + const stored = store.get(STORE_KEY) as number; + expect(stored).toBeGreaterThan(0); + expect(Date.now() - stored).toBeLessThan(1000); + }); + + it('shows the correct app store link for iOS', () => { + Object.defineProperty(navigator, 'userAgent', { + value: IOS_UA, + configurable: true + }); + render(); + expect(screen.getByRole('link')).toHaveAttribute( + 'href', + 'https://apps.apple.com/us/app/freecodecamp/id6446908151?itsct=apps_box_link&itscg=30200' + ); + expect(screen.getByRole('link')).toHaveTextContent('mobile-app-modal.ios'); + }); + + it('shows the correct app store link for Android', () => { + render(); + expect(screen.getByRole('link')).toHaveAttribute( + 'href', + 'https://play.google.com/store/apps/details?id=org.freecodecamp' + ); + expect(screen.getByRole('link')).toHaveTextContent( + 'mobile-app-modal.android' + ); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/mobile-app-modal.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/mobile-app-modal.tsx new file mode 100644 index 0000000000000000000000000000000000000000..7e155dd98618bef3b4949a92bc695a383af0248a --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/mobile-app-modal.tsx @@ -0,0 +1,121 @@ +import React, { useEffect, useState } from 'react'; +import { useTranslation } from 'react-i18next'; +import { useSelector } from 'react-redux'; +import { Button, Modal, Spacer } from '@freecodecamp/ui'; +import { SuperBlocks } from '@freecodecamp/shared/config/curriculum'; +import store from 'store'; + +import { isProjectPreviewModalOpenSelector } from '../redux/selectors'; + +// Superblocks that are available in the freeCodeCamp mobile app. +// Only includes non-legacy public superblocks from orderedSuperBlockInfo +// (client/tools/external-curriculum/build-external-curricula-data-v2.ts). +const mobileAvailableSuperBlocks = new Set([ + SuperBlocks.RespWebDesignV9, + SuperBlocks.JsV9, + SuperBlocks.PythonV9, + SuperBlocks.A2English, + SuperBlocks.B1English, + SuperBlocks.A1Spanish, + SuperBlocks.TheOdinProject +]); + +const STORE_KEY = 'mobileAppModalDismissedAt'; +const THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1000; + +const IOS_URL = + 'https://apps.apple.com/us/app/freecodecamp/id6446908151?itsct=apps_box_link&itscg=30200'; +const ANDROID_URL = + 'https://play.google.com/store/apps/details?id=org.freecodecamp'; + +function detectOS(): 'ios' | 'android' | 'other' { + if (typeof navigator === 'undefined') return 'other'; + const ua = navigator.userAgent; + if (/iPad|iPhone|iPod/.test(ua)) return 'ios'; + if (/Android/.test(ua)) return 'android'; + return 'other'; +} + +function isDismissedFor30Days(): boolean { + const dismissedAt = store.get(STORE_KEY) as number | undefined; + if (!dismissedAt) return false; + return Date.now() - dismissedAt < THIRTY_DAYS_MS; +} + +interface MobileAppModalProps { + superBlock: string; +} + +function MobileAppModal({ + superBlock +}: MobileAppModalProps): JSX.Element | null { + const { t } = useTranslation(); + const isAvailable = mobileAvailableSuperBlocks.has(superBlock); + const isProjectPreviewOpen = useSelector( + isProjectPreviewModalOpenSelector + ); + + const os = detectOS(); + const [dismissed, setDismissed] = useState(isDismissedFor30Days); + + // Defer rendering until after the first browser paint. On a direct page + // load the component hydrates before the browser has computed layout, so + // document.documentElement.clientWidth is 0. The Modal's scroll-lock + // utility calculates the scrollbar compensation as + // window.innerWidth - clientWidth, which produces window.innerWidth when + // clientWidth is 0, and stamps that value as padding-right on , + // breaking the layout. Waiting for useEffect guarantees that layout has + // been computed before the modal (and its scroll-lock) opens. + const [mounted, setMounted] = useState(false); + + useEffect(() => { + setMounted(true); + }, []); + + useEffect(() => { + if (isProjectPreviewOpen) setDismissed(true); + }, [isProjectPreviewOpen]); + + const dismiss = () => setDismissed(true); + + const dismissPermanently = () => { + store.set(STORE_KEY, Date.now()); + setDismissed(true); + }; + + const storeUrl = os === 'ios' ? IOS_URL : ANDROID_URL; + const storeName = + os === 'ios' ? t('mobile-app-modal.ios') : t('mobile-app-modal.android'); + + if ( + !mounted || + os === 'other' || + !isAvailable || + isProjectPreviewOpen || + dismissed + ) + return null; + + return ( + + + + {t('mobile-app-modal.heading')} + + + +

{t('mobile-app-modal.body')}

+ + + + +
+
+ ); +} + +export default MobileAppModal; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/multiple-choice-questions.test.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/multiple-choice-questions.test.tsx new file mode 100644 index 0000000000000000000000000000000000000000..8c9a81e34649656d070016325b7a3e224a0ca167 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/multiple-choice-questions.test.tsx @@ -0,0 +1,125 @@ +import React from 'react'; +import { Provider } from 'react-redux'; +import { SuperBlocks } from '@freecodecamp/shared/config/curriculum'; +import { render, screen } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; + +import { createStore } from '../../../redux/create-store'; +import type { Question } from '../../../redux/prop-types'; +import MultipleChoiceQuestions from './multiple-choice-questions'; + +vi.mock('../../../utils/get-words'); + +const originalResizeObserver = globalThis.ResizeObserver; + +class ResizeObserverMock { + observe = vi.fn(); + unobserve = vi.fn(); + disconnect = vi.fn(); +} + +beforeAll(() => { + globalThis.ResizeObserver = ResizeObserverMock; +}); + +afterAll(() => { + globalThis.ResizeObserver = originalResizeObserver; +}); + +const questionsWithAudio = [ + { + text: '

Repeat the sentence.

', + solution: 1, + answers: [ + { + answer: '

First spoken answer.

', + feedback: null, + audioId: 'first-answer' + }, + { + answer: '

Second spoken answer.

', + feedback: null, + audioId: 'second-answer' + } + ] + } +]; + +const questionsWithoutAudio = Array.from({ length: 3 }, (_, questionIndex) => ({ + text: `

Question ${questionIndex + 1}

`, + solution: 1, + answers: Array.from({ length: 4 }, (_, answerIndex) => ({ + answer: `

Question ${questionIndex + 1} answer ${answerIndex + 1}

`, + feedback: null, + audioId: null + })) +})); + +function renderQuestions({ + questions = questionsWithAudio, + selectedOptions, + submittedMcqAnswers, + showFeedback = false +}: { + questions?: Question[]; + selectedOptions?: (number | null)[]; + submittedMcqAnswers?: (number | null)[]; + showFeedback?: boolean; +} = {}) { + const store = createStore(); + const handleOptionChange = vi.fn(); + + render( + + null)} + handleOptionChange={handleOptionChange} + submittedMcqAnswers={submittedMcqAnswers ?? questions.map(() => null)} + showFeedback={showFeedback} + superBlock={SuperBlocks.B1English} + /> + + ); + + return { handleOptionChange, store }; +} + +describe('MultipleChoiceQuestions', () => { + it('renders speaking controls for answers with audio', async () => { + const user = userEvent.setup(); + const { store } = renderQuestions(); + + expect(screen.getAllByRole('radio')).toHaveLength(2); + + const speakingButtons = screen.getAllByRole('button', { + name: 'speaking-modal.speaking-button' + }); + expect(speakingButtons).toHaveLength(2); + + expect(speakingButtons[0]).toHaveAttribute( + 'aria-describedby', + 'mc-question-0-answer-0-label' + ); + expect(speakingButtons[1]).toHaveAttribute( + 'aria-describedby', + 'mc-question-0-answer-1-label' + ); + + await user.click(speakingButtons[0]); + + expect(store.getState().challenge.modal.speaking).toBe(true); + }); + + it('does not render speaking controls for answers without audio', () => { + renderQuestions({ questions: questionsWithoutAudio }); + + expect(screen.getAllByRole('radio')).toHaveLength(12); + expect( + screen.queryByRole('button', { + name: 'speaking-modal.speaking-button' + }) + ).not.toBeInTheDocument(); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/multiple-choice-questions.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/multiple-choice-questions.tsx new file mode 100644 index 0000000000000000000000000000000000000000..a09ee579b0d7dbff571450e97852e1584adad2d4 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/multiple-choice-questions.tsx @@ -0,0 +1,221 @@ +import React, { useEffect, useState } from 'react'; +import { connect } from 'react-redux'; +import { useTranslation } from 'react-i18next'; +import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; +import { faMicrophone } from '@fortawesome/free-solid-svg-icons'; + +import { Button, Spacer } from '@freecodecamp/ui'; +import { Question } from '../../../redux/prop-types'; +import { openModal } from '../redux/actions'; +import { SuperBlocks } from '@freecodecamp/shared/config/curriculum'; +import { initializeMathJax, isMathJaxAllowed } from '../../../utils/math-jax'; +import { getChallengeContentLangProps } from '../../../utils/challenge-content-lang'; +import SpeakingModal from './speaking-modal'; +import ChallengeHeading from './challenge-heading'; +import PrismFormatted from './prism-formatted'; +import { stripHtmlTags } from './speaking-modal-helpers'; +import { sounds } from './scene/scene-assets'; + +type MultipleChoiceQuestionsProps = { + questions: Question[]; + selectedOptions: (number | null)[]; + handleOptionChange: (questionIndex: number, answerIndex: number) => void; + submittedMcqAnswers: (number | null)[]; + showFeedback: boolean; + openSpeakingModal: () => void; + superBlock: SuperBlocks; +}; + +function removeParagraphTags(text: string): string { + return text.replace(/^

|<\/p>$/g, ''); +} + +function MultipleChoiceQuestions({ + questions, + selectedOptions, + handleOptionChange, + submittedMcqAnswers, + showFeedback, + openSpeakingModal, + superBlock +}: MultipleChoiceQuestionsProps): JSX.Element { + const { t } = useTranslation(); + const contentLangProps = getChallengeContentLangProps(superBlock); + + useEffect(() => { + if (isMathJaxAllowed(superBlock)) { + initializeMathJax(); + } + }, [superBlock]); + + const [modalText, setModalText] = useState(''); + const [modalAnswerIndex, setModalAnswerIndex] = useState(0); + const [modalQuestionIndex, setModalQuestionIndex] = useState(0); + + const handleSpeakingButtonClick = ( + answer: string, + answerIndex: number, + questionIndex: number + ) => { + setModalText(stripHtmlTags(answer)); + setModalAnswerIndex(answerIndex); + setModalQuestionIndex(questionIndex); + openSpeakingModal(); + }; + + const constructAudioUrl = (audioId?: string): string | undefined => + audioId ? `${sounds}/${audioId}` : undefined; + + const getAudioUrl = ( + questionIndex: number, + answerIndex: number + ): string | undefined => { + const answer = questions[questionIndex]?.answers[answerIndex]; + const audioId = answer?.audioId ?? undefined; + return constructAudioUrl(audioId); + }; + + return ( +

+ 1 ? t('learn.questions') : t('learn.question') + } + /> + {questions.map((question, questionIndex) => ( +
+ + + +
+ {question.answers.map(({ answer }, answerIndex) => { + const isSubmittedAnswer = + submittedMcqAnswers[questionIndex] === answerIndex; + const feedback = + questions[questionIndex].answers[answerIndex].feedback; + const isCorrect = + submittedMcqAnswers[questionIndex] === + // -1 because the solution is 1-indexed + questions[questionIndex].solution - 1; + + const labelId = `mc-question-${questionIndex}-answer-${answerIndex}-label`; + const hasAudio = + questions[questionIndex]?.answers[answerIndex]?.audioId; + + return ( +
+
+
+ +
+ {showFeedback && isSubmittedAnswer && ( +
+

+ {isCorrect + ? t('learn.quiz.correct-answer') + : t('learn.quiz.incorrect-answer')} +

+ {feedback && ( +

+ +

+ )} +
+ )} +
+ + {hasAudio && ( +
+ +
+ )} +
+ ); + })} +
+ +
+ ))} + + + +
+ ); +} + +const mapDispatchToProps = { + openSpeakingModal: () => openModal('speaking') +}; + +MultipleChoiceQuestions.displayName = 'MultipleChoiceQuestions'; + +export default connect(null, mapDispatchToProps)(MultipleChoiceQuestions); diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/notes.test.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/notes.test.tsx new file mode 100644 index 0000000000000000000000000000000000000000..0d019dd38237d839739978b7888043dd6a55cb94 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/notes.test.tsx @@ -0,0 +1,19 @@ +import React from 'react'; +import { render, screen } from '@testing-library/react'; +import { describe, expect, it } from 'vitest'; + +import Notes from './notes'; + +describe('', () => { + it('renders note content', () => { + render(); + + expect(screen.getByText('This is a test note')).toBeVisible(); + }); + + it('renders nothing when there are no notes', () => { + const { container } = render(); + + expect(container).toBeEmptyDOMElement(); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/notes.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/notes.tsx new file mode 100644 index 0000000000000000000000000000000000000000..ecb279d15c1ca2445ef1e477e5d765ee7faf43e2 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/notes.tsx @@ -0,0 +1,14 @@ +import React from 'react'; +import PrismFormatted from './prism-formatted'; + +interface NotesProps { + notes?: string; +} + +function Notes({ notes }: NotesProps): JSX.Element | null { + return notes ? : null; +} + +Notes.displayName = 'Notes'; + +export default Notes; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/output.css b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/output.css new file mode 100644 index 0000000000000000000000000000000000000000..b692af97eae79e726ed5b7a084f287fd348c19e1 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/output.css @@ -0,0 +1,25 @@ +.output-text { + white-space: pre-wrap; + word-break: normal; + padding-top: 0; + height: 100%; + width: 100%; + overflow-y: auto; +} + +pre.output-text code { + background-color: var(--quaternary-background); + color: var(--tertiary-color); + font-size: 90%; + padding: 2px 4px; +} + +.output-text:focus-visible { + outline-offset: -2px; +} + +@supports not selector(:focus-visible) { + .output-text:focus { + outline-offset: -2px; + } +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/output.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/output.tsx new file mode 100644 index 0000000000000000000000000000000000000000..56f91edcc992685dd04fa273387a232e7b1cf63e --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/output.tsx @@ -0,0 +1,30 @@ +import { isEmpty } from 'lodash-es'; +import React from 'react'; +import sanitizeHtml from 'sanitize-html'; +import i18next from 'i18next'; + +import './output.css'; + +interface OutputProps { + defaultOutput: string; + output: string; +} + +function Output({ defaultOutput, output }: OutputProps): JSX.Element { + const message = sanitizeHtml(!isEmpty(output) ? output : defaultOutput, { + allowedTags: ['b', 'i', 'em', 'strong', 'code', 'wbr'] + }); + return ( +
+  );
+}
+
+export default Output;
diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/pinyin-to-hanzi-input.test.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/pinyin-to-hanzi-input.test.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..2cfada9ab659e7e5467e3c1fa60d3b49f4bc2147
--- /dev/null
+++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/pinyin-to-hanzi-input.test.tsx
@@ -0,0 +1,361 @@
+import React from 'react';
+import { describe, test, expect, vi } from 'vitest';
+import userEvent from '@testing-library/user-event';
+
+import { render, screen } from '@testing-library/react';
+import PinyinToHanziInput, { convertToHanzi } from './pinyin-to-hanzi-input';
+
+describe('convertToHanzi', () => {
+  test('should convert when tone number appears after final letter', () => {
+    // Only the correct tone gets converted to hanzi
+    expect(convertToHanzi('shen2', { hanzi: '什', pinyin: 'shén' })).toBe('什');
+
+    // Incorrect tones stay as pinyin
+    expect(convertToHanzi('shen1', { hanzi: '什', pinyin: 'shén' })).toBe(
+      'shēn'
+    );
+    expect(convertToHanzi('shen3', { hanzi: '什', pinyin: 'shén' })).toBe(
+      'shěn'
+    );
+    expect(convertToHanzi('shen4', { hanzi: '什', pinyin: 'shén' })).toBe(
+      'shèn'
+    );
+    expect(convertToHanzi('shen5', { hanzi: '什', pinyin: 'shén' })).toBe(
+      'shen'
+    );
+  });
+
+  test('should convert when tone number appears before final letter', () => {
+    // Only the correct tone gets converted to hanzi
+    expect(convertToHanzi('she2n', { hanzi: '什', pinyin: 'shén' })).toBe('什');
+
+    // Incorrect tones stay as pinyin
+    expect(convertToHanzi('she1n', { hanzi: '什', pinyin: 'shén' })).toBe(
+      'shēn'
+    );
+    expect(convertToHanzi('she3n', { hanzi: '什', pinyin: 'shén' })).toBe(
+      'shěn'
+    );
+    expect(convertToHanzi('she4n', { hanzi: '什', pinyin: 'shén' })).toBe(
+      'shèn'
+    );
+    expect(convertToHanzi('she5n', { hanzi: '什', pinyin: 'shén' })).toBe(
+      'shen'
+    );
+  });
+
+  test('should convert both correct syllables to hanzi', () => {
+    expect(convertToHanzi('ni3hao3', { hanzi: '你好', pinyin: 'nǐ hǎo' })).toBe(
+      '你好'
+    );
+  });
+
+  test('should handle multiple syllables with space', () => {
+    expect(
+      convertToHanzi('ni3    hao3', { hanzi: '你好', pinyin: 'nǐ hǎo' })
+    ).toBe('你    好');
+  });
+
+  test('should allow extra syllables and render them as pinyin', () => {
+    expect(
+      convertToHanzi('ni3hao3ma3', { hanzi: '你好', pinyin: 'nǐ hǎo' })
+    ).toBe('你好mǎ');
+  });
+
+  test('should show toned pinyin for wrong syllable and convert correct one', () => {
+    expect(convertToHanzi('ni4hao3', { hanzi: '你好', pinyin: 'nǐ hǎo' })).toBe(
+      'nì好'
+    );
+
+    expect(convertToHanzi('ni3hao4', { hanzi: '你好', pinyin: 'nǐ hǎo' })).toBe(
+      '你hào'
+    );
+  });
+
+  test('should only convert when input has tone 5', () => {
+    expect(
+      convertToHanzi('shen2me', { hanzi: '什么', pinyin: 'shén me' })
+    ).toBe('什me');
+
+    expect(
+      convertToHanzi('shen2me5', { hanzi: '什么', pinyin: 'shén me' })
+    ).toBe('什么');
+  });
+
+  test('should convert long phrase properly', () => {
+    const longPhrase = {
+      hanzi: '请问你叫什么名字',
+      pinyin: 'qǐng wèn nǐ jiào shén me míng zi'
+    };
+    expect(
+      convertToHanzi('qing3 wen4 ni3 jiao4 shen2 me5 ming2 zi5', longPhrase)
+    ).toBe('请 问 你 叫 什 么 名 字');
+  });
+
+  test('should handle uppercase input case-insensitively', () => {
+    expect(convertToHanzi('NI3HAO3', { hanzi: '你好', pinyin: 'nǐ hǎo' })).toBe(
+      '你好'
+    );
+    expect(convertToHanzi('Ni3hAO3', { hanzi: '你好', pinyin: 'nǐ hǎo' })).toBe(
+      '你好'
+    );
+  });
+
+  test('should convert "v" to "ü" and support tone marks', () => {
+    // Correct tone gets converted to hanzi
+    expect(convertToHanzi('nv3', { hanzi: '女', pinyin: 'nǚ' })).toBe('女');
+
+    // Incorrect tones stay as pinyin
+    expect(convertToHanzi('nv1', { hanzi: '女', pinyin: 'nǚ' })).toBe('nǖ');
+    expect(convertToHanzi('nv2', { hanzi: '女', pinyin: 'nǚ' })).toBe('nǘ');
+    expect(convertToHanzi('nv4', { hanzi: '女', pinyin: 'nǚ' })).toBe('nǜ');
+    expect(convertToHanzi('nv5', { hanzi: '女', pinyin: 'nǚ' })).toBe('nü');
+  });
+});
+
+describe('PinyinToHanziInput component', () => {
+  test.each([
+    [null, false],
+    [true, false],
+    [false, true]
+  ])(
+    'should have aria-invalid="%s" when isCorrect is %s',
+    (isCorrect, expectedAriaInvalid) => {
+      const expectedAnswer = { hanzi: '你好', pinyin: 'nǐ hǎo' };
+      const mockOnChange = vi.fn();
+
+      render(
+        
+      );
+
+      const input = screen.getByLabelText('blank');
+      expect(input.getAttribute('aria-invalid')).toBe(
+        expectedAriaInvalid ? 'true' : null
+      );
+    }
+  );
+
+  test('should convert when tone number appears before final letter (she2n me5)', async () => {
+    const expectedAnswer = { hanzi: '什么', pinyin: 'shén me' };
+    const mockOnChange = vi.fn();
+
+    render(
+      
+    );
+
+    const input = screen.getByLabelText('blank');
+
+    await userEvent.type(input, 'she2nme');
+    expect(input.value).toBe('什me');
+
+    // Type the final tone digit to complete the pinyin
+    await userEvent.type(input, '5');
+    expect(input.value).toBe('什么');
+  });
+
+  test('should convert when tone number appears after final letter (shen2 me)', async () => {
+    const expectedAnswer = { hanzi: '什么', pinyin: 'shén me' };
+    const mockOnChange = vi.fn();
+
+    render(
+      
+    );
+
+    const input = screen.getByLabelText('blank');
+
+    await userEvent.type(input, 'shen2me');
+    expect(input.value).toBe('什me');
+
+    // Type the final tone digit to complete the pinyin
+    await userEvent.type(input, '5');
+    expect(input.value).toBe('什么');
+  });
+
+  test('should revert hanzi back to toned pinyin and remove tone when backspacing', async () => {
+    const expectedAnswer = { hanzi: '什么', pinyin: 'shén me' };
+    const mockOnChange = vi.fn();
+    const expectedMap: Record = {
+      she2nme: '什me',
+      she2nm: '什m',
+      she2n: '什',
+      she2: 'shé',
+      she: 'she'
+    };
+
+    render(
+      
+    );
+
+    const input = screen.getByLabelText('blank');
+
+    await userEvent.type(input, 'she2nme5');
+    expect(input.value).toBe('什么');
+
+    const rawSteps = ['she2nme', 'she2nm', 'she2n', 'she2', 'she'];
+    for (const step of rawSteps) {
+      await userEvent.type(input, '{Backspace}');
+      expect(input.value).toBe(expectedMap[step]);
+    }
+  });
+
+  test('should clear the input when selecting all and pressing backspace', async () => {
+    const expectedAnswer = { hanzi: '你好', pinyin: 'nǐ hǎo' };
+    const mockOnChange = vi.fn();
+
+    render(
+      
+    );
+
+    const input = screen.getByLabelText('blank');
+
+    await userEvent.type(input, 'ni3hao3');
+    expect(input.value).toBe('你好');
+
+    await userEvent.clear(input);
+    expect(input.value).toBe('');
+  });
+
+  test('should revert a single hanzi character to partial pinyin when backspacing', async () => {
+    const expectedAnswer = { hanzi: '你', pinyin: 'nǐ' };
+    const mockOnChange = vi.fn();
+
+    render(
+      
+    );
+
+    const input = screen.getByLabelText('blank');
+
+    await userEvent.type(input, 'ni3');
+    expect(input.value).toBe('你');
+
+    // Backspace to revert the character to partial pinyin
+    await userEvent.type(input, '{Backspace}');
+    expect(input.value).toBe('ni');
+  });
+
+  test('should allow changing the tone digit for a syllable (shen3 -> shěn -> shèn)', async () => {
+    const expectedAnswer = { hanzi: '什么', pinyin: 'shén me' };
+    const mockOnChange = vi.fn();
+
+    render(
+      
+    );
+
+    const input = screen.getByLabelText('blank');
+
+    await userEvent.type(input, 'shen3');
+    expect(input.value).toBe('shěn');
+
+    // Replace tone 3 with 4
+    await userEvent.type(input, '4');
+    expect(input.value).toBe('shèn');
+  });
+
+  test('should allow extra syllables beyond expected answer', async () => {
+    const expectedAnswer = { hanzi: '你好', pinyin: 'nǐ hǎo' };
+    const mockOnChange = vi.fn();
+
+    render(
+      
+    );
+
+    const input = screen.getByLabelText('blank');
+
+    await userEvent.type(input, 'ni3hao3ma3');
+    expect(input.value).toBe('你好mǎ');
+  });
+
+  test('should allow inserting mid-string and preserve converted hanzi', async () => {
+    const expectedAnswer = { hanzi: '你好', pinyin: 'nǐ hǎo' };
+    const mockOnChange = vi.fn();
+
+    render(
+      
+    );
+
+    const input = screen.getByLabelText('blank');
+
+    await userEvent.type(input, 'ni3hao3');
+    expect(input.value).toBe('你好');
+
+    // Simulate mid-string edit: insert 'x' between the characters
+    await userEvent.type(input, 'x', {
+      initialSelectionStart: 1,
+      initialSelectionEnd: 1
+    });
+
+    expect(input.value).toBe('你x好');
+  });
+});
diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/pinyin-to-hanzi-input.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/pinyin-to-hanzi-input.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..c220bc4d60cf22f1f0991f4320e18831d69b45ed
--- /dev/null
+++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/pinyin-to-hanzi-input.tsx
@@ -0,0 +1,236 @@
+import React, { useState } from 'react';
+import { convertUnspacedPinyin } from 'pinyin-tone/v2';
+
+// Removing tone marks from pinyin for base letter comparison.
+// Uses Unicode NFD to decompose accented characters, then removes combining marks
+const normalize = (s: string) =>
+  s.normalize('NFD').replace(/\p{M}/gu, '').toLowerCase();
+
+/**
+ * Converts raw pinyin input (with tone numbers) to hanzi characters when matching expected answer.
+ *
+ * Key behaviors:
+ * 1. When a complete syllable with tone matches expected pinyin -> convert to hanzi
+ * 2. When base letters match but tone differs -> show toned pinyin (incorrect)
+ * 3. When syllable is a prefix of expected -> wait for more letters (e.g., 'shé' is prefix of 'shén')
+ * 4. Spaces are preserved in the output
+ */
+export function convertToHanzi(
+  raw: string,
+  expectedAnswer: { hanzi: string; pinyin: string }
+): string {
+  if (!raw.trim()) return raw;
+
+  const correctPinyins = expectedAnswer.pinyin.toLowerCase().split(/\s+/);
+  const correctHanzi = [...expectedAnswer.hanzi];
+
+  // The final string shown to the user.
+  // Example: '你好' for correct input, 'nǐhǎo' for incorrect
+  let displayOutput = '';
+
+  // Accumulates characters for the current pinyin syllable.
+  // Example: 'ni' while typing 'nǐ'
+  let currentPinyin = '';
+
+  // Index of the next expected pinyin syllable.
+  // Example: 0 for first syllable, 1 for second
+  let currentCorrectPinyinIndex = 0;
+
+  // Pinyin syllable waiting for more input to complete.
+  // Example: 'shé' when expecting 'shén' and waiting for 'n'
+  let pendingPinyin = '';
+
+  // Process each character in the raw input
+  for (const character of raw) {
+    // Handle spaces: flush current syllable to output and reset state
+    if (character === ' ') {
+      displayOutput += currentPinyin + ' ';
+      currentPinyin = '';
+      pendingPinyin = '';
+      continue;
+    }
+
+    // Add character to current syllable
+    currentPinyin += character;
+
+    // When a tone digit is encountered, process the completed syllable
+    if (/[1-5]/.test(character)) {
+      // Normalize to lowercase for case-insensitive handling
+      currentPinyin = currentPinyin.toLowerCase();
+
+      const diacriticPinyin = convertUnspacedPinyin(currentPinyin); // Add tone mark
+
+      // If all expected syllables have been processed and the user has typed more
+      // syllables than the expected answer contains, append the additional pinyin
+      // syllables as-is without attempting to convert them to hanzi.
+      if (currentCorrectPinyinIndex >= correctPinyins.length) {
+        displayOutput += diacriticPinyin;
+        currentPinyin = '';
+        continue;
+      }
+
+      const correctSyllable = correctPinyins[currentCorrectPinyinIndex];
+
+      // Check if the input matches the expected syllable exactly.
+      // If so, convert to hanzi.
+      if (diacriticPinyin.toLowerCase() === correctSyllable.toLowerCase()) {
+        displayOutput += correctHanzi[currentCorrectPinyinIndex]; // Convert to hanzi
+        currentCorrectPinyinIndex++;
+        currentPinyin = '';
+        pendingPinyin = '';
+      }
+      // Check if base letters match but tone differs.
+      // If so, show incorrect toned pinyin.
+      else if (normalize(diacriticPinyin) === normalize(correctSyllable)) {
+        displayOutput += diacriticPinyin;
+        currentCorrectPinyinIndex++;
+        currentPinyin = '';
+        pendingPinyin = '';
+      }
+      // Check if input is a prefix of expected (e.g., 'shé' for 'shén').
+      // If so, show pinyin and wait for more input.
+      else if (
+        normalize(correctSyllable).startsWith(normalize(diacriticPinyin))
+      ) {
+        displayOutput += diacriticPinyin;
+        pendingPinyin = diacriticPinyin;
+        currentPinyin = '';
+      }
+      // No match: show pinyin and move to next expected syllable
+      else {
+        displayOutput += diacriticPinyin;
+        currentCorrectPinyinIndex++;
+        currentPinyin = '';
+        pendingPinyin = '';
+      }
+    }
+    // Handle non-tone characters when there's pending pinyin.
+    // Pending pinyin occurs when the user's input is a prefix of the expected syllable
+    // (e.g., 'shé' for 'shén'). In this case, combine the pending pinyin with the new
+    // non-tone characters and check if it now matches the expected syllable. If it does,
+    // replace the pending pinyin in the output with the correct hanzi character.
+    else if (
+      pendingPinyin &&
+      currentCorrectPinyinIndex < correctPinyins.length
+    ) {
+      const combinedPinyin = pendingPinyin + currentPinyin;
+      const correctPinyin = correctPinyins[currentCorrectPinyinIndex];
+
+      // Check if combined input now matches the expected syllable exactly.
+      if (combinedPinyin.toLowerCase() === correctPinyin.toLowerCase()) {
+        // Replace the pending pinyin at the end of displayOutput with the correct hanzi character
+        const endIndex = displayOutput.length - pendingPinyin.length;
+        displayOutput =
+          displayOutput.slice(0, endIndex) +
+          correctHanzi[currentCorrectPinyinIndex];
+        currentCorrectPinyinIndex++;
+        currentPinyin = '';
+        pendingPinyin = '';
+      }
+      // Check if combined input matches the base letters but tone differs
+      else if (normalize(combinedPinyin) === normalize(correctPinyin)) {
+        // Replace the pending pinyin at the end of displayOutput with the combined pinyin
+        const endIndex = displayOutput.length - pendingPinyin.length;
+        displayOutput = displayOutput.slice(0, endIndex) + combinedPinyin;
+        currentCorrectPinyinIndex++;
+        currentPinyin = '';
+        pendingPinyin = '';
+      }
+    }
+  }
+
+  // Append any unfinished syllable at the end
+  return displayOutput + currentPinyin;
+}
+
+interface PinyinToHanziInputProps {
+  index: number;
+  expectedAnswer: { hanzi: string; pinyin: string };
+  isCorrect: boolean | null;
+  onChange: (index: number, value: string) => void;
+  className?: string;
+  maxLength: number;
+  size: number;
+  ariaLabel: string;
+}
+
+function PinyinToHanziInput({
+  index,
+  expectedAnswer,
+  isCorrect,
+  onChange,
+  className,
+  maxLength,
+  size,
+  ariaLabel
+}: PinyinToHanziInputProps): JSX.Element {
+  const [rawInput, setRawInput] = useState('');
+  const [displayValue, setDisplayValue] = useState('');
+
+  const handleChange = (e: React.ChangeEvent) => {
+    const inputValue = e.target.value;
+    const prevLength = displayValue.length;
+    const inputLength = inputValue.length;
+
+    const isAppendingAtEnd =
+      inputLength > prevLength && inputValue.startsWith(displayValue);
+    const isDeletingFromEnd =
+      inputLength < prevLength && displayValue.startsWith(inputValue);
+
+    let newRawInput: string;
+
+    if (isAppendingAtEnd) {
+      const added = inputValue.substring(prevLength);
+
+      // Handle tone digit replacement
+      if (
+        added.length === 1 &&
+        /[1-5]/.test(added) &&
+        /[1-5]$/.test(rawInput)
+      ) {
+        newRawInput = rawInput.slice(0, -1) + added;
+      } else {
+        newRawInput = rawInput + added;
+      }
+    } else if (isDeletingFromEnd) {
+      if (inputLength === 0) {
+        // When clearing the entire input:
+        // - If the previous display was a single character,
+        //   assume the user wants to remove the last character from raw input
+        //   (e.g., undo the tone digit that converted it, like 'ni3' -> 'ni').
+        // - Otherwise, fully clear raw input to an empty string.
+        newRawInput = prevLength === 1 ? rawInput.slice(0, -1) : '';
+      } else {
+        // Remove characters from raw input
+        const charsToRemove = prevLength - inputLength;
+        newRawInput = rawInput.slice(0, -charsToRemove);
+      }
+    } else {
+      // Mid-string edit - update new raw input directly
+      newRawInput = inputValue;
+    }
+
+    setRawInput(newRawInput);
+    const newDisplayValue = convertToHanzi(newRawInput, expectedAnswer);
+    setDisplayValue(newDisplayValue);
+    onChange(index, newDisplayValue);
+  };
+
+  return (
+    
+  );
+}
+
+PinyinToHanziInput.displayName = 'PinyinToHanziInput';
+
+export default PinyinToHanziInput;
diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/pinyin-tone-input.test.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/pinyin-tone-input.test.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..989bbd7836b368fba382d496e6f18c6b3305be83
--- /dev/null
+++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/pinyin-tone-input.test.tsx
@@ -0,0 +1,284 @@
+import React from 'react';
+import { describe, test, expect, vi } from 'vitest';
+import { render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+
+import PinyinToneInput, { convertToPinyinWithTones } from './pinyin-tone-input';
+
+describe('convertToPinyinWithTones', () => {
+  test('should convert single syllable with tone number to pinyin with tone mark', () => {
+    expect(convertToPinyinWithTones('ni3')).toBe('nǐ');
+    expect(convertToPinyinWithTones('hao3')).toBe('hǎo');
+  });
+
+  test('should handle all five tones correctly', () => {
+    expect(convertToPinyinWithTones('ma1')).toBe('mā');
+    expect(convertToPinyinWithTones('ma2')).toBe('má');
+    expect(convertToPinyinWithTones('ma3')).toBe('mǎ');
+    expect(convertToPinyinWithTones('ma4')).toBe('mà');
+    expect(convertToPinyinWithTones('ma5')).toBe('ma');
+
+    expect(convertToPinyinWithTones('v1')).toBe('ǖ');
+    expect(convertToPinyinWithTones('v2')).toBe('ǘ');
+    expect(convertToPinyinWithTones('v3')).toBe('ǚ');
+    expect(convertToPinyinWithTones('v4')).toBe('ǜ');
+    expect(convertToPinyinWithTones('v5')).toBe('ü');
+  });
+
+  test('should convert tone number before final letter', () => {
+    expect(convertToPinyinWithTones('she2n')).toBe('shén');
+  });
+
+  test('should convert tone number after final letter', () => {
+    expect(convertToPinyinWithTones('shen2')).toBe('shén');
+    expect(convertToPinyinWithTones('dian3')).toBe('diǎn');
+  });
+
+  test('should chain multiple syllables without spaces', () => {
+    expect(convertToPinyinWithTones('qing3wen4ni3jiao4shen2me5ming2zi5')).toBe(
+      'qǐngwènnǐjiàoshénmemíngzi'
+    );
+  });
+
+  test('should preserve spaces between syllables', () => {
+    expect(
+      convertToPinyinWithTones('qing3 wen4 ni3 jiao4 shen2 me5 ming2 zi5')
+    ).toBe('qǐng wèn nǐ jiào shén me míng zi');
+    expect(convertToPinyinWithTones('ni3    hao3')).toBe('nǐ    hǎo');
+  });
+
+  test('should handle uppercase input case-insensitively', () => {
+    expect(convertToPinyinWithTones('NI3HAO3')).toBe('nǐhǎo');
+    expect(convertToPinyinWithTones('Ni3hAO3')).toBe('nǐhǎo');
+  });
+
+  test('should handle incomplete syllables without tone numbers', () => {
+    expect(convertToPinyinWithTones('ni')).toBe('ni');
+    expect(convertToPinyinWithTones('niha')).toBe('niha');
+  });
+
+  test('should handle mixed complete and incomplete syllables', () => {
+    expect(convertToPinyinWithTones('ni3ha')).toBe('nǐha');
+    expect(convertToPinyinWithTones('ni3hao')).toBe('nǐhao');
+  });
+});
+
+describe('PinyinToneInput component', () => {
+  test('should convert syllable when tone number is typed', async () => {
+    const mockOnChange = vi.fn();
+
+    render(
+      
+    );
+
+    const input = screen.getByLabelText('blank');
+
+    await userEvent.type(input, 'ni3');
+    expect(input.value).toBe('nǐ');
+  });
+
+  test('should chain multiple syllables without spaces', async () => {
+    const mockOnChange = vi.fn();
+
+    render(
+      
+    );
+
+    const input = screen.getByLabelText('blank');
+
+    await userEvent.type(input, 'ni3hao3');
+    expect(input.value).toBe('nǐhǎo');
+  });
+
+  test('should convert syllables with spaces', async () => {
+    const mockOnChange = vi.fn();
+
+    render(
+      
+    );
+
+    const input = screen.getByLabelText('blank');
+
+    await userEvent.type(input, 'ni3 hao3');
+    expect(input.value).toBe('nǐ hǎo');
+  });
+
+  test('should allow changing the tone digit for a syllable', async () => {
+    const mockOnChange = vi.fn();
+
+    render(
+      
+    );
+
+    const input = screen.getByLabelText('blank');
+
+    await userEvent.type(input, 'ni3');
+    expect(input.value).toBe('nǐ');
+
+    // Replace tone 3 with tone 4
+    await userEvent.type(input, '4');
+    expect(input.value).toBe('nì');
+  });
+
+  test('should clear the input when selecting all and pressing backspace', async () => {
+    const mockOnChange = vi.fn();
+
+    render(
+      
+    );
+
+    const input = screen.getByLabelText('blank');
+
+    await userEvent.type(input, 'ni3hao3');
+    expect(input.value).toBe('nǐhǎo');
+
+    await userEvent.clear(input);
+    expect(input.value).toBe('');
+  });
+
+  test('should handle tone number before final letter', async () => {
+    const mockOnChange = vi.fn();
+
+    render(
+      
+    );
+
+    const input = screen.getByLabelText('blank');
+
+    await userEvent.type(input, 'she2n');
+    expect(input.value).toBe('shén');
+  });
+
+  test('should remove tone mark when backspacing', async () => {
+    const mockOnChange = vi.fn();
+    const expectedMap: Record = {
+      ni3hao: 'nǐhao',
+      ni3ha: 'nǐha',
+      ni3h: 'nǐh',
+      ni3: 'nǐ',
+      ni: 'ni',
+      n: 'n'
+    };
+
+    render(
+      
+    );
+
+    const input = screen.getByLabelText('blank');
+
+    await userEvent.type(input, 'ni3hao3');
+    expect(input.value).toBe('nǐhǎo');
+
+    const rawSteps = ['ni3hao', 'ni3ha', 'ni3h', 'ni3', 'ni', 'n'];
+    for (const step of rawSteps) {
+      await userEvent.type(input, '{Backspace}');
+      expect(input.value).toBe(expectedMap[step]);
+    }
+  });
+
+  test('should remove final letter before tone mark when backspacing syllables with tone before final letter', async () => {
+    const mockOnChange = vi.fn();
+
+    render(
+      
+    );
+
+    const input = screen.getByLabelText('blank');
+
+    // Type 'she2n' - tone digit before final letter
+    await userEvent.type(input, 'she2n');
+    expect(input.value).toBe('shén');
+
+    // First backspace removes the final letter 'n'
+    await userEvent.type(input, '{Backspace}');
+    expect(input.value).toBe('shé');
+
+    // Second backspace removes the tone mark
+    await userEvent.type(input, '{Backspace}');
+    expect(input.value).toBe('she');
+  });
+
+  test('should allow inserting mid-string', async () => {
+    const mockOnChange = vi.fn();
+
+    render(
+      
+    );
+
+    const input = screen.getByLabelText('blank');
+
+    await userEvent.type(input, 'ni3hao3');
+    expect(input.value).toBe('nǐhǎo');
+
+    // Simulate mid-string edit: insert 'x' between the syllables
+    await userEvent.type(input, 'x', {
+      initialSelectionStart: 1,
+      initialSelectionEnd: 1
+    });
+
+    expect(input.value).toBe('nxǐhǎo');
+  });
+});
diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/pinyin-tone-input.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/pinyin-tone-input.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..1847445c72af87275ce3b044a6f31732504c1ba9
--- /dev/null
+++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/pinyin-tone-input.tsx
@@ -0,0 +1,133 @@
+import React, { useState } from 'react';
+import { convertUnspacedPinyin } from 'pinyin-tone/v2';
+
+/**
+ * Converts raw pinyin input (with tone numbers) to pinyin with tone marks.
+ *
+ * Key behaviors:
+ * 1. When a tone digit (1-5) is encountered -> convert syllable to toned pinyin
+ * 2. Spaces are preserved in the output
+ * 3. Incomplete syllables (without tone numbers) remain as-is
+ */
+export function convertToPinyinWithTones(raw: string): string {
+  if (!raw.trim()) return raw;
+
+  let displayOutput = '';
+  let currentSyllable = '';
+
+  // Process each character in the raw input
+  for (const character of raw) {
+    // Handle spaces: flush current syllable and preserve space
+    if (character === ' ') {
+      displayOutput += currentSyllable + ' ';
+      currentSyllable = '';
+      continue;
+    }
+
+    // Add character to current syllable
+    currentSyllable += character;
+
+    // When a tone digit is encountered, convert the syllable
+    if (/[1-5]/.test(character)) {
+      // Normalize to lowercase for conversion
+      const normalizedSyllable = currentSyllable.toLowerCase();
+      const convertedPinyin = convertUnspacedPinyin(normalizedSyllable);
+
+      displayOutput += convertedPinyin;
+      currentSyllable = '';
+    }
+  }
+
+  // Append any unfinished syllable at the end
+  return displayOutput + currentSyllable;
+}
+
+interface PinyinToneInputProps {
+  index: number;
+  isCorrect: boolean | null;
+  onChange: (index: number, value: string) => void;
+  className?: string;
+  maxLength: number;
+  size: number;
+  ariaLabel: string;
+}
+
+function PinyinToneInput({
+  index,
+  isCorrect,
+  onChange,
+  className,
+  maxLength,
+  size,
+  ariaLabel
+}: PinyinToneInputProps): JSX.Element {
+  const [rawInput, setRawInput] = useState('');
+  const [displayValue, setDisplayValue] = useState('');
+
+  const handleChange = (e: React.ChangeEvent) => {
+    const inputValue = e.target.value;
+    const prevLength = displayValue.length;
+    const inputLength = inputValue.length;
+
+    const isAppendingAtEnd =
+      inputLength > prevLength && inputValue.startsWith(displayValue);
+    const isDeletingFromEnd =
+      inputLength < prevLength && displayValue.startsWith(inputValue);
+
+    let newRawInput: string;
+
+    if (isAppendingAtEnd) {
+      const added = inputValue.substring(prevLength);
+
+      // Handle tone digit replacement
+      if (
+        added.length === 1 &&
+        /[1-5]/.test(added) &&
+        /[1-5]$/.test(rawInput)
+      ) {
+        newRawInput = rawInput.slice(0, -1) + added;
+      } else {
+        newRawInput = rawInput + added;
+      }
+    } else if (isDeletingFromEnd) {
+      if (inputLength === 0) {
+        // When clearing the entire input:
+        // - If the previous display was a single character,
+        //   assume the user wants to remove the last character from raw input
+        //   (e.g., undo the tone digit that converted it, like 'ni3' -> 'ni').
+        // - Otherwise, fully clear raw input to an empty string.
+        newRawInput = prevLength === 1 ? rawInput.slice(0, -1) : '';
+      } else {
+        // Remove characters from raw input
+        const charsToRemove = prevLength - inputLength;
+        newRawInput = rawInput.slice(0, -charsToRemove);
+      }
+    } else {
+      // Mid-string edit - update new raw input directly
+      newRawInput = inputValue;
+    }
+
+    setRawInput(newRawInput);
+    const newDisplayValue = convertToPinyinWithTones(newRawInput);
+    setDisplayValue(newDisplayValue);
+    onChange(index, newDisplayValue);
+  };
+
+  return (
+    
+  );
+}
+
+PinyinToneInput.displayName = 'PinyinToneInput';
+
+export default PinyinToneInput;
diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/preview-portal.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/preview-portal.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..32a7efa7b1846d89b24857c508da421a3d890336
--- /dev/null
+++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/preview-portal.tsx
@@ -0,0 +1,184 @@
+import { Component, ReactElement } from 'react';
+import ReactDOM from 'react-dom';
+import type { TFunction } from 'i18next';
+import { withTranslation } from 'react-i18next';
+import { connect } from 'react-redux';
+import { createSelector } from 'reselect';
+import {
+  storePortalWindow,
+  removePortalWindow,
+  setShowPreviewPortal,
+  setShowPreviewPane,
+  setIsAdvancing,
+  setChapterSlug
+} from '../redux/actions';
+import {
+  showPreviewPortalSelector,
+  portalWindowSelector,
+  isAdvancingToChallengeSelector,
+  chapterSlugSelector
+} from '../redux/selectors';
+import { MAX_MOBILE_WIDTH } from '../../../../config/misc';
+
+interface PreviewPortalProps {
+  children: ReactElement | null;
+  windowTitle: string;
+  t: TFunction;
+  storePortalWindow: (window: Window | null) => void;
+  removePortalWindow: () => void;
+  showPreviewPortal: boolean;
+  portalWindow: null | Window;
+  setShowPreviewPortal: (arg: boolean) => void;
+  setShowPreviewPane: (arg: boolean) => void;
+  setIsAdvancing: (arg: boolean) => void;
+  isAdvancing: boolean;
+  setChapterSlug: (arg: string) => void;
+  chapterSlug: string;
+  onResize: () => void;
+}
+
+const mapDispatchToProps = {
+  storePortalWindow,
+  removePortalWindow,
+  setShowPreviewPortal,
+  setShowPreviewPane,
+  setIsAdvancing,
+  setChapterSlug
+};
+
+const mapStateToProps = createSelector(
+  isAdvancingToChallengeSelector,
+  chapterSlugSelector,
+  showPreviewPortalSelector,
+  portalWindowSelector,
+  (
+    isAdvancing: boolean,
+    chapterSlug: string,
+    showPreviewPortal: boolean,
+    portalWindow: null | Window
+  ) => ({
+    isAdvancing,
+    chapterSlug,
+    showPreviewPortal,
+    portalWindow
+  })
+);
+
+const getChapterSlug = (w: Window): string => {
+  const urlSegments = w.location.href.split('/');
+  // minus two to account for starting at zero and skipping the "step" number segment
+  return urlSegments[urlSegments.length - 2];
+};
+
+class PreviewPortal extends Component {
+  static displayName = 'PreviewPortal';
+  mainWindow: Window;
+  externalWindow: Window | null = null;
+  isAdvancing: boolean;
+  chapterSlug: string;
+  containerEl;
+  titleEl;
+  styleEl;
+
+  constructor(props: PreviewPortalProps) {
+    super(props);
+    this.mainWindow = window;
+    this.externalWindow = this.props.portalWindow;
+    this.isAdvancing = this.props.isAdvancing;
+    this.chapterSlug = this.props.chapterSlug;
+    this.containerEl = document.createElement('div');
+    this.titleEl = document.createElement('title');
+    this.styleEl = document.createElement('style');
+  }
+
+  componentDidMount() {
+    const { t, windowTitle } = this.props;
+
+    if (!this.externalWindow) {
+      this.externalWindow = window.open(
+        '',
+        '',
+        'width=960,height=540,left=100,top=100'
+      );
+      this.props.setChapterSlug(getChapterSlug(this.mainWindow));
+    } else {
+      this.externalWindow.document.head.innerHTML = '';
+      this.externalWindow.document.body.innerHTML = '';
+    }
+
+    this.titleEl.innerText = `${t(
+      'learn.editor-tabs.preview'
+    )} | ${windowTitle}`;
+
+    this.styleEl.innerHTML = `
+      #fcc-main-frame {
+        width: 100%;
+        height: 100%;
+        border: none;
+      }
+    `;
+
+    this.externalWindow?.document.head.appendChild(this.titleEl);
+    this.externalWindow?.document.head.appendChild(this.styleEl);
+    this.externalWindow?.document.body.setAttribute(
+      'style',
+      `
+        margin: 0px;
+        padding: 0px;
+        overflow: hidden;
+      `
+    );
+    this.externalWindow?.document.body.appendChild(this.containerEl);
+    this.externalWindow?.addEventListener('beforeunload', () => {
+      this.props.setShowPreviewPortal(false);
+      if (this.mainWindow.innerWidth < MAX_MOBILE_WIDTH) {
+        this.props.setShowPreviewPane(true);
+      }
+      this.props.removePortalWindow();
+    });
+
+    this.externalWindow?.addEventListener('resize', () => {
+      this.props.onResize();
+    });
+
+    this.props.storePortalWindow(this.externalWindow);
+
+    // close the portal if the main window closes
+    this.mainWindow?.addEventListener('beforeunload', () => {
+      this.externalWindow?.close();
+    });
+  }
+
+  componentWillUnmount() {
+    const currentSlug = getChapterSlug(this.mainWindow);
+
+    // if not moving between pages in chapters and chapter slug changes
+    if (!this.props.isAdvancing && currentSlug !== this.props.chapterSlug) {
+      // means we navigated away from current chapter so close preview window
+      this.props.setChapterSlug('');
+      this.externalWindow?.close();
+      this.props.removePortalWindow();
+      // else if moving between pages in chapters
+    } else if (this.props.isAdvancing) {
+      // if moving from one chapter to the next
+      if (currentSlug !== this.props.chapterSlug) {
+        // update chapter slug
+        this.props.setChapterSlug(currentSlug);
+      }
+
+      // set moving chapter state to false now
+      this.props.setIsAdvancing(false);
+    }
+  }
+
+  render() {
+    return ReactDOM.createPortal(this.props.children, this.containerEl);
+  }
+}
+
+PreviewPortal.displayName = 'PreviewPortal';
+
+export default connect(
+  mapStateToProps,
+  mapDispatchToProps
+)(withTranslation()(PreviewPortal));
diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/preview.css b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/preview.css
new file mode 100644
index 0000000000000000000000000000000000000000..4601370abb2239ecbe0bbfe98422986ed10b4632
--- /dev/null
+++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/preview.css
@@ -0,0 +1,17 @@
+.challenge-preview,
+.challenge-preview-frame {
+  height: 100%;
+  width: 100%;
+  padding: 0;
+  margin: 0;
+  border: none;
+  background-color: white;
+}
+
+.enable-iframe {
+  pointer-events: auto;
+}
+
+.disable-iframe {
+  pointer-events: none;
+}
diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/preview.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/preview.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..d7d164ef59455e0df56032e4b9117d5a0b5dbfe5
--- /dev/null
+++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/templates/Challenges/components/preview.tsx
@@ -0,0 +1,53 @@
+import React, { useState, useEffect } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { mainPreviewId, scrollManager } from '../utils/frame';
+
+import './preview.css';
+
+export interface PreviewProps {
+  className?: string;
+  disableIframe?: boolean;
+  previewMounted: () => void;
+  previewId?: string;
+}
+
+function Preview({
+  disableIframe,
+  previewMounted,
+  previewId
+}: PreviewProps): JSX.Element {
+  const { t } = useTranslation();
+  const [iframeStatus, setIframeStatus] = useState(false);
+  const iframeToggle = iframeStatus ? 'disable' : 'enable';
+
+  useEffect(() => {
+    previewMounted();
+  }, [previewMounted]);
+
+  useEffect(() => {
+    setIframeStatus(disableIframe);
+  }, [disableIframe]);
+
+  useEffect(() => {
+    return () => {
+      scrollManager.setPreviewScrollPosition(0);
+    };
+  }, []);
+
+  const id = previewId ?? mainPreviewId;
+
+  return (
+    
+