-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuse-typing.ts
More file actions
181 lines (149 loc) · 5.47 KB
/
use-typing.ts
File metadata and controls
181 lines (149 loc) · 5.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
"use client";
import { useState, useEffect, useMemo, useCallback, useRef } from 'react';
type State = 'start' | 'run' | 'finish';
type CharState = 'correct' | 'incorrect' | 'untyped';
export const useTyping = (text: string, language: string) => {
const [state, setState] = useState<State>('start');
const [typed, setTyped] = useState<string>('');
const [errors, setErrors] = useState<number>(0);
const startTime = useRef<number>(0);
const [totalTime, setTotalTime] = useState<number>(0);
const characters = useMemo(
() =>
text.split('').map((char, index) => {
let state: CharState = 'untyped';
if (index < typed.length) {
state = typed[index] === char ? 'correct' : 'incorrect';
}
return { char, state };
}),
[text, typed]
);
const currentPosition = typed.length;
const isFinished = currentPosition === text.length;
const { wpm, cpm } = useMemo(() => {
if (state !== 'run' || !startTime.current) return { wpm: 0, cpm: 0 };
const currentTime = Date.now();
const elapsedTime = (currentTime - startTime.current) / 1000 / 60; // in minutes
if (elapsedTime === 0) return { wpm: 0, cpm: 0 };
const correctChars = typed.split('').filter((char, index) => char === text[index]).length;
const grossWPM = (correctChars / 5) / elapsedTime;
const grossCPM = correctChars / elapsedTime;
return {
wpm: grossWPM > 0 ? grossWPM : 0,
cpm: grossCPM > 0 ? grossCPM : 0
};
}, [typed, text, state]);
const accuracy = useMemo(() => {
if (typed.length === 0) return 100;
const correctChars = typed.split('').filter((char, index) => char === text[index]).length;
return (correctChars / typed.length) * 100;
}, [typed, text]);
const reset = useCallback(() => {
setState('start');
setTyped('');
setErrors(0);
startTime.current = 0;
setTotalTime(0);
}, []);
const saveProgress = useCallback((wpm: number, cpm: number, accuracy: number, time: number, language: string, chapterTitle: string) => {
const progress = JSON.parse(localStorage.getItem('typingProgress') || '[]');
progress.push({
date: new Date().toISOString(),
wpm,
cpm,
accuracy,
time,
language,
chapter: chapterTitle
});
localStorage.setItem('typingProgress', JSON.stringify(progress));
}, []);
const finalWPM = useMemo(() => {
if (!isFinished || !totalTime) return 0;
const durationInMinutes = totalTime / 60;
const correctChars = typed.split('').filter((char, index) => char === text[index]).length;
const finalWPMValue = (correctChars / 5) / durationInMinutes;
return finalWPMValue > 0 ? finalWPMValue : 0;
}, [isFinished, totalTime, typed, text]);
const finalCPM = useMemo(() => {
if (!isFinished || !totalTime) return 0;
const durationInMinutes = totalTime / 60;
const correctChars = typed.split('').filter((char, index) => char === text[index]).length;
const finalCPMValue = correctChars / durationInMinutes;
return finalCPMValue > 0 ? finalCPMValue : 0;
}, [isFinished, totalTime, typed, text]);
useEffect(() => {
if (isFinished) {
setState('finish');
if (startTime.current) {
const endTime = Date.now();
const duration = (endTime - startTime.current) / 1000;
setTotalTime(duration);
}
}
}, [isFinished]);
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if (state === 'finish') {
if (e.key === 'Enter') reset();
return;
}
const isSpecialKey = e.ctrlKey || e.metaKey || e.altKey;
if (e.key === 'Escape') {
e.preventDefault();
reset();
return;
}
if (state === 'start' && e.key.length === 1 && !isSpecialKey) {
setState('run');
startTime.current = Date.now();
}
if (state === 'run') {
e.preventDefault();
if (e.key === 'Tab') {
const spaces = language === 'javascript' ? ' ' : ' ';
let correct = true;
for (let i = 0; i < spaces.length; i++) {
if (currentPosition + i >= text.length || text[currentPosition + i] !== ' ') {
correct = false;
break;
}
}
if(!correct) setErrors(prev => prev + spaces.length);
setTyped(prev => prev + spaces);
return;
}
if (e.key === 'Enter') {
if (text[currentPosition] === '\n') {
setTyped(prev => prev + '\n');
} else {
setErrors(prev => prev + 1);
setTyped(prev => prev + '\n');
}
return;
}
if (e.key.length === 1 && !isSpecialKey) {
if (typed.length < text.length) {
if (text[currentPosition] !== e.key) {
setErrors(prev => prev + 1);
}
setTyped(prev => prev + e.key);
}
} else if (e.key === 'Backspace') {
if (typed.length > 0) {
setTyped(prev => prev.slice(0, -1));
}
}
}
};
window.addEventListener('keydown', handleKeyDown);
return () => {
window.removeEventListener('keydown', handleKeyDown);
};
}, [text, typed, state, reset, currentPosition, language]);
useEffect(() => {
reset();
}, [text, reset]);
return { state, characters, typed, errors, wpm: state === 'finish' ? finalWPM : wpm, cpm: state === 'finish' ? finalCPM : cpm, accuracy, totalTime, reset, saveProgress };
};