| 1 | import { useEffect, useRef, useState } from "react"; |
| 2 | |
| 3 | export function useAppendedString( |
| 4 | fullString: string, |
| 5 | append: (chunk: string, lineCount: number) => void, |
| 6 | ) { |
| 7 | // Queue of fullString updated versions to be processed atomically |
| 8 | const [updateQueue, setUpdateQueue] = useState<string[]>([]); |
| 9 | const lastString = useRef(""); |
| 10 | const processing = useRef(false); |
| 11 | |
| 12 | useEffect(() => { |
| 13 | setUpdateQueue((prev) => [...prev, fullString]); |
| 14 | }, [fullString]); |
| 15 | |
| 16 | useEffect(() => { |
| 17 | if (updateQueue.length === 0 || processing.current) return; |
| 18 | |
| 19 | processing.current = true; |
| 20 | setUpdateQueue((currentQueue) => { |
| 21 | while (currentQueue.length > 0) { |
| 22 | const nextString = currentQueue.shift()!; |
| 23 | if (!nextString.startsWith(lastString.current)) { |
| 24 | // Invalid |
| 25 | continue; |
| 26 | } |
| 27 | const appendedPart = nextString.slice(lastString.current.length); |
| 28 | lastString.current = nextString; |
| 29 | append(appendedPart, lastString.current.split("\n").length); |
| 30 | } |
| 31 | return currentQueue; |
| 32 | }); |
| 33 | processing.current = false; |
| 34 | }, [updateQueue]); |
| 35 | } |