aboutsummaryrefslogtreecommitdiffstats
path: root/src/js/ui.js
blob: b674c70d2f7b45ba72c0d052b4e8603c1eb6edb4 (plain)
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
// ==========================================================================
// Plyr UI
// ==========================================================================

import captions from './captions';
import controls from './controls';
import support from './support';
import browser from './utils/browser';
import { getElement, toggleClass } from './utils/elements';
import { ready, triggerEvent } from './utils/events';
import i18n from './utils/i18n';
import is from './utils/is';
import loadImage from './utils/load-image';

const ui = {
  addStyleHook() {
    toggleClass(this.elements.container, this.config.selectors.container.replace('.', ''), true);
    toggleClass(this.elements.container, this.config.classNames.uiSupported, this.supported.ui);
  },

  // Toggle native HTML5 media controls
  toggleNativeControls(toggle = false) {
    if (toggle && this.isHTML5) {
      this.media.setAttribute('controls', '');
    } else {
      this.media.removeAttribute('controls');
    }
  },

  // Setup the UI
  build() {
    // Re-attach media element listeners
    // TODO: Use event bubbling?
    this.listeners.media();

    // Don't setup interface if no support
    if (!this.supported.ui) {
      this.debug.warn(`Basic support only for ${this.provider} ${this.type}`);

      // Restore native controls
      ui.toggleNativeControls.call(this, true);

      // Bail
      return;
    }

    // Inject custom controls if not present
    if (!is.element(this.elements.controls)) {
      // Inject custom controls
      controls.inject.call(this);

      // Re-attach control listeners
      this.listeners.controls();
    }

    // Remove native controls
    ui.toggleNativeControls.call(this);

    // Setup captions for HTML5
    if (this.isHTML5) {
      captions.setup.call(this);
    }

    // Reset volume
    this.volume = null;

    // Reset mute state
    this.muted = null;

    // Reset loop state
    this.loop = null;

    // Reset quality setting
    this.quality = null;

    // Reset speed
    this.speed = null;

    // Reset volume display
    controls.updateVolume.call(this);

    // Reset time display
    controls.timeUpdate.call(this);

    // Reset duration display
    controls.durationUpdate.call(this);

    // Update the UI
    ui.checkPlaying.call(this);

    // Check for picture-in-picture support
    toggleClass(
      this.elements.container,
      this.config.classNames.pip.supported,
      support.pip && this.isHTML5 && this.isVideo,
    );

    // Check for airplay support
    toggleClass(this.elements.container, this.config.classNames.airplay.supported, support.airplay && this.isHTML5);

    // Add iOS class
    toggleClass(this.elements.container, this.config.classNames.isIos, browser.isIos);

    // Add touch class
    toggleClass(this.elements.container, this.config.classNames.isTouch, this.touch);

    // Ready for API calls
    this.ready = true;

    // Ready event at end of execution stack
    setTimeout(() => {
      triggerEvent.call(this, this.media, 'ready');
    }, 0);

    // Set the title
    ui.setTitle.call(this);

    // Assure the poster image is set, if the property was added before the element was created
    if (this.poster) {
      ui.setPoster.call(this, this.poster, false).catch(() => {});
    }

    // Manually set the duration if user has overridden it.
    // The event listeners for it doesn't get called if preload is disabled (#701)
    if (this.config.duration) {
      controls.durationUpdate.call(this);
    }
  },

  // Setup aria attribute for play and iframe title
  setTitle() {
    // Find the current text
    let label = i18n.get('play', this.config);

    // If there's a media title set, use that for the label
    if (is.string(this.config.title) && !is.empty(this.config.title)) {
      label += `, ${this.config.title}`;
    }

    // If there's a play button, set label
    Array.from(this.elements.buttons.play || []).forEach((button) => {
      button.setAttribute('aria-label', label);
    });

    // Set iframe title
    // https://github.com/sampotts/plyr/issues/124
    if (this.isEmbed) {
      const iframe = getElement.call(this, 'iframe');

      if (!is.element(iframe)) {
        return;
      }

      // Default to media type
      const title = !is.empty(this.config.title) ? this.config.title : 'video';
      const format = i18n.get('frameTitle', this.config);

      iframe.setAttribute('title', format.replace('{title}', title));
    }
  },

  // Toggle poster
  togglePoster(enable) {
    toggleClass(this.elements.container, this.config.classNames.posterEnabled, enable);
  },

  // Set the poster image (async)
  // Used internally for the poster setter, with the passive option forced to false
  setPoster(poster, passive = true) {
    // Don't override if call is passive
    if (passive && this.poster) {
      return Promise.reject(new Error('Poster already set'));
    }

    // Set property synchronously to respect the call order
    this.media.setAttribute('data-poster', poster);

    // Show the poster
    this.elements.poster.removeAttribute('hidden');

    // Wait until ui is ready
    return (
      ready
        .call(this)
        // Load image
        .then(() => loadImage(poster))
        .catch((error) => {
          // Hide poster on error unless it's been set by another call
          if (poster === this.poster) {
            ui.togglePoster.call(this, false);
          }
          // Rethrow
          throw error;
        })
        .then(() => {
          // Prevent race conditions
          if (poster !== this.poster) {
            throw new Error('setPoster cancelled by later call to setPoster');
          }
        })
        .then(() => {
          Object.assign(this.elements.poster.style, {
            backgroundImage: `url('${poster}')`,
            // Reset backgroundSize as well (since it can be set to "cover" for padded thumbnails for youtube)
            backgroundSize: '',
          });

          ui.togglePoster.call(this, true);

          return poster;
        })
    );
  },

  // Check playing state
  checkPlaying(event) {
    // Class hooks
    toggleClass(this.elements.container, this.config.classNames.playing, this.playing);
    toggleClass(this.elements.container, this.config.classNames.paused, this.paused);
    toggleClass(this.elements.container, this.config.classNames.stopped, this.stopped);

    // Set state
    Array.from(this.elements.buttons.play || []).forEach((target) => {
      Object.assign(target, { pressed: this.playing });
      target.setAttribute('aria-label', i18n.get(this.playing ? 'pause' : 'play', this.config));
    });

    // Only update controls on non timeupdate events
    if (is.event(event) && event.type === 'timeupdate') {
      return;
    }

    // Toggle controls
    ui.toggleControls.call(this);
  },

  // Check if media is loading
  checkLoading(event) {
    this.loading = ['stalled', 'waiting'].includes(event.type);

    // Clear timer
    clearTimeout(this.timers.loading);

    // Timer to prevent flicker when seeking
    this.timers.loading = setTimeout(
      () => {
        // Update progress bar loading class state
        toggleClass(this.elements.container, this.config.classNames.loading, this.loading);

        // Update controls visibility
        ui.toggleControls.call(this);
      },
      this.loading ? 250 : 0,
    );
  },

  // Toggle controls based on state and `force` argument
  toggleControls(force) {
    const { controls: controlsElement } = this.elements;

    if (controlsElement && this.config.hideControls) {
      // Don't hide controls if a touch-device user recently seeked. (Must be limited to touch devices, or it occasionally prevents desktop controls from hiding.)
      const recentTouchSeek = this.touch && this.lastSeekTime + 2000 > Date.now();

      // Show controls if force, loading, paused, button interaction, or recent seek, otherwise hide
      this.toggleControls(
        Boolean(
          force || this.loading || this.paused || controlsElement.pressed || controlsElement.hover || recentTouchSeek,
        ),
      );
    }
  },

  // Migrate any custom properties from the media to the parent
  migrateStyles() {
    // Loop through values (as they are the keys when the object is spread 🤔)
    Object.values({ ...this.media.style })
      // We're only fussed about Plyr specific properties
      .filter((key) => !is.empty(key) && is.string(key) && key.startsWith('--plyr'))
      .forEach((key) => {
        // Set on the container
        this.elements.container.style.setProperty(key, this.media.style.getPropertyValue(key));

        // Clean up from media element
        this.media.style.removeProperty(key);
      });

    // Remove attribute if empty
    if (is.empty(this.media.style)) {
      this.media.removeAttribute('style');
    }
  },
};

export default ui;