main.js 19 KB

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