about summary refs log tree commit diff
path: root/src/view/com/util/post-embeds/VideoEmbedInner.web.tsx
blob: cb02743c6f8640ac6fd6e844d701e2fd51fda3a0 (plain) (blame)
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
import React, {useEffect, useRef} from 'react'
import Hls from 'hls.js'

import {atoms as a} from '#/alf'

export const VideoEmbedInner = ({source}: {source: string}) => {
  const ref = useRef<HTMLVideoElement>(null)

  // Use HLS.js to play HLS video
  useEffect(() => {
    if (ref.current) {
      if (ref.current.canPlayType('application/vnd.apple.mpegurl')) {
        ref.current.src = source
      } else if (Hls.isSupported()) {
        var hls = new Hls()
        hls.loadSource(source)
        hls.attachMedia(ref.current)
      } else {
        // TODO: fallback
      }
    }
  }, [source])

  useEffect(() => {
    if (ref.current) {
      const observer = new IntersectionObserver(
        ([entry]) => {
          if (ref.current) {
            if (entry.isIntersecting) {
              if (ref.current.paused) {
                ref.current.play()
              }
            } else {
              if (!ref.current.paused) {
                ref.current.pause()
              }
            }
          }
        },
        {threshold: 0},
      )

      observer.observe(ref.current)

      return () => {
        observer.disconnect()
      }
    }
  }, [])

  return <video ref={ref} style={a.flex_1} controls playsInline autoPlay loop />
}