-
Notifications
You must be signed in to change notification settings - Fork 614
Expand file tree
/
Copy pathsegment-hooks.ts
More file actions
84 lines (71 loc) · 1.99 KB
/
segment-hooks.ts
File metadata and controls
84 lines (71 loc) · 1.99 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
import { useMemo, useRef } from "react";
import type { Segment } from "~/stt/live-segment";
import { getTranscriptTimingSource } from "~/stt/timing";
export function useStableSegments(segments: Segment[]): Segment[] {
const cacheRef = useRef<Map<string, Segment>>(new Map());
return useMemo(() => {
const nextCache = new Map<string, Segment>();
const stable = segments.map((segment) => {
const cached = cacheRef.current.get(segment.id);
if (cached && segmentsEqual(cached, segment)) {
nextCache.set(segment.id, cached);
return cached;
}
nextCache.set(segment.id, segment);
return segment;
});
cacheRef.current = nextCache;
return stable;
}, [segments]);
}
export function createSegmentKey(
segment: Segment,
transcriptId: string,
fallbackIndex: number,
) {
return segment.id || `${transcriptId}-segment-${fallbackIndex}`;
}
function segmentsEqual(a: Segment, b: Segment) {
if (
a.id !== b.id ||
a.start_ms !== b.start_ms ||
a.end_ms !== b.end_ms ||
a.text !== b.text ||
a.key.channel !== b.key.channel ||
a.key.speaker_index !== b.key.speaker_index ||
a.key.speaker_human_id !== b.key.speaker_human_id ||
a.words.length !== b.words.length
) {
return false;
}
for (let index = 0; index < a.words.length; index += 1) {
const aw = a.words[index]!;
const bw = b.words[index]!;
if (
aw.id !== bw.id ||
aw.text !== bw.text ||
aw.start_ms !== bw.start_ms ||
aw.end_ms !== bw.end_ms ||
aw.channel !== bw.channel ||
aw.is_final !== bw.is_final ||
getTranscriptTimingSource(aw) !== getTranscriptTimingSource(bw)
) {
return false;
}
}
return true;
}
export function segmentsShallowEqual(a: Segment[], b: Segment[]) {
if (a === b) {
return true;
}
if (a.length !== b.length) {
return false;
}
for (let index = 0; index < a.length; index += 1) {
if (a[index] !== b[index]) {
return false;
}
}
return true;
}