main.js 54 KB

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