main.js 62 KB

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