-
Notifications
You must be signed in to change notification settings - Fork 837
/
utils.js
352 lines (299 loc) · 8.96 KB
/
utils.js
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
// Copyright 2014 Globo.com Player authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
/*jshint -W079 */
import './polyfills'
import Browser from '../components/browser'
import $ from 'clappr-zepto'
import Media from './media'
export function assign(obj, source) {
if (source) {
for (const prop in source) {
const propDescriptor = Object.getOwnPropertyDescriptor(source, prop)
propDescriptor ? Object.defineProperty(obj, prop, propDescriptor) : obj[prop] = source[prop]
}
}
return obj
}
export function extend(parent, properties) {
class Surrogate extends parent {
constructor(...args) {
super(...args)
if (properties.initialize)
properties.initialize.apply(this, args)
}
}
assign(Surrogate.prototype, properties)
return Surrogate
}
export function formatTime(time, paddedHours) {
if (!isFinite(time))
return '--:--'
time = time * 1000
time = parseInt(time/1000)
const seconds = time % 60
time = parseInt(time/60)
const minutes = time % 60
time = parseInt(time/60)
const hours = time % 24
const days = parseInt(time/24)
let out = ''
if (days && days > 0) {
out += days + ':'
if (hours < 1) out += '00:'
}
if (hours && hours > 0 || paddedHours) out += ('0' + hours).slice(-2) + ':'
out += ('0' + minutes).slice(-2) + ':'
out += ('0' + seconds).slice(-2)
return out.trim()
}
export const Fullscreen = {
getFullscreenElement: function() {
return document.webkitFullscreenElement ||
document.webkitIsFullScreen ||
document.mozFullScreen ||
document.msFullscreenElement
},
requestFullscreen: function(el) {
if (el.requestFullscreen)
el.requestFullscreen()
else if (el.webkitRequestFullscreen)
el.webkitRequestFullscreen()
else if (el.mozRequestFullScreen)
el.mozRequestFullScreen()
else if (el.msRequestFullscreen)
el.msRequestFullscreen()
else if (el.querySelector && el.querySelector('video') && el.querySelector('video').webkitEnterFullScreen)
el.querySelector('video').webkitEnterFullScreen()
else if (el.webkitEnterFullScreen)
el.webkitEnterFullScreen()
},
cancelFullscreen: function(el=document) {
if (el.exitFullscreen)
el.exitFullscreen()
else if (el.webkitCancelFullScreen)
el.webkitCancelFullScreen()
else if (el.webkitExitFullscreen)
el.webkitExitFullscreen()
else if (el.mozCancelFullScreen)
el.mozCancelFullScreen()
else if (el.msExitFullscreen)
el.msExitFullscreen()
},
fullscreenEnabled: function() {
return !!(
document.fullscreenEnabled ||
document.webkitFullscreenEnabled ||
document.mozFullScreenEnabled ||
document.msFullscreenEnabled
)
}
}
export class Config {
static _defaultConfig() {
return {
volume: {
value: 100,
parse: parseInt
}
}
}
static _defaultValueFor(key) {
try {
return this._defaultConfig()[key].parse(this._defaultConfig()[key].value)
} catch (e) {
return undefined
}
}
static _createKeyspace(key) {
return `clappr.${document.domain}.${key}`
}
static restore(key) {
if (Browser.hasLocalstorage && localStorage[this._createKeyspace(key)])
return this._defaultConfig()[key].parse(localStorage[this._createKeyspace(key)])
return this._defaultValueFor(key)
}
static persist(key, value) {
if (Browser.hasLocalstorage) {
try {
localStorage[this._createKeyspace(key)] = value
return true
} catch (e) {
return false
}
}
}
}
export class QueryString {
static get params() {
const query = window.location.search.substring(1)
if (query !== this.query) {
this._urlParams = this.parse(query)
this.query = query
}
return this._urlParams
}
static get hashParams() {
const hash = window.location.hash.substring(1)
if (hash !== this.hash) {
this._hashParams = this.parse(hash)
this.hash = hash
}
return this._hashParams
}
static parse(paramsString) {
let match
const pl = /\+/g, // Regex for replacing addition symbol with a space
search = /([^&=]+)=?([^&]*)/g,
decode = (s) => decodeURIComponent(s.replace(pl, ' ')),
params = {}
while (match = search.exec(paramsString)) { // eslint-disable-line no-cond-assign
params[decode(match[1]).toLowerCase()] = decode(match[2])
}
return params
}
}
export function seekStringToSeconds(paramName = 't') {
let seconds = 0
const seekString = QueryString.params[paramName] || QueryString.hashParams[paramName] || ''
const parts = seekString.match(/[0-9]+[hms]+/g) || []
if (parts.length > 0) {
const factor = { 'h': 3600, 'm': 60, 's': 1 }
parts.forEach(function(el) {
if (el) {
const suffix = el[el.length - 1]
const time = parseInt(el.slice(0, el.length - 1), 10)
seconds += time * (factor[suffix])
}
})
} else if (seekString) { seconds = parseInt(seekString, 10) }
return seconds
}
const idsCounter = {}
export function uniqueId(prefix) {
idsCounter[prefix] || (idsCounter[prefix] = 0)
const id = ++idsCounter[prefix]
return prefix + id
}
export function isNumber(value) {
return value - parseFloat(value) + 1 >= 0
}
export function currentScriptUrl() {
const scripts = document.getElementsByTagName('script')
return scripts.length ? scripts[scripts.length - 1].src : ''
}
export const requestAnimationFrame = (window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
function(fn) { window.setTimeout(fn, 1000/60) }).bind(window)
export const cancelAnimationFrame = (window.cancelAnimationFrame ||
window.mozCancelAnimationFrame ||
window.webkitCancelAnimationFrame ||
window.clearTimeout).bind(window)
export function getBrowserLanguage() {
return window.navigator && window.navigator.language
}
export function now() {
if (window.performance && window.performance.now)
return performance.now()
return Date.now()
}
// remove the item from the array if it exists in the array
export function removeArrayItem(arr, item) {
const i = arr.indexOf(item)
if (i >= 0)
arr.splice(i, 1)
}
// find an item regardless of its letter case
export function listContainsIgnoreCase(item, items) {
if (item === undefined || items === undefined) return false
return items.find((itemEach) => item.toLowerCase() === itemEach.toLowerCase()) !== undefined
}
// https://github.com/video-dev/can-autoplay
export function canAutoPlayMedia(cb, options) {
options = Object.assign({
inline: false,
muted: false,
timeout: 250,
type: 'video',
source: Media.mp4,
element: null
}, options)
let element = options.element ? options.element : document.createElement(options.type)
element.muted = options.muted
if (options.muted === true)
element.setAttribute('muted', 'muted')
if (options.inline === true)
element.setAttribute('playsinline', 'playsinline')
element.src = options.source
let promise = element.play()
let timeoutId = setTimeout(() => {
setResult(false, new Error(`Timeout ${options.timeout} ms has been reached`))
}, options.timeout)
let setResult = (result, error = null) => {
clearTimeout(timeoutId)
cb(result, error)
}
if (promise !== undefined) {
promise
.then(() => setResult(true))
.catch(err => setResult(false, err))
} else {
setResult(true)
}
}
// Simple Zepto element factory with video recycle feature.
const videoStack = []
export class DomRecycler {
static configure(options) {
this.options = $.extend(this.options, options)
}
static create(name) {
if (this.options.recycleVideo && name === 'video' && videoStack.length > 0)
return videoStack.shift()
return $('<' + name + '>')
}
static garbage($el) {
// Expect Zepto collection with single element (does not iterate!)
if (!this.options.recycleVideo || $el[0].tagName.toUpperCase() !== 'VIDEO') return
$el.children().remove()
videoStack.push($el)
}
}
DomRecycler.options = { recycleVideo: false }
export class DoubleEventHandler {
constructor(delay = 500) {
this.delay = delay
this.lastTime = 0
}
handle(event, cb, prevented = true) {
// Based on http://jsfiddle.net/brettwp/J4djY/
let currentTime = new Date().getTime()
let diffTime = currentTime - this.lastTime
if (diffTime < this.delay && diffTime > 0) {
cb()
prevented && event.preventDefault()
}
this.lastTime = currentTime
}
}
export default {
Config,
Fullscreen,
QueryString,
DomRecycler,
extend,
formatTime,
seekStringToSeconds,
uniqueId,
currentScriptUrl,
isNumber,
requestAnimationFrame,
cancelAnimationFrame,
getBrowserLanguage,
now,
removeArrayItem,
canAutoPlayMedia,
Media,
DoubleEventHandler
}