-
Notifications
You must be signed in to change notification settings - Fork 109
Expand file tree
/
Copy pathuseSmoothStreamingText.ts
More file actions
174 lines (151 loc) · 5.35 KB
/
useSmoothStreamingText.ts
File metadata and controls
174 lines (151 loc) · 5.35 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
import { useEffect, useRef, useState } from "react";
import { SmoothTextEngine } from "@/browser/utils/streaming/SmoothTextEngine";
export interface UseSmoothStreamingTextOptions {
fullText: string;
isStreaming: boolean;
bypassSmoothing: boolean;
/** Changing this resets the engine (new stream). */
streamKey: string;
/**
* Optional hint at the source's current emission rate (chars/sec). When
* supplied, the smoothing engine targets this rate instead of the BASE
* fallback so the visible cursor tracks the model's actual output. Pass 0
* (or omit) when unknown.
*/
liveCharsPerSec?: number;
}
export interface UseSmoothStreamingTextResult {
visibleText: string;
isCaughtUp: boolean;
}
const graphemeSegmenter =
typeof Intl !== "undefined" && typeof Intl.Segmenter === "function"
? new Intl.Segmenter(undefined, { granularity: "grapheme" })
: null;
function sliceAtGraphemeBoundary(text: string, maxCodeUnitLength: number): string {
if (maxCodeUnitLength <= 0) {
return "";
}
if (maxCodeUnitLength >= text.length) {
return text;
}
if (graphemeSegmenter) {
let safeEnd = 0;
for (const segment of graphemeSegmenter.segment(text)) {
const segmentEnd = segment.index + segment.segment.length;
if (segmentEnd > maxCodeUnitLength) {
break;
}
safeEnd = segmentEnd;
}
return text.slice(0, safeEnd);
}
let safeEnd = 0;
for (const codePoint of Array.from(text)) {
const codePointEnd = safeEnd + codePoint.length;
if (codePointEnd > maxCodeUnitLength) {
break;
}
safeEnd = codePointEnd;
}
return text.slice(0, safeEnd);
}
export function useSmoothStreamingText(
options: UseSmoothStreamingTextOptions
): UseSmoothStreamingTextResult {
const engineRef = useRef(new SmoothTextEngine());
const previousStreamKeyRef = useRef(options.streamKey);
if (previousStreamKeyRef.current !== options.streamKey) {
engineRef.current.reset();
previousStreamKeyRef.current = options.streamKey;
}
const engine = engineRef.current;
// engine.update is idempotent (pure projection of inputs onto engine state),
// so calling it during render is safe — including under StrictMode double-render.
// Keeping it inline lets the returned visibleText reflect the very latest fullText
// on the same render the stream ends, avoiding a one-frame visual lag at the seam.
engine.update(
options.fullText,
options.isStreaming,
options.bypassSmoothing,
options.liveCharsPerSec ?? 0
);
const [visibleLength, setVisibleLength] = useState(() => engine.visibleLength);
const visibleLengthRef = useRef(visibleLength);
visibleLengthRef.current = visibleLength;
const rafIdRef = useRef<number | null>(null);
const previousTimestampRef = useRef<number | null>(null);
// Frame callback stored as a ref so effects don't depend on it, preventing
// teardown/restart of the RAF loop on every text delta. Reads from refs and
// the stable engine instance, so the captured closure is always correct.
const frameRef = useRef<FrameRequestCallback>(null!);
frameRef.current = (timestampMs: number) => {
if (previousTimestampRef.current !== null) {
const nextLength = engine.tick(timestampMs - previousTimestampRef.current);
if (nextLength !== visibleLengthRef.current) {
visibleLengthRef.current = nextLength;
setVisibleLength(nextLength);
}
}
previousTimestampRef.current = timestampMs;
if (!engine.isCaughtUp) {
rafIdRef.current = requestAnimationFrame(frameRef.current);
} else {
rafIdRef.current = null;
previousTimestampRef.current = null;
}
};
// Sync engine state → React and re-arm RAF when new deltas arrive after
// catch-up. No cleanup: this effect only observes + one-shot starts; the
// lifecycle effect below owns resource teardown.
useEffect(() => {
if (visibleLengthRef.current !== engine.visibleLength) {
visibleLengthRef.current = engine.visibleLength;
setVisibleLength(engine.visibleLength);
}
if (
rafIdRef.current === null &&
options.isStreaming &&
!options.bypassSmoothing &&
!engine.isCaughtUp
) {
rafIdRef.current = requestAnimationFrame(frameRef.current);
}
}, [
engine,
options.fullText,
options.isStreaming,
options.bypassSmoothing,
options.streamKey,
options.liveCharsPerSec,
]);
// Lifecycle: stop RAF when streaming ends or stream key changes, and on unmount.
useEffect(() => {
if (!options.isStreaming || options.bypassSmoothing) {
if (rafIdRef.current !== null) cancelAnimationFrame(rafIdRef.current);
rafIdRef.current = null;
previousTimestampRef.current = null;
}
return () => {
if (rafIdRef.current !== null) cancelAnimationFrame(rafIdRef.current);
rafIdRef.current = null;
previousTimestampRef.current = null;
};
}, [options.isStreaming, options.bypassSmoothing, options.streamKey]);
if (!options.isStreaming || options.bypassSmoothing) {
return {
visibleText: options.fullText,
isCaughtUp: true,
};
}
const visiblePrefixLength = Math.min(
visibleLength,
engine.visibleLength,
options.fullText.length
);
const visibleText = sliceAtGraphemeBoundary(options.fullText, visiblePrefixLength);
return {
visibleText,
isCaughtUp: visibleText.length === options.fullText.length,
};
}