main.js 56 KB

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