about summary refs log tree commit diff
path: root/modules/expo-bluesky-gif-view/src/GifView.web.tsx
blob: c197e01a1d229c41ce9df4210ea79dc02919cfbf (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
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
import * as React from 'react'
import {StyleSheet} from 'react-native'

import {GifViewProps} from './GifView.types'

export class GifView extends React.PureComponent<GifViewProps> {
  private readonly videoPlayerRef: React.RefObject<HTMLMediaElement> =
    React.createRef()
  private isLoaded = false

  constructor(props: GifViewProps | Readonly<GifViewProps>) {
    super(props)
  }

  componentDidUpdate(prevProps: Readonly<GifViewProps>) {
    if (prevProps.autoplay !== this.props.autoplay) {
      if (this.props.autoplay) {
        this.playAsync()
      } else {
        this.pauseAsync()
      }
    }
  }

  static async prefetchAsync(_: string[]): Promise<void> {
    console.warn('prefetchAsync is not supported on web')
  }

  private firePlayerStateChangeEvent = () => {
    this.props.onPlayerStateChange?.({
      nativeEvent: {
        isPlaying: !this.videoPlayerRef.current?.paused,
        isLoaded: this.isLoaded,
      },
    })
  }

  private onLoad = () => {
    // Prevent multiple calls to onLoad because onCanPlay will fire after each loop
    if (this.isLoaded) {
      return
    }

    this.isLoaded = true
    this.firePlayerStateChangeEvent()
  }

  async playAsync(): Promise<void> {
    this.videoPlayerRef.current?.play()
  }

  async pauseAsync(): Promise<void> {
    this.videoPlayerRef.current?.pause()
  }

  async toggleAsync(): Promise<void> {
    if (this.videoPlayerRef.current?.paused) {
      await this.playAsync()
    } else {
      await this.pauseAsync()
    }
  }

  render() {
    return (
      <video
        src={this.props.source}
        autoPlay={this.props.autoplay ? 'autoplay' : undefined}
        preload={this.props.autoplay ? 'auto' : undefined}
        playsInline={true}
        loop="loop"
        muted="muted"
        style={StyleSheet.flatten(this.props.style)}
        onCanPlay={this.onLoad}
        onPlay={this.firePlayerStateChangeEvent}
        onPause={this.firePlayerStateChangeEvent}
        aria-label={this.props.accessibilityLabel}
        ref={this.videoPlayerRef}
      />
    )
  }
}