main.js 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667
  1. (function($, Drupal, drupalSettings) {
  2. EdlpTheme = function(){
  3. var _ajax_settings = drupalSettings.edlp_ajax;
  4. var _$body = $('body');
  5. // var _is_front = drupalSettings.path.isFront;
  6. var _corpus_ready = false;
  7. var _$corpus_canvas;
  8. var _$row = $('main[role="main"]>.layout-content>.row');
  9. var _$ajaxLinks;
  10. var _audioPlayer;
  11. var _randomPlayer;
  12. var _compoPlayer;
  13. var _ajax_timing = {
  14. start:0,
  15. end:0
  16. };
  17. var _corpus_promise;
  18. // ___ _ _
  19. // |_ _|_ _ (_) |_
  20. // | || ' \| | _|
  21. // |___|_||_|_|\__|
  22. function init(){
  23. console.log("EdlpTheme init()");
  24. if(!drupalSettings.path.isFront)
  25. return;
  26. initEvents();
  27. _audioPlayer = new AudioPlayer();
  28. _compoPlayer = new CompoPlayer();
  29. checkLayout();
  30. initAjaxLinks();
  31. initHistory();
  32. // if(!drupalSettings.path.isFront)
  33. // return;
  34. //
  35. // initEvents();
  36. };
  37. // ___ _
  38. // | __|_ _____ _ _| |_ ___
  39. // | _|\ V / -_) ' \ _(_-<
  40. // |___|\_/\___|_||_\__/__/
  41. function initEvents(){
  42. // https://www.html5rocks.com/en/tutorials/async/deferred/
  43. var $corpus_df = $.Deferred();
  44. _corpus_promise = $corpus_df.promise();
  45. _$body
  46. .on('corpus-map-ready', function(e){
  47. onCorpusMapReady(e);
  48. $corpus_df.resolve();
  49. })
  50. .on('on-studio-chutier-updated', initAjaxLinks)
  51. .on('studio-initialized', function(e){
  52. _compoPlayer.newCompo();
  53. })
  54. .on('studio-not-active', function(e){
  55. _compoPlayer.deactivate();
  56. })
  57. .on('on-studio-compo-updated', function(e){
  58. initAjaxLinks();
  59. _compoPlayer.refresh();
  60. })
  61. .on('on-studio-compo-opened', function(e){
  62. initAjaxLinks();
  63. _compoPlayer.newCompo();
  64. })
  65. .on('search-results-loaded', initAjaxLinks)
  66. // do not close index or notice modale on entree click
  67. .on('open_entree', function(e){
  68. console.log('on_open_entree : e', e);
  69. closeAllModals();
  70. checkLayout();
  71. // add body class for currently loaded content
  72. // var body_classes = [
  73. // 'path-'+sys_path.replace(/\//g, '-'),
  74. // 'entity-type-'+data.entity_type,
  75. // 'bundle-'+data.bundle,
  76. // 'view-mode-'+data.view_mode
  77. // ];
  78. _$body.removeClass();//.addClass(body_classes.join(' '));
  79. // record new history state
  80. if(typeof e.url != 'undefined'){
  81. var state = getSysPathState(e.sys_path);
  82. history.pushState(state, null, e.url);
  83. // piwik
  84. if(typeof _paq !== 'undefined'){
  85. // page tracking
  86. // https://matomo.org/blog/2017/02/how-to-track-single-page-websites-using-piwik-analytics/
  87. _paq.push(['setCustomUrl', e.url]);
  88. _paq.push(['setDocumentTitle', e.title]);
  89. _paq.push(['trackPageView']);
  90. }
  91. }
  92. })
  93. .on('close_entree', function(e){
  94. backToFrontPage();
  95. checkLayout();
  96. });
  97. window.addEventListener('resize', checkLayout, false);
  98. }
  99. // __ ___ _ ___ _
  100. // \ \ / (_)_ _ __| |_____ __ __ | _ \___ __(_)______
  101. // \ \/\/ /| | ' \/ _` / _ \ V V / | / -_|_-< |_ / -_)
  102. // \_/\_/ |_|_||_\__,_\___/\_/\_/ |_|_\___/__/_/__\___|
  103. function checkLayout(){
  104. var $audioplayer = $("#audio-player");
  105. if($audioplayer.length){
  106. var navpos = $('#block-mainnavigation').position();
  107. console.log('navpos', navpos);
  108. $audioplayer.css({
  109. 'width':navpos.left+'px'
  110. });
  111. }
  112. // entrees
  113. // TODO: center the entrees menu
  114. };
  115. // ___ _ _ ___
  116. // / __| __ _ _ ___| | | _ ) __ _ _ _ ___
  117. // \__ \/ _| '_/ _ \ | | _ \/ _` | '_(_-<
  118. // |___/\__|_| \___/_|_|___/\__,_|_| /__/
  119. function initScrollbars(){
  120. // console.log("initScrollbars");
  121. // TODO: find a better js scroll than overlayScrollbars which does not handle well max-height + overflow-y:auto;
  122. // $('.os-scroll').overlayScrollbars({
  123. // overflowBehavior:{
  124. // x:'h',
  125. // y:'scroll',
  126. // clipAlways:false
  127. // }
  128. // });
  129. };
  130. // _ _
  131. // /_\ (_)__ ___ __
  132. // / _ \ | / _` \ \ /
  133. // /_/ \_\/ \__,_/_\_\
  134. // |__/
  135. function getSysPathState(sys_path, view_mode){
  136. // console.log('Theme : getSysPathState', sys_path);
  137. var state = {
  138. 'sys_path':sys_path,
  139. 'ajax_path': sys_path
  140. };
  141. // convert node link to edlp_ajax_node module links
  142. var node_match = state.ajax_path.match(/^\/?(node\/(\d+))$/i);
  143. console.log('node_match', node_match);
  144. var term_match = state.ajax_path.match(/^\/?(taxonomy\/term\/(\d+))$/i);
  145. console.log('term_match', term_match);
  146. if(node_match){
  147. // TODO: detect audio links which will open audioplayer and wont load any ajax content unless view_mode "article" or "transcript"
  148. state.ajax_path = _ajax_settings.entityjson_path+'/'+node_match[1];
  149. state.node_nid = node_match[2];
  150. // check for viewmode attribute
  151. if(view_mode){
  152. state.ajax_path += '/'+view_mode;
  153. state.view_mode = view_mode;
  154. }
  155. }else if(term_match){
  156. // terms are always entrees, there's no other vocabulary links in front
  157. state.ajax_path = _ajax_settings.entityjson_path+'/'+term_match[1];
  158. state.ajax_path = state.ajax_path.replace(/taxonomy\/term/, 'taxonomy_term');
  159. state.entree_tid = term_match[2];
  160. // check for viewmode attribute
  161. if(view_mode){
  162. state.ajax_path += '/'+view_mode;
  163. state.view_mode = view_mode;
  164. }else{
  165. state.ajax_path = null;
  166. }
  167. }else{
  168. // convert other link to ajax
  169. // TODO: we assume that other links (no node, no term) are all from own modules (e.g. productions) !! may not be true !!
  170. state.ajax_path += '/ajax'
  171. }
  172. return state;
  173. };
  174. function ajaxLoadContent(state){
  175. console.log('ajaxLoadContent : state', state);
  176. _$body.addClass('ajax-loading');
  177. _ajax_timing.start = performance.now();
  178. var path = window.location.origin + Drupal.url(state.ajax_path);
  179. $.getJSON(path, {})
  180. .done(function(data){
  181. onAjaxLoaded(data, state);
  182. })
  183. .fail(function(jqxhr, textStatus, error){
  184. onAjaxLoadError(jqxhr, textStatus, error, state.sys_path);
  185. });
  186. };
  187. function onAjaxLoadError(jqxhr, textStatus, error, sys_path){
  188. console.warn('ajaxlink load failed for '+sys_path+' : '+error, jqxhr.responseText);
  189. $('.ajax-loading').removeClass('ajax-loading');
  190. _$body.removeClass('ajax-loading');
  191. };
  192. function onAjaxLoaded(data, state){
  193. console.log('ajax loaded : state', state);
  194. // console.log(data);
  195. // reset all style may been added by other pages (like masonry for productions)
  196. // and replace all content with newly loaded
  197. // TODO: build a system to replace or append contents (like studio + search)
  198. if(data.entity_type == "node" && data.bundle == "evenement"){
  199. if(_$row.find('.col.event').length){
  200. _$row.find('.col.event').replaceWith(data.rendered);
  201. }else if(_$row.find('.col.aside').length){
  202. _$row.find('.col.aside').replaceWith(data.rendered);
  203. }else{
  204. _$row.append(data.rendered);
  205. }
  206. }else{
  207. _$row.removeAttr('style').html(data.rendered);
  208. }
  209. // add body class for currently loaded content
  210. var body_classes = [
  211. 'path-'+state.sys_path.replace(/\//g, '-'),
  212. 'entity-type-'+data.entity_type,
  213. 'bundle-'+data.bundle,
  214. 'view-mode-'+data.view_mode
  215. ];
  216. _$body.removeClass().addClass(body_classes.join(' '));
  217. // id node add a generic path-node class to body
  218. // m = state.sys_path.match(/^\/?(node\/\d+)$/g);
  219. // if(m)
  220. if(state.node_nid)
  221. _$body.addClass('path-edlp-node');
  222. // handle clicked link classes
  223. $('.ajax-loading').removeClass('ajax-loading');
  224. $('.ajax-link.is-active').removeClass('is-active');
  225. $('.is-active-trail').removeClass('is-active-trail');
  226. if(typeof state.selector != 'undefined'){
  227. // in case of entree link (actualy, selector is used only for entries links)
  228. // TODO: unfortunatly on initFirstLoad there is no selector property
  229. console.log('selector', state.selector);
  230. $('a[selector="'+state.selector+'"]').addClass('is-active');
  231. initAudioLinksInContent();
  232. }else{
  233. if(typeof state.view_mode != 'undefined'){
  234. $('a[viewmode="'+state.view_mode+'"][data-drupal-link-system-path="'+state.sys_path+'"]').addClass('is-active');
  235. }else{
  236. $('a[data-drupal-link-system-path="'+state.sys_path+'"]').addClass('is-active');
  237. }
  238. // as new content is not related to entree, we trigger close entree
  239. _$body.trigger({'type':'new-content-not-entree-ajax-loaded'});
  240. }
  241. // if bundle page (productions) activate production links
  242. if (typeof data.bundle != 'undefined' && data.bundle == "page") {
  243. $('a[data-drupal-link-system-path="productions"]').addClass('is-active-trail');
  244. }
  245. // if node is in production menu tree, set first level of tree active, e.g. pieces sonores
  246. if (typeof data.menu_parents != 'undefined') {
  247. for (var i = 0; i < data.menu_parents.length; i++) {
  248. var menu_sys_path = data.menu_parents[i];
  249. $('a[data-drupal-link-system-path="'+menu_sys_path+'"]').addClass('is-active-trail');
  250. }
  251. }
  252. // if entity has corpus-map's linked document call a filter to corpus map
  253. if(typeof data.documents_lies != 'undefined'){
  254. if(_corpus_ready){
  255. _$body.trigger({
  256. type:'ajax-node-loaded-linked-documents',
  257. nids:data.documents_lies
  258. });
  259. }else{
  260. _corpus_promise.done(function(){
  261. _$body.trigger({
  262. type:'ajax-node-loaded-linked-documents',
  263. nids:data.documents_lies
  264. });
  265. });
  266. }
  267. }
  268. // if block attached (eg : from edlp_productions module)
  269. // not used anymore as production block is always present (but not visible)
  270. if(typeof data.block != 'undefined'){
  271. // if block not already added
  272. if(!$('#'+data.block.id, '.region-'+data.block.region).length){
  273. $('.region-'+data.block.region).append(data.block.rendered);
  274. }
  275. }
  276. // initScrollbars();
  277. if(state.sys_path == "productions"){
  278. initProductions();
  279. }else{
  280. addCloseModalBtnToCols();
  281. }
  282. // enregistrement transcription
  283. if(data.entity_type == "node" && data.bundle == "enregistrement" && data.view_mode == "transcript"){
  284. // window.requestAnimationFrame(initEnregistrementTranscript);
  285. initEnregistrementTranscript();
  286. }
  287. if(state.sys_path == "search"){
  288. initSearch();
  289. }
  290. // update the language switcher block if it comes in the response
  291. if(typeof data.translations_links != 'undefined'){
  292. console.log('state',state);
  293. var lang_code = drupalSettings.path.currentLanguage;
  294. var $links = $(data.translations_links);
  295. // set active link
  296. $links.find('li[hreflang="'+lang_code+'"]').addClass('is-active').find('a').addClass('is-active');
  297. if(state.view_mode){
  298. $links.find('a').each(function(i,e){
  299. var $a = $(this);
  300. $a.attr('href', $a.attr('href')+'#'+state.view_mode);
  301. });
  302. }
  303. // if(state.selector){
  304. // $links.find('a').attr('selector', state.selector);
  305. // }
  306. $('ul','.block.language-switcher-language-url').replaceWith($links);
  307. }
  308. initAjaxLinks();
  309. checkVisibleCorpusMapSpace();
  310. // trigger other modules behaviours
  311. _$body.trigger({'type':'new-content-ajax-loaded'});
  312. // and call druapl behaviours
  313. Drupal.attachBehaviors(_$row[0]);
  314. _$body.attr('booted', 'booted');
  315. _$body.removeClass('ajax-loading');
  316. // url is null means that we are loading content on popState event
  317. // so we don't record the state again
  318. if(state.url){
  319. // var state = {
  320. // ajax_path:ajax_path,
  321. // sys_path:sys_path,
  322. // };
  323. // console.log('url:'+url+' ; state',state);
  324. // console.log(window.location);
  325. // /!\ we can not pushestate with absolute url /!\
  326. history.pushState(state, null, state.url);
  327. // piwik
  328. if(typeof _paq !== 'undefined'){
  329. // page tracking
  330. // https://matomo.org/blog/2017/02/how-to-track-single-page-websites-using-piwik-analytics/
  331. _paq.push(['setCustomUrl', state.url]);
  332. _paq.push(['setDocumentTitle', data.title]);
  333. // TODO: piwik track load time
  334. _ajax_timing.end = performance.now();
  335. _paq.push(['setGenerationTimeMs', _ajax_timing.end-_ajax_timing.start]);
  336. _paq.push(['trackPageView']);
  337. // js event
  338. // trackEvent(category, action, [name], [value])
  339. // _paq.push(['trackEvent', 'AjaxNav', 'loaded', state.url]);
  340. }
  341. }
  342. };
  343. function initAudioLinksInContent(){
  344. _$row.find('a.audio-link')
  345. .on('mouseover', function(event) {
  346. event.preventDefault();
  347. if(_corpus_ready){
  348. _$corpus_canvas.trigger({
  349. type:'mouseover-audio-link',
  350. nid:$(this).attr('nid')
  351. });
  352. }
  353. })
  354. .on('mouseout', function(event) {
  355. event.preventDefault();
  356. if(_corpus_ready){
  357. _$corpus_canvas.trigger({
  358. type:'mouseout-audio-link',
  359. nid:$(this).attr('nid')
  360. });
  361. }
  362. });
  363. };
  364. function addCloseModalBtnToCols(){
  365. $('.col', _$row).each(function(index, el) {
  366. if($('span.close-col-btn', this).length)
  367. return true;
  368. $(this).children('.wrapper').prepend($('<span>')
  369. .addClass('close-col-btn')
  370. .on('click', onCloseModal)
  371. );
  372. });
  373. };
  374. function onCloseModal(e){
  375. // check for theme attribute and emmit event
  376. var $col = $(this).parents('.col');
  377. var theme = $col.attr('theme');
  378. if(theme != ''){
  379. _$body.trigger({'type':theme+'-col-closed'});
  380. }
  381. if(_$body.is('.entity-type-node.bundle-page')){
  382. // remove all the col (prod page and agenda in case)
  383. $col.add($col.siblings('.col')).remove();
  384. }else{
  385. // remove the col
  386. $col.remove();
  387. }
  388. checkRowEmpty();
  389. checkVisibleCorpusMapSpace();
  390. };
  391. // _ _ ___ _ _
  392. // /_\ (_)__ ___ __ | _ ) |___ __| |__ ___
  393. // / _ \ | / _` \ \ / | _ \ / _ \/ _| / /(_-<
  394. // /_/ \_\/ \__,_/_\_\ |___/_\___/\__|_\_\/__/
  395. // |__/
  396. // NOT USED (YET)
  397. // function refreshAllBlocks(){
  398. // var path = window.location.origin + Drupal.url(_ajax_settings.blocksjson_path);
  399. // $.getJSON(path, {})
  400. // .done(function(data){
  401. // onAjaxBlockLoaded(data);
  402. // })
  403. // .fail(function(jqxhr, textStatus, error){
  404. // onAjaxBlockLoadError(jqxhr, textStatus, error);
  405. // });
  406. // };
  407. // function onAjaxBlockLoadError(jqxhr, textStatus, error){
  408. // console.warn('ajax block load failed: '+error, jqxhr.responseText);
  409. // };
  410. // function onAjaxBlockLoaded(data){
  411. // console.log('onAjaxBlockLoaded', data);
  412. // // TODO: update each blocks (exepted language switcher)
  413. // for (var blockname in data.blocks) {
  414. // var block = data.blocks[blockname];
  415. // console.log(blockname, block);
  416. // $(block.id).replaceWith(block.rendered);
  417. // }
  418. // };
  419. // _ _ _ _
  420. // | || (_)__| |_ ___ _ _ _ _
  421. // | __ | (_-< _/ _ \ '_| || |
  422. // |_||_|_/__/\__\___/_| \_, |
  423. // |__/
  424. function initHistory(){
  425. initFirstLoad();
  426. window.addEventListener('popstate', onHistoryPopState);
  427. };
  428. function initFirstLoad(){
  429. console.log('theme : initFirstLoad()');
  430. // var origin_sys_path = window.localStorage.getItem('edlp_origin_path');
  431. var edlp_origin = JSON.parse(window.localStorage.getItem('edlp_origin'));
  432. console.log('edlp_origin', edlp_origin);
  433. if(edlp_origin != null && edlp_origin.sys_path){
  434. // hash is used as viewmode for taxonomy term entrees load (index or notice)
  435. // and for audio contents (article|transcript)
  436. var view_mode = edlp_origin.hash.replace('#', '');
  437. // create history state
  438. var state = getSysPathState(edlp_origin.sys_path, view_mode);
  439. // open entree tray in case of entree index|notice
  440. // (index or notice will be opened with ajaxLoadContent)
  441. // refactorized with new infos from edlp_origin
  442. // if(view_mode){
  443. if(edlp_origin.entity_type == "taxonomy_term"
  444. && edlp_origin.entity_bundle == "entrees"
  445. && view_mode){
  446. // var $link = $('[href="'+edlp_origin.url+'"][viewmode="'+view_mode+'"]');
  447. // var selector = $link.attr('selector') || null;
  448. // record the selector in the state for actions after ajaxContentLoaded
  449. state.selector = 'entree-'+view_mode+'-link-'+edlp_origin.entity_id; // entree-index-link-125
  450. // if(selector){
  451. // in case of entree link (actualy, selector is used only for entries links)
  452. // TODO: use a promise
  453. // TODO: but what if corpus ready before onAjaxLoaded >> use a promise !!
  454. if(_corpus_ready){
  455. _$corpus_canvas.trigger({
  456. type:'open-entree',
  457. // tid:$link.attr('tid')
  458. tid:edlp_origin.entity_id
  459. });
  460. }else{
  461. // else : EdlpCorpus will check when ready if entry item (notice or index) is already .is-active
  462. // .is-active class is added by onAjaxLoaded() (when content is loaded)
  463. // $('li.entree[tid="'+$link.attr('tid')+'"] a.term-link').addClass('is-active');
  464. $('li.entree[tid="'+edlp_origin.entity_id+'"] a.term-link').addClass('is-active');
  465. }
  466. // }
  467. }
  468. // check if audio link
  469. if(edlp_origin.audio_url){
  470. var node = {
  471. nid:edlp_origin.entity_id,
  472. audio_url:edlp_origin.audio_url
  473. };
  474. _audioPlayer.openDocument(node, 'history_first_load');
  475. if(view_mode == ""){
  476. // if audio only record in state
  477. state.audio = true;
  478. state.node = node;
  479. // we don't laod ajax content so we boot the home
  480. _$body.attr('booted', 'booted');
  481. }else{
  482. // ajax load content for audio only if article or transcript
  483. ajaxLoadContent(state);
  484. }
  485. }
  486. // only if not entree path
  487. // only if not audio (without article or transcript) path
  488. else if(state.ajax_path){
  489. // load content through ajax
  490. // ajaxLoadContent(null, state.sys_path, state.ajax_path, selector);
  491. ajaxLoadContent(state);
  492. }
  493. if(state.entree_tid){
  494. openEntree(state.entree_tid);
  495. }
  496. // record history state
  497. history.replaceState(state, null, edlp_origin.url+edlp_origin.hash);
  498. // reset the storage
  499. window.localStorage.removeItem("edlp_origin");
  500. // window.localStorage.removeItem("edlp_origin_url");
  501. }else{
  502. history.replaceState({home:true}, null, window.location.pathname);
  503. _$body.attr('booted', 'booted');
  504. }
  505. };
  506. function onHistoryPopState(e){
  507. console.log('onPopState',e.state);
  508. if(e.state.home){
  509. backToFrontPage(true);
  510. }
  511. else if (e.state.audio) {
  512. _audioPlayer.openDocument(e.state.node, 'popstate', e.state.historic_index);
  513. }
  514. else{
  515. if(e.state.entree_tid){
  516. openEntree(e.state.entree_tid);
  517. }
  518. if(e.state.ajax_path){
  519. e.state.url = null;
  520. // ajaxLoadContent(null, e.state.sys_path, e.state.ajax_path)
  521. ajaxLoadContent(e.state);
  522. }
  523. }
  524. };
  525. // _ _ _ _ _
  526. // /_\ (_)__ ___ _| | (_)_ _ | |__ ___
  527. // / _ \ | / _` \ \ / |__| | ' \| / /(_-<
  528. // /_/ \_\/ \__,_/_\_\____|_|_||_|_\_\/__/
  529. // |__/
  530. function initAjaxLinks(){
  531. // console.log('initAjaxLinks');
  532. $('a.site-name', '#block-edlptheme-branding')
  533. .add('a', '#block-mainnavigation')
  534. // .add('a', '.block.language-switcher-language-url')
  535. .add('a', '#block-footer.menu--footer')
  536. .add('a', '#block-productions')
  537. .add('a', 'article.node:not(.node--type-enregistrement) h2.node-title')
  538. // .add('a', 'article.node--type-evenement.node--view-mode-teaser .field--name-field-page-liee')
  539. .add('a', '.productions-subtree')
  540. .add('a', '.productions-parent')
  541. // .add('a.index-link, a.notice-link', '#block-edlpentreesblock')
  542. .add('a', '.field--name-field-son')
  543. .addClass('ajax-link');
  544. $('a[data-drupal-link-system-path="<front>"]', '#block-mainnavigation').removeClass('is-active');
  545. _$ajaxLinks = $('.ajax-link:not(.ajax-enabled)')
  546. .each(function(i,e){
  547. var $this = $(this);
  548. // avoid already ajaxified links
  549. if($this.is('.ajax-enable')) return;
  550. if($this.attr('data-drupal-link-system-path') || $this.is('[type^="audio"]')){
  551. $this.on('click', onClickAjaxLink).addClass('ajax-enable');
  552. }
  553. });
  554. };
  555. function onClickAjaxLink(e){
  556. e.preventDefault();
  557. var $link = $(this);
  558. if($link.is('.is-active'))
  559. return false;
  560. // Audio links
  561. // launch audio player and stop here
  562. if($link.is('.audio-link')){
  563. _audioPlayer
  564. .emmit('stop-shuffle')
  565. .openDocument({
  566. nid:$link.attr('nid'),
  567. audio_url:$link.attr('audio_url'),
  568. title:$link.find('.field--name-title').html()
  569. });
  570. return false;
  571. }
  572. // other sounds playing
  573. if($link.is('[type^="audio"]')){
  574. _audioPlayer
  575. .emmit('stop-shuffle')
  576. .openSound($link.attr('href'), $link.html());
  577. return false;
  578. }
  579. // NOT USED ( YET ? )
  580. // if($link.is('.language-link')){
  581. // TODO: change global site current language
  582. // load all blocks translated (exepted language switcher) ... :/
  583. // refreshAllBlocks();
  584. // TODO: use a promise to initAjaxLinks again after blocks updated
  585. // then let load the content
  586. // }
  587. // other links
  588. var sys_path = $(this).attr('data-drupal-link-system-path');
  589. // front page
  590. // just remove contents and stop here
  591. if(sys_path == '<front>'){
  592. backToFrontPage();
  593. return false;
  594. }
  595. var view_mode = $link.attr('viewmode');
  596. var state = getSysPathState(sys_path, view_mode);
  597. state.url = $(this).attr('href');
  598. if(view_mode){
  599. state.url += "#"+view_mode;
  600. }
  601. if($link.is('[selector]')){
  602. state.selector = $link.attr('selector');
  603. }
  604. $link.addClass('ajax-loading');
  605. // ajaxLoadContent(url, sys_path, state.ajax_path, selector);
  606. ajaxLoadContent(state);
  607. return false;
  608. };
  609. // ___
  610. // / __|___ _ _ _ __ _ _ ___
  611. // | (__/ _ \ '_| '_ \ || (_-<
  612. // \___\___/_| | .__/\_,_/__/
  613. // |_|
  614. function onCorpusMapReady(e){
  615. //console.log('theme : onCorpusReady', e);
  616. _corpus_ready = true;
  617. _$corpus_canvas = $('canvas#corpus-map');
  618. _$corpus_canvas
  619. .on('corpus-cliked-on-map', function(e) {
  620. //console.log('theme : corpus-cliked-on-map');
  621. backToFrontPage();
  622. })
  623. .on('corpus-cliked-on-node', function(e) {
  624. //console.log('theme : corpus-cliked-on-node', e);
  625. _audioPlayer
  626. .emmit('stop-shuffle')
  627. .setAutoOpenArticle(e.article)
  628. .openDocument(e.target_node);
  629. });
  630. _randomPlayer = new RandomPlayer(e.playlist);
  631. _$body.attr('corpus-map', 'ready');
  632. }
  633. function openEntree(tid){
  634. if(tid){
  635. closeAllModals();
  636. _$body.removeClass();//.addClass(body_classes.join(' '));
  637. // open entree
  638. if(_corpus_ready){
  639. _$corpus_canvas.trigger({
  640. type:'open-entree',
  641. tid:tid
  642. });
  643. }else{
  644. // else : EdlpCorpus will check when ready if entry item (notice or index) is already .is-active
  645. $('li.entree[tid="'+tid+'"] a.term-link').addClass('is-active');
  646. }
  647. }
  648. };
  649. function checkVisibleCorpusMapSpace(){
  650. var left_limit = 0, right_limit = 0;
  651. _$row.find('.col').each(function(i,e){
  652. var $col = $(this);
  653. var offset = $col.offset();
  654. switch(true){
  655. case $col.is('.float-right'):
  656. right_limit = Math.max(right_limit, Math.abs(offset.left-window.innerWidth));
  657. break;
  658. default:
  659. left_limit = Math.max(left_limit, offset.left+$col.width());
  660. break;
  661. }
  662. });
  663. console.log('checkVisibleCorpusMapSpace left_limit:'+left_limit+" right_limit:"+right_limit);
  664. if(_corpus_ready){
  665. _$body.trigger({
  666. type:'visible-space-changed',
  667. left_limit:left_limit,
  668. right_limit:right_limit
  669. });
  670. }else{
  671. _corpus_promise.done(function(){
  672. _$body.trigger({
  673. type:'visible-space-changed',
  674. left_limit:left_limit,
  675. right_limit:right_limit
  676. });
  677. });
  678. }
  679. };
  680. // _ _ _
  681. // /_\ _ _ __| (_)___
  682. // / _ \ || / _` | / _ \
  683. // /_/ \_\_,_\__,_|_\___/
  684. //
  685. // https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement
  686. // https://docs.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/samples/gg589528%28v%3dvs.85%29
  687. // https://www.binarytides.com/using-html5-audio-element-javascript/
  688. function AudioPlayer(){
  689. var that = this;
  690. this.fid;
  691. this.audio = new Audio();
  692. // audio events
  693. this.audio_events = ["loadedmetadata","playing","pause","timeupdate","ended","error"]; // ,"canplay"
  694. // UI dom objects
  695. this.$container = $('<div id="audio-player">');
  696. // btns
  697. this.$btns = $('<div>').addClass('btns').appendTo(this.$container);
  698. this.$previous = $('<div>').addClass('previous').appendTo(this.$btns);
  699. this.$playpause = $('<div>').addClass('play-pause').appendTo(this.$btns);
  700. this.$next = $('<div>').addClass('next').appendTo(this.$btns);
  701. // timeline
  702. this.$timelinecont= $('<div>').addClass('time-line-container').appendTo(this.$container);
  703. this.$timeline = $('<div>').addClass('time-line').appendTo(this.$timelinecont);
  704. this.$loader = $('<div>').addClass('loader').appendTo(this.$timeline);
  705. this.$cursor = $('<div>').addClass('cursor').appendTo(this.$timeline);
  706. // time
  707. this.$time = $('<div>').addClass('time').appendTo(this.$container);
  708. this.$currentTime = $('<div>').addClass('current-time').html('00:00').appendTo(this.$time);
  709. this.$duration = $('<div>').addClass('duration').html('00:00').appendTo(this.$time);
  710. // favoris
  711. this.$fav = $('<div>').addClass('favoris').appendTo(this.$container);
  712. // cartel
  713. this.$cartel = $('<div>').addClass('cartel').appendTo(this.$container);
  714. // hiding
  715. this.hideTimer = false;
  716. this.hideTimeMS = 15000;
  717. // history
  718. this.currentHistoricIndex = null;
  719. this.historic = [];
  720. this.shuffle_is_active = false;
  721. // artciles
  722. this.auto_open_article = false;
  723. // object events
  724. this.event_handlers = {
  725. 'audio-open-document':[],
  726. 'audio-play':[],
  727. 'audio-pause':[],
  728. 'audio-play-next':[],
  729. 'audio-ended':[],
  730. 'stop-shuffle':[]
  731. };
  732. this.init();
  733. };
  734. AudioPlayer.prototype = {
  735. init(){
  736. this.$container_parent = $('header[role="banner"] .region-header');
  737. // append ui to document
  738. this.$container.appendTo(this.$container_parent);
  739. // record timeline width
  740. this.timeline_w = parseInt(this.$timeline.width());
  741. // init audio events
  742. var fn = '';
  743. for (var i = 0; i < this.audio_events.length; i++) {
  744. fn = this.audio_events[i];
  745. // capitalize first letter of event (only cosmetic :p )
  746. fn = 'on'+fn.charAt(0).toUpperCase()+fn.slice(1);
  747. this.audio.addEventListener(
  748. this.audio_events[i],
  749. this[fn].bind(this),
  750. true);
  751. }
  752. // init btns events
  753. this.$previous.on('click', this.playPrevious.bind(this));
  754. this.$playpause.on('click', this.togglePlayPause.bind(this));
  755. this.$next.on('click', this.playNext.bind(this));
  756. },
  757. openDocument(node, caller, historic_index){
  758. // console.log('AudioPlayer openDocument', node);
  759. if(typeof node == 'undefined'
  760. || typeof node.nid == 'undefined'
  761. || typeof node.audio_url == 'undfined'
  762. || typeof node.document_url == 'undfined'){
  763. console.warn('AudioPlayer openDocument() node is malformed', node);
  764. return false;
  765. }
  766. // if we don't come from history popstate
  767. if(typeof caller == 'undefined' || caller != 'popstate'){
  768. this.historic.push(node);
  769. this.currentHistoricIndex = this.historic.length-1;
  770. // this.shuffle_mode = shuffle_mode || false;
  771. // add the document opening to history to be able to share and play audio from any where
  772. if(caller != "history_first_load"){
  773. var state = {
  774. audio:true,
  775. node:{
  776. nid:node.nid,
  777. audio_url:node.audio_url,
  778. document_url:node.document_url,
  779. title:node.title || null,
  780. },
  781. historic_index : this.currentHistoricIndex,
  782. };
  783. history.pushState(state, null, node.document_url);
  784. }
  785. }else{
  786. // if the call commes from popstate, we update the current position of index
  787. this.currentHistoricIndex = historic_index;
  788. }
  789. // TODO: stop random player if playing from studio
  790. this.emmit('audio-open-document', {caller:caller});
  791. // piwik
  792. // debugger;
  793. if(typeof _paq !== 'undefined'){
  794. // page tracking
  795. // https://matomo.org/blog/2017/02/how-to-track-single-page-websites-using-piwik-analytics/
  796. // _paq.push(['setCustomUrl', state.url]);
  797. // _paq.push(['setDocumentTitle', data.title]);
  798. // _paq.push(['trackPageView']);
  799. // js event
  800. // trackEvent(category, action, [name], [value])
  801. if(typeof node.title != 'undefined'){
  802. _paq.push(['trackEvent', 'Audio', 'play', node.title]);
  803. }
  804. }
  805. this.launch();
  806. },
  807. launch(){
  808. this.clearTimeOutToHide();
  809. this.setSRC(this.historic[this.currentHistoricIndex].audio_url);
  810. this.loadNode(this.historic[this.currentHistoricIndex].nid);
  811. // emmit new playing doc (e.g.: corpus map nowing that audio played from RandomPlayer)
  812. try {
  813. _$corpus_canvas.trigger({
  814. 'type':'audio-node-opened',
  815. 'nid':this.historic[this.currentHistoricIndex].nid
  816. });
  817. } catch (e) {
  818. console.info('AudioPlayer : _$corpus_canvas does not exists');
  819. }
  820. this.showHidePreviousBtn();
  821. this.showHideNextBtn();
  822. this.show();
  823. },
  824. openSound(url, title){
  825. this.hide();
  826. this.clearTimeOutToHide();
  827. this.$cartel.html("");
  828. this.setSRC(url);
  829. this.show();
  830. if(typeof _paq !== 'undefined'){
  831. _paq.push(['trackEvent', 'Audio', 'play', url]);
  832. }
  833. },
  834. // audio functions
  835. setSRC(url){
  836. console.log('AudioPlayer setSRC : url', url);
  837. this.audio.src = url;
  838. // need to trigger play right now to prevent safari blocking auto-play
  839. this.play();
  840. },
  841. onLoadedmetadata(){
  842. var rem = parseInt(this.audio.duration, 10),
  843. mins = Math.floor(rem/60,10),
  844. secs = rem - mins*60;
  845. this.$duration.html('<span>'+(mins<10 ? '0':'')+mins+':'+(secs<10 ? '0':'')+secs+'</span>');
  846. this.updateLoadingBar();
  847. },
  848. updateLoadingBar(){
  849. console.log("updateLoadingBar");
  850. // var that = this;
  851. // if (this.audio.readyState === 4){
  852. if(this.audio.buffered.length>0){
  853. // debugger;
  854. this.$loader.css({
  855. 'width':parseInt((100 * this.audio.buffered.end(0) / this.audio.duration), 10)+'%'
  856. });
  857. if( this.audio.buffered.end(0) < this.audio.duration ){
  858. // loop through this function until file is fully loaded
  859. window.requestAnimationFrame(this.updateLoadingBar.bind(this));
  860. }else{
  861. console.log('Audio fully loaded');
  862. }
  863. }else{
  864. // as audio buffer is not ready, recall updateLoadingBar in next frame
  865. window.requestAnimationFrame(this.updateLoadingBar.bind(this));
  866. }
  867. },
  868. // onCanplay(){
  869. // // this.play();
  870. // },
  871. onError(){
  872. console.warn("Audio Error " + this.audio.error.code + "; details: " + this.audio.error.message);
  873. },
  874. play(){
  875. this.clearTimeOutToHide();
  876. // this.audio.play();
  877. // Not really needed has we trigger play right after setting the source https://stackoverflow.com/questions/47431439/mp4-video-safari-showing-unhandled-promise-rejection-object-domerror-in-c
  878. var promise = this.audio.play();
  879. // console.log('promise', promise);
  880. if (promise !== undefined) {
  881. promise.catch(function(error){
  882. // Auto-play was prevented
  883. // Show a UI element to let the user manually start playback
  884. console.warn('autoplay failed, ask for playing', error);
  885. }).then(function(){
  886. // Auto-play started
  887. console.log('autoplay succeed');
  888. });
  889. }
  890. },
  891. playPrevious(){
  892. if(this.currentHistoricIndex > 0){
  893. this.currentHistoricIndex -= 1;
  894. this.launch();
  895. }
  896. },
  897. playNext(){
  898. if(this.currentHistoricIndex < this.historic.length-1){
  899. this.currentHistoricIndex += 1;
  900. this.launch();
  901. }else{
  902. this.emmit('audio-play-next');
  903. }
  904. },
  905. togglePlayPause(e){
  906. if(this.audio.paused){
  907. this.audio.play();
  908. }else{
  909. this.audio.pause();
  910. }
  911. },
  912. stop(){
  913. // console.log('AudioPlayer stop()');
  914. // debugger;
  915. this.audio.pause();
  916. // don't close player if article or transcript is open
  917. if(!(_$body.is('.path-node-'+this.historic[this.currentHistoricIndex].nid)
  918. && (_$body.is('.view-mode-article') || _$body.is('.view-mode-transcript')))){
  919. this.timeOutToHide();
  920. }
  921. },
  922. // audio events
  923. onPlaying(){
  924. this.$btns.addClass('is-playing');
  925. this.emmit('audio-play');
  926. },
  927. onPause(){
  928. this.$btns.removeClass('is-playing');
  929. this.emmit('audio-pause');
  930. },
  931. onTimeupdate(){
  932. // move cursor
  933. this.$cursor.css({
  934. 'left':(this.audio.currentTime/this.audio.duration * this.timeline_w)+"px"
  935. });
  936. // update time text display
  937. var rem = parseInt(this.audio.currentTime, 10),
  938. mins = Math.floor(rem/60,10),
  939. secs = rem - mins*60;
  940. this.$currentTime.html('<span>'+(mins<10 ? '0':'')+mins+':'+(secs<10 ? '0':'')+secs+'</span>');
  941. },
  942. onEnded(){
  943. console.log('AudioPlayer onEnded()');
  944. this.stop();
  945. this.emmit('audio-ended');
  946. },
  947. // cartel functions
  948. loadNode(nid){
  949. this.$cartel.addClass('loading');
  950. var vm = 'player_cartel';
  951. var ajax_path = _ajax_settings.entityjson_path+'/node/'+nid+'/'+vm;
  952. var path = window.location.origin + Drupal.url(ajax_path);
  953. $.getJSON(path, {})
  954. .done(this.onNodeLoaded.bind(this))
  955. .fail(this.onNodeLoadFail.bind(this));
  956. },
  957. onNodeLoaded(data){
  958. // console.log('AudioPlayer node loaded');
  959. this.$cartel.html(data.rendered).removeClass('loading');
  960. _$body.trigger({'type':'new-audio-cartel-loaded'});
  961. initAjaxLinks();
  962. if(this.auto_open_article){
  963. this.$cartel.find('a.link-article').trigger('click');
  964. this.auto_open_article = false;
  965. }
  966. },
  967. onNodeLoadFail(jqxhr, textStatus, error){
  968. console.warn('AudioPlayer node load failed', jqxhr.responseText);
  969. this.$cartel.removeClass('loading').html('');
  970. },
  971. setAutoOpenArticle(art){
  972. this.auto_open_article = art;
  973. return this;
  974. },
  975. // global
  976. show(){
  977. this.$container_parent.addClass('audio-player-visible');
  978. this.$container.addClass('visible');
  979. },
  980. showHidePreviousBtn(){
  981. if(this.historic.length > 1 && this.currentHistoricIndex > 0){
  982. this.$previous.addClass('is-active');
  983. }else{
  984. this.$previous.removeClass('is-active');
  985. }
  986. },
  987. showHideNextBtn(){
  988. if(this.currentHistoricIndex < this.historic.length-1 || this.shuffle_is_active){
  989. this.$next.addClass('is-active');
  990. }else{
  991. this.$next.removeClass('is-active');
  992. }
  993. },
  994. timeOutToHide(){
  995. // console.log('AudioPlayer timeOutToHide()');
  996. this.clearTimeOutToHide();
  997. this.hideTimer = setTimeout(this.hide.bind(this), this.hideTimeMS);
  998. },
  999. clearTimeOutToHide(){
  1000. // console.log('AudioPlayer clearTimeOutToHide()',this.hideTimer);
  1001. if(this.hideTimer){
  1002. clearTimeout(this.hideTimer);
  1003. this.hideTimer = false;
  1004. }
  1005. },
  1006. hide(){
  1007. // console.log('AudioPlayer hide()');
  1008. this.$container_parent.removeClass('audio-player-visible');
  1009. this.$container.removeClass('visible');
  1010. // trigger highlighted node remove on corpus map
  1011. try {
  1012. _$corpus_canvas.trigger('audio-node-closed');
  1013. } catch (e) {
  1014. console.info('AudioPlayer hide() : _$corpus_canvas does not exists');
  1015. }
  1016. },
  1017. // object events
  1018. on(event_name, handler){
  1019. if(typeof this.event_handlers[event_name] == 'undefined'){
  1020. console.warn('AudioPlayer : event '+event_name+' does not exists');
  1021. }
  1022. this.event_handlers[event_name].push(handler);
  1023. return this;
  1024. },
  1025. emmit(event_name, args){
  1026. console.log('AudioPlayer emmit()', event_name, args, this.event_handlers[event_name]);
  1027. // console.log('AudioPlayer emmit() handlers', this.event_handlers[event_name]);
  1028. var handler;
  1029. var args = args || {};
  1030. for (var i = this.event_handlers[event_name].length-1; i >= 0 ; i--) {
  1031. handler = this.event_handlers[event_name][i];
  1032. // console.log('AudioPlayer emmit() loop handler', handler);
  1033. (function(handler, args){
  1034. setTimeout(function(){
  1035. // console.log('AudioPlayer emmit() timeout handler', handler);
  1036. handler(args);
  1037. }, 0);
  1038. }(handler, args));
  1039. }
  1040. return this;
  1041. },
  1042. }
  1043. // ___ _ ___ _
  1044. // | _ \__ _ _ _ __| |___ _ __ | _ \ |__ _ _ _ ___ _ _
  1045. // | / _` | ' \/ _` / _ \ ' \| _/ / _` | || / -_) '_|
  1046. // |_|_\__,_|_||_\__,_\___/_|_|_|_| |_\__,_|\_, \___|_|
  1047. // |__/
  1048. function RandomPlayer(playlist){
  1049. this.active = false;
  1050. this.playlist = playlist;
  1051. this.$btn = $('<a>').html('Shuffle').addClass('random-player-btn');
  1052. this.init();
  1053. };
  1054. RandomPlayer.prototype = {
  1055. init(){
  1056. // this.shuffle();
  1057. $('<div>')
  1058. .addClass('block random-player')
  1059. .append(this.$btn)
  1060. // .insertAfter('#block-userlogin, #block-studiolinkblock');
  1061. .prependTo('.region-footer-right');
  1062. // events
  1063. this.$btn.on('click', this.toggleActive.bind(this));
  1064. // attach an event on AudioPlayer
  1065. _audioPlayer
  1066. .on('audio-play-next', this.onAudioPlayNext.bind(this))
  1067. .on('audio-ended', this.onAudioPlayerEnded.bind(this))
  1068. // .on('audio-ended', function(e){
  1069. // console.log('RandomPlayer, audio-ended', e);
  1070. // })
  1071. .on('stop-shuffle', this.stop.bind(this));
  1072. _$corpus_canvas
  1073. .on('update-random-playlist', this.updatePlaylist.bind(this));
  1074. },
  1075. updatePlaylist(e){
  1076. // debugger;
  1077. this.playlist = e.playlist;
  1078. this.shuffle();
  1079. },
  1080. shuffle(){
  1081. var tempPLaylist = [];
  1082. for (var i = this.playlist.length-1; i >= 0 ; i--) {
  1083. tempPLaylist.push(this.playlist[i]);
  1084. }
  1085. this.shuffledPlaylist = [];
  1086. while(tempPLaylist.length > 0){
  1087. var r = Math.floor(Math.random() * tempPLaylist.length);
  1088. this.shuffledPlaylist.push(tempPLaylist.splice(r,1)[0]);
  1089. }
  1090. //console.log('RandomPlayer, this.shuffledPlaylist', this.shuffledPlaylist);
  1091. },
  1092. toggleActive(e){
  1093. if (this.active) {
  1094. this.stop();
  1095. }else{
  1096. this.start();
  1097. }
  1098. },
  1099. start(){
  1100. this.active = _audioPlayer.shuffle_is_active = true;
  1101. this.$btn.addClass('is-active');
  1102. this.shuffle();
  1103. this.next();
  1104. // piwik
  1105. if(typeof _paq !== 'undefined'){
  1106. // trackEvent(category, action, [name], [value])
  1107. _paq.push(['trackEvent', 'RandomPlayer', 'start']);
  1108. }
  1109. },
  1110. stop(){
  1111. this.active = _audioPlayer.shuffle_is_active = false;
  1112. this.$btn.removeClass('is-active');
  1113. // stop audio player
  1114. // _audioPlayer.stop();
  1115. if(typeof _paq !== 'undefined'){
  1116. // trackEvent(category, action, [name], [value])
  1117. _paq.push(['trackEvent', 'RandomPlayer', 'stop']);
  1118. }
  1119. },
  1120. next(){
  1121. console.log('RandomPlayer next', this.active, this.shuffledPlaylist.length);
  1122. if(this.active && this.shuffledPlaylist.length > 0)
  1123. _audioPlayer.openDocument(this.shuffledPlaylist.splice(0,1)[0]);
  1124. },
  1125. onAudioPlayNext(){
  1126. console.log('RandomPlayer : onAudioPlayNext()');
  1127. if(this.active){
  1128. this.next();
  1129. }
  1130. },
  1131. onAudioPlayerEnded(){
  1132. console.log('RandomPlayer : onAudioPlayerEnded()');
  1133. if(this.active){
  1134. this.next();
  1135. }
  1136. }
  1137. };
  1138. // ___ ___ _
  1139. // / __|___ _ __ _ __ ___| _ \ |__ _ _ _ ___ _ _
  1140. // | (__/ _ \ ' \| '_ \/ _ \ _/ / _` | || / -_) '_|
  1141. // \___\___/_|_|_| .__/\___/_| |_\__,_|\_, \___|_|
  1142. // |_| |__/
  1143. function CompoPlayer(){
  1144. this.active = false;
  1145. this.playing = false;
  1146. this.paused = false;
  1147. this.playlist = [];
  1148. this.current_index = 0;
  1149. this.$composer = null;
  1150. this.$compo = null;
  1151. this.$controls = null;
  1152. this.init();
  1153. };
  1154. CompoPlayer.prototype = {
  1155. init(){
  1156. // console.log('CompoPlayer init()');
  1157. // attach an event on AudioPlayer
  1158. _audioPlayer
  1159. .on('audio-open-document', this.onAudioOpenDocument.bind(this))
  1160. .on('audio-play', this.onAudioPlayerPlay.bind(this))
  1161. .on('audio-pause', this.onAudioPlayerPause.bind(this))
  1162. .on('audio-ended', this.onAudioPlayerEnded.bind(this));
  1163. // .on('audio-play-next', this.onAudioPlayNext.bind(this));
  1164. // this.newCompo();
  1165. },
  1166. newCompo(){
  1167. //console.log('CompoPlayer newCompo()');
  1168. // this.$compo = $('.composition_ui .composer .composition');
  1169. this.initControls();
  1170. },
  1171. initControls(){
  1172. //console.log('CompoPlayer initControls()');
  1173. this.$composer = $('.composition_ui .composer');
  1174. this.$compo = $('.composition_ui .composer .composition');
  1175. this.$controls = $('.composition_ui .composer .compo-player-controls');
  1176. if(!this.$controls.is('.ready') && this.$compo){
  1177. this.$previous = $('<div>').addClass('previous')
  1178. .on('click', this.prev.bind(this))
  1179. .appendTo(this.$controls);
  1180. this.$playpause = $('<div>').addClass('play-pause')
  1181. .on('click', this.togglePlayPause.bind(this))
  1182. .appendTo(this.$controls);
  1183. this.$next = $('<div>').addClass('next')
  1184. .on('click', this.next.bind(this))
  1185. .appendTo(this.$controls);
  1186. this.$controls.addClass('ready');
  1187. this.refresh();
  1188. this.active = true;
  1189. // this.newCompo();
  1190. }
  1191. },
  1192. refresh(){
  1193. // console.log('CompoPlayer refresh(), this', this);
  1194. this.stop();
  1195. // load new playlist
  1196. this.playlist = [];
  1197. var that = this;
  1198. $('.field--name-documents .field__item',this.$compo).each(function(i,el){
  1199. var $link = $('a.audio-link',this);
  1200. that.playlist.push({
  1201. item:$(this),
  1202. audio_url:$link.attr("audio_url"),
  1203. nid:$link.attr("nid"),
  1204. });
  1205. });
  1206. this.showHideControls();
  1207. },
  1208. togglePlayPause(){
  1209. // console.log('CompoPlayer togglePlayPause');
  1210. if (this.playing && !this.paused) {
  1211. this.pause();
  1212. }else{
  1213. if(this.playing && this.paused){
  1214. this.play();
  1215. }else{
  1216. this.start();
  1217. }
  1218. }
  1219. },
  1220. start(){
  1221. //console.log('start');
  1222. // console.log('CompoPlayer start()');
  1223. this.playing = true;
  1224. this.play();
  1225. },
  1226. play(){
  1227. // console.log('play');
  1228. if(this.paused){
  1229. this.paused = false;
  1230. _audioPlayer.play();
  1231. }else{
  1232. // _audioPlayer;
  1233. _audioPlayer.emmit('stop-shuffle').openDocument(this.playlist[this.current_index], this);
  1234. // TODO: stop random player
  1235. }
  1236. this.setActiveItem().showHideControls();
  1237. },
  1238. pause(){
  1239. //console.log('pause');
  1240. this.paused = true;
  1241. this.showHideControls();
  1242. _audioPlayer.stop();
  1243. },
  1244. next(){
  1245. // console.log('CompoPlayer next()');
  1246. if(this.playing){
  1247. this.current_index += 1;
  1248. if(this.current_index < this.playlist.length){
  1249. this.play();
  1250. }else{
  1251. this.stop();
  1252. }
  1253. }
  1254. },
  1255. prev(){
  1256. // console.log('CompoPlayer prev()');
  1257. if(this.playing){
  1258. this.current_index -= 1;
  1259. if(this.current_index >= 0){
  1260. this.play();
  1261. }else{
  1262. this.stop();
  1263. }
  1264. }
  1265. },
  1266. stop(){
  1267. if(this.playing){
  1268. _audioPlayer.stop();
  1269. }
  1270. this.reset();
  1271. },
  1272. reset(){
  1273. this.playing = false;
  1274. this.paused = false;
  1275. this.resetIndex();
  1276. },
  1277. resetIndex(){
  1278. this.current_index = 0;
  1279. this.showHideControls().resetActiveItems();
  1280. },
  1281. setActiveItem(){
  1282. this.resetActiveItems();
  1283. if(this.playing && this.current_index >= 0){
  1284. this.playlist[this.current_index].item.addClass('is-active');
  1285. }
  1286. // this call shoud not be here
  1287. this.showHideControls();
  1288. return this;
  1289. },
  1290. resetActiveItems(){
  1291. for (var n = 0; n < this.playlist.length; n++) {
  1292. // console.log('node',node);
  1293. this.playlist[n].item.removeClass('is-active');
  1294. }
  1295. return this;
  1296. },
  1297. showHideControls(){
  1298. // console.log('CompoPlayer showHideNextBtn(), playing:'+this.playing+', paused:'+this.paused);
  1299. // global playing
  1300. if(this.$controls){
  1301. if(this.playing && !this.paused){
  1302. this.$controls.addClass('is-playing');
  1303. }else{
  1304. this.$controls.removeClass('is-playing');
  1305. }
  1306. }
  1307. // playpause
  1308. if(this.$playpause){
  1309. if(this.playlist.length > 0){
  1310. this.$playpause.addClass('is-active');
  1311. }else{
  1312. this.$playpause.removeClass('is-active');
  1313. }
  1314. }
  1315. // next
  1316. if(this.$next){
  1317. if(this.playing && this.playlist.length > 1 && this.current_index < this.playlist.length -1){
  1318. this.$next.addClass('is-active');
  1319. }else{
  1320. this.$next.removeClass('is-active');
  1321. }
  1322. }
  1323. // previous
  1324. if(this.$previous){
  1325. if(this.playing && this.playlist.length > 1 && this.current_index > 0){
  1326. this.$previous.addClass('is-active');
  1327. }else{
  1328. this.$previous.removeClass('is-active');
  1329. }
  1330. }
  1331. return this;
  1332. },
  1333. deactivate(){
  1334. this.stop();
  1335. this.active = false;
  1336. },
  1337. // _audioPlayer events
  1338. onAudioOpenDocument(args){
  1339. if(args.caller !== this){
  1340. // console.log('CompoPlayer onAudioOpenDocument() called by other');
  1341. this.reset();
  1342. }
  1343. // else{
  1344. // // console.log('CompoPlayer onAudioOpenDocument() self calling');
  1345. // }
  1346. },
  1347. onAudioPlayerPlay(){
  1348. if(this.playing && this.paused){
  1349. this.paused = false;
  1350. this.showHideControls();
  1351. }
  1352. },
  1353. onAudioPlayerPause(){
  1354. if(this.playing && !this.paused){
  1355. this.paused = true;
  1356. this.showHideControls();
  1357. }
  1358. },
  1359. onAudioPlayerEnded(){
  1360. if(this.playing){
  1361. this.next();
  1362. }
  1363. },
  1364. // onAudioPlayNext(){
  1365. // this.next();
  1366. // }
  1367. };
  1368. // ___ _ _ _
  1369. // | _ \_ _ ___ __| |_ _ __| |_(_)___ _ _ ___
  1370. // | _/ '_/ _ \/ _` | || / _| _| / _ \ ' \(_-<
  1371. // |_| |_| \___/\__,_|\_,_\__|\__|_\___/_||_/__/
  1372. function initProductions(){
  1373. console.log('theme : initProductions');
  1374. _$row.find('.col').addClass('offfield');
  1375. var $grid = $('.grid',_$row).masonry({
  1376. itemSelector:'.col',
  1377. columnWidth:'.col-2',
  1378. horizontalOrder: true,
  1379. containerStyle: null,
  1380. transitionDuration:0,//'0.2s',
  1381. // stagger:30,
  1382. // disable initial layout
  1383. // initLayout: false,
  1384. });
  1385. // bind event
  1386. // $grid.masonry( 'on', 'layoutComplete', function() {
  1387. // console.log('layout is complete');
  1388. // });
  1389. // layout Masonry after each image loads
  1390. $grid.imagesLoaded().progress( function() {
  1391. $grid.masonry('layout');
  1392. });
  1393. $grid.imagesLoaded(function(){
  1394. $grid.masonry('layout');
  1395. // checkProductionBlockVisible();
  1396. });
  1397. $grid.on('layoutComplete', checkProductionBlockVisible);
  1398. };
  1399. function checkProductionBlockVisible(e,items){
  1400. console.log('checkProductionBlockVisible', e, items);
  1401. for (var i in items) {
  1402. if(!items[i].isTransitioning){
  1403. if(items[i].position.y+items[i].size.outerHeight < _$row.height()){
  1404. $(items[i].element).removeClass('offfield');
  1405. }else{
  1406. $(items[i].element).addClass('offfield');
  1407. }
  1408. }
  1409. }
  1410. }
  1411. // ___ _
  1412. // / __| ___ __ _ _ _ __| |_
  1413. // \__ \/ -_) _` | '_/ _| ' \
  1414. // |___/\___\__,_|_| \__|_||_|
  1415. function initSearch(){
  1416. // if($('#edit-entries input:checked', '#edlp-search-form').length){
  1417. // $('#edit-entries--wrapper', '#edlp-search-form').toggleClass('opened');
  1418. // }
  1419. $('#edit-entries--wrapper legend', '#edlp-search-form').on('click', function(){
  1420. $(this).parent().toggleClass('opened');
  1421. });
  1422. };
  1423. // ___ _ _ _
  1424. // | __|_ _ _ _ ___ __ _(_)__| |_ _ _ ___ _ __ ___ _ _| |_
  1425. // | _|| ' \| '_/ -_) _` | (_-< _| '_/ -_) ' \/ -_) ' \ _|
  1426. // |___|_||_|_| \___\__, |_/__/\__|_| \___|_|_|_\___|_||_\__|
  1427. // |___/
  1428. function initEnregistrementTranscript(){
  1429. console.log('initEnregistrementTranscript');
  1430. var $node = _$row.find('article.node--type-enregistrement.node--view-mode-transcript');
  1431. var $nav = $('<nav>').prependTo($node);
  1432. $node.find('.field--name-field-transcript-vo').addClass('visible').find('.field__label')
  1433. .clone().appendTo($nav).addClass('is-active')
  1434. .attr('field_target', '.field--name-field-transcript-vo');
  1435. $node.find('.field--name-field-transcript-trad').find('.field__label')
  1436. .clone().appendTo($nav)
  1437. .attr('field_target', '.field--name-field-transcript-trad');
  1438. $nav.find('.field__label').on('click', function(){
  1439. var $this = $(this).addClass('is-active');
  1440. $this.siblings('.is-active').removeClass('is-active');
  1441. $this.parents('article.node').find('.field.visible').removeClass('visible');
  1442. $this.parents('article.node').find($this.attr('field_target')).addClass('visible');
  1443. });
  1444. };
  1445. // ___ _ ___
  1446. // | __| _ ___ _ _| |_| _ \__ _ __ _ ___
  1447. // | _| '_/ _ \ ' \ _| _/ _` / _` / -_)
  1448. // |_||_| \___/_||_\__|_| \__,_\__, \___|
  1449. // |___/
  1450. function backToFrontPage(pop_state){
  1451. console.log('backToFrontPage', pop_state);
  1452. closeAllModals();
  1453. // assume we are going back to front page
  1454. $('body').removeClass().addClass('path-frontpage');
  1455. $('a[data-drupal-link-system-path="<front>"]').addClass('is-active');
  1456. // close entrees
  1457. _$corpus_canvas.trigger({'type':'close-all-entree'});
  1458. _$corpus_canvas.trigger({'type':'scramble-collection'});
  1459. if(typeof pop_state == "undefined" || !pop_state){
  1460. console.log('backToFrontPage push state');
  1461. history.pushState({home:true}, null, drupalSettings.path.baseUrl+drupalSettings.path.currentLanguage);
  1462. }
  1463. }
  1464. function initHome(){
  1465. addCloseModalBtnToCols();
  1466. // console.log('theme : initHome');
  1467. // console.log('theme : initProductions');
  1468. var $grid = $('.grid',_$row).masonry({
  1469. itemSelector:'.col',
  1470. columnWidth:'.col-2',
  1471. horizontalOrder: true,
  1472. containerStyle: null,
  1473. // disable initial layout
  1474. // initLayout: false,
  1475. });
  1476. // bind event
  1477. // $grid.masonry( 'on', 'layoutComplete', function() {
  1478. // console.log('layout is complete');
  1479. // });
  1480. // layout Masonry after each image loads
  1481. $grid.imagesLoaded().progress( function() {
  1482. $grid.masonry('layout');
  1483. });
  1484. $grid.imagesLoaded(function(){
  1485. $grid.masonry('layout');
  1486. });
  1487. }
  1488. // __ __ _ _
  1489. // | \/ |___ __| |__ _| |___
  1490. // | |\/| / _ \/ _` / _` | (_-<
  1491. // |_| |_\___/\__,_\__,_|_/__/
  1492. function closeAllModals(){
  1493. //console.log('theme : closeAllModals');
  1494. // TODO: animate the remove
  1495. _$row.html('');
  1496. _$ajaxLinks.removeClass('is-active');
  1497. _$body.trigger({'type':'all-modal-closed'});
  1498. // checkRowEmpty();
  1499. };
  1500. function checkRowEmpty(){
  1501. // if row is empty and we are not in productions or entree notice|index call closeAllModals()
  1502. if(!$('.col', _$row).length){
  1503. if(!_$body.is('.entity-type-taxonomy_term.bundle-entrees')){
  1504. if(!_$body.is('.entity-type-node.bundle-page')){
  1505. // we weren't on production or entree, so go back to front page
  1506. backToFrontPage();
  1507. }else{
  1508. // if we were on production page just scramble collection in case of map was filtered
  1509. _$corpus_canvas.trigger({'type':'scramble-collection'});
  1510. // reload production home
  1511. $('a[data-drupal-link-system-path="productions"]', '#block-mainnavigation')
  1512. .removeClass('is-active').trigger('click');
  1513. }
  1514. }else{
  1515. // remove is-active class from index or notice entree links
  1516. $('.entree-content a.is-active').removeClass('is-active');
  1517. // TODO: remove the hash index or notice
  1518. }
  1519. }
  1520. };
  1521. init();
  1522. } // end EdlpTheme()
  1523. $(document).ready(function($) {
  1524. if(drupalSettings.path.isFront){
  1525. var edlptheme = new EdlpTheme();
  1526. }else{
  1527. $('body').attr('booted', 'booted');
  1528. }
  1529. });
  1530. })(jQuery, Drupal, drupalSettings);