forked from skillrecordings/egghead-next
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTranscript.tsx
More file actions
104 lines (94 loc) · 2.61 KB
/
Transcript.tsx
File metadata and controls
104 lines (94 loc) · 2.61 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
import React, {FunctionComponent, useState, useEffect} from 'react'
import {animateScroll as scroll} from 'react-scroll'
import {get, first, noop} from 'lodash'
import ReactMarkdown from 'react-markdown'
type TranscriptProps = {
player: any
className?: string
playVideo: () => any
initialTranscript?: string
enhancedTranscript: string
playerAvailable: boolean
}
const hmsToSeconds = (str: string) => {
let p = str.split(':') || [],
s = 0,
m = 1
while (p.length > 0) {
s += m * parseInt(p.pop() as string, 10)
m *= 60
}
return s
}
const Transcript: FunctionComponent<TranscriptProps> = ({
player,
className,
playVideo = noop,
initialTranscript = '',
enhancedTranscript,
playerAvailable,
}: TranscriptProps) => {
const transcriptText = enhancedTranscript || initialTranscript
const [transcript, setTranscript] = useState<string>()
const LinkReference = (props: any) => {
const children = get(props, 'children', [''])
const linkText: any = first(children)
const secondsToSeek = hmsToSeconds(
linkText.props.children.replace('[', '').replace(']', ''),
)
return (
<button
className="text-blue-600 hover:underline"
onClick={() => {
const duration = player.current.getDuration()
const fractionToSeek = secondsToSeek / duration
player.current.seekTo(fractionToSeek)
playVideo()
scroll.scrollToTop({
duration: 300,
smooth: 'true',
})
}}
>
{children}
</button>
)
}
useEffect(() => {
if (transcriptText && playerAvailable) {
const matches =
transcriptText &&
transcriptText.match(
/[0-9]:[0-9][0-9]|[0-9]{2}:[0-9][0-9]|[[0-9]{2}:[0-9][0-9]]|[[0-9]{3}:[0-9][0-9]]/g, // https://regexr.com/58bnr
)
let result = transcriptText
matches &&
matches.forEach((match: any, i: number) => {
result = result.replace(
match,
`[[${match.replace('[', '').replace(']', '')}]](${match
.replace('[', '')
.replace(']', '')})`,
)
if (i === matches.length - 1) {
setTranscript(result)
}
})
} else {
setTranscript(transcriptText)
}
}, [transcriptText, playerAvailable, initialTranscript])
if (!transcript) {
return null
}
return (
<ReactMarkdown
skipHtml={false}
renderers={{link: LinkReference}}
className={className ? className : 'prose md:prose-xl max-w-none'}
>
{transcript || ''}
</ReactMarkdown>
)
}
export default Transcript