main.js 20 KB

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