-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbar-ui.js
More file actions
1676 lines (1117 loc) · 40.7 KB
/
bar-ui.js
File metadata and controls
1676 lines (1117 loc) · 40.7 KB
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*jslint plusplus: true, white: true, nomen: true */
/*global console, document, navigator, soundManager, window */
(function(window) {
/**
* SoundManager 2: "Bar UI" player
* Copyright (c) 2014, Scott Schiller. All rights reserved.
* http://www.schillmania.com/projects/soundmanager2/
* Code provided under BSD license.
* http://schillmania.com/projects/soundmanager2/license.txt
*/
"use strict";
var Player,
players = [],
// CSS selector that will get us the top-level DOM node for the player UI.
playerSelector = '.sm2-bar-ui',
playerOptions,
utils;
/**
* Slightly hackish: event callbacks.
* Override globally by setting window.sm2BarPlayers.on = {}, or individually by window.sm2BarPlayers[0].on = {} etc.
*/
players.on = {
/*
play: function(player) {
console.log('playing', player);
},
finish: function(player) {
// each sound
console.log('finish', player);
},
pause: function(player) {
console.log('pause', player);
},
error: function(player) {
console.log('error', player);
}
end: function(player) {
// end of playlist
console.log('end', player);
}
*/
};
playerOptions = {
// useful when multiple players are in use, or other SM2 sounds are active etc.
stopOtherSounds: true,
// CSS class to let the browser load the URL directly e.g., <a href="foo.mp3" class="sm2-exclude">download foo.mp3</a>
excludeClass: 'sm2-exclude'
};
soundManager.setup({
// trade-off: higher UI responsiveness (play/progress bar), but may use more CPU.
html5PollingInterval: 50,
flashVersion: 9
});
soundManager.onready(function() {
var nodes, i, j;
nodes = utils.dom.getAll(playerSelector);
if (nodes && nodes.length) {
for (i=0, j=nodes.length; i<j; i++) {
players.push(new Player(nodes[i]));
}
}
});
/**
* player bits
*/
Player = function(playerNode) {
var css, dom, extras, playlistController, soundObject, actions, actionData, defaultItem, defaultVolume, firstOpen, exports;
css = {
disabled: 'disabled',
selected: 'selected',
active: 'active',
legacy: 'legacy',
noVolume: 'no-volume',
playlistOpen: 'playlist-open'
};
dom = {
o: null,
playlist: null,
playlistTarget: null,
playlistContainer: null,
time: null,
player: null,
progress: null,
progressTrack: null,
progressBar: null,
duration: null,
volume: null
};
// prepended to tracks when a sound fails to load/play
extras = {
loadFailedCharacter: '<span title="Failed to load/play." class="load-error">✖</span>'
};
function stopOtherSounds() {
if (playerOptions.stopOtherSounds) {
soundManager.stopAll();
}
}
function callback(method) {
if (method) {
// fire callback, passing current turntable object
if (exports.on && exports.on[method]) {
exports.on[method](exports);
} else if (players.on[method]) {
players.on[method](exports);
}
}
}
function getTime(msec, useString) {
// convert milliseconds to hh:mm:ss, return as object literal or string
var nSec = Math.floor(msec/1000),
hh = Math.floor(nSec/3600),
min = Math.floor(nSec/60) - Math.floor(hh * 60),
sec = Math.floor(nSec -(hh*3600) -(min*60));
// if (min === 0 && sec === 0) return null; // return 0:00 as null
return (useString ? ((hh ? hh + ':' : '') + (hh && min < 10 ? '0' + min : min) + ':' + ( sec < 10 ? '0' + sec : sec ) ) : { 'min': min, 'sec': sec });
}
function setTitle(item) {
// given a link, update the "now playing" UI.
// if this is an <li> with an inner link, grab and use the text from that.
var links = item.getElementsByTagName('a');
if (links.length) {
item = links[0];
}
// remove any failed character sequence, also
dom.playlistTarget.innerHTML = '<ul class="sm2-playlist-bd"><li>' + item.innerHTML.replace(extras.loadFailedCharacter, '') + '</li></ul>';
if (dom.playlistTarget.getElementsByTagName('li')[0].scrollWidth > dom.playlistTarget.offsetWidth) {
// this item can use <marquee>, in fact.
dom.playlistTarget.innerHTML = '<ul class="sm2-playlist-bd"><li><marquee>' + item.innerHTML + '</marquee></li></ul>';
}
}
function makeSound(url) {
var sound = soundManager.createSound({
url: url,
volume: defaultVolume,
whileplaying: function() {
var progressMaxLeft = 100,
left,
width;
left = Math.min(progressMaxLeft, Math.max(0, (progressMaxLeft * (this.position / this.durationEstimate)))) + '%';
width = Math.min(100, Math.max(0, (100 * this.position / this.durationEstimate))) + '%';
if (this.duration) {
dom.progress.style.left = left;
dom.progressBar.style.width = width;
// TODO: only write changes
dom.time.innerHTML = getTime(this.position, true);
}
},
onbufferchange: function(isBuffering) {
if (isBuffering) {
utils.css.add(dom.o, 'buffering');
} else {
utils.css.remove(dom.o, 'buffering');
}
},
onplay: function() {
utils.css.swap(dom.o, 'paused', 'playing');
callback('play');
},
onpause: function() {
utils.css.swap(dom.o, 'playing', 'paused');
callback('pause');
},
onresume: function() {
utils.css.swap(dom.o, 'paused', 'playing');
},
whileloading: function() {
if (!this.isHTML5) {
dom.duration.innerHTML = getTime(this.durationEstimate, true);
}
},
onload: function(ok) {
if (ok) {
dom.duration.innerHTML = getTime(this.duration, true);
} else if (this._iO && this._iO.onerror) {
this._iO.onerror();
}
},
onerror: function() {
// sound failed to load.
var item, element, html;
item = playlistController.getItem();
if (item) {
// note error, delay 2 seconds and advance?
// playlistTarget.innerHTML = '<ul class="sm2-playlist-bd"><li>' + item.innerHTML + '</li></ul>';
if (extras.loadFailedCharacter) {
dom.playlistTarget.innerHTML = dom.playlistTarget.innerHTML.replace('<li>' ,'<li>' + extras.loadFailedCharacter + ' ');
if (playlistController.data.playlist && playlistController.data.playlist[playlistController.data.selectedIndex]) {
element = playlistController.data.playlist[playlistController.data.selectedIndex].getElementsByTagName('a')[0];
html = element.innerHTML;
if (html.indexOf(extras.loadFailedCharacter) === -1) {
element.innerHTML = extras.loadFailedCharacter + ' ' + html;
}
}
}
}
callback('error');
// load next, possibly with delay.
if (navigator.userAgent.match(/mobile/i)) {
// mobile will likely block the next play() call if there is a setTimeout() - so don't use one here.
actions.next();
} else {
if (playlistController.data.timer) {
window.clearTimeout(playlistController.data.timer);
}
playlistController.data.timer = window.setTimeout(actions.next, 2000);
}
},
onstop: function() {
utils.css.remove(dom.o, 'playing');
},
onfinish: function() {
var lastIndex, item;
utils.css.remove(dom.o, 'playing');
dom.progress.style.left = '0%';
lastIndex = playlistController.data.selectedIndex;
callback('finish');
// next track?
item = playlistController.getNext();
// don't play the same item over and over again, if at end of playlist etc.
if (item && playlistController.data.selectedIndex !== lastIndex) {
playlistController.select(item);
setTitle(item);
stopOtherSounds();
// play next
this.play({
url: playlistController.getURL()
});
} else {
// end of playlist case
// explicitly stop?
// this.stop();
callback('end');
}
}
});
return sound;
}
function playLink(link) {
// if a link is OK, play it.
if (soundManager.canPlayURL(link.href)) {
// if there's a timer due to failure to play one track, cancel it.
// catches case when user may use previous/next after an error.
if (playlistController.data.timer) {
window.clearTimeout(playlistController.data.timer);
playlistController.data.timer = null;
}
if (!soundObject) {
soundObject = makeSound(link.href);
}
// required to reset pause/play state on iOS so whileplaying() works? odd.
soundObject.stop();
playlistController.select(link.parentNode);
setTitle(link.parentNode);
// reset the UI
// TODO: function that also resets/hides timing info.
dom.progress.style.left = '0px';
dom.progressBar.style.width = '0px';
stopOtherSounds();
soundObject.play({
url: link.href,
position: 0
});
}
}
function PlaylistController() {
var data;
data = {
// list of nodes?
playlist: [],
// NOTE: not implemented yet.
// shuffledIndex: [],
// shuffleMode: false,
// selection
selectedIndex: 0,
loopMode: false,
timer: null
};
function getPlaylist() {
return data.playlist;
}
function getItem(offset) {
var list,
item;
// given the current selection (or an offset), return the current item.
// if currently null, may be end of list case. bail.
if (data.selectedIndex === null) {
return offset;
}
list = getPlaylist();
// use offset if provided, otherwise take default selected.
offset = (offset !== undefined ? offset : data.selectedIndex);
// safety check - limit to between 0 and list length
offset = Math.max(0, Math.min(offset, list.length));
item = list[offset];
return item;
}
function findOffsetFromItem(item) {
// given an <li> item, find it in the playlist array and return the index.
var list,
i,
j,
offset;
offset = -1;
list = getPlaylist();
if (list) {
for (i=0, j=list.length; i<j; i++) {
if (list[i] === item) {
offset = i;
break;
}
}
}
return offset;
}
function getNext() {
// don't increment if null.
if (data.selectedIndex !== null) {
data.selectedIndex++;
}
if (data.playlist.length > 1) {
if (data.selectedIndex >= data.playlist.length) {
if (data.loopMode) {
// loop to beginning
data.selectedIndex = 0;
} else {
// no change
data.selectedIndex--;
// end playback
// data.selectedIndex = null;
}
}
} else {
data.selectedIndex = null;
}
return getItem();
}
function getPrevious() {
data.selectedIndex--;
if (data.selectedIndex < 0) {
// wrapping around beginning of list? loop or exit.
if (data.loopMode) {
data.selectedIndex = data.playlist.length - 1;
} else {
// undo
data.selectedIndex++;
}
}
return getItem();
}
function resetLastSelected() {
// remove UI highlight(s) on selected items.
var items,
i, j;
items = utils.dom.getAll(dom.playlist, '.' + css.selected);
for (i=0, j=items.length; i<j; i++) {
utils.css.remove(items[i], css.selected);
}
}
function select(item) {
var offset,
itemTop,
itemBottom,
containerHeight,
scrollTop,
itemPadding,
liElement;
// remove last selected, if any
resetLastSelected();
if (item) {
liElement = utils.dom.ancestor('li', item);
utils.css.add(liElement, css.selected);
itemTop = item.offsetTop;
itemBottom = itemTop + item.offsetHeight;
containerHeight = dom.playlistContainer.offsetHeight;
scrollTop = dom.playlist.scrollTop;
itemPadding = 8;
if (itemBottom > containerHeight + scrollTop) {
// bottom-align
dom.playlist.scrollTop = itemBottom - containerHeight + itemPadding;
} else if (itemTop < scrollTop) {
// top-align
dom.playlist.scrollTop = item.offsetTop - itemPadding;
}
}
// update selected offset, too.
offset = findOffsetFromItem(liElement);
data.selectedIndex = offset;
}
function playItemByOffset(offset) {
var item;
offset = (offset || 0);
item = getItem(offset);
if (item) {
playLink(item.getElementsByTagName('a')[0]);
}
}
function getURL() {
// return URL of currently-selected item
var item, url;
item = getItem();
if (item) {
url = item.getElementsByTagName('a')[0].href;
}
return url;
}
function refreshDOM() {
// get / update playlist from DOM
if (!dom.playlist) {
if (window.console && console.warn) {
console.warn('refreshDOM(): playlist node not found?');
}
return false;
}
data.playlist = dom.playlist.getElementsByTagName('li');
}
function initDOM() {
dom.playlistTarget = utils.dom.get(dom.o, '.sm2-playlist-target');
dom.playlistContainer = utils.dom.get(dom.o, '.sm2-playlist-drawer');
dom.playlist = utils.dom.get(dom.o, '.sm2-playlist-bd');
}
function init() {
// inherit the default SM2 volume
defaultVolume = soundManager.defaultOptions.volume;
initDOM();
refreshDOM();
// animate playlist open, if HTML classname indicates so.
if (utils.css.has(dom.o, css.playlistOpen)) {
// hackish: run this after API has returned
window.setTimeout(function() {
actions.menu(true);
}, 1);
}
}
init();
return {
data: data,
refresh: refreshDOM,
getNext: getNext,
getPrevious: getPrevious,
getItem: getItem,
getURL: getURL,
playItemByOffset: playItemByOffset,
select: select
};
}
function isRightClick(e) {
// only pay attention to left clicks. old IE differs where there's no e.which, but e.button is 1 on left click.
if (e && ((e.which && e.which === 2) || (e.which === undefined && e.button !== 1))) {
// http://www.quirksmode.org/js/events_properties.html#button
return true;
}
}
function getActionData(target) {
// DOM measurements for volume slider
if (!target) {
return false;
}
actionData.volume.x = utils.position.getOffX(target);
actionData.volume.y = utils.position.getOffY(target);
actionData.volume.width = target.offsetWidth;
actionData.volume.height = target.offsetHeight;
// potentially dangerous: this should, but may not be a percentage-based value.
actionData.volume.backgroundSize = parseInt(utils.style.get(target, 'background-size'), 10);
// IE gives pixels even if background-size specified as % in CSS. Boourns.
if (window.navigator.userAgent.match(/msie|trident/i)) {
actionData.volume.backgroundSize = (actionData.volume.backgroundSize / actionData.volume.width) * 100;
}
}
function handleMouseDown(e) {
var links,
target;
target = e.target || e.srcElement;
if (isRightClick(e)) {
return true;
}
// normalize to <a>, if applicable.
if (target.nodeName.toLowerCase() !== 'a') {
links = target.getElementsByTagName('a');
if (links && links.length) {
target = target.getElementsByTagName('a')[0];
}
}
if (utils.css.has(target, 'sm2-volume-control')) {
// drag case for volume
getActionData(target);
utils.events.add(document, 'mousemove', actions.adjustVolume);
utils.events.add(document, 'mouseup', actions.releaseVolume);
// and apply right away
return actions.adjustVolume(e);
}
}
function handleClick(e) {
var evt,
target,
offset,
targetNodeName,
methodName,
href,
handled;
evt = (e || window.event);
target = evt.target || evt.srcElement;
if (target && target.nodeName) {
targetNodeName = target.nodeName.toLowerCase();
if (targetNodeName !== 'a') {
// old IE (IE 8) might return nested elements inside the <a>, eg., <b> etc. Try to find the parent <a>.
if (target.parentNode) {
do {
target = target.parentNode;
targetNodeName = target.nodeName.toLowerCase();
} while (targetNodeName !== 'a' && target.parentNode);
if (!target) {
// something went wrong. bail.
return false;
}
}
}
if (targetNodeName === 'a') {
// yep, it's a link.
href = target.href;
if (soundManager.canPlayURL(href)) {
// not excluded
if (!utils.css.has(target, playerOptions.excludeClass)) {
// find this in the playlist
playLink(target);
handled = true;
}
} else {
// is this one of the action buttons, eg., play/pause, volume, etc.?
offset = target.href.lastIndexOf('#');
if (offset !== -1) {
methodName = target.href.substr(offset+1);
if (methodName && actions[methodName]) {
handled = true;
actions[methodName](e);
}
}
}
// fall-through case
if (handled) {
// prevent browser fall-through
return utils.events.preventDefault(evt);
}
}
}
}
function handleMouse(e) {
var target, barX, barWidth, x, newPosition, sound;
target = dom.progressTrack;
barX = utils.position.getOffX(target);
barWidth = target.offsetWidth;
x = (e.clientX - barX);
newPosition = (x / barWidth);
sound = soundObject;
if (sound && sound.duration) {
sound.setPosition(sound.duration * newPosition);
// a little hackish: ensure UI updates immediately with current position, even if audio is buffering and hasn't moved there yet.
if (sound._iO && sound._iO.whileplaying) {
sound._iO.whileplaying.apply(sound);
}
}
if (e.preventDefault) {
e.preventDefault();
}
return false;
}
function releaseMouse(e) {
utils.events.remove(document, 'mousemove', handleMouse);
utils.css.remove(dom.o, 'grabbing');
utils.events.remove(document, 'mouseup', releaseMouse);
utils.events.preventDefault(e);
return false;
}
function init() {
// init DOM?
if (!playerNode) {
console.warn('init(): No playerNode element?');
}
dom.o = playerNode;
// are we dealing with a crap browser? apply legacy CSS if so.
if (window.navigator.userAgent.match(/msie [678]/i)) {
utils.css.add(dom.o, css.legacy);
}
if (window.navigator.userAgent.match(/mobile/i)) {
// majority of mobile devices don't let HTML5 audio set volume.
utils.css.add(dom.o, css.noVolume);
}
dom.progress = utils.dom.get(dom.o, '.sm2-progress-ball');
dom.progressTrack = utils.dom.get(dom.o, '.sm2-progress-track');
dom.progressBar = utils.dom.get(dom.o, '.sm2-progress-bar');
dom.volume = utils.dom.get(dom.o, 'a.sm2-volume-control');
// measure volume control dimensions
if (dom.volume) {
getActionData(dom.volume);
}
dom.duration = utils.dom.get(dom.o, '.sm2-inline-duration');
dom.time = utils.dom.get(dom.o, '.sm2-inline-time');
playlistController = new PlaylistController();
defaultItem = playlistController.getItem(0);
playlistController.select(defaultItem);
if (defaultItem) {
setTitle(defaultItem);
}
utils.events.add(dom.o, 'mousedown', handleMouseDown);
utils.events.add(dom.o, 'click', handleClick);
utils.events.add(dom.progressTrack, 'mousedown', function(e) {
if (isRightClick(e)) {
return true;
}
utils.css.add(dom.o, 'grabbing');
utils.events.add(document, 'mousemove', handleMouse);
utils.events.add(document, 'mouseup', releaseMouse);
return handleMouse(e);
});
}
// ---
actionData = {
volume: {
x: 0,
y: 0,
width: 0,
height: 0,
backgroundSize: 0
}
};
actions = {
play: function(offsetOrEvent) {
/**
* This is an overloaded function that takes mouse/touch events or offset-based item indices.
* Remember, "auto-play" will not work on mobile devices unless this function is called immediately from a touch or click event.
* If you have the link but not the offset, you can also pass a fake event object with a target of an <a> inside the playlist - e.g. { target: someMP3Link }
*/
var target,
href,
e;
if (offsetOrEvent !== undefined && !isNaN(offsetOrEvent)) {
// smells like a number.
return playlistController.playItemByOffset(offsetOrEvent);
}
// DRY things a bit
e = offsetOrEvent;
if (e && e.target) {
target = e.target || e.srcElement;
href = target.href;
}
// haaaack - if null due to no event, OR '#' due to play/pause link, get first link from playlist
if (!href || href.indexOf('#') !== -1) {
href = dom.playlist.getElementsByTagName('a')[0].href;
}
if (!soundObject) {
soundObject = makeSound(href);
}
// edge case: if the current sound is not playing, stop all others.
if (!soundObject.playState) {
stopOtherSounds();
}
// TODO: if user pauses + unpauses a sound that had an error, try to play next?
soundObject.togglePause();
// special case: clear "play next" timeout, if one exists.
// edge case: user pauses after a song failed to load.
if (soundObject.paused && playlistController.data.timer) {
window.clearTimeout(playlistController.data.timer);
playlistController.data.timer = null;
}
},
pause: function() {