Skip to content
TheChatArchiveThe Chat Archive
o1-preview-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

import React, {forwardRef, useState} from 'react'; import {useUnit} from…

  1. 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 и открывать символы

  2. Assistant

    It would be best to handle the 'Enter' key in the GamePage component. Since the GamePage component has access to both the progressBarRef (to reset the ProgressBar) and the triggerReveal function (to reveal the symbols), it's the most suitable place to handle the 'Enter' key event.

    Here's how you can do it:

    1. Add a keydown event listener in GamePage component 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>
      );
    };
    
    1. Explanation:

      • useEffect Hook: Inside the useEffect hook, 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.
      • handleKeyDown Function: This function checks if the pressed key is 'Enter'. If it is, it resets and restarts the ProgressBar by using progressBarRef.current.reset() and progressBarRef.current.start(). It then calls triggerReveal() to reveal the symbols.
      • Checking canReveal: After triggering the reveal, we check if we can continue revealing symbols by accessing the $canReveal state. If we can't, we stop the ProgressBar.
      • Event Listener Cleanup: It's important to remove the event listener when the component unmounts to avoid potential bugs or memory leaks.
    2. Advantages of Handling in GamePage:

      • Access to Necessary Functions: GamePage has direct access to both progressBarRef and triggerReveal, 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 GamePage level, you avoid the need to pass down functions or refs through multiple components, keeping your component hierarchy clean and reducing coupling.
    3. Alternative Approaches:

      • Handling in WordInput or SymbolInput: While you could handle the 'Enter' key in the SymbolInput or WordInput components, you would need to pass down the progressBarRef and triggerReveal functions 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.
    4. Final Note:

      • By handling the 'Enter' key in the GamePage component, 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.