Skip to content

Instantly share code, notes, and snippets.

@louismullie
Created July 22, 2025 05:04
Show Gist options
  • Save louismullie/35ffe6fa6f2997203af1244105594a28 to your computer and use it in GitHub Desktop.
Save louismullie/35ffe6fa6f2997203af1244105594a28 to your computer and use it in GitHub Desktop.
const segments = splitIntoPatternedSequences(state.typingBuffer)
if (state.currentTypingPosition <= segments.length) {
const currentText = segments
.slice(0, state.currentTypingPosition)
.join('')
.trim()
state.currentText = currentText
state.shownReferences = state.references
state.currentTypingPosition++
const remainingBufferLength =
segments.length - state.currentTypingPosition
if (document.visibilityState === 'hidden' || state.isReconnecting) {
typeNextWord(state)
} else {
// Timeouts are paused when the document is hidden.
// Even in the background.
setTimeout(
() => typeNextWord(state),
getAdaptiveTypingDelay(
Math.max(remainingBufferLength, 0),
state.status === 'finishing',
),
)
}
}
export function getAdaptiveTypingDelay(
bufferWordCount: number,
isFinishing: boolean,
): number {
const BASE_DELAY = 100 // Maximum delay in milliseconds when bufferWordCount = 0
const MAX_BUFFER = 100 // Buffer count at which delay reaches 0
const MIN_DELAY = 10 // Minimum delay in milliseconds
if (isFinishing) {
return MIN_DELAY
}
// Clamp bufferWordCount between 0 and MAX_BUFFER
const clampedBuffer = Math.max(0, Math.min(bufferWordCount, MAX_BUFFER))
// Calculate delay based on bufferWordCount
// Linear decrease: delay = BASE_DELAY * (1 - (bufferWordCount / MAX_BUFFER))
const adjustedDelay = BASE_DELAY * (1 - clampedBuffer / MAX_BUFFER)
return Math.round(adjustedDelay)
}
// Splits input text into sequences of words following the pattern 1-2-3-2-1-2-...
export function splitIntoPatternedSequences(text: string): string[] {
// Split the text into words, handling multiple spaces and trimming whitespace
const words: string[] = text.split(/ +/)
// Define the repeating pattern of sequence lengths
const pattern: number[] = [1, 2, 3, 2] // 1-2-3-2-1-2-3-2-...
const sequences: string[] = []
let wordIndex = 0 // Current index in the words array
let patternIndex = 0 // Current index in the pattern array
// Loop until all words are processed
while (wordIndex < words.length) {
// Determine the current sequence length based on the pattern
const currentSequenceLength = pattern[patternIndex % pattern.length]
// Extract the sequence of words for the current pattern step
const sequenceWords = words
.slice(wordIndex, wordIndex + (currentSequenceLength ?? 0))
.join(' ')
// Add the sequence to the result array, appending a space if desired
sequences.push(`${sequenceWords} `)
// Move the word index forward by the length of the current sequence
wordIndex += currentSequenceLength ?? 0
// Move to the next step in the pattern
patternIndex++
}
return sequences
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment