main.js 59 KB

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