main.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  1. (function($, Drupal, drupalSettings) {
  2. EdlpTheme = function(){
  3. var _$body = $('body');
  4. var _is_front = _$body.is('.path-frontpage');
  5. var _$corpus_canvas;
  6. var _$row = $('main[role="main"]>.layout-content>.row');
  7. var _$ajaxLinks;
  8. var _audio_player;
  9. var _randomPlayer;
  10. // ___ _ _
  11. // |_ _|_ _ (_) |_
  12. // | || ' \| | _|
  13. // |___|_||_|_|\__|
  14. function init(){
  15. console.log("EdlpTheme init()");
  16. // TODO: redirect all no-front pages to front with write hash
  17. _$body.on('corpus-map-ready', onCorpusMapReady);
  18. _audio_player = new AudioPlayer();
  19. initAjaxLinks();
  20. if (_$body.is('.path-productions')) {
  21. initProductions();
  22. }
  23. // initScrollbars();
  24. initEvents();
  25. };
  26. // ___ _
  27. // | __|_ _____ _ _| |_ ___
  28. // | _|\ V / -_) ' \ _(_-<
  29. // |___|\_/\___|_||_\__/__/
  30. function initEvents(){
  31. $('body')
  32. .on('on-studio-chutier-updated', function(e){
  33. initAjaxLinks();
  34. })
  35. .on('search-results-loaded',function(e){
  36. initAjaxLinks();
  37. })
  38. .on('open_entree', function(e){
  39. // e.tid available
  40. closeAllModals();
  41. })
  42. .on('close_entree', function(e){
  43. // e.tid available
  44. closeAllModals();
  45. });
  46. }
  47. // _ _ _
  48. // /_\ _ _ __| (_)___
  49. // / _ \ || / _` | / _ \
  50. // /_/ \_\_,_\__,_|_\___/
  51. //
  52. // https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement
  53. // https://docs.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/samples/gg589528%28v%3dvs.85%29
  54. // https://www.binarytides.com/using-html5-audio-element-javascript/
  55. function AudioPlayer(){
  56. var that = this;
  57. this.fid;
  58. this.audio = new Audio();
  59. // audio events
  60. this.audio_events = ["loadedmetadata","canplay","playing","pause","timeupdate","ended"];
  61. // UI dom objects
  62. this.$container = $('<div id="audio-player">');
  63. // btns
  64. this.$btns = $('<div>').addClass('btns').appendTo(this.$container);
  65. this.$previous = $('<div>').addClass('previous').appendTo(this.$btns);
  66. this.$playpause = $('<div>').addClass('play-pause').appendTo(this.$btns);
  67. this.$next = $('<div>').addClass('next').appendTo(this.$btns);
  68. // timeline
  69. this.$timelinecont= $('<div>').addClass('time-line-container').appendTo(this.$container);
  70. this.$timeline = $('<div>').addClass('time-line').appendTo(this.$timelinecont);
  71. this.$loader = $('<div>').addClass('loader').appendTo(this.$timeline);
  72. this.$cursor = $('<div>').addClass('cursor').appendTo(this.$timeline);
  73. // time
  74. this.$time = $('<div>').addClass('time').appendTo(this.$container);
  75. this.$currentTime = $('<div>').addClass('current-time').html('00:00').appendTo(this.$time);
  76. this.$duration = $('<div>').addClass('duration').html('00:00').appendTo(this.$time);
  77. // favoris
  78. this.$fav = $('<div>').addClass('favoris').appendTo(this.$container);
  79. // cartel
  80. this.$cartel = $('<div>').addClass('cartel').appendTo(this.$container);
  81. // hiding
  82. this.hideTimer = false;
  83. this.hideTimeMS = 10000;
  84. // history
  85. this.currentHistoricIndex = null;
  86. this.historic = [];
  87. this.shuffle_is_active = false;
  88. // object events
  89. this.event_handlers = {
  90. 'audio-play-next':[],
  91. 'audio-ended':[]
  92. };
  93. this.init();
  94. };
  95. AudioPlayer.prototype = {
  96. init(){
  97. // append ui to document
  98. this.$container.appendTo('header[role="banner"] .region-header');
  99. // record timeline width
  100. this.timeline_w = parseInt(this.$timeline.width());
  101. // init audio events
  102. var fn = '';
  103. for (var i = 0; i < this.audio_events.length; i++) {
  104. fn = this.audio_events[i];
  105. // capitalize first letter of event (only cosmetic :p )
  106. fn = 'on'+fn.charAt(0).toUpperCase()+fn.slice(1);
  107. this.audio.addEventListener(
  108. this.audio_events[i],
  109. this[fn].bind(this),
  110. true);
  111. }
  112. // init btns events
  113. this.$previous.on('click', this.playPrevious.bind(this));
  114. this.$playpause.on('click', this.togglePlayPause.bind(this));
  115. this.$next.on('click', this.playNext.bind(this));
  116. // TODO: previous and next btns
  117. },
  118. openDocument(node){
  119. console.log('AudioPlayer openDocument', node);
  120. this.historic.push(node);
  121. this.currentHistoricIndex = this.historic.length-1;
  122. // this.shuffle_mode = shuffle_mode || false;
  123. this.launch();
  124. },
  125. launch(){
  126. this.setSRC(this.historic[this.currentHistoricIndex].audio_url);
  127. this.loadNode(this.historic[this.currentHistoricIndex].nid);
  128. // emmit new playing doc (e.g.: corpus map nowing that audio played from RandomPlayer)
  129. _$corpus_canvas.trigger({
  130. 'type':'audio-node-opened',
  131. 'id':this.historic[this.currentHistoricIndex].id
  132. });
  133. this.showHidePreviousBtn();
  134. this.showHideNextBtn();
  135. this.show();
  136. },
  137. // audio functions
  138. setSRC(url){
  139. // console.log('AudioPlayer setSRC : url', url);
  140. this.clearTimeOutToHide();
  141. this.audio.src = url;
  142. },
  143. onLoadedmetadata(){
  144. var rem = parseInt(this.audio.duration, 10),
  145. mins = Math.floor(rem/60,10),
  146. secs = rem - mins*60;
  147. this.$duration.html('<span>'+(mins<10 ? '0':'')+mins+':'+(secs<10 ? '0':'')+secs+'</span>');
  148. this.updateLoadingBar();
  149. },
  150. updateLoadingBar(){
  151. this.$loader.css({
  152. 'width':parseInt((100 * this.audio.buffered.end(0) / this.audio.duration), 10)+'%'
  153. });
  154. if( this.audio.buffered.end(0) < this.audio.duration ){
  155. // loop through this function until file is fully loaded
  156. var that = this;
  157. window.requestAnimationFrame(that.updateLoadingBar.bind(that));
  158. }else{
  159. console.log('Audio fully loaded');
  160. }
  161. },
  162. onCanplay(){
  163. this.play();
  164. },
  165. play(){
  166. this.audio.play();
  167. },
  168. playPrevious(){
  169. if(this.currentHistoricIndex > 0){
  170. this.currentHistoricIndex -= 1;
  171. this.launch();
  172. }
  173. },
  174. playNext(){
  175. if(this.currentHistoricIndex < this.historic.length-1){
  176. this.currentHistoricIndex += 1;
  177. this.launch();
  178. }else{
  179. this.emmit('audio-play-next');
  180. }
  181. },
  182. togglePlayPause(e){
  183. if(this.audio.paused){
  184. this.audio.play();
  185. }else{
  186. this.audio.pause();
  187. }
  188. },
  189. stop(){
  190. this.audio.pause();
  191. this.timeOutToHide();
  192. },
  193. // audio events
  194. onPlaying(){
  195. this.$container.addClass('is-playing');
  196. },
  197. onPause(){
  198. this.$container.removeClass('is-playing');
  199. },
  200. onTimeupdate(){
  201. // move cursor
  202. this.$cursor.css({
  203. 'left':(this.audio.currentTime/this.audio.duration * this.timeline_w)+"px"
  204. });
  205. // update time text display
  206. var rem = parseInt(this.audio.currentTime, 10),
  207. mins = Math.floor(rem/60,10),
  208. secs = rem - mins*60;
  209. this.$currentTime.html('<span>'+(mins<10 ? '0':'')+mins+':'+(secs<10 ? '0':'')+secs+'</span>');
  210. },
  211. onEnded(){
  212. this.emmit('audio-ended');
  213. this.stop();
  214. },
  215. // cartel functions
  216. loadNode(nid){
  217. this.$cartel.addClass('loading');
  218. $.getJSON('/edlp/ajax/json/node/'+nid+'/player_cartel', {})
  219. .done(this.onNodeLoaded.bind(this))
  220. .fail(this.onNodeLoadFail.bind(this));
  221. },
  222. onNodeLoaded(data){
  223. console.log('AudioPlayer node loaded', data);
  224. this.$cartel.html(data.rendered).removeClass('loading');
  225. _$body.trigger({'type':'new-audio-cartel-loaded'});
  226. initAjaxLinks();
  227. },
  228. onNodeLoadFail(jqxhr, textStatus, error){
  229. console.warn('AudioPlayer node load failed', jqxhr.responseText);
  230. this.$cartel.removeClass('loading').html('');
  231. },
  232. // global
  233. show(){
  234. this.$container.addClass('visible');
  235. },
  236. showHidePreviousBtn(){
  237. if(this.historic.length > 1 && this.currentHistoricIndex > 0){
  238. this.$previous.addClass('is-active');
  239. }else{
  240. this.$previous.removeClass('is-active');
  241. }
  242. },
  243. showHideNextBtn(){
  244. if(this.currentHistoricIndex < this.historic.length-1 || this.shuffle_is_active){
  245. this.$next.addClass('is-active');
  246. }else{
  247. this.$next.removeClass('is-active');
  248. }
  249. },
  250. timeOutToHide(){
  251. this.clearTimeOutToHide();
  252. this.hideTimer = setTimeout(this.hide.bind(this), this.hideTimeMS);
  253. },
  254. clearTimeOutToHide(){
  255. if(this.hideTimer){
  256. clearTimeout(this.hideTimer);
  257. }
  258. },
  259. hide(){
  260. this.$container.removeClass('visible');
  261. // trigger highlighted node remove on corpus map
  262. _$corpus_canvas.trigger('audio-node-closed');
  263. },
  264. // object events
  265. on(event_name, handler){
  266. if(typeof this.event_handlers[event_name] == 'undefined'){
  267. console.warn('AudioPlayer : event '+event_name+' does not exists');
  268. }
  269. this.event_handlers[event_name].push(handler);
  270. return this;
  271. },
  272. emmit(event_name){
  273. var handler;
  274. for (var i = this.event_handlers[event_name].length; i >= 0 ; i--) {
  275. handler = this.event_handlers[event_name][i];
  276. setTimeout(handler, 0);
  277. }
  278. },
  279. }
  280. // ___ _ _ ___
  281. // / __| __ _ _ ___| | | _ ) __ _ _ _ ___
  282. // \__ \/ _| '_/ _ \ | | _ \/ _` | '_(_-<
  283. // |___/\__|_| \___/_|_|___/\__,_|_| /__/
  284. function initScrollbars(){
  285. // console.log("initScrollbars");
  286. // TODO: find a better js scroll than overlayScrollbars which does not handle well max-height + overflow-y:auto;
  287. // $('.os-scroll').overlayScrollbars({
  288. // overflowBehavior:{
  289. // x:'h',
  290. // y:'scroll',
  291. // clipAlways:false
  292. // }
  293. // });
  294. };
  295. // _ _
  296. // /_\ (_)__ ___ __
  297. // / _ \ | / _` \ \ /
  298. // /_/ \_\/ \__,_/_\_\
  299. // |__/
  300. // TODO: add url hash nav
  301. // TODO: implement history.js
  302. function initAjaxLinks(){
  303. console.log('initAjaxLinks');
  304. $('a', '#block-mainnavigation')
  305. .add('a', '#block-footer.menu--footer')
  306. .add('a', '#block-productions')
  307. .add('a', 'article.node:not(.node--type-enregistrement) h2.node-title')
  308. .add('a', '.productions-subtree')
  309. .add('a', '.productions-parent')
  310. // .add('a.index-link, a.notice-link', '#block-edlpentreesblock')
  311. .addClass('ajax-link');
  312. _$ajaxLinks = $('.ajax-link:not(.ajax-enabled)')
  313. .each(function(i,e){
  314. var $this = $(this);
  315. // avoid already ajaxified links
  316. if($this.is('.ajax-enable')) return;
  317. if($this.attr('data-drupal-link-system-path')){
  318. $this.on('click', onClickAjaxLink).addClass('ajax-enable');
  319. }
  320. });
  321. };
  322. function onClickAjaxLink(e){
  323. e.preventDefault();
  324. var $link = $(this);
  325. if($link.is('.is-active'))
  326. return false;
  327. // Audio links
  328. if($link.is('.audio-link')){
  329. _audio_player.openDocument({
  330. nid:$link.attr('nid'),
  331. audio_url:$link.attr('audio_url')
  332. });
  333. return false;
  334. }
  335. // other links
  336. var sys_path = $(this).attr('data-drupal-link-system-path');
  337. var ajax_path = sys_path;
  338. if(sys_path == '<front>'){
  339. backToFrontPage();
  340. return false;
  341. }
  342. // convert node link to edlp_ajax_node module links
  343. var node_match = ajax_path.match(/^\/?(node\/\d+)$/g);
  344. var term_match = ajax_path.match(/^\/?(taxonomy\/term\/\d+)$/g);
  345. if(node_match){
  346. ajax_path = 'edlp/ajax/json/'+node_match[0];
  347. // check for viewmode attribute
  348. if($link.attr('viewmode')){
  349. ajax_path += '/'+$link.attr('viewmode');
  350. }
  351. }else if(term_match){
  352. ajax_path = 'edlp/ajax/json/'+term_match[0];
  353. ajax_path = ajax_path.replace(/taxonomy\/term/, 'taxonomy_term');
  354. // check for viewmode attribute
  355. if($link.attr('viewmode')){
  356. ajax_path += '/'+$link.attr('viewmode');
  357. }
  358. }else{
  359. // convert other link to ajax
  360. ajax_path += '/ajax'
  361. }
  362. _$body.addClass('ajax-loading');
  363. $link.addClass('ajax-loading');
  364. // TODO: use Drupal.url()
  365. // Drupal.url = function (path) {
  366. // return drupalSettings.path.baseUrl + drupalSettings.path.pathPrefix + path;
  367. // };
  368. var path = window.location.origin + drupalSettings.path.baseUrl + ajax_path;
  369. $.getJSON(path, {})
  370. .done(function(data){
  371. onAjaxLinkLoaded(data, $link, sys_path);
  372. })
  373. .fail(function(jqxhr, textStatus, error){
  374. onAjaxLinkLoadError(jqxhr, textStatus, error, $link, sys_path);
  375. });
  376. return false;
  377. };
  378. function onAjaxLinkLoadError(jqxhr, textStatus, error, $link, sys_path){
  379. console.warn('ajaxlink load failed for '+sys_path+' : '+error, jqxhr.responseText);
  380. $link.removeClass('ajax-loading');
  381. _$body.removeClass('ajax-loading');
  382. };
  383. function onAjaxLinkLoaded(data, $link, sys_path){
  384. console.log('ajax link loaded : data', data);
  385. _$body.removeClass('ajax-loading');
  386. // replace all content with newly loaded
  387. // TODO: build a system to replace or append contents (like studio + search)
  388. _$row.html(data.rendered);
  389. // add body class for currently loaded content
  390. var body_classes = [
  391. 'path-'+sys_path.replace(/\//g, '-'),
  392. 'entity-type-'+data.entity_type,
  393. 'bundle-'+data.bundle,
  394. 'view-mode-'+data.view_mode
  395. ];
  396. _$body.removeClass().addClass(body_classes.join(' '));
  397. // id node add a generic path-node class to body
  398. m = sys_path.match(/^\/?(node\/\d+)$/g);
  399. if(m)
  400. _$body.addClass('path-edlp-node');
  401. // handle clicked link classes
  402. _$ajaxLinks.removeClass('is-active');
  403. $link.removeClass('ajax-loading').addClass('is-active');
  404. // if block attached (eg : from edlp_productions module)
  405. if(typeof data.block != 'undefined'){
  406. // if block not already added
  407. if(!$('#'+data.block.id, '.region-'+data.block.region).length){
  408. $('.region-'+data.block.region).append(data.block.rendered);
  409. }
  410. }
  411. initScrollbars();
  412. if(sys_path == "productions")
  413. initProductions();
  414. initAjaxLinks();
  415. _$body.trigger({'type':'new-content-ajax-loaded'});
  416. // TODO: call behaviours
  417. Drupal.attachBehaviors(_$row[0]);
  418. };
  419. // ___
  420. // / __|___ _ _ _ __ _ _ ___
  421. // | (__/ _ \ '_| '_ \ || (_-<
  422. // \___\___/_| | .__/\_,_/__/
  423. // |_|
  424. function onCorpusMapReady(e){
  425. console.log('theme : onCorpusReady', e);
  426. _$corpus_canvas = $('canvas#corpus-map');
  427. _$corpus_canvas
  428. .on('corpus-cliked-on-map', function(e) {
  429. console.log('theme : corpus-cliked-on-map');
  430. backToFrontPage();
  431. })
  432. .on('corpus-cliked-on-node', function(e) {
  433. console.log('theme : corpus-cliked-on-node', e);
  434. _audio_player.openDocument(e.target_node);
  435. });
  436. _randomPlayer = new RandomPlayer(e.playlist);
  437. _$body.attr('corpus-map', 'ready');
  438. }
  439. // ___ _ ___ _
  440. // | _ \__ _ _ _ __| |___ _ __ | _ \ |__ _ _ _ ___ _ _
  441. // | / _` | ' \/ _` / _ \ ' \| _/ / _` | || / -_) '_|
  442. // |_|_\__,_|_||_\__,_\___/_|_|_|_| |_\__,_|\_, \___|_|
  443. // |__/
  444. function RandomPlayer(playlist){
  445. this.active = false;
  446. this.playlist = playlist;
  447. this.$btn = $('<a>').html('Shuffle').addClass('random-player-btn');
  448. this.init()
  449. };
  450. RandomPlayer.prototype = {
  451. init(){
  452. // this.shuffle();
  453. $('<div>')
  454. .addClass('block random-player')
  455. .append(this.$btn)
  456. .insertAfter('#block-userlogin, #block-studiolinkblock');
  457. // events
  458. this.$btn.on('click', this.toggleActive.bind(this));
  459. // attach an event on AudioPlayer
  460. _audio_player
  461. .on('audio-ended', this.onAudioPlayerEnded.bind(this))
  462. .on('audio-play-next', this.onAudioPlayNext.bind(this));
  463. },
  464. shuffle(){
  465. var tempPLaylist = [];
  466. for (var i = this.playlist.length-1; i >= 0 ; i--) {
  467. tempPLaylist.push(this.playlist[i]);
  468. }
  469. this.shuffledPlaylist = [];
  470. while(tempPLaylist.length > 0){
  471. var r = Math.floor(Math.random() * tempPLaylist.length);
  472. this.shuffledPlaylist.push(tempPLaylist.splice(r,1)[0]);
  473. }
  474. console.log('RandomPlayer, this.shuffledPlaylist', this.shuffledPlaylist);
  475. },
  476. toggleActive(e){
  477. if (this.active) {
  478. this.$btn.removeClass('is-active');
  479. this.stop();
  480. }else{
  481. this.$btn.addClass('is-active');
  482. this.shuffle();
  483. this.start();
  484. }
  485. },
  486. start(){
  487. this.active = _audio_player.shuffle_is_active = true;
  488. this.next();
  489. },
  490. stop(){
  491. this.active = _audio_player.shuffle_is_active = false;
  492. // stop audio player
  493. _audio_player.stop();
  494. },
  495. next(){
  496. if(this.active && this.shuffledPlaylist.length > 0)
  497. _audio_player.openDocument(this.shuffledPlaylist.splice(0,1)[0]);
  498. },
  499. onAudioPlayNext(){
  500. console.log('RandomPlayer : onAudioPlayNext()');
  501. this.next();
  502. },
  503. onAudioPlayerEnded(){
  504. console.log('RandomPlayer : onAudioPlayerEnded()');
  505. this.next();
  506. }
  507. };
  508. // ___ _ _ _
  509. // | _ \_ _ ___ __| |_ _ __| |_(_)___ _ _ ___
  510. // | _/ '_/ _ \/ _` | || / _| _| / _ \ ' \(_-<
  511. // |_| |_| \___/\__,_|\_,_\__|\__|_\___/_||_/__/
  512. function initProductions(){
  513. console.log('theme : initProductions');
  514. var $grid = $('.row', _$row).masonry({
  515. itemSelector:'.col',
  516. columnWidth:'.col-2'
  517. });
  518. // layout Masonry after each image loads
  519. $grid.imagesLoaded().progress( function() {
  520. $grid.masonry('layout');
  521. });
  522. // var $grid = $('.row', _$row).imagesLoaded( function() {
  523. // // init Masonry after all images have loaded
  524. // $grid.masonry({
  525. // itemSelector:'.col',
  526. // columnWidth:'.col-2'
  527. // });
  528. // });
  529. };
  530. // ___ _ ___
  531. // | __| _ ___ _ _| |_| _ \__ _ __ _ ___
  532. // | _| '_/ _ \ ' \ _| _/ _` / _` / -_)
  533. // |_||_| \___/_||_\__|_| \__,_\__, \___|
  534. // |___/
  535. function backToFrontPage(){
  536. closeAllModals();
  537. // assume we are going back to front page
  538. $('body').removeClass().addClass('path-frontpage');
  539. $('a[data-drupal-link-system-path="<front>"]').addClass('is-active');
  540. }
  541. // __ __ _ _
  542. // | \/ |___ __| |__ _| |___
  543. // | |\/| / _ \/ _` / _` | (_-<
  544. // |_| |_\___/\__,_\__,_|_/__/
  545. function closeAllModals(){
  546. console.log('theme : closeAllModals');
  547. // TODO: animate the remove
  548. _$row.html('');
  549. _$ajaxLinks.removeClass('is-active');
  550. };
  551. init();
  552. } // end EdlpTheme()
  553. $(document).ready(function($) {
  554. var edlptheme = new EdlpTheme();
  555. });
  556. })(jQuery, Drupal, drupalSettings);