Unverified Commit 75e3a77d authored by Hampton Maxwell's avatar Hampton Maxwell Committed by GitHub
Browse files

[WIP] Support react-native-dom (#1253)

Add support for react-native-dom
parent d9eef0fd
Loading
Loading
Loading
Loading
+25 −0
Changes for README.md: 25 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -192,6 +192,31 @@ using System.Collections.Generic;
```
</details>

<details>
  <summary>DOM</summary>

Make the following additions to the given files manually:

**dom/bootstrap.js**

Import RCTVideoManager and add it to the list of nativeModules:

```javascript
import { RNDomInstance } from "react-native-dom";
import { name as appName } from "../app.json";
import RCTVideoManager from 'react-native-video/dom/RCTVideoManager'; // Add this

// Path to RN Bundle Entrypoint ================================================
const rnBundlePath = "./entry.bundle?platform=dom&dev=true";

// React Native DOM Runtime Options =============================================
const ReactNativeDomOptions = {
  enableHotReload: false,
  nativeModules: [RCTVideoManager] // Add this
};
```
</details>

## Usage

```javascript

dom/LICENSE.md

0 → 100644
+9 −0
Changes for dom/LICENSE.md: 9 added lines, 0 removed lines.
Original line number Diff line number Diff line
MIT License

Copyright (c) 2018 Vincent Riemer

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

dom/RCTVideo.js

0 → 100644
+245 −0
Changes for dom/RCTVideo.js: 245 added lines, 0 removed lines.
Original line number Diff line number Diff line
// @flow

import { RCTEvent, RCTView, type RCTBridge } from "react-native-dom";

import resizeModes from "./resizeModes";
import type { VideoSource } from "./types";
import RCTVideoEvent from "./RCTVideoEvent";

class RCTVideo extends RCTView {
  playPromise: Promise<void> = Promise.resolve();
  progressTimer: number;
  videoElement: HTMLVideoElement;

  onEnd: boolean = false;
  onLoad: boolean = false;
  onLoadStart: boolean = false;
  onProgress: boolean = false;

  _paused: boolean = false;
  _progressUpdateInterval: number = 250.0;
  _savedVolume: number = 1.0;

  constructor(bridge: RCTBridge) {
    super(bridge);

    this.eventDispatcher = bridge.getModuleByName("EventDispatcher");

    this.onEnd = this.onEnd.bind(this);
    this.onLoad = this.onLoad.bind(this);
    this.onLoadStart = this.onLoadStart.bind(this);
    this.onPlay = this.onPlay.bind(this);
    this.onProgress = this.onProgress.bind(this);

    this.videoElement = this.initializeVideoElement();
    this.videoElement.addEventListener("ended", this.onEnd);
    this.videoElement.addEventListener("loadeddata", this.onLoad);
    this.videoElement.addEventListener("loadstart", this.onLoadStart);
    this.videoElement.addEventListener("pause", this.onPause);
    this.videoElement.addEventListener("play", this.onPlay);

    this.muted = false;
    this.rate = 1.0;
    this.volume = 1.0;
    this.childContainer.appendChild(this.videoElement);
  }

  detachFromView(view: UIView) {
    this.videoElement.removeEventListener("ended", this.onEnd);
    this.videoElement.removeEventListener("loadeddata", this.onLoad);
    this.videoElement.removeEventListener("loadstart", this.onLoadStart);
    this.videoElement.removeEventListener("pause", this.onPause);
    this.videoElement.removeEventListener("play", this.onPlay);

    this.stopProgressTimer();
  }

  initializeVideoElement() {
    const elem = document.createElement("video");

    Object.assign(elem.style, {
      display: "block",
      position: "absolute",
      top: "0",
      left: "0",
      width: "100%",
      height: "100%"
    });

    return elem;
  }

  presentFullscreenPlayer() {
    console.log("V PF");
    this.videoElement.webkitRequestFullScreen();
  }

  set controls(value: boolean) {
    if (value) {
      this.videoElement.controls = true;
      this.videoElement.style.pointerEvents = "auto";
    } else {
      this.videoElement.controls = false;
      this.videoElement.style.pointerEvents = "";
    }
  }

  set muted(value: boolean) {
    if (value) {
      this.videoElement.muted = true;
    } else {
      this.videoElement.muted = false;
    }
  }

  set paused(value: boolean) {
    this.playPromise.then(() => {
      if (value) {
        this.videoElement.pause();
      } else {
        this.playPromise = this.videoElement.play().catch(console.error);
      }
    });
    this._paused = value;
  }

  set progressUpdateInterval(value: number) {
    this._progressUpdateInterval = value;
    this.stopProgressTimer();
    this.startProgressTimer();
  }

  set rate(value: number) {
    this.videoElement.defaultPlaybackRate = value; // playbackRate doesn't work on Chrome
    this.videoElement.playbackRate = value;
  }

  set repeat(value: boolean) {
    if (value) {
      this.videoElement.setAttribute("loop", "true");
    } else {
      this.videoElement.removeAttribute("loop");
    }
  }

  set resizeMode(value: number) {
    switch (value) {
      case resizeModes.ScaleNone: {
        this.videoElement.style.objectFit = "none";
        break;
      }
      case resizeModes.ScaleToFill: {
        this.videoElement.style.objectFit = "fill";
        break;
      }
      case resizeModes.ScaleAspectFit: {
        this.videoElement.style.objectFit = "contain";
        break;
      }
      case resizeModes.ScaleAspectFill: {
        this.videoElement.style.objectFit = "cover";
        break;
      }
    }
  }

  set seek(value: number) {
    this.videoElement.currentTime = value;
  }

  set source(value: VideoSource) {
    let uri = value.uri;

    if (uri.startsWith("blob:")) {
      let blob = this.bridge.blobManager.resolveURL(uri);
      if (blob.type === "text/xml") {
        blob = new Blob([blob], { type: "video/mp4" });
      }
      uri = URL.createObjectURL(blob);
    }

    this.videoElement.setAttribute("src", uri);
    if (!this._paused) {
      this.playPromise = this.videoElement.play();
    }
  }

  set volume(value: number) {
    if (value === 0) {
      this.muted = true;
    } else {
      this.videoElement.volume = value;
      this.muted = false;
    }
  }

  onEnd = () => {
    this.onProgress();
    this.sendEvent("topVideoEnd", null);
    this.stopProgressTimer();    
  }

  onLoad = () => {
    // height & width are safe with audio, will be 0
    const height = this.videoElement.videoHeight;
    const width = this.videoElement.videoWidth;
    const payload = {
      currentPosition: this.videoElement.currentTime,
      duration: this.videoElement.duration,
      naturalSize: {
        width,
        height,
        orientation: width >= height ? "landscape" : "portrait"
      }
    };
    this.sendEvent("topVideoLoad", payload);
  }

  onLoadStart = () => {
    const src = this.videoElement.currentSrc;
    const payload = {
      isNetwork: !src.match(/^https?:\/\/localhost/), // require is served from localhost
      uri: this.videoElement.currentSrc
    };
    this.sendEvent("topVideoLoadStart", payload);
  }

  onPause = () => {
    this.stopProgressTimer();
  }

  onPlay = () => {
    this.startProgressTimer();
  }

  onProgress = () => {
    const payload = {
      currentTime: this.videoElement.currentTime,
      duration: this.videoElement.duration
    };
    this.sendEvent("topVideoProgress", payload);
  }

  sendEvent(eventName, payload) {
    const event = new RCTVideoEvent(eventName, this.reactTag, 0, payload);
    this.eventDispatcher.sendEvent(event);
  }

  startProgressTimer() {
    if (!this.progressTimer && this._progressUpdateInterval) {
      this.onProgress();
      this.progressTimer = setInterval(this.onProgress, this._progressUpdateInterval);
    }
  }

  stopProgressTimer() {
    if (this.progressTimer) {
      clearInterval(this.progressTimer);
      this.progressTimer = null;
    }
  }
}

customElements.define("rct-video", RCTVideo);

export default RCTVideo;

dom/RCTVideoEvent.js

0 → 100644
+56 −0
Changes for dom/RCTVideoEvent.js: 56 added lines, 0 removed lines.
Original line number Diff line number Diff line
// import { RCTEvent } from "react-native-dom";

interface RCTEvent {
    viewTag: number;
    eventName: string;
    coalescingKey: number;
  
    canCoalesce(): boolean;
    coalesceWithEvent(event: RCTEvent): RCTEvent;
  
    moduleDotMethod(): string;
    arguments(): Array<any>;
  }

export default class RCTVideoEvent implements RCTEvent {
  viewTag: number;
  eventName: string;
  coalescingKey: number;

  constructor(
    eventName: string,
    reactTag: number,
    coalescingKey: number,
    data: ?Object
  ) {
    this.viewTag = reactTag;
    this.eventName = eventName;
    this.coalescingKey = coalescingKey;
    this.data = data;
  }

  canCoalesce(): boolean {
    return false;
  }

  coalesceWithEvent(event: RCTEvent): RCTEvent {
    return;
  }

  moduleDotMethod(): string {
    return "RCTEventEmitter.receiveEvent";
  }

  arguments(): Array<any> {
    const args = [
      this.viewTag,
      this.eventName,
      this.data
    ];
    return args;
  }

  coalescingKey(): number {
    return this.coalescingKey;
  }
}

dom/RCTVideoManager.js

0 → 100644
+77 −0
Changes for dom/RCTVideoManager.js: 77 added lines, 0 removed lines.
Original line number Diff line number Diff line
// @flow

import { RCTViewManager } from "react-native-dom";

import RCTVideo from "./RCTVideo";
import resizeModes from "./resizeModes";

import type { VideoSource } from "./types";

class RCTVideoManager extends RCTViewManager {
  static moduleName = "RCTVideoManager";

  view() {
    return new RCTVideo(this.bridge);
  }

  describeProps() {
    return super
      .describeProps()
      .addBooleanProp("controls", this.setControls)
      .addBooleanProp("muted", this.setMuted)
      .addBooleanProp("paused", this.setPaused)
      .addNumberProp("progressUpdateInterval", this.setProgressUpdateInterval)
      .addBooleanProp("rate", this.setRate)
      .addBooleanProp("repeat", this.setRepeat)
      .addNumberProp("resizeMode", this.setResizeMode)
      .addNumberProp("seek", this.setSeek)
      .addObjectProp("src", this.setSource)
      .addNumberProp("volume", this.setVolume)
      .addDirectEvent("onVideoEnd")
      .addDirectEvent("onVideoLoad")
      .addDirectEvent("onVideoLoadStart")
      .addDirectEvent("onVideoProgress");
  }

  presentFullscreenPlayer() {
    // not currently working
  }

  setControls(view: RCTVideo, value: boolean) {
    view.controls = value;
  }

  setMuted(view: RCTVideo, value: boolean) {
    view.muted = value;
  }

  setPaused(view: RCTVideo, value: boolean) {
    view.paused = value;
  }

  setRate(view: RCTVideo, value: number) {
    view.rate = value;
  }

  setRepeat(view: RCTVideo, value: boolean) {
    view.repeat = value;
  }

  setResizeMode(view: RCTVideo, value: number) {
    view.resizeMode = value;
  }

  setSeek(view: RCTVideo, value: number) {
    view.seek = value;
  }

  setSource(view: RCTVideo, value: VideoSource) {
    view.source = value;
  }

  constantsToExport() {
    return { ...resizeModes };
  }
}

export default RCTVideoManager;
Loading