-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
dee4ef9
commit 7932f22
Showing
2 changed files
with
77 additions
and
51 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,63 @@ | ||
import { useState, useRef } from 'react' | ||
|
||
interface IUsePlayText { | ||
play: (text: string) => void | ||
stop: () => void | ||
isPlaying: boolean | ||
} | ||
|
||
const usePlayText = (): IUsePlayText => { | ||
const [isPlaying, setIsPlaying] = useState<boolean>(false) | ||
const intervalIdRef = useRef<NodeJS.Timeout | null>(null) | ||
|
||
const play = (text: string) => { | ||
if (text === '') { | ||
return | ||
} | ||
|
||
setIsPlaying(true) | ||
|
||
let index = 0 | ||
const textArray = text.split('') | ||
const id = setInterval(() => { | ||
const keyId = textArray[index].toLowerCase() | ||
const event = new CustomEvent('threekeyboardevent', { | ||
detail: { | ||
keyId, | ||
}, | ||
}) | ||
document.dispatchEvent(event) | ||
|
||
index++ | ||
|
||
if (index === textArray.length) { | ||
clearInterval(id) | ||
setIsPlaying(false) | ||
intervalIdRef.current = null | ||
} | ||
}, 200) | ||
|
||
intervalIdRef.current = id | ||
} | ||
|
||
const stop = () => { | ||
if (intervalIdRef.current) { | ||
clearInterval(intervalIdRef.current) | ||
|
||
intervalIdRef.current = null | ||
setIsPlaying(false) | ||
|
||
document.dispatchEvent( | ||
new CustomEvent('threekeyboardevent', { | ||
detail: { | ||
keyId: null, | ||
}, | ||
}), | ||
) | ||
} | ||
} | ||
|
||
return { play, stop, isPlaying } | ||
} | ||
|
||
export default usePlayText |