1.4.2 • Published 1 year ago

react-typing-game-hook v1.4.2

Weekly downloads
14
License
Apache-2.0
Repository
github
Last release
1 year ago

GitHub Workflow Status

npm npm bundle size

React Typing Game Hook

Easily create typing games functionalty (10fastestfinger, monkeytype, keybr, etc) with this react hook that handles the typing logic

About

This hook takes care of the states and the little details that goes on when users type in a typing game/test/challenge! Your part is to just capture the inputs from the user!

Demos

Basic Demo

Simple typing via input box Demo

Simple typing on text Demo

Getting Started

Importing

npm install react-typing-game-hook

or

yarn add react-typing-game-hook

Usage

Here's a simple example of it (live here)

import React from 'react';
// import it
import useTypingGame, { CharStateType } from 'react-typing-game-hook';

const TypingGameComponent = () => {
  // Call the hook
  const {
    states: { chars, charsState },
    actions: { insertTyping, resetTyping, deleteTyping },
  } = useTypingGame('Click on me and start typing away!');

  // Capture and display!
  return (
    <h1
      onKeyDown={e => {
        e.preventDefault();
        const key = e.key;
        if (key === 'Escape') {
          resetTyping();
          return;
        }
        if (key === 'Backspace') {
          deleteTyping(false);
          return;
        }
        if (key.length === 1) {
          insertTyping(key);
        }
      }}
      tabIndex={0}
    >
      {chars.split('').map((char, index) => {
        let state = charsState[index];
        let color =
          state === CharStateType.Incomplete
            ? 'black'
            : state === CharStateType.Correct
            ? 'green'
            : 'red';
        return (
          <span key={char + index} style={{ color }}>
            {char}
          </span>
        );
      })}
    </h1>
  );
};
export default TypingGameComponent;

Have a look at the demos above as well as the hooks details below to find out more!

Hook Details

Structure Breakdown

const {
  states: {
    startTime,
    endTime,
    chars,
    charsState,
    length,
    currIndex,
    currChar,
    correctChar,
    errorChar,
    phase,
  },
  actions: {
    resetTyping,
    endTyping,
    insertTyping,
    deleteTyping,
    setCurrIndex,
    getDuration,
  },
} = useTypingGame(text, {
  skipCurrentWordOnSpace: true,
  pauseOnError: false,
  countErrors: 'everytime',
});

Enumeration Breakdown

import { PhaseType, CharStateType } from 'react-typing-game-hook';

PhaseType {
  NotStarted = 0,
  Started = 1,
  Ended = 2,
}

CharStateType {
  Incomplete = 0,
  Correct = 1,
  Incorrect = 2,
}

Hook Parameters

NameFunctionaltyDefault value
skipCurrentWordOnSpaceWhen true, moves on to the next word when space is inputted. Otherwise, it moves on to the next character insteadtrue
pauseOnErrorWhen true, stays on the same character until it is correctly inputted. Otherwise, it moves on to the next character insteadfalse
countErrorsWhen value is 'everytime', count errors anytime a mistake is made. When value is 'once', count errors only once for each mistake made at the position where the letter is typed.'everytime'

Hook States

NameFunctionaltyData TypeInitial value
startTimeTime in milliseconds (since the Unix Epoch) when the typing started.numberPrior to when the typing starts, it is null
endTimeTime in milliseconds(since the Unix Epoch) when the typing test ended.numberPrior to when the typing ended, it is null
charsThe inputted text to be used for typing.string-
lengthThe lengh of the inputted textnumberLength of the inputted text chars
charsStateArray of each character's state of the inputted text. Each item represents the corresponding chararacter of the text inputted. CharStateType.Incomplete - has yet to be determined to be correct or incorrect CharStateType.Correct - is determined to be correct CharStateType.Incorrect - is determined to be incorrect.Use of CharStateType over numeric literal is recommendedCharStateType[]Array length of chars filled with CharStateType.Incomplete
currIndexCurrent character index of the text the user have typed till.number-1
currCharCurrent character the user have typed till.string''
correctCharNumber of correct character the user had typed.number0
errorCharNumber of incorrect character the user had typed.number0
phaseRepresent the current state of the typing test. PhaseType.NotStarted - typing haven't started PhaseType.Started - typing started PhaseType.Ended - typing ended Use of PhaseType over numeric literal is recommendedPhaseTypePhaseType.NotStarted

Hook Methods

NameFunctionaltySignatureReturn value
insertTypingInsert a character into the current typing sequence. It will start the typing if it hasn't been started as well as end the typing for you when the last character has been entered.insertTyping(char:string)-
deleteTypingIt only works when the typing has been started. Allows for the current word in the typing sequence to be deleted when passed with a parameter of true, otherwise it deletes only a character from the current typing (default behavior).deleteTyping(deleteWord?: boolean)-
resetTypingReset to its initial state.resetTyping()-
endTypingEnds the current typing sequence if it had started. States persist when ended and endTime is captured.endTyping()-
setCurrIndexSet the current index manually. Only works when phase is PhaseType.NotStarted (haven't started typing) or PhaseType.Started (during typing).setCurrIndex(index:number)true if successfull, otherwise false
getDurationDuration in milliseconds since the typing started.getDuration()0 if the typing has yet to start.