main.js 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837
  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. // TODO: update language switcher for document url
  844. // TODO: stop random player if playing from studio
  845. this.emmit('audio-open-document', {caller:caller});
  846. // piwik
  847. // debugger;
  848. if(typeof _paq !== 'undefined'){
  849. // page tracking
  850. // https://matomo.org/blog/2017/02/how-to-track-single-page-websites-using-piwik-analytics/
  851. // _paq.push(['setCustomUrl', state.url]);
  852. // _paq.push(['setDocumentTitle', data.title]);
  853. // _paq.push(['trackPageView']);
  854. // js event
  855. // trackEvent(category, action, [name], [value])
  856. if(typeof node.title != 'undefined'){
  857. _paq.push(['trackEvent', 'Audio', 'play', node.title]);
  858. }
  859. }
  860. this.launch();
  861. },
  862. launch(){
  863. this.clearTimeOutToHide();
  864. this.setSRC(this.historic[this.currentHistoricIndex].audio_url);
  865. this.loadNode(this.historic[this.currentHistoricIndex].nid);
  866. // emmit new playing doc (e.g.: corpus map nowing that audio played from RandomPlayer)
  867. try {
  868. _$corpus_canvas.trigger({
  869. 'type':'audio-node-opened',
  870. 'nid':this.historic[this.currentHistoricIndex].nid
  871. });
  872. } catch (e) {
  873. console.info('AudioPlayer : _$corpus_canvas does not exists, testing promise');
  874. var that = this;
  875. _corpus_promise.done(function(){
  876. _$corpus_canvas.trigger({
  877. 'type':'audio-node-opened',
  878. 'nid':that.historic[that.currentHistoricIndex].nid
  879. });
  880. });
  881. }
  882. this.showHidePreviousBtn();
  883. this.showHideNextBtn();
  884. this.show();
  885. },
  886. openSound(url, title){
  887. this.hide();
  888. this.clearTimeOutToHide();
  889. this.$cartel.html("");
  890. this.setSRC(url);
  891. this.show();
  892. if(typeof _paq !== 'undefined'){
  893. _paq.push(['trackEvent', 'Audio', 'play', url]);
  894. }
  895. },
  896. // audio functions
  897. setSRC(url){
  898. console.log('AudioPlayer setSRC : url', url);
  899. this.audio.src = url;
  900. // need to trigger play right now to prevent safari blocking auto-play
  901. this.play();
  902. },
  903. onLoadedmetadata(){
  904. var rem = parseInt(this.audio.duration, 10),
  905. mins = Math.floor(rem/60,10),
  906. secs = rem - mins*60;
  907. this.$duration.html('<span>'+(mins<10 ? '0':'')+mins+':'+(secs<10 ? '0':'')+secs+'</span>');
  908. this.updateLoadingBar();
  909. },
  910. updateLoadingBar(){
  911. console.log("updateLoadingBar");
  912. // var that = this;
  913. // if (this.audio.readyState === 4){
  914. if(this.audio.buffered.length>0){
  915. // debugger;
  916. this.$loader.css({
  917. 'width':parseInt((100 * this.audio.buffered.end(0) / this.audio.duration), 10)+'%'
  918. });
  919. if( this.audio.buffered.end(0) < this.audio.duration ){
  920. // loop through this function until file is fully loaded
  921. window.requestAnimationFrame(this.updateLoadingBar.bind(this));
  922. }else{
  923. console.log('Audio fully loaded');
  924. }
  925. }else{
  926. // as audio buffer is not ready, recall updateLoadingBar in next frame
  927. window.requestAnimationFrame(this.updateLoadingBar.bind(this));
  928. }
  929. },
  930. // onCanplay(){
  931. // // this.play();
  932. // },
  933. onError(){
  934. console.warn("Audio Error " + this.audio.error.code + "; details: " + this.audio.error.message);
  935. },
  936. play(){
  937. this.clearTimeOutToHide();
  938. // this.audio.play();
  939. // 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
  940. var promise = this.audio.play();
  941. // console.log('promise', promise);
  942. if (promise !== undefined) {
  943. promise.catch(function(error){
  944. // Auto-play was prevented
  945. // Show a UI element to let the user manually start playback
  946. console.warn('autoplay failed, ask for playing', error);
  947. }).then(function(){
  948. // Auto-play started
  949. console.log('autoplay succeed');
  950. });
  951. }
  952. },
  953. playPrevious(){
  954. if(this.currentHistoricIndex > 0){
  955. this.currentHistoricIndex -= 1;
  956. this.launch();
  957. // TODO: update history state
  958. }
  959. },
  960. playNext(){
  961. if(this.currentHistoricIndex < this.historic.length-1){
  962. this.currentHistoricIndex += 1;
  963. this.launch();
  964. // TODO: update history state
  965. }else{
  966. this.emmit('audio-play-next');
  967. }
  968. },
  969. togglePlayPause(e){
  970. if(this.audio.paused){
  971. // this.audio.play();
  972. this.play();
  973. }else{
  974. // this.audio.pause();
  975. this.stop();
  976. }
  977. },
  978. stop(){
  979. // console.log('AudioPlayer stop()');
  980. // debugger;
  981. this.audio.pause();
  982. // don't close player if article or transcript is open
  983. if(!(_$body.is('.path-node-'+this.historic[this.currentHistoricIndex].nid)
  984. && (_$body.is('.view-mode-article') || _$body.is('.view-mode-transcript')))){
  985. this.timeOutToHide();
  986. }
  987. },
  988. // audio events
  989. onPlaying(){
  990. this.$btns.addClass('is-playing');
  991. this.emmit('audio-play');
  992. },
  993. onPause(){
  994. this.$btns.removeClass('is-playing');
  995. this.emmit('audio-pause');
  996. },
  997. onTimeupdate(){
  998. // move cursor
  999. this.$cursor.css({
  1000. 'left':(this.audio.currentTime/this.audio.duration * this.timeline_w)+"px"
  1001. });
  1002. // update time text display
  1003. var rem = parseInt(this.audio.currentTime, 10),
  1004. mins = Math.floor(rem/60,10),
  1005. secs = rem - mins*60;
  1006. this.$currentTime.html('<span>'+(mins<10 ? '0':'')+mins+':'+(secs<10 ? '0':'')+secs+'</span>');
  1007. },
  1008. onEnded(){
  1009. console.log('AudioPlayer onEnded()');
  1010. this.stop();
  1011. this.emmit('audio-ended');
  1012. },
  1013. // cartel functions
  1014. loadNode(nid){
  1015. this.$cartel.addClass('loading');
  1016. var vm = 'player_cartel';
  1017. var ajax_path = _ajax_settings.entityjson_path+'/node/'+nid+'/'+vm;
  1018. var path = window.location.origin + Drupal.url(ajax_path);
  1019. $.getJSON(path, {})
  1020. .done(this.onNodeLoaded.bind(this))
  1021. .fail(this.onNodeLoadFail.bind(this));
  1022. },
  1023. onNodeLoaded(data){
  1024. // console.log('AudioPlayer node loaded');
  1025. this.$cartel.html(data.rendered).removeClass('loading');
  1026. _$body.trigger({'type':'new-audio-cartel-loaded'});
  1027. initAjaxLinks();
  1028. if(this.auto_open_article){
  1029. this.$cartel.find('a.link-article').trigger('click');
  1030. this.auto_open_article = false;
  1031. }
  1032. },
  1033. onNodeLoadFail(jqxhr, textStatus, error){
  1034. console.warn('AudioPlayer node load failed', jqxhr.responseText);
  1035. this.$cartel.removeClass('loading').html('');
  1036. },
  1037. setAutoOpenArticle(art){
  1038. this.auto_open_article = art;
  1039. return this;
  1040. },
  1041. // global
  1042. show(){
  1043. this.$container_parent.addClass('audio-player-visible');
  1044. this.$container.addClass('visible');
  1045. },
  1046. showHidePreviousBtn(){
  1047. if(this.historic.length > 1 && this.currentHistoricIndex > 0){
  1048. this.$previous.addClass('is-active');
  1049. }else{
  1050. this.$previous.removeClass('is-active');
  1051. }
  1052. },
  1053. showHideNextBtn(){
  1054. if(this.currentHistoricIndex < this.historic.length-1 || this.shuffle_is_active){
  1055. this.$next.addClass('is-active');
  1056. }else{
  1057. this.$next.removeClass('is-active');
  1058. }
  1059. },
  1060. timeOutToHide(){
  1061. // console.log('AudioPlayer timeOutToHide()');
  1062. this.clearTimeOutToHide();
  1063. this.hideTimer = setTimeout(this.hide.bind(this), this.hideTimeMS);
  1064. },
  1065. clearTimeOutToHide(){
  1066. // console.log('AudioPlayer clearTimeOutToHide()',this.hideTimer);
  1067. if(this.hideTimer){
  1068. clearTimeout(this.hideTimer);
  1069. this.hideTimer = false;
  1070. }
  1071. },
  1072. hide(){
  1073. // console.log('AudioPlayer hide()');
  1074. this.$container_parent.removeClass('audio-player-visible');
  1075. this.$container.removeClass('visible');
  1076. // trigger highlighted node remove on corpus map
  1077. try {
  1078. _$corpus_canvas.trigger('audio-node-closed');
  1079. } catch (e) {
  1080. console.info('AudioPlayer hide() : _$corpus_canvas does not exists');
  1081. }
  1082. },
  1083. deActivateRandom(){
  1084. this.shuffle_is_active = false;
  1085. this.showHideNextBtn();
  1086. },
  1087. // object events
  1088. on(event_name, handler){
  1089. if(typeof this.event_handlers[event_name] == 'undefined'){
  1090. console.warn('AudioPlayer : event '+event_name+' does not exists');
  1091. }
  1092. this.event_handlers[event_name].push(handler);
  1093. return this;
  1094. },
  1095. emmit(event_name, args){
  1096. console.log('AudioPlayer emmit()', event_name, args, this.event_handlers[event_name]);
  1097. // console.log('AudioPlayer emmit() handlers', this.event_handlers[event_name]);
  1098. var handler;
  1099. var args = args || {};
  1100. for (var i = this.event_handlers[event_name].length-1; i >= 0 ; i--) {
  1101. handler = this.event_handlers[event_name][i];
  1102. // console.log('AudioPlayer emmit() loop handler', handler);
  1103. (function(handler, args){
  1104. setTimeout(function(){
  1105. // console.log('AudioPlayer emmit() timeout handler', handler);
  1106. handler(args);
  1107. }, 0);
  1108. }(handler, args));
  1109. }
  1110. return this;
  1111. },
  1112. }
  1113. // ___ _ ___ _
  1114. // | _ \__ _ _ _ __| |___ _ __ | _ \ |__ _ _ _ ___ _ _
  1115. // | / _` | ' \/ _` / _ \ ' \| _/ / _` | || / -_) '_|
  1116. // |_|_\__,_|_||_\__,_\___/_|_|_|_| |_\__,_|\_, \___|_|
  1117. // |__/
  1118. function RandomPlayer(playlist){
  1119. this.active = false;
  1120. this.playlist = playlist;
  1121. this.path = drupalSettings.path.baseUrl+drupalSettings.path.pathPrefix+'#random'
  1122. this.$btn = $('<a>').html('Shuffle').attr('href',this.path).addClass('random-player-btn');
  1123. this.init();
  1124. };
  1125. RandomPlayer.prototype = {
  1126. init(){
  1127. // this.shuffle();
  1128. $('<div>')
  1129. .addClass('block random-player')
  1130. .append(this.$btn)
  1131. // .insertAfter('#block-userlogin, #block-studiolinkblock');
  1132. .prependTo('.region-footer-right');
  1133. // events
  1134. this.$btn.on('click', this.toggleActive.bind(this));
  1135. // attach an event on AudioPlayer
  1136. _audioPlayer
  1137. .on('audio-play-next', this.onAudioPlayNext.bind(this))
  1138. .on('audio-ended', this.onAudioPlayerEnded.bind(this))
  1139. // .on('audio-ended', function(e){
  1140. // console.log('RandomPlayer, audio-ended', e);
  1141. // })
  1142. .on('stop-shuffle', this.stop.bind(this));
  1143. _$corpus_canvas
  1144. .on('update-random-playlist', this.updatePlaylist.bind(this));
  1145. // provide a link to auto start random player
  1146. if(window.location.hash == '#random'){
  1147. this.start();
  1148. // window.location.hash = '';
  1149. }
  1150. },
  1151. updatePlaylist(e){
  1152. // debugger;
  1153. this.playlist = e.playlist;
  1154. this.shuffle();
  1155. },
  1156. shuffle(){
  1157. var tempPLaylist = [];
  1158. for (var i = this.playlist.length-1; i >= 0 ; i--) {
  1159. tempPLaylist.push(this.playlist[i]);
  1160. }
  1161. this.shuffledPlaylist = [];
  1162. while(tempPLaylist.length > 0){
  1163. var r = Math.floor(Math.random() * tempPLaylist.length);
  1164. this.shuffledPlaylist.push(tempPLaylist.splice(r,1)[0]);
  1165. }
  1166. //console.log('RandomPlayer, this.shuffledPlaylist', this.shuffledPlaylist);
  1167. },
  1168. toggleActive(e){
  1169. e.preventDefault();
  1170. if (this.active) {
  1171. this.stop();
  1172. }else{
  1173. this.start();
  1174. }
  1175. return false;
  1176. },
  1177. start(){
  1178. this.active = _audioPlayer.shuffle_is_active = true;
  1179. this.$btn.addClass('is-active');
  1180. this.shuffle();
  1181. this.next();
  1182. // piwik
  1183. if(typeof _paq !== 'undefined'){
  1184. // trackEvent(category, action, [name], [value])
  1185. _paq.push(['trackEvent', 'RandomPlayer', 'start']);
  1186. }
  1187. },
  1188. stop(){
  1189. this.active = false;
  1190. this.$btn.removeClass('is-active');
  1191. // stop audio player
  1192. // _audioPlayer.stop();
  1193. // remove hash
  1194. history.replaceState(history.state, null, window.location.pathname);
  1195. // tell to AudioPlayer to deactivate netx btn
  1196. _audioPlayer.deActivateRandom();
  1197. if(typeof _paq !== 'undefined'){
  1198. // trackEvent(category, action, [name], [value])
  1199. _paq.push(['trackEvent', 'RandomPlayer', 'stop']);
  1200. }
  1201. },
  1202. next(){
  1203. console.log('RandomPlayer next', this.active, this.shuffledPlaylist.length);
  1204. if(this.active && this.shuffledPlaylist.length > 0)
  1205. _audioPlayer.openDocument(this.shuffledPlaylist.splice(0,1)[0], 'random');
  1206. },
  1207. onAudioPlayNext(){
  1208. console.log('RandomPlayer : onAudioPlayNext()');
  1209. if(this.active){
  1210. this.next();
  1211. }
  1212. },
  1213. onAudioPlayerEnded(){
  1214. console.log('RandomPlayer : onAudioPlayerEnded()');
  1215. if(this.active){
  1216. this.next();
  1217. }
  1218. }
  1219. };
  1220. // ___ ___ _
  1221. // / __|___ _ __ _ __ ___| _ \ |__ _ _ _ ___ _ _
  1222. // | (__/ _ \ ' \| '_ \/ _ \ _/ / _` | || / -_) '_|
  1223. // \___\___/_|_|_| .__/\___/_| |_\__,_|\_, \___|_|
  1224. // |_| |__/
  1225. function CompoPlayer(){
  1226. this.active = false;
  1227. this.playing = false;
  1228. this.paused = false;
  1229. this.playlist = [];
  1230. this.current_index = 0;
  1231. this.$composer = null;
  1232. this.$compo = null;
  1233. this.$controls = null;
  1234. this.init();
  1235. };
  1236. CompoPlayer.prototype = {
  1237. init(){
  1238. // console.log('CompoPlayer init()');
  1239. // attach an event on AudioPlayer
  1240. _audioPlayer
  1241. .on('audio-open-document', this.onAudioOpenDocument.bind(this))
  1242. .on('audio-play', this.onAudioPlayerPlay.bind(this))
  1243. .on('audio-pause', this.onAudioPlayerPause.bind(this))
  1244. .on('audio-ended', this.onAudioPlayerEnded.bind(this));
  1245. // .on('audio-play-next', this.onAudioPlayNext.bind(this));
  1246. // this.newCompo();
  1247. },
  1248. newCompo(){
  1249. //console.log('CompoPlayer newCompo()');
  1250. // this.$compo = $('.composition_ui .composer .composition');
  1251. this.initControls();
  1252. },
  1253. initControls(){
  1254. //console.log('CompoPlayer initControls()');
  1255. this.$composer = $('.composition_ui .composer');
  1256. this.$compo = $('.composition_ui .composer .composition');
  1257. this.$controls = $('.composition_ui .composer .compo-player-controls');
  1258. if(!this.$controls.is('.ready') && this.$compo){
  1259. this.$previous = $('<div>').addClass('previous')
  1260. .on('click', this.prev.bind(this))
  1261. .appendTo(this.$controls);
  1262. this.$playpause = $('<div>').addClass('play-pause')
  1263. .on('click', this.togglePlayPause.bind(this))
  1264. .appendTo(this.$controls);
  1265. this.$next = $('<div>').addClass('next')
  1266. .on('click', this.next.bind(this))
  1267. .appendTo(this.$controls);
  1268. this.$controls.addClass('ready');
  1269. this.refresh();
  1270. this.active = true;
  1271. // this.newCompo();
  1272. }
  1273. },
  1274. refresh(){
  1275. // console.log('CompoPlayer refresh(), this', this);
  1276. this.stop();
  1277. // load new playlist
  1278. this.playlist = [];
  1279. var that = this;
  1280. $('.field--name-documents .field__item',this.$compo).each(function(i,el){
  1281. var $link = $('a.audio-link',this);
  1282. that.playlist.push({
  1283. item:$(this),
  1284. audio_url:$link.attr("audio_url"),
  1285. nid:$link.attr("nid"),
  1286. });
  1287. });
  1288. this.showHideControls();
  1289. },
  1290. togglePlayPause(){
  1291. // console.log('CompoPlayer togglePlayPause');
  1292. if (this.playing && !this.paused) {
  1293. this.pause();
  1294. }else{
  1295. if(this.playing && this.paused){
  1296. this.play();
  1297. }else{
  1298. this.start();
  1299. }
  1300. }
  1301. },
  1302. start(){
  1303. //console.log('start');
  1304. // console.log('CompoPlayer start()');
  1305. this.playing = true;
  1306. this.play();
  1307. },
  1308. play(){
  1309. // console.log('play');
  1310. if(this.paused){
  1311. this.paused = false;
  1312. _audioPlayer.play();
  1313. }else{
  1314. // _audioPlayer;
  1315. _audioPlayer.emmit('stop-shuffle').openDocument(this.playlist[this.current_index], this);
  1316. // TODO: stop random player
  1317. }
  1318. this.setActiveItem().showHideControls();
  1319. },
  1320. pause(){
  1321. //console.log('pause');
  1322. this.paused = true;
  1323. this.showHideControls();
  1324. _audioPlayer.stop();
  1325. },
  1326. next(){
  1327. // console.log('CompoPlayer next()');
  1328. if(this.playing){
  1329. this.current_index += 1;
  1330. if(this.current_index < this.playlist.length){
  1331. this.play();
  1332. }else{
  1333. this.stop();
  1334. }
  1335. }
  1336. },
  1337. prev(){
  1338. // console.log('CompoPlayer prev()');
  1339. if(this.playing){
  1340. this.current_index -= 1;
  1341. if(this.current_index >= 0){
  1342. this.play();
  1343. }else{
  1344. this.stop();
  1345. }
  1346. }
  1347. },
  1348. stop(){
  1349. if(this.playing){
  1350. _audioPlayer.stop();
  1351. }
  1352. this.reset();
  1353. },
  1354. reset(){
  1355. this.playing = false;
  1356. this.paused = false;
  1357. this.resetIndex();
  1358. },
  1359. resetIndex(){
  1360. this.current_index = 0;
  1361. this.showHideControls().resetActiveItems();
  1362. },
  1363. setActiveItem(){
  1364. this.resetActiveItems();
  1365. if(this.playing && this.current_index >= 0){
  1366. this.playlist[this.current_index].item.addClass('is-active');
  1367. }
  1368. // this call shoud not be here
  1369. this.showHideControls();
  1370. return this;
  1371. },
  1372. resetActiveItems(){
  1373. for (var n = 0; n < this.playlist.length; n++) {
  1374. // console.log('node',node);
  1375. this.playlist[n].item.removeClass('is-active');
  1376. }
  1377. return this;
  1378. },
  1379. showHideControls(){
  1380. // console.log('CompoPlayer showHideNextBtn(), playing:'+this.playing+', paused:'+this.paused);
  1381. // global playing
  1382. if(this.$controls){
  1383. if(this.playing && !this.paused){
  1384. this.$controls.addClass('is-playing');
  1385. }else{
  1386. this.$controls.removeClass('is-playing');
  1387. }
  1388. }
  1389. // playpause
  1390. if(this.$playpause){
  1391. if(this.playlist.length > 0){
  1392. this.$playpause.addClass('is-active');
  1393. }else{
  1394. this.$playpause.removeClass('is-active');
  1395. }
  1396. }
  1397. // next
  1398. if(this.$next){
  1399. if(this.playing && this.playlist.length > 1 && this.current_index < this.playlist.length -1){
  1400. this.$next.addClass('is-active');
  1401. }else{
  1402. this.$next.removeClass('is-active');
  1403. }
  1404. }
  1405. // previous
  1406. if(this.$previous){
  1407. if(this.playing && this.playlist.length > 1 && this.current_index > 0){
  1408. this.$previous.addClass('is-active');
  1409. }else{
  1410. this.$previous.removeClass('is-active');
  1411. }
  1412. }
  1413. return this;
  1414. },
  1415. deactivate(){
  1416. this.stop();
  1417. this.active = false;
  1418. },
  1419. // _audioPlayer events
  1420. onAudioOpenDocument(args){
  1421. if(args.caller !== this){
  1422. // console.log('CompoPlayer onAudioOpenDocument() called by other');
  1423. this.reset();
  1424. }
  1425. // else{
  1426. // // console.log('CompoPlayer onAudioOpenDocument() self calling');
  1427. // }
  1428. },
  1429. onAudioPlayerPlay(){
  1430. if(this.playing && this.paused){
  1431. this.paused = false;
  1432. this.showHideControls();
  1433. }
  1434. },
  1435. onAudioPlayerPause(){
  1436. if(this.playing && !this.paused){
  1437. this.paused = true;
  1438. this.showHideControls();
  1439. }
  1440. },
  1441. onAudioPlayerEnded(){
  1442. if(this.playing){
  1443. this.next();
  1444. }
  1445. },
  1446. // onAudioPlayNext(){
  1447. // this.next();
  1448. // }
  1449. };
  1450. // ___ _ _
  1451. // / __|_ _(_)__| |
  1452. // | (_ | '_| / _` |
  1453. // \___|_| |_\__,_|
  1454. function initGrid(){
  1455. console.log('theme : initGrid');
  1456. checkGridBlockHeight();
  1457. _$row.find('.col').addClass('offfield');
  1458. if(false){
  1459. var $grid = $('.grid',_$row).masonry({
  1460. itemSelector:'.col',
  1461. columnWidth:'.col-2',
  1462. containerStyle: null,
  1463. resizeContainer:false,
  1464. // horizontalOrder: true,
  1465. transitionDuration:0,//'0.2s',
  1466. // stagger:30,
  1467. // disable initial layout
  1468. // initLayout: false,
  1469. });
  1470. // layout Masonry after each image loads
  1471. $grid.imagesLoaded().progress( function() {
  1472. $grid.masonry('layout');
  1473. });
  1474. $grid.imagesLoaded(function(){
  1475. $grid.masonry('layout');
  1476. // checkProductionBlockVisible();
  1477. });
  1478. // bind event
  1479. // $grid.masonry( 'on', 'layoutComplete', function() {
  1480. // console.log('layout is complete');
  1481. // });
  1482. $grid.on('layoutComplete', checkGridBlockVisible);
  1483. }else{
  1484. // setTimeout(checkGridBlockVisible, 100);
  1485. checkGridBlockVisible();
  1486. }
  1487. };
  1488. function checkGridBlockHeight(){
  1489. // console.log('checkGridBlockHeight');
  1490. var $r_h = _$row.height();
  1491. var $this;
  1492. // console.log($r_h);
  1493. $('.grid .col', _$row).each(function(i,e){
  1494. $this = $(this);
  1495. if(!$this.is('[init-height]')){
  1496. $this.attr('init-height', $this.outerHeight())
  1497. }
  1498. // console.log($(this).height(), $(this).innerHeight(), $(this).outerHeight());
  1499. // if($this.height() > $r_h){
  1500. // $this.height($r_h);
  1501. // }else{
  1502. // $this.height('auto');
  1503. // }
  1504. $this.height(Math.min($this.attr('init-height'), _$row.height()));
  1505. });
  1506. };
  1507. function checkGridBlockVisible(){
  1508. // console.log('checkGridBlockVisible');
  1509. var $r_h = _$row.height();
  1510. var $this,pos;
  1511. $('.grid .col', _$row).each(function(i,e){
  1512. // $(this).on('load',function(event){
  1513. $this = $(this);
  1514. pos = $this.position();
  1515. // console.log(pos.top, $this.height(), pos.top+$this.height(), $r_h, $this);
  1516. if(pos.top+$this.height() <= $r_h){
  1517. $this.removeClass('offfield');
  1518. }else{
  1519. $this.addClass('offfield');
  1520. }
  1521. // });
  1522. });
  1523. // for (var i in items) {
  1524. // if(!items[i].isTransitioning){
  1525. // console.log('y+outerHeight', items[i].position.y+items[i].size.outerHeight);
  1526. // console.log('_$row.height()', _$row.height());
  1527. // if(items[i].position.y+items[i].size.outerHeight < _$row.height()){
  1528. // $(items[i].element).removeClass('offfield');
  1529. // }else{
  1530. // // $(items[i].element).addClass('offfield');
  1531. // }
  1532. // }
  1533. // }
  1534. }
  1535. // ___ _ _ _
  1536. // | _ \_ _ ___ __| |_ _ __| |_(_)___ _ _ ___
  1537. // | _/ '_/ _ \/ _` | || / _| _| / _ \ ' \(_-<
  1538. // |_| |_| \___/\__,_|\_,_\__|\__|_\___/_||_/__/
  1539. // function initProductions(){
  1540. // console.log('theme : initProductions');
  1541. //
  1542. // // _$row.find('.col').addClass('offfield');
  1543. // var $grid = $('.grid',_$row).masonry({
  1544. // itemSelector:'.col',
  1545. // columnWidth:'.col-2',
  1546. // containerStyle: null,
  1547. // resizeContainer:false,
  1548. // // horizontalOrder: true,
  1549. // transitionDuration:0,//'0.2s',
  1550. // // stagger:30,
  1551. // // disable initial layout
  1552. // // initLayout: false,
  1553. // });
  1554. //
  1555. // // layout Masonry after each image loads
  1556. // $grid.imagesLoaded().progress( function() {
  1557. // $grid.masonry('layout');
  1558. // });
  1559. //
  1560. // $grid.imagesLoaded(function(){
  1561. // $grid.masonry('layout');
  1562. // // checkProductionBlockVisible();
  1563. // });
  1564. //
  1565. // // bind event
  1566. // // $grid.masonry( 'on', 'layoutComplete', function() {
  1567. // // console.log('layout is complete');
  1568. // // });
  1569. // // $grid.on('layoutComplete', checkProductionBlockVisible);
  1570. // };
  1571. // ___ _
  1572. // / __| ___ __ _ _ _ __| |_
  1573. // \__ \/ -_) _` | '_/ _| ' \
  1574. // |___/\___\__,_|_| \__|_||_|
  1575. function initSearch(){
  1576. // if($('#edit-entries input:checked', '#edlp-search-form').length){
  1577. // $('#edit-entries--wrapper', '#edlp-search-form').toggleClass('opened');
  1578. // }
  1579. $('#edit-entries--wrapper legend', '#edlp-search-form').on('click', function(){
  1580. $(this).parent().toggleClass('opened');
  1581. });
  1582. };
  1583. // ___ _ _ _
  1584. // | __|_ _ _ _ ___ __ _(_)__| |_ _ _ ___ _ __ ___ _ _| |_
  1585. // | _|| ' \| '_/ -_) _` | (_-< _| '_/ -_) ' \/ -_) ' \ _|
  1586. // |___|_||_|_| \___\__, |_/__/\__|_| \___|_|_|_\___|_||_\__|
  1587. // |___/
  1588. function initEnregistrementTranscript(){
  1589. console.log('initEnregistrementTranscript');
  1590. var $node = _$row.find('article.node--type-enregistrement.node--view-mode-transcript');
  1591. var $nav = $('<nav>').prependTo($node);
  1592. $node.find('.field--name-field-transcript-vo').addClass('visible').find('.field__label')
  1593. .clone().appendTo($nav).addClass('is-active')
  1594. .attr('field_target', '.field--name-field-transcript-vo');
  1595. $node.find('.field--name-field-transcript-trad').find('.field__label')
  1596. .clone().appendTo($nav)
  1597. .attr('field_target', '.field--name-field-transcript-trad');
  1598. $nav.find('.field__label').on('click', function(){
  1599. var $this = $(this).addClass('is-active');
  1600. $this.siblings('.is-active').removeClass('is-active');
  1601. $this.parents('article.node').find('.field.visible').removeClass('visible');
  1602. $this.parents('article.node').find($this.attr('field_target')).addClass('visible');
  1603. });
  1604. };
  1605. // ___ _ ___
  1606. // | __| _ ___ _ _| |_| _ \__ _ __ _ ___
  1607. // | _| '_/ _ \ ' \ _| _/ _` / _` / -_)
  1608. // |_||_| \___/_||_\__|_| \__,_\__, \___|
  1609. // |___/
  1610. function backToFrontPage(pop_state){
  1611. console.log('backToFrontPage', pop_state);
  1612. closeAllModals();
  1613. // assume we are going back to front page
  1614. $('body').removeClass().addClass('path-frontpage');
  1615. $('a[data-drupal-link-system-path="<front>"]').addClass('is-active');
  1616. // close entrees
  1617. _$corpus_canvas.trigger({'type':'close-all-entree'});
  1618. _$corpus_canvas.trigger({'type':'scramble-collection'});
  1619. if(typeof pop_state == "undefined" || !pop_state){
  1620. console.log('backToFrontPage push state');
  1621. history.pushState({home:true}, null, drupalSettings.path.baseUrl+drupalSettings.path.currentLanguage);
  1622. }
  1623. }
  1624. function initHome(){
  1625. addCloseModalBtnToCols();
  1626. return;
  1627. console.log('theme : initHome');
  1628. var $grid = $('.grid',_$row).masonry({
  1629. itemSelector:'.col',
  1630. columnWidth:'.col-2',
  1631. horizontalOrder: true,
  1632. containerStyle: null,
  1633. // disable initial layout
  1634. // initLayout: false,
  1635. });
  1636. // bind event
  1637. // $grid.masonry( 'on', 'layoutComplete', function() {
  1638. // console.log('layout is complete');
  1639. // });
  1640. // layout Masonry after each image loads
  1641. $grid.imagesLoaded().progress( function() {
  1642. $grid.masonry('layout');
  1643. });
  1644. $grid.imagesLoaded(function(){
  1645. $grid.masonry('layout');
  1646. });
  1647. }
  1648. // __ __ _ _
  1649. // | \/ |___ __| |__ _| |___
  1650. // | |\/| / _ \/ _` / _` | (_-<
  1651. // |_| |_\___/\__,_\__,_|_/__/
  1652. function closeAllModals(){
  1653. //console.log('theme : closeAllModals');
  1654. // TODO: animate the remove
  1655. _$row.html('');
  1656. _$ajaxLinks.removeClass('is-active');
  1657. _$body.trigger({'type':'all-modal-closed'});
  1658. // checkRowEmpty();
  1659. };
  1660. function checkRowEmpty(){
  1661. // if row is empty and we are not in productions or entree notice|index call closeAllModals()
  1662. if(!$('.col', _$row).length){
  1663. if(!_$body.is('.entity-type-taxonomy_term.bundle-entrees')){
  1664. if(!_$body.is('.entity-type-node.bundle-page')){
  1665. // we weren't on production or entree, so go back to front page
  1666. backToFrontPage();
  1667. }else{
  1668. // if we were on production page just scramble collection in case of map was filtered
  1669. _$corpus_canvas.trigger({'type':'scramble-collection'});
  1670. // reload production home
  1671. $('a[data-drupal-link-system-path="productions"]', '#block-mainnavigation')
  1672. .removeClass('is-active').trigger('click');
  1673. }
  1674. }else{
  1675. // remove is-active class from index or notice entree links
  1676. $('.entree-content a.is-active').removeClass('is-active');
  1677. // TODO: remove the hash index or notice
  1678. }
  1679. }
  1680. };
  1681. init();
  1682. } // end EdlpTheme()
  1683. $(document).ready(function($) {
  1684. if(drupalSettings.path.isFront){
  1685. var edlptheme = new EdlpTheme();
  1686. }else{
  1687. $('body').attr('booted', 'booted');
  1688. }
  1689. });
  1690. })(jQuery, Drupal, drupalSettings);