import React, {forwardRef, useState} from 'react'; import {useUnit} from…
- User
import React, {forwardRef, useState} from 'react'; import {useUnit} from "effector-react/compat";
import * as styles from './symbol-input.module.css'; import {TEXT_REGEX} from "@/shared/constants/index.js"; import {setSymbol} from "@/features/input-word/model/events.js";
const CSS_CLASS_OPENED = styles['symbol-opened']
export const SymbolInput = forwardRef(( {idx, focusNext, focusPrev, value, isRevealed = false}, ref ) => { const triggerSetSymbol = useUnit(setSymbol); const symbolClasses =
${styles.symbol} ${isRevealed ? CSS_CLASS_OPENED : ''};const handleInput = (key) => { const formattedKey = key.toLowerCase();
if(TEXT_REGEX.test(formattedKey) && formattedKey.length === 1) { triggerSetSymbol({value: formattedKey, idx}); focusNext(idx); }};
const handleKeyDown = (e) => { switch (e.key) { case 'ArrowLeft': focusPrev(idx); break; case 'ArrowRight': focusNext(idx); break; case 'Backspace': e.preventDefault(); triggerSetSymbol({value: '', idx}); focusPrev(idx); break; default: handleInput(e.key); break; } };
return ( <input ref={ref} type={'text'} className={symbolClasses} disabled={isRevealed} maxLength={1} value={value} onKeyDown={handleKeyDown} > ); })import {useUnit} from 'effector-react'; import {useRef} from 'react';
import {SymbolInput} from '@/features/input-word/ui/symbol-input/index.jsx'; import * as styles from './word-input.module.css'; import {$userGuess} from '@/features/input-word/model/store.js';
export const WordInput = ({}) => { const userGuess = useUnit($userGuess); const inputRefs = useRef([]);
const focusNextUnopenedSymbol = (currentIdx, step) => { for(let i = currentIdx + step; i >= 0 && i < userGuess.length; i += step) { if(!userGuess[i].isRevealed) { inputRefs.current[i].focus(); return; } }
inputRefs.current[currentIdx].focus();};
const handleEnter = () => {
}
const focusNextSymbol = (currentIdx) => { focusNextUnopenedSymbol(currentIdx, 1); }
const focusPrevSymbol = (currentIdx) => { focusNextUnopenedSymbol(currentIdx, -1); }
return ( { userGuess.map(({idx, value, isRevealed}) => <SymbolInput key={
${value}-${idx}} ref={el => inputRefs.current[idx] = el} idx={idx} value={value} isRevealed={isRevealed} focusNext={focusNextSymbol} focusPrev={focusPrevSymbol} /> )} ); }; import { useEffect, useRef } from 'react'; import { useUnit } from 'effector-react';import { WordInput } from '@/features/input-word/ui/word-input/index.jsx'; import { iterateReveal, startGame } from '@/pages/game-page/model/events.js'; import {$canReveal} from '../model/store.js'; import { ProgressBar } from '@/shared/ui/progress-bar'; import * as styles from './game-page.module.css';
export const GamePage = () => { const progressBarRef = useRef(null); const triggerStartGame = useUnit(startGame); const triggerReveal = useUnit(iterateReveal);
useEffect(() => { triggerStartGame(); progressBarRef.current.start(); }, []);
const onProgressEnd = () => { triggerReveal();
const canReveal = $canReveal.getState(); if(!canReveal) return; progressBarRef.current.start();}
return ( ); }; где лучше отлавливать enter чтобы сбрасывать progressBar и открывать символы
- Assistant
It would be best to handle the 'Enter' key in the
GamePagecomponent. Since theGamePagecomponent has access to both theprogressBarRef(to reset theProgressBar) and thetriggerRevealfunction (to reveal the symbols), it's the most suitable place to handle the 'Enter' key event.Here's how you can do it:
- Add a keydown event listener in
GamePagecomponent that listens for the 'Enter' key:
import { useEffect, useRef } from 'react'; import { useUnit } from 'effector-react'; import { WordInput } from '@/features/input-word/ui/word-input/index.jsx'; import { iterateReveal, startGame } from '@/pages/game-page/model/events.js'; import {$canReveal} from '../model/store.js'; import { ProgressBar } from '@/shared/ui/progress-bar'; import * as styles from './game-page.module.css'; export const GamePage = () => { const progressBarRef = useRef(null); const triggerStartGame = useUnit(startGame); const triggerReveal = useUnit(iterateReveal); useEffect(() => { triggerStartGame(); progressBarRef.current.start(); const handleKeyDown = (e) => { if (e.key === 'Enter') { // Reset the progress bar progressBarRef.current.reset(); progressBarRef.current.start(); // Reveal the symbols triggerReveal(); // Check if we can continue revealing const canReveal = $canReveal.getState(); if (!canReveal) { progressBarRef.current.stop(); } } }; window.addEventListener('keydown', handleKeyDown); // Cleanup the event listener on component unmount return () => { window.removeEventListener('keydown', handleKeyDown); }; }, []); const onProgressEnd = () => { triggerReveal(); const canReveal = $canReveal.getState(); if (!canReveal) return; progressBarRef.current.start(); } return ( <div className={styles.page}> <WordInput /> <ProgressBar ref={progressBarRef} fillingDuration={30000} onProgressEnd={onProgressEnd} /> </div> ); };-
Explanation:
useEffectHook: Inside theuseEffecthook, we're adding an event listener for the 'keydown' event when the component mounts, and removing it when the component unmounts to prevent memory leaks.handleKeyDownFunction: This function checks if the pressed key is 'Enter'. If it is, it resets and restarts theProgressBarby usingprogressBarRef.current.reset()andprogressBarRef.current.start(). It then callstriggerReveal()to reveal the symbols.- Checking
canReveal: After triggering the reveal, we check if we can continue revealing symbols by accessing the$canRevealstate. If we can't, we stop theProgressBar. - Event Listener Cleanup: It's important to remove the event listener when the component unmounts to avoid potential bugs or memory leaks.
-
Advantages of Handling in
GamePage:- Access to Necessary Functions:
GamePagehas direct access to bothprogressBarRefandtriggerReveal, making it straightforward to control both the progress bar and the reveal logic. - Global Keyboard Handling: Since 'Enter' is a key that might be pressed anywhere on the page, handling it at the top-level component ensures it catches the event regardless of which input or element is focused.
- Avoiding Prop Drilling: By handling the event at the
GamePagelevel, you avoid the need to pass down functions or refs through multiple components, keeping your component hierarchy clean and reducing coupling.
- Access to Necessary Functions:
-
Alternative Approaches:
- Handling in
WordInputorSymbolInput: While you could handle the 'Enter' key in theSymbolInputorWordInputcomponents, you would need to pass down theprogressBarRefandtriggerRevealfunctions through props, leading to prop drilling and tighter coupling between components. - Event Bubbling: Relying on event bubbling to catch the 'Enter' key event in a parent component can lead to less predictable behavior, especially if other components might also be handling key events.
- Handling in
-
Final Note:
- By handling the 'Enter' key in the
GamePagecomponent, you ensure that the logic for starting/restarting the game and handling the progress bar is centralized, making your code more maintainable and easier to understand.
- By handling the 'Enter' key in the
- Add a keydown event listener in