main.js 54 KB

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