main.js 59 KB

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