plyr 0.0.4

Rust bindings for plyr
Documentation
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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
//!
//! RAII types which are used to manage Plyr event listeners.
//!
//! When the some kind of `EventListener` is dropped, it will automatically deregister the event listener and
//! clean up the closure's memory.
//!
//! ## Example
//!
//! ```rust
//! use plyr::events::{PlyrStandardEventType, PlyrYoutubeEventListener};
//! use plyr::Plyr;
//!
//! let player = Plyr::new("#player");
//!
//! let listener = PlyrYoutubeEventListener::new(
//!     &player,
//!     PlyrStandardEventType::playing.into(),
//!     move |_| log("playing")
//! );
//! ```

use crate::plyr::{Plyr, PlyrEvent, PlyrStateChangeEvent};
use crate::{Error as PlyrError, Provider};
use wasm_bindgen::{
    prelude::{Closure, JsValue},
    JsCast, UnwrapThrowExt,
};

use std::fmt::Display;
use strum_macros::Display as StrumDisplay;

// -------------------------------------------------------------------------------------------------
// PlyrEventListener

/// base plyr event listener
#[allow(clippy::type_complexity)]
struct PlyrEventListener {
    target: Plyr,
    event_type: String,
    callback: Option<Closure<dyn FnMut(&JsValue)>>,
}

impl PlyrEventListener {
    fn new<F: FnMut(&JsValue) + 'static>(target: &Plyr, event_type: String, callback: F) -> Self {
        let callback = Closure::wrap(Box::new(callback) as Box<dyn FnMut(&JsValue)>);
        target.on(&event_type, callback.as_ref().unchecked_ref());
        Self {
            target: target.clone(),
            event_type,
            callback: Some(callback),
        }
    }
    fn once<F: FnOnce(&JsValue) + 'static>(target: &Plyr, event_type: String, callback: F) -> Self {
        let callback = Closure::once(Box::new(callback));
        target.once(&event_type, callback.as_ref().unchecked_ref());
        Self {
            target: target.clone(),
            event_type,
            callback: Some(callback),
        }
    }
    /// Forget inner closure. This should be use when you want the closure to last forever.
    fn forget(&mut self) {
        self.callback.take().unwrap_throw().forget();
    }
}

impl Drop for PlyrEventListener {
    fn drop(&mut self) {
        if let Some(callback) = &self.callback {
            self.target
                .off(&self.event_type, callback.as_ref().unchecked_ref());
        }
    }
}

// -------------------------------------------------------------------------------------------------
// PlyrStandardEventListener

/// EventType for Plyr standard events.
#[allow(non_camel_case_types)]
#[derive(StrumDisplay, Debug, Clone)]
pub enum PlyrStandardEventType {
    progress,
    playing,
    play,
    pause,
    timeupdate,
    volumechange,
    seeking,
    seeked,
    ratechange,
    ended,
    enterfullscreen,
    exitfullscreen,
    captionenabled,
    captiondisabled,
    languagechange,
    controlshidden,
    controlsshown,
    ready,
}

/// EventListener for Plyr standard events.
pub struct PlyrStandardEventListener {
    base_event_listener: PlyrEventListener,
}

impl PlyrStandardEventListener {
    /// Constructor of EventListener for Plyr standard events.
    pub fn new<F: FnMut(&PlyrEvent) + 'static>(
        target: &Plyr,
        standard_event_type: PlyrStandardEventType,
        mut callback: F,
    ) -> Self {
        let callback =
            move |event: &JsValue| callback(event.clone().unchecked_into::<PlyrEvent>().as_ref());
        Self {
            base_event_listener: PlyrEventListener::new(
                target,
                standard_event_type.to_string(),
                callback,
            ),
        }
    }
    /// Constructor of EventListener for Plyr standard events. The callback is called only once.
    pub fn once<F: FnOnce(&PlyrEvent) + 'static>(
        target: &Plyr,
        standard_event_type: PlyrStandardEventType,
        callback: F,
    ) -> Self {
        let callback =
            move |event: &JsValue| callback(event.clone().unchecked_into::<PlyrEvent>().as_ref());
        Self {
            base_event_listener: PlyrEventListener::once(
                target,
                standard_event_type.to_string(),
                callback,
            ),
        }
    }

    /// Forget inner closure. This should be use when you want the closure to last forever.
    pub fn forget(&mut self) {
        self.base_event_listener.forget();
    }
}

// -------------------------------------------------------------------------------------------------
// PlyrHtml5EventListener

/// EventType for Plyr html5 events.
#[cfg(feature = "html5")]
#[allow(non_camel_case_types)]
#[derive(Debug, Clone)]
pub enum PlyrHtml5EventType {
    loadstart,
    loadeddata,
    loadedmetadata,
    canplay,
    canplaythrough,
    stalled,
    waiting,
    emptied,
    cuechange,
    error,
    PlyrStandardEventType(PlyrStandardEventType),
}

#[cfg(feature = "html5")]
impl From<PlyrStandardEventType> for PlyrHtml5EventType {
    fn from(standard_event_type: PlyrStandardEventType) -> Self {
        Self::PlyrStandardEventType(standard_event_type)
    }
}

#[cfg(feature = "html5")]
impl Display for PlyrHtml5EventType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let formatted = match self {
            Self::loadstart => "loadstart".to_string(),
            Self::loadeddata => "loadeddata".to_string(),
            Self::loadedmetadata => "loadedmetadata".to_string(),
            Self::canplay => "canplay".to_string(),
            Self::canplaythrough => "canplaythrough".to_string(),
            Self::stalled => "stalled".to_string(),
            Self::waiting => "waiting".to_string(),
            Self::emptied => "emptied".to_string(),
            Self::cuechange => "cuechange".to_string(),
            Self::error => "error".to_string(),
            Self::PlyrStandardEventType(event_type) => event_type.to_string(),
        };
        write!(f, "{formatted}")
    }
}

/// EventListener for standard and Html5 events. *This module requires the following crate features to be activated: `html5`.*
#[cfg(feature = "html5")]
pub struct PlyrHtml5EventListener {
    base_event_listener: PlyrEventListener,
}

#[cfg(feature = "html5")]
impl PlyrHtml5EventListener {
    /// Constructor of EventListener for Plyr standard and html5 events.
    pub fn new<F: FnMut(&PlyrEvent) + 'static>(
        target: &Plyr,
        event_type: PlyrHtml5EventType,
        mut callback: F,
    ) -> Result<Self, PlyrError> {
        if let Provider::html5 = target.provider() {
            let callback = move |event: &JsValue| {
                callback(event.clone().unchecked_into::<PlyrEvent>().as_ref())
            };
            Ok(Self {
                base_event_listener: PlyrEventListener::new(
                    target,
                    event_type.to_string(),
                    callback,
                ),
            })
        } else {
            Err(PlyrError::WrongEventProviderError)
        }
    }
    /// Constructor of EventListener for Plyr standard and html5 events. The callback is called only once.
    pub fn once<F: FnOnce(&PlyrEvent) + 'static>(
        target: &Plyr,
        event_type: PlyrHtml5EventType,
        callback: F,
    ) -> Result<Self, PlyrError> {
        if let Provider::html5 = target.provider() {
            let callback = move |event: &JsValue| {
                callback(event.clone().unchecked_into::<PlyrEvent>().as_ref())
            };
            Ok(Self {
                base_event_listener: PlyrEventListener::once(
                    target,
                    event_type.to_string(),
                    callback,
                ),
            })
        } else {
            Err(PlyrError::WrongEventProviderError)
        }
    }
    /// Forget inner closure. This should be use when you want the closure to last forever.
    pub fn forget(&mut self) {
        self.base_event_listener.forget();
    }
}

// -------------------------------------------------------------------------------------------------
// PlyrYoutubeEventListener

/// EventType for Plyr youtube events.
#[allow(non_camel_case_types)]
#[derive(Debug, Clone)]
pub enum PlyrYoutubeEventType {
    qualitychange,
    qualityrequested,
    PlyrStandardEventType(PlyrStandardEventType),
}

impl From<PlyrStandardEventType> for PlyrYoutubeEventType {
    fn from(event_type: PlyrStandardEventType) -> Self {
        Self::PlyrStandardEventType(event_type)
    }
}

impl Display for PlyrYoutubeEventType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let formatted = match self {
            Self::qualitychange => "qualitychange".to_string(),
            Self::qualityrequested => "qualityrequested".to_string(),
            Self::PlyrStandardEventType(event_type) => event_type.to_string(),
        };
        write!(f, "{formatted}")
    }
}

/// EventListener for Plyr standard and youtube events, which includes statechange event .
pub struct PlyrYoutubeEventListener {
    base_event_listener: PlyrEventListener,
}

impl PlyrYoutubeEventListener {
    /// Constructor of EventListener for Plyr standard and youtube events.
    pub fn new<F: FnMut(&PlyrEvent) + 'static>(
        target: &Plyr,
        event_type: PlyrYoutubeEventType,
        mut callback: F,
    ) -> Result<Self, PlyrError> {
        if let Provider::youtube = target.provider() {
            let callback = move |event: &JsValue| {
                callback(event.clone().unchecked_into::<PlyrEvent>().as_ref())
            };
            Ok(Self {
                base_event_listener: PlyrEventListener::new(
                    target,
                    event_type.to_string(),
                    callback,
                ),
            })
        } else {
            Err(PlyrError::WrongEventProviderError)
        }
    }
    /// Constructor of EventListener for Plyr standard and youtube events. The callback is called only once.
    pub fn once<F: FnOnce(&PlyrEvent) + 'static>(
        target: &Plyr,
        event_type: PlyrYoutubeEventType,
        callback: F,
    ) -> Result<Self, PlyrError> {
        if let Provider::youtube = target.provider() {
            let callback = move |event: &JsValue| {
                callback(event.clone().unchecked_into::<PlyrEvent>().as_ref())
            };
            Ok(Self {
                base_event_listener: PlyrEventListener::once(
                    target,
                    event_type.to_string(),
                    callback,
                ),
            })
        } else {
            Err(PlyrError::WrongEventProviderError)
        }
    }
    /// Constructor of EventListener for youtube statechange event.
    pub fn new_on_statechange<F: FnMut(&PlyrStateChangeEvent) + 'static>(
        target: &Plyr,
        mut callback: F,
    ) -> Result<Self, PlyrError> {
        if let Provider::youtube = target.provider() {
            let callback = move |event: &JsValue| {
                callback(
                    event
                        .clone()
                        .unchecked_into::<PlyrStateChangeEvent>()
                        .as_ref(),
                )
            };
            Ok(Self {
                base_event_listener: PlyrEventListener::new(
                    target,
                    "statechange".to_string(),
                    callback,
                ),
            })
        } else {
            Err(PlyrError::WrongEventProviderError)
        }
    }
    /// Constructor of EventListener for youtube statechange event. The callback is called only once.
    pub fn once_on_statechange<F: FnOnce(&PlyrStateChangeEvent) + 'static>(
        target: &Plyr,
        callback: F,
    ) -> Result<Self, PlyrError> {
        if let Provider::youtube = target.provider() {
            let callback = move |event: &JsValue| {
                callback(
                    event
                        .clone()
                        .unchecked_into::<PlyrStateChangeEvent>()
                        .as_ref(),
                )
            };
            Ok(Self {
                base_event_listener: PlyrEventListener::once(
                    target,
                    "statechange".to_string(),
                    callback,
                ),
            })
        } else {
            Err(PlyrError::WrongEventProviderError)
        }
    }
    /// Forget inner closure. This should be use when you want the closure to last forever.
    pub fn forget(&mut self) {
        self.base_event_listener.forget();
    }
}

// -------------------------------------------------------------------------------------------------
// DestroyEventListener

/// EventListener for Plyr destroy event.
pub struct DestroyEventListener {
    callback: Option<Closure<dyn FnMut()>>,
}

impl DestroyEventListener {
    /// Constructor of EventListener for Plyr destroy event.
    pub fn new<F: FnOnce() + 'static>(target: &Plyr, callback: F) -> Self {
        let callback = Closure::once(Box::new(callback));
        target.destroy_with_callback(callback.as_ref().unchecked_ref());
        Self {
            callback: Some(callback),
        }
    }
    /// Constructor of EventListener for Plyr destroy event with a soft flag.
    pub fn new_with_soft<F: FnOnce() + 'static>(target: &Plyr, callback: F, soft: bool) -> Self {
        let callback = Closure::once(Box::new(callback));
        target.destroy_with_callback_and_soft(callback.as_ref().unchecked_ref(), soft);
        Self {
            callback: Some(callback),
        }
    }
    /// Forget inner closure. This should be use when you want the closure to last forever.
    pub fn forget(&mut self) {
        self.callback.take().unwrap_throw().forget();
    }
}