| 3 | import { Dynamic } from "solid-js/web" |
| 4 | |
| 5 | export const Typewriter = <T extends ValidComponent = "p">(props: { text?: string; class?: string; as?: T }) => { |
| 6 | const [store, setStore] = createStore({ |
| 7 | typing: false, |
| 8 | displayed: "", |
| 9 | cursor: true, |
| 10 | }) |
| 11 | |
| 12 | createEffect(() => { |
| 13 | const text = props.text |
| 14 | if (!text) return |
| 15 | |
| 16 | let i = 0 |
| 17 | const timeouts: ReturnType<typeof setTimeout>[] = [] |
| 18 | setStore("typing", true) |
| 19 | setStore("displayed", "") |
| 20 | setStore("cursor", true) |
| 21 | |
| 22 | const getTypingDelay = () => { |
| 23 | const random = Math.random() |
| 24 | if (random < 0.05) return 150 + Math.random() * 100 |
| 25 | if (random < 0.15) return 80 + Math.random() * 60 |
| 26 | return 30 + Math.random() * 50 |
| 27 | } |
| 28 | |
| 29 | const type = () => { |
| 30 | if (i < text.length) { |
| 31 | setStore("displayed", text.slice(0, i + 1)) |
| 32 | i++ |
| 33 | timeouts.push(setTimeout(type, getTypingDelay())) |
| 34 | } else { |
| 35 | setStore("typing", false) |
| 36 | timeouts.push(setTimeout(() => setStore("cursor", false), 2000)) |
| 37 | } |
| 38 | } |
| 39 | |
| 40 | timeouts.push(setTimeout(type, 200)) |
| 41 | |
| 42 | onCleanup(() => { |
| 43 | for (const timeout of timeouts) clearTimeout(timeout) |
| 44 | }) |
| 45 | }) |
| 46 | |
| 47 | return ( |
| 48 | <Dynamic component={props.as || "p"} class={props.class}> |
| 49 | {store.displayed} |
| 50 | <Show when={store.cursor}> |
| 51 | <span classList={{ "blinking-cursor": !store.typing }}>│</span> |
| 52 | </Show> |
| 53 | </Dynamic> |
| 54 | ) |
| 55 | } |