All files / src/components video.ts

34.9% Statements 37/106
14.28% Branches 9/63
20% Functions 5/25
34.9% Lines 37/106

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396                                                                                                                                                                        1x     1x     1x     1x     1x 7x       1x 7x   1x     1x         1x     1x     1x           7x 7x 7x         1x         1x                 5x 5x       5x 5x 5x 5x           5x               5x               5x           5x         5x       5x 5x                                                                                                                                                                                                                                                                                                                                                 5x       5x                               5x 1x   4x     5x                  
import * as dom from '../dom/dom';
import * as func from '../func/func';
 
import {LitElement, html} from 'lit';
import {property, query} from 'lit/decorators.js';
import {ifDefined} from 'lit/directives/if-defined.js';
import * as domCanvas from '../dom/dom-canvas';
import {DomWatcher} from '../dom/dom-watcher';
import {
  type ElementVisibilityObject,
  elementVisibility,
} from '../dom/element-visibility';
import {Vector} from '../mathf/vector';
import {Raf} from '../raf/raf';
 
/**
 * Degu Video Component
 *
 * Usage:
 *
 * ```ts
 * import { DeguVideo} from '@blinkk/degu/lib/components/video';
 *
 * window.customElements.define('degu-video', DeguVideo);
 * ```
 *
 * ```html
 *   <degu-video
 *     src="https://storage.googleapis.com/mannequin/blobs/7b0c13d7-e9cc-4efa-93c1-9db323d7283b.mp4"
 *     width="640"
 *     height="640"
 *     style="aspect-ratio: 1"
 *     aria-label="Video Aria Label"
 *     autoplayinview="true"
 *     controls="true"
 *   ></degu-video>
 * ```
 *
 * ```css
 *
 *   degu-video {
 *     display: inline-block;
 *     line-height: 0;
 *     width: 100%;
 *   }
 *
 *   degu-video .degu-video {
 *     position: relative;
 *   }
 *
 *    degu-video video {
 *        width: 100%;
 *    }
 *
 *    degu-video[canvas="true"] video {
 *      visibility: hidden;
 *    }
 *
 *    degu-video canvas {
 *        width: 100%;
 *        position: absolute;
 *        height: 100%;
 *        top: 0;
 *        left: 0%;
 *        z-index: 1;
 *    }
 * ```
 *
 *
 * # Support for different video types, you can add comma separated sources.
 * ```html
 *   <degu-video>
 *     src="video.mp4, video.webm"
 *     width="640"
 *     height="640"
 *     style="aspect-ratio: 1"
 *     aria-label="Video Aria Label"
 *     autoplayinview="true"
 *     controls="true"
 *   >
 * </degu-video>
 * ```
 */
export class DeguVideo extends LitElement {
  @property({type: String, attribute: 'src'})
  src: string;
 
  @property({type: String, attribute: 'aria-label'})
  ariaLabel: string;
 
  @property({type: String, attribute: 'width'})
  private width: number;
 
  @property({type: String, attribute: 'height'})
  private height: number;
 
  @property({type: String, attribute: 'load-scalar'})
  private loadScalar = 2;
 
  // Set `autoplayinview="true" to play video on inview.
  // Video gets reset on outview and plays again on the next inview.
  @property({type: Boolean, attribute: 'autoplayinview'})
  private autoplayInview = false;
 
  @property({type: Boolean, attribute: 'loop'})
  loop: boolean;
 
  @property({type: Boolean, attribute: 'controls'})
  controls: boolean;
 
  // Whether to render out to a canvas instead of video.  The main advantage
  // of this is it normalizes color discoloration across browsers.
  @property({type: Boolean, attribute: 'canvas'})
  canvas: boolean;
 
  @query('canvas')
  canvasElement: HTMLCanvasElement;
 
  @query('video')
  videoElement: HTMLCanvasElement;
 
  ev: ElementVisibilityObject;
  private inviewEv: ElementVisibilityObject;
  private watcher: DomWatcher;
  private hasStartedLoad = false;
  public hasLoaded = false;
  public canvasReady = false;
  private raf: Raf;
 
  video: HTMLVideoElement;
 
  static CmsOptions: Record<string, string> = {
    LOOP: 'loop',
    CONTROLS: 'controls',
  };
 
  static Events: Record<string, string> = {
    LOAD_START: 'LOAD_START',
    LOAD_LOADED: 'LOAD_LOADED',
    FORCE_LOAD: 'FORCE_LOAD',
    RUN_UPDATE: 'RUN_UPDATE',
    CANVAS_READY: 'CANVAS_READY',
  };
 
  connectedCallback() {
    super.connectedCallback();
    this.canvas = !!this.getAttribute('canvas');
  }
 
  firstUpdated() {
    this.video = this.querySelector('video');
    this.video.crossOrigin = 'Anonymous';
    this.watcher = new DomWatcher();
    this.watcher.add({
      element: this,
      on: 'resize',
      callback: func.debounce(this.onResize.bind(this), 500),
    });
 
    this.watcher.add({
      element: this,
      on: DeguVideo.Events.FORCE_LOAD,
      callback: () => {
        this.runUpdate(true);
      },
    });
 
    this.watcher.add({
      element: this,
      on: DeguVideo.Events.RUN_UPDATE,
      callback: () => {
        this.runUpdate();
      },
    });
 
    this.ev = elementVisibility.inview(
      this.video,
      {rootMargin: window.innerHeight * this.loadScalar + 'px'},
      () => this.runUpdate.bind(this)
    );
 
    this.inviewEv = elementVisibility.inview(this.video, {}, () => {
      this.runUpdate();
    });
 
    // // If we are in range, try loading the video.
    this.ev.readyPromise.then(() => {
      this.runUpdate();
    });
 
    this.raf = new Raf(this.onRaf.bind(this));
    Iif (this.canvas && this.canvasElement) {
      this.raf.start();
    }
  }
 
  disconnectedCallback() {
    super.disconnectedCallback();
    this.raf && this.raf.dispose();
    this.watcher && this.watcher.dispose();
    this.ev && this.ev.dispose();
    this.inviewEv && this.inviewEv.dispose();
  }
 
  onRaf() {
    if (this.canvas && this.canvasElement) {
      this.canvasElement
        .getContext('2d')
        .drawImage(
          this.videoElement,
          0,
          0,
          this.canvasElement.width,
          this.canvasElement.height
        );
    }
  }
 
  /**
   * Given that degu-video is using canvas mode, gets the hex value of the video
   * at a given coordinate.
   */
  getHexColorAt(x: number, y: number, seconds = undefined): string {
    if (!this.canvas) {
      throw new Error('Video must be set to canvas mode to extract color');
    }
 
    const timeBeforeStop = this.video.currentTime;
    const isPlaying = dom.testVideoIsPlaying(this.video);
 
    if (seconds !== undefined) {
      this.video.currentTime = seconds;
    }
 
    const v = new Vector(x, y);
    const color = domCanvas.getColorAtPointAsHex(
      this.canvasElement.getContext('2d'),
      v
    );
 
    if (isPlaying) {
      this.video.currentTime = timeBeforeStop;
      this.play();
    }
 
    return color;
  }
 
  onResize() {
    if (!this.hasStartedLoad) {
      this.runUpdate();
    }
  }
 
  /**
   * Determines whether this element was painted (displayed on the screen). An
   * element is "painted" if it doesn't have display: none in its ancestors and
   * is in range of inview criteria.
   */
  isPainted() {
    return !dom.isDisplayNoneWithAncestors(this) && this.ev.state().inview;
  }
 
  private updateCanvasSize() {
    if (this.canvasElement) {
      this.canvasElement.width = this.videoElement.offsetWidth;
      this.canvasElement.height = this.videoElement.offsetHeight;
    }
  }
 
  /**
   * Given the video source adds HTML source elements to the video.
   * src can be singlar or have multiple videos comma separated.
   *
   * For example:
   * src="video.mp4, video.webm"
   * src="video.mp4"
   */
  private addVideoSources() {
    let sources = this.src.split(',');
    sources = sources.map((src) => {
      return src.trim();
    });
 
    for (const source of sources) {
      if (!source || source === '') {
        continue;
      }
      const sourceElement = document.createElement('source');
      sourceElement.src = source;
      const type = source.split('.').slice(-1)[0];
      sourceElement.type = `video/${type.toLowerCase()}`;
      this.video.appendChild(sourceElement);
    }
  }
 
  runUpdate(force = false) {
    // If the video hasn't been loaded yet.
    if ((this.isPainted() && !this.hasStartedLoad) || force) {
      this.hasStartedLoad = true;
 
      this.addVideoSources();
 
      dom.whenVideosLoaded([this.video]).then(() => {
        this.hasLoaded = true;
        this.updateCanvasSize();
        dom.event(this, DeguVideo.Events.LOAD_LOADED, {});
 
        // Play the video if we opted to play on inview.
        this.autoplayInview && this.play();
 
        // Run onRaf once so the canvas is in sync with the video.
        this.onRaf();
        dom.event(this, DeguVideo.Events.CANVAS_READY, {});
        this.canvasReady = true;
      });
 
      // Tell the parent element (video) to load.
      this.video.load();
      this.video.setAttribute('load', 'true');
      this.video.pause();
 
      dom.event(this, DeguVideo.Events.LOAD_START, {});
    }
 
    // If we have already loaded this, then reset the video on outview,
    // replay on inview.
    if (this.hasStartedLoad && this.autoplayInview) {
      this.updateCanvasSize();
 
      if (!this.isPainted() && !this.inviewEv.state().inview) {
        this.reset();
      } else {
        this.play();
      }
    }
  }
 
  /**
   * Plays the video if it isn't already playing.
   */
  play() {
    if (!dom.testVideoIsPlaying(this.video)) {
      const playPromise = this.video.play();
      if (playPromise !== undefined) {
        playPromise.then(() => {}).catch(() => {});
      }
    }
  }
 
  reset() {
    this.video.currentTime = 0;
    this.video.pause();
  }
 
  pause() {
    this.video.pause();
  }
 
  createRenderRoot() {
    return this;
  }
 
  renderVideo() {
    return html`<video
        ?loop="${this.loop}"
        aria-hidden="${ifDefined(this.ariaLabel ? true : null)}"
        disableRemotePlayback
        muted
        playsinline
        controls="${ifDefined(this.controls ? true : null)}"
      ></video>
      ${this.canvas ? html`<canvas></canvas>` : ''} `;
  }
 
  /**
   * If aria-label is set, the root gets role="img" and the inner video
   * should be hidden.
   */
  render() {
    if (this.ariaLabel) {
      this.setAttribute('role', 'img');
    } else {
      this.removeAttribute('role');
    }
 
    return html`
      ${
        this.canvas
          ? html`<div class="degu-video">${this.renderVideo()}</div>`
          : this.renderVideo()
      }
    `;
  }
}