main.js 54 KB

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