main.js 62 KB

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