-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathjabradoodle.js
389 lines (323 loc) · 12.7 KB
/
jabradoodle.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
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
/**
* @preserve jabradoodle - v0.0.11 - 2017-09-11
* jQuery Audio Button + 🐩
* http://sjwilliams.github.io/jabradoodle/
* Copyright (c) 2016 Josh Williams; Licensed MIT
*
* SVG Icons by Open Iconic
* v1.1.1 | MIT
* https://github.com/iconic/open-iconic
*/
(function(factory) {
if (typeof define === 'function' && define.amd) {
define(['jquery'], factory);
} else {
factory(jQuery);
}
}(function($) {
var pluginName = 'jabradoodle';
var statePrefix = 'jab-state';
var $body = $('body');
var PLAYICON = '<div class="jab-svg-icon"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 8 8" preserveAspectRatio="xMidYMin slice" width="100%" style="padding-bottom: 100%; height: 1px; overflow: visible"><path d="M0 0v6l6-3-6-3z" transform="translate(1 1)" /></svg></div>';
var PAUSEICON = '<div class="jab-svg-icon"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 8 8" preserveAspectRatio="xMidYMin slice" width="100%" style="padding-bottom: 100%; height: 1px; overflow: visible"><path d="M0 0v6h2v-6h-2zm4 0v6h2v-6h-2z" transform="translate(1 1)" /></svg></div>';
function Plugin(element, options){
this.defaultOptions = {
preload: false, // create audio element on init and start download, or wait until button click.
exclusive: true, // play only one player at a time
fillcontainer: false, // whether or not the button expands as wide as the container it's in (display block vs display table)
showduration: true, // show duration in MM:SS format
showprogressbar: true, // show the moving progress bar in the background
showloader: true, // show the loading icon while audio is downloading
countdown: false,
iconsmaintainwidth: true,
buttonmaintainwidth: true,
statusmaintainwidth: false,
playtext: 'Play',
pausetext: 'Pause',
resumetext: 'Resume',
playicon: PLAYICON,
pauseicon: PAUSEICON,
resumeicon: PLAYICON
};
var settings = $.extend({}, this.defaultOptions, options);
var players = [];
$(element).each(function(){
var el = this;
var $el = $(el);
var data = $el.data();
// override any global settings with local ones
var localSettings = $.extend({}, settings, data);
if (!localSettings.src || !localSettings.duration) {
warn('Each element must have a src and duration. Skipping this one.');
} else {
var markup = [
'<div class="jab-icon jab-inline-el jab-icon-play">'+localSettings.playicon+'</div>',
'<div class="jab-icon jab-inline-el jab-icon-pause">'+localSettings.pauseicon+'</div>',
'<div class="jab-icon jab-inline-el jab-icon-resume">'+localSettings.resumeicon+'</div>',
'<div class="jab-icon jab-inline-el jab-icon-loader"><div class="jab-loader"></div></div>',
'<div class="jab-text jab-inline-el jab-text-play">'+localSettings.playtext+'</div>',
'<div class="jab-text jab-inline-el jab-text-pause">'+localSettings.pausetext+'</div>',
'<div class="jab-text jab-inline-el jab-text-resume">'+localSettings.resumetext+'</div>',
'<div class="jab-text jab-inline-el jab-text-duration">'+secondsToTimecodeString(localSettings.duration)+'</div>',
'<div class="jab-progress"><div class="jab-bar"></div></div>'
].join('');
// Classes on the main element dictate what is shown.
var initClasses = 'jab-container jab-init';
[{
setting: 'fillcontainer',
value: 'fillcontainer'
},{
setting: 'playtext',
value: 'status'
}, {
setting: 'playicon',
value: 'icons'
}, {
setting: 'showduration',
value: 'duration'
}, {
setting: 'showprogressbar',
value: 'progressbar'
}].forEach(function(option){
if (localSettings[option.setting]) {
initClasses = initClasses + ' jab-show-' + option.value;
}
});
// Append new markup
$el.addClass(initClasses).append(markup);
// Maintain equal spacing between icons / text messages?
if (localSettings.iconsmaintainwidth) {
equalHorizontalWidth($('.jab-icon', $el));
}
if (localSettings.statusmaintainwidth) {
equalHorizontalWidth($('.jab-text', $el));
}
// Set button to the max possible size of any state
if (localSettings.buttonmaintainwidth) {
var maxButtonWidth = Math.max.apply(null, [
'active',
'pause',
'loading',
'inactive' // end on this, the default state
].map(function(state){
containerClass(el, statePrefix, state);
return $el.width();
}));
$el.css('min-width', maxButtonWidth);
} else {
containerClass(el, statePrefix, 'inactive');
}
$el.addClass('jab-post-init');
// obj represents player UI and functionality
var player = {
$el: $el,
$progress: $el.find('.jab-progress'),
$bar: $el.find('.jab-bar'),
$duration: $el.find('.jab-text-duration'),
settings: localSettings,
/**
* Load and bind events.
*/
load: function(){
if (!this.audio) {
this.$audio = $('<audio class="jab-audio" src="' + this.settings.src + '"></audio>').appendTo($body);
this.audio = this.$audio[0];
this.$audio.on('play', this._onPlay.bind(this));
this.$audio.on('pause', this._onPause.bind(this));
this.$audio.on('timeupdate', this._onTimeUpdate.bind(this));
this.$audio.on('ended', this._onEnded.bind(this));
this.$audio.on('loadstart', this._onLoadStart.bind(this));
this.$audio.on('canplaythrough', this._onLoadEnd.bind(this));
}
},
/**
* Return the state of the player. It's
* based on the jab-state-* class name
* on the container.
*
* 'jab-state-active' returns 'active', etc.
*
* @return {String}
*/
getState: function(){
var classList = Array.prototype.slice.call(el.classList);
for (var i = classList.length - 1; i >= 0; i--) {
if (classList[i].lastIndexOf(statePrefix + '-') === 0) {
return classList[i].split('-')[2]; // bail early if we find it. and only return the last part of jab-state-active
}
}
return; // not found. return undefined.
},
// audio element event handlers
_onLoadStart: function(){
if (this.settings.showloader) {
this._preLoadingState = this.getState();
containerClass(el, statePrefix, 'loading');
}
},
_onLoadEnd: function(){
if (this.settings.showloader) {
// on return to preLoad state if, in fact,
// user has requested a new state, which would
// have updated current getState way from 'loading'
if (this.getState() === 'loading') {
containerClass(el, statePrefix, this._preLoadingState);
}
}
$el.trigger('load', this);
},
_onPlay: function(){
var player = this;
// stop other players?
if (player.settings.exclusive) {
players.forEach(function(otherPlayer){
if (otherPlayer !== player && otherPlayer.audio && !otherPlayer.audio.paused) {
otherPlayer.audio.pause();
}
});
}
containerClass(el, statePrefix, 'active');
$el.trigger( 'play', this);
},
_onPause: function(){
var player = this;
containerClass(el, statePrefix, 'pause');
$el.trigger( 'pause', this);
},
_onEnded: function(){
var player = this;
// reset duration text, if needed
if (player.settings.countdown) {
player.$duration.html(secondsToTimecodeString(player.settings.duration));
}
containerClass(el, statePrefix, 'inactive');
$el.trigger( 'ended', this);
},
_onTimeUpdate: function(){
var player = this;
var percentComplete;
var displayTime;
var width;
// prefer more accurate duration info from player. Fallback to user input if needed.
var duration = (function(){
var duration = player.audio.duration || player.settings.duration;
// Safari + no content length from server returns infinity intead of a number. Fallback if needd.
return isFinite(duration) ? duration : player.settings.duration;
})();
if (duration && duration >= 1) {
// move progress bar
if (player.settings.showprogressbar) {
percentComplete = (player.audio.currentTime / duration);
width = Math.floor(player.$progress.width() * percentComplete);
player.$bar.css('width', width);
}
// duration text counts down?
if (player.settings.countdown) {
displayTime = Math.floor(duration - player.audio.currentTime);
displayTime = (displayTime < duration) ? displayTime : duration; // ensure it's smaller than passed in (and perhaps incorrect) duration
displayTime = secondsToTimecodeString(displayTime); // convert to 00:00 format.
player.$duration.html(displayTime);
}
}
$el.trigger('timeupdate', this);
}
};
// bind play/pause
player.$el.on('click', function(){
player.load(); // incase preload was set to false
if (player.audio.paused) {
player.audio.play();
} else {
player.audio.pause();
}
});
// preload audio?
if (player.settings.preload) {
player.load();
}
// add to running list of players
players.push(player);
}
});
}
function warn(msg){
console.log(pluginName + ': ' + msg);
}
function die(msg){
throw new Error(pluginName + ': ' + msg);
}
function equalHorizontalWidth($els){
var maxWidth = Math.max.apply(null, $els.map(function() {
return Math.ceil($(this).width());
}).get());
$els.width(maxWidth);
}
/**
* Convert number of seconds into object with time parts.
*
* 92 to:
*
* {
* h: 0,
* m: 1,
* s: 32
* }
*
* From: http://codeaid.net/javascript/convert-seconds-to-hours-minutes-and-seconds-%28javascript%29
* Released under http://creativecommons.org/licenses/by/3.0/.
*
* @param Number seconds, as integer
* @return object
*/
function secondsToTime(secs){
var hours = Math.floor(secs / (60 * 60));
var divisor_for_minutes = secs % (60 * 60);
var minutes = Math.floor(divisor_for_minutes / 60);
var divisor_for_seconds = divisor_for_minutes % 60;
var seconds = Math.ceil(divisor_for_seconds);
seconds = '0' + seconds; // cast to string with a padded zero, in case we need it
seconds = seconds.substr(-2); // return last two digets
var obj = {
"h": hours,
"m": minutes,
"s": seconds
};
return obj;
}
/**
* Convert seconds as integer into timecode string.
*
* @param {Number} secs Timecode in seconds, like: 92
* @return {String} Timecdoe as string, like: 1:32
*/
function secondsToTimecodeString(secs){
var obj = secondsToTime(secs);
return obj.m + ':' + obj.s;
}
/**
* Given a prefix string like 'theme' and a value like
* 'dark', add 'theme-dark' class to the given element
* after removing any other theme-* classes.
*
* Extracted from, see for details:
* https://www.npmjs.com/package/container-class
*
* @param {Object} el Target DOM element
* @param {String} prefix Broad prefix slug/category, before the '-' separator.
* @param {String} value Specific suffix value, after the '-' separator.
*/
function containerClass(el, prefix, value){
var classList = Array.prototype.slice.call(el.classList);
classList.forEach(function(c){
if (c.lastIndexOf(prefix + '-') === 0 ){
el.classList.remove(c);
}
});
el.classList.add(prefix+'-'+value);
}
// Wrapper around the constructor preventing
// multiple instantiations on an element
$.fn[pluginName] = function(options) {
return new Plugin($(this).not('.jab-init').get(), options);
};
}));