main.js 79 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348
  1. (function($, Drupal, drupalSettings) {
  2. EdlpTheme = function(){
  3. var _origin = window.location.origin;
  4. var _base_url = drupalSettings.path.baseUrl;
  5. var _ajax_settings = drupalSettings.edlp_ajax;
  6. var _$body = $('body');
  7. // var _is_front = drupalSettings.path.isFront;
  8. var _corpus_ready = false;
  9. var _$corpus_canvas;
  10. var _$row = $('main[role="main"]>.layout-content>.row');
  11. var _$ajaxLinks;
  12. var _audioPlayer;
  13. var _randomPlayer;
  14. var _compoPlayer;
  15. var _ajax_timing = {
  16. start:0,
  17. end:0
  18. };
  19. var _corpus_promise;
  20. var _is_mobile = edlp_mobile.device_is_mobile;
  21. var _is_loggedin = drupalSettings.user.uid === 0 ? false : true;
  22. var _$log_form;
  23. var _user_tokens;
  24. var _states_history = [];
  25. var _is_expo = $('body').hasClass('domain-expo-encyclopediedelaparole-org');
  26. // ___ _ _
  27. // |_ _|_ _ (_) |_
  28. // | || ' \| | _|
  29. // |___|_||_|_|\__|
  30. function init(){
  31. console.log("EdlpTheme init()");
  32. if (!_is_loggedin) {
  33. initLogForm();
  34. }
  35. if(_is_mobile){
  36. initMobile();
  37. }
  38. initEvents();
  39. _audioPlayer = new AudioPlayer();
  40. _compoPlayer = new CompoPlayer();
  41. initAjaxLinks();
  42. initHistory();
  43. if(!_is_mobile){
  44. checkLayout();
  45. initAudioLinksHover();
  46. }
  47. if(_is_mobile){
  48. if(drupalSettings.path.isFront){
  49. initHomeMobile();
  50. }
  51. _$body.attr('booted', 'booted');
  52. }
  53. };
  54. // _ ___
  55. // | | ___ __ _ | __|__ _ _ _ __
  56. // | |__/ _ \/ _` | | _/ _ \ '_| ' \
  57. // |____\___/\__, | |_|\___/_| |_|_|_|
  58. // |___/
  59. function initLogForm(){
  60. console.log('initLogForm');
  61. _$log_form = $('#user-login-form:not(ajax-enebled)')
  62. .on('submit', onSubmitLogForm)
  63. .addClass('ajax-enabled');
  64. };
  65. function onSubmitLogForm(e){
  66. e.preventDefault();
  67. // console.log('onSubmitLogForm', e);
  68. var args = {
  69. name : $('input#edit-name[type="text"]', this).val(),
  70. pass : $('input#edit-pass[type="password"]', this).val()
  71. };
  72. // console.log(args);
  73. logIn(args).then(logedin);
  74. return false;
  75. };
  76. function logIn(args){
  77. console.log('logIn', args);
  78. _$log_form.addClass('ajax-loading');
  79. _$body.addClass('ajax-loading');
  80. return $.ajax({
  81. type: 'POST',
  82. headers: {'Content-Type': 'application/json'},
  83. xhrFields: {
  84. withCredentials: true
  85. },
  86. // accessToken : 'tokenvaluehere',
  87. url: _origin+_base_url+"user/login?_format=json",
  88. data: JSON.stringify(args),
  89. // name: args.mail,
  90. // pass: args.pass,
  91. success: function(response){
  92. // console.log('sucess', response);
  93. _user_tokens = response;
  94. },
  95. error: function (xhr, ajaxOptions, thrownError){
  96. console.log(xhr.status);
  97. console.log(thrownError);
  98. }
  99. });
  100. };
  101. function logedin(){
  102. $('body').addClass('user-logged-in');
  103. getStudioLinkBlock();
  104. };
  105. function getStudioLinkBlock(){
  106. var path = _origin+_base_url+'edlp/ajax/blocks/json/';
  107. $.getJSON(path+"studiolinkblock", {})
  108. .done(onStudioLinkBlockLoaded)
  109. .fail(function(jqxhr, textStatus, error){
  110. console.warn('Studio ink block load failed', jqxhr.responseText);
  111. });
  112. };
  113. function onStudioLinkBlockLoaded(data){
  114. console.log('onStudioLinkBlockLoaded', data);
  115. $('#block-studiouserlogin').replaceWith(data.blocks.studiolinkblock.rendered);
  116. initAjaxLinks();
  117. refreshFavoritesLinks();
  118. _$log_form.removeClass('ajax-loading');
  119. _$body.removeClass('ajax-loading');
  120. }
  121. // __ __ _ _ _
  122. // | \/ |___| |__(_) |___
  123. // | |\/| / _ \ '_ \ | / -_)
  124. // |_| |_\___/_.__/_|_\___|
  125. function initMobile(){
  126. console.log('initMobile');
  127. // $('[data-drupal-link-system-path="<front>"]','#block-mainnavigation')
  128. // .removeClass('is-active')
  129. // .attr('href', '#collection');
  130. // edlp_mobile.mobile_home_path.replace(/^\//, '')
  131. // TODO: remove collection from mobile home
  132. // TODO: replace ajax link to only collection for mobile
  133. $('h2, a', '#block-mainnavigation')
  134. .add('h2, a', '#block-mainnavigation-2')
  135. .on('click', onclickHomeMobileMenu);
  136. }
  137. function onclickHomeMobileMenu(e){
  138. // $('#block-mainnavigation').toggleClass('opened');
  139. $('#block-mainnavigation-2').toggleClass('opened');
  140. };
  141. function initHomeMobile(){
  142. // taxonomy-term.vocabulary-entrees.home_mobile
  143. // $('.field--name-field-notice, .index', '.entrees .taxonomy-term.vocabulary-entrees')
  144. // .addClass('closed');
  145. // $('.field--name-field-notice>.field__label', '.entrees .taxonomy-term.vocabulary-entrees')
  146. // .on('click', onClickHomeMobileNotice);
  147. // $('.index>.field__label', '.entrees .taxonomy-term.vocabulary-entrees')
  148. // .on('click', onClickHomeMobileIndex);
  149. };
  150. // function onClickHomeMobileNotice(e){
  151. // // console.log('onClickHomeMobileNotice');
  152. // // var $part = $(this).parent();//parents('.taxonomy-term');
  153. // toggleEntreeOpening($(this).parent(), 'notice');
  154. // };
  155. // function onClickHomeMobileIndex(e){
  156. // // console.log('onClickHomeMobileIndex');
  157. // // var $part = $(this).parent();//parents('.taxonomy-term');
  158. // toggleEntreeOpening($(this).parent(), 'index');
  159. // };
  160. // function toggleEntreeOpening($e, part){
  161. // $e.toggleClass('closed')
  162. // .parents('.taxonomy-term.vocabulary-entrees.home_mobile').toggleClass(part+'-opened');
  163. // }
  164. // ___ _
  165. // | __|_ _____ _ _| |_ ___
  166. // | _|\ V / -_) ' \ _(_-<
  167. // |___|\_/\___|_||_\__/__/
  168. function initEvents(){
  169. // https://www.html5rocks.com/en/tutorials/async/deferred/
  170. var $corpus_df = $.Deferred();
  171. _corpus_promise = $corpus_df.promise();
  172. _$body
  173. .on('corpus-map-ready', function(e){
  174. onCorpusMapReady(e);
  175. $corpus_df.resolve();
  176. })
  177. .on('on-studio-chutier-updated', initAjaxLinks)
  178. .on('studio-initialized', function(e){
  179. _compoPlayer.newCompo();
  180. })
  181. .on('studio-not-active', function(e){
  182. _compoPlayer.deactivate();
  183. })
  184. .on('on-studio-compo-updated', function(e){
  185. initAjaxLinks();
  186. _compoPlayer.refresh();
  187. })
  188. .on('on-studio-compo-opened', function(e){
  189. initAjaxLinks();
  190. _compoPlayer.newCompo();
  191. })
  192. .on('search-results-loaded', function(e){
  193. initAjaxLinks();
  194. initAudioLinksHover();
  195. checkVisibleCorpusMapSpace();
  196. })
  197. // do not close index or notice modale on entree click
  198. .on('open_entree', function(e){
  199. console.log('on_open_entree : e', e);
  200. closeAllModals();
  201. checkLayout();
  202. // add body class for currently loaded content
  203. // var body_classes = [
  204. // 'path-'+sys_path.replace(/\//g, '-'),
  205. // 'entity-type-'+data.entity_type,
  206. // 'bundle-'+data.bundle,
  207. // 'view-mode-'+data.view_mode
  208. // ];
  209. _$body.removeClass();//.addClass(body_classes.join(' '));
  210. // record new history state
  211. if(typeof e.url != 'undefined'){
  212. var state = getSysPathState(e.sys_path);
  213. history.pushState(state, null, e.url);
  214. // piwik
  215. if(typeof _paq !== 'undefined'){
  216. // page tracking
  217. // https://matomo.org/blog/2017/02/how-to-track-single-page-websites-using-piwik-analytics/
  218. _paq.push(['setCustomUrl', e.url]);
  219. _paq.push(['setDocumentTitle', e.title]);
  220. _paq.push(['trackPageView']);
  221. }
  222. }
  223. })
  224. .on('close_entree', function(e){
  225. backToFrontPage();
  226. checkLayout();
  227. });
  228. window.addEventListener('resize', checkLayout, false);
  229. }
  230. // __ ___ _ ___ _
  231. // \ \ / (_)_ _ __| |_____ __ __ | _ \___ __(_)______
  232. // \ \/\/ /| | ' \/ _` / _ \ V V / | / -_|_-< |_ / -_)
  233. // \_/\_/ |_|_||_\__,_\___/\_/\_/ |_|_\___/__/_/__\___|
  234. function checkLayout(){
  235. var $audioplayer = $("#audio-player");
  236. if($audioplayer.length){
  237. var navpos = $('#block-mainnavigation').position();
  238. // console.log('navpos', navpos);
  239. if(typeof navpos != 'undefined'){
  240. $audioplayer.css({
  241. 'width':navpos.left+'px'
  242. });
  243. }
  244. }
  245. checkGridBlockHeight();
  246. checkGridBlockVisible();
  247. // entrees
  248. // TODO: center the entrees menu
  249. };
  250. // ___ _ _ ___
  251. // / __| __ _ _ ___| | | _ ) __ _ _ _ ___
  252. // \__ \/ _| '_/ _ \ | | _ \/ _` | '_(_-<
  253. // |___/\__|_| \___/_|_|___/\__,_|_| /__/
  254. function initScrollbars(){
  255. // console.log("initScrollbars");
  256. // TODO: find a better js scroll than overlayScrollbars which does not handle well max-height + overflow-y:auto;
  257. // $('.os-scroll').overlayScrollbars({
  258. // overflowBehavior:{
  259. // x:'h',
  260. // y:'scroll',
  261. // clipAlways:false
  262. // }
  263. // });
  264. };
  265. // _ _
  266. // /_\ (_)__ ___ __
  267. // / _ \ | / _` \ \ /
  268. // /_/ \_\/ \__,_/_\_\
  269. // |__/
  270. function getSysPathState(sys_path, view_mode){
  271. // console.log('Theme : getSysPathState', sys_path);
  272. var state = {
  273. 'sys_path':sys_path,
  274. 'ajax_path': sys_path
  275. };
  276. // convert node link to edlp_ajax_node module links
  277. var node_match = state.ajax_path.match(/^\/?(node\/(\d+))$/i);
  278. console.log('node_match', node_match);
  279. var term_match = state.ajax_path.match(/^\/?(taxonomy\/term\/(\d+))$/i);
  280. console.log('term_match', term_match);
  281. if(node_match){
  282. // TODO: detect audio links which will open audioplayer and wont load any ajax content unless view_mode "article" or "transcript"
  283. state.ajax_path = _ajax_settings.entityjson_path+'/'+node_match[1];
  284. state.node_nid = node_match[2];
  285. // check for viewmode attribute
  286. if(view_mode){
  287. state.ajax_path += '/'+view_mode;
  288. state.view_mode = view_mode;
  289. }
  290. }else if(term_match){
  291. // terms are always entrees, there's no other vocabulary links in front
  292. state.ajax_path = _ajax_settings.entityjson_path+'/'+term_match[1];
  293. state.ajax_path = state.ajax_path.replace(/taxonomy\/term/, 'taxonomy_term');
  294. state.entree_tid = term_match[2];
  295. // check for viewmode attribute
  296. if(view_mode){
  297. state.ajax_path += '/'+view_mode;
  298. state.view_mode = view_mode;
  299. }else{
  300. state.ajax_path = null;
  301. }
  302. }else{
  303. // convert other link to ajax
  304. // TODO: we assume that other links (no node, no term) are all from own modules (e.g. productions) !! may not be true !!
  305. state.ajax_path += '/ajax'
  306. }
  307. return state;
  308. };
  309. function ajaxLoadContent(state){
  310. console.log('ajaxLoadContent : state', state);
  311. _$body.addClass('ajax-loading');
  312. _ajax_timing.start = performance.now();
  313. var path = _origin + Drupal.url(state.ajax_path);
  314. $.getJSON(path, {})
  315. .done(function(data){
  316. onAjaxLoaded(data, state);
  317. })
  318. .fail(function(jqxhr, textStatus, error){
  319. onAjaxLoadError(jqxhr, textStatus, error, state.sys_path);
  320. });
  321. };
  322. function onAjaxLoadError(jqxhr, textStatus, error, sys_path){
  323. console.warn('ajaxlink load failed for '+sys_path+' : '+error, jqxhr.responseText);
  324. $('.ajax-loading').removeClass('ajax-loading');
  325. _$body.removeClass('ajax-loading');
  326. };
  327. function onAjaxLoaded(data, state){
  328. console.log('ajax loaded', state, data);
  329. var $rendered = $(data.rendered);
  330. $rendered.attr({
  331. 'sys_path':state.sys_path,
  332. 'view_mode': state.view_mode
  333. });
  334. // console.log(data);
  335. // reset all style may been added by other pages (like masonry for productions)
  336. // and replace all content with newly loaded
  337. // TODO: build a system to replace or append contents (like studio + search)
  338. if(data.entity_type == "node" && data.bundle == "evenement"){
  339. if(_$row.find('.col.event').length){
  340. _$row.find('.col.event').replaceWith($rendered);
  341. }else if(_$row.find('.col.aside').length){
  342. _$row.find('.col.aside').replaceWith($rendered);
  343. }else{
  344. _$row.append($rendered);
  345. }
  346. }
  347. else if(
  348. (state.context == 'document-transcript' || state.context == 'document-artcile')
  349. && state.caller == "search"
  350. ){
  351. _$row.append($rendered);
  352. }
  353. else{
  354. _$row.removeAttr('style').html($rendered);
  355. }
  356. // remove article is-active class is static content loaded
  357. if ((data.entity_type == "node" && data.bundle == "static")
  358. || state.sys_path == "docsindex") {
  359. $('.ajax-link.is-active.articles-link').removeClass('is-active');
  360. }
  361. // add body class for currently loaded content
  362. var body_classes = [
  363. 'path-'+state.sys_path.replace(/\//g, '-'),
  364. 'entity-type-'+data.entity_type,
  365. 'bundle-'+data.bundle,
  366. 'view-mode-'+data.view_mode
  367. ];
  368. _$body.removeClass().addClass(body_classes.join(' '));
  369. // id node add a generic path-node class to body
  370. // m = state.sys_path.match(/^\/?(node\/\d+)$/g);
  371. // if(m)
  372. if(state.node_nid)
  373. _$body.addClass('path-edlp-node');
  374. // handle clicked link classes
  375. $('.ajax-loading').removeClass('ajax-loading');
  376. $('.ajax-link.is-active:not(.articles-link)').removeClass('is-active');
  377. $('.is-active-trail').removeClass('is-active-trail');
  378. if(typeof state.selector != 'undefined'){
  379. // in case of entree link (actualy, selector is used only for entries links)
  380. // TODO: unfortunatly on initFirstLoad there is no selector property
  381. console.log('selector', state.selector);
  382. $('a[selector="'+state.selector+'"]').addClass('is-active');
  383. initAudioLinksHover();
  384. }else{
  385. if(typeof state.view_mode != 'undefined'){
  386. $('a[viewmode="'+state.view_mode+'"][data-drupal-link-system-path="'+state.sys_path+'"]').addClass('is-active');
  387. }else{
  388. // wait for corpus map beeing ready (e.g. for articles link)
  389. _corpus_promise.done(function(){
  390. $('a[data-drupal-link-system-path="'+state.sys_path+'"]').addClass('is-active');
  391. });
  392. }
  393. // as new content is not related to entree, we trigger close entree
  394. _$body.trigger({'type':'new-content-not-entree-ajax-loaded'});
  395. }
  396. // if bundle page (productions) activate production links
  397. if (typeof data.bundle != 'undefined' && data.bundle == "page") {
  398. $('a[data-drupal-link-system-path="productions"]').addClass('is-active-trail');
  399. }
  400. // if node is in production menu tree, set first level of tree active, e.g. pieces sonores
  401. if (typeof data.menu_parents != 'undefined') {
  402. for (var i = 0; i < data.menu_parents.length; i++) {
  403. var menu_sys_path = data.menu_parents[i];
  404. $('a[data-drupal-link-system-path="'+menu_sys_path+'"]').addClass('is-active-trail');
  405. }
  406. }
  407. // if entity has corpus-map's linked document call a filter to corpus map
  408. if(typeof data.documents_lies != 'undefined'){
  409. if(_corpus_ready){
  410. _$body.trigger({
  411. type:'ajax-node-loaded-linked-documents',
  412. nids:data.documents_lies
  413. });
  414. }else{
  415. _corpus_promise.done(function(){
  416. _$body.trigger({
  417. type:'ajax-node-loaded-linked-documents',
  418. nids:data.documents_lies
  419. });
  420. });
  421. }
  422. }
  423. // if block attached (eg : from edlp_productions module)
  424. // not used anymore as production block is always present (but not visible)
  425. if(typeof data.block != 'undefined'){
  426. // if block not already added
  427. if(!$('#'+data.block.id, '.region-'+data.block.region).length){
  428. $('.region-'+data.block.region).append(data.block.rendered);
  429. }
  430. }
  431. // initScrollbars();
  432. if(state.sys_path == "productions"){
  433. // initProductions();
  434. initGrid();
  435. }else{
  436. addCloseModalBtnToCols();
  437. }
  438. if(state.sys_path == "collection"){
  439. // only for mobile version of collection
  440. initCollectionNav();
  441. }
  442. // enregistrement transcription
  443. if(data.entity_type == "node" && data.bundle == "enregistrement" && data.view_mode == "transcript"){
  444. // window.requestAnimationFrame(initEnregistrementTranscript);
  445. initEnregistrementTranscript();
  446. }
  447. if(state.sys_path == "search"){
  448. initSearch();
  449. }
  450. // update the language switcher block if it comes in the response
  451. if(typeof data.translations_links != 'undefined'){
  452. console.log('state',state);
  453. var lang_code = drupalSettings.path.currentLanguage;
  454. var $links = $(data.translations_links);
  455. // set active link
  456. $links.find('li[hreflang="'+lang_code+'"]').addClass('is-active').find('a').addClass('is-active');
  457. if(state.view_mode){
  458. $links.find('a').each(function(i,e){
  459. var $a = $(this);
  460. $a.attr('href', $a.attr('href')+'#'+state.view_mode);
  461. });
  462. }
  463. // if(state.selector){
  464. // $links.find('a').attr('selector', state.selector);
  465. // }
  466. $('ul','.block.language-switcher-language-url').replaceWith($links);
  467. }
  468. initAjaxLinks();
  469. initAudioLinksHover();
  470. checkVisibleCorpusMapSpace();
  471. // trigger other modules behaviours
  472. _$body.trigger({'type':'new-content-ajax-loaded'});
  473. // and call drupal behaviours
  474. Drupal.attachBehaviors(_$row[0]);
  475. _$body.attr('booted', 'booted');
  476. _$body.removeClass('ajax-loading');
  477. // record the states history as we can't get them from history api
  478. _states_history.unshift(state);
  479. // url is null means that we are loading content on popState event
  480. // so we don't record the state again
  481. if(state.url){
  482. // /!\ we can not pushestate with absolute url /!\
  483. history.pushState(state, null, state.url);
  484. // piwik
  485. if(typeof _paq !== 'undefined'){
  486. // page tracking
  487. // https://matomo.org/blog/2017/02/how-to-track-single-page-websites-using-piwik-analytics/
  488. _paq.push(['setCustomUrl', state.url]);
  489. _paq.push(['setDocumentTitle', data.title]);
  490. // TODO: piwik track load time
  491. _ajax_timing.end = performance.now();
  492. _paq.push(['setGenerationTimeMs', _ajax_timing.end-_ajax_timing.start]);
  493. _paq.push(['trackPageView']);
  494. // js event
  495. // trackEvent(category, action, [name], [value])
  496. // _paq.push(['trackEvent', 'AjaxNav', 'loaded', state.url]);
  497. }
  498. }
  499. };
  500. function initAudioLinksHover(){
  501. console.log("initAudioLinksHover()");
  502. _$row.find('a.audio-link')
  503. .not('article.node--view-mode-docsindex a.audio-link')
  504. .on('mouseover', function(event) {
  505. event.preventDefault();
  506. if(_corpus_ready){
  507. _$corpus_canvas.trigger({
  508. type:'mouseover-audio-link',
  509. nid:$(this).attr('nid')
  510. });
  511. }
  512. })
  513. .on('mouseout', function(event) {
  514. event.preventDefault();
  515. if(_corpus_ready){
  516. _$corpus_canvas.trigger({
  517. type:'mouseout-audio-link',
  518. nid:$(this).attr('nid')
  519. });
  520. }
  521. });
  522. };
  523. function addCloseModalBtnToCols(){
  524. if(_is_mobile) return;
  525. $('.col', _$row).each(function(index, el) {
  526. if($('span.close-col-btn', this).length)
  527. return true;
  528. $(this).children('.wrapper').prepend($('<span>')
  529. .addClass('close-col-btn')
  530. .on('click', onCloseModal)
  531. );
  532. });
  533. };
  534. function onCloseModal(e){
  535. console.log("onCloseModal");
  536. // check from production to audio text back to production
  537. console.log("onCloseModal _states_history",_states_history);
  538. if(['document-transcript', 'document-article'].indexOf(_states_history[0].context) != -1)
  539. {
  540. if (_states_history[0].caller == "production") {
  541. for (var i = 0; i < _states_history.length; i++) {
  542. if (_states_history[i].context == "production") {
  543. // history.go(i*-1-1);
  544. console.log("onCloseModal return to production", _states_history[i]);
  545. ajaxLoadContent(_states_history[i]);
  546. return;
  547. }
  548. }
  549. }
  550. if (_states_history[0].caller == "entree-index") {
  551. for (var i = 0; i < _states_history.length; i++) {
  552. if (_states_history[i].context == "entree-index") {
  553. console.log("onCloseModal return to entree-index", _states_history[i]);
  554. ajaxLoadContent(_states_history[i]);
  555. return;
  556. }
  557. }
  558. }
  559. if (_states_history[0].caller == "entree-notice") {
  560. for (var i = 0; i < _states_history.length; i++) {
  561. if (_states_history[i].context == "entree-notice") {
  562. console.log("onCloseModal return to entree-notice", _states_history[i]);
  563. ajaxLoadContent(_states_history[i]);
  564. return;
  565. }
  566. }
  567. }
  568. }
  569. // return to productions home when closing a prod
  570. // if(['production'].indexOf(_states_history[0].context) != -1)
  571. // {
  572. // var i = 0;
  573. // while (_states_history[i].caller == "production-home") {
  574. // if (_states_history[i].context == "production-home") {
  575. // // history.go(i*-1-1);
  576. // console.log("onCloseModal return to productions home", _states_history[i]);
  577. // ajaxLoadContent(_states_history[i]);
  578. // return;
  579. // }
  580. // i++;
  581. // }
  582. // }
  583. // check for theme attribute and emmit event
  584. var $col = $(this).parents('.col');
  585. var theme = $col.attr('theme');
  586. if(theme != ''){
  587. _$body.trigger({'type':theme+'-col-closed'});
  588. }
  589. if(_$body.is('.entity-type-node.bundle-page') && $(this).next().is('.node--type-page')){
  590. // remove all the col (prod page and agenda in case) only if closing the main page col
  591. // if closing the aside col (agenda) leave the main col in place
  592. $col.add($col.siblings('.col')).remove();
  593. }else{
  594. // remove the col
  595. $col.remove();
  596. }
  597. checkRowEmpty();
  598. checkVisibleCorpusMapSpace();
  599. // set links to this modal to not active (tested on articles from audio cartel)
  600. if( $col.attr('view_mode') && $col.attr('sys_path')){
  601. $('a[data-drupal-link-system-path="'+$col.attr('sys_path')+'"][viewmode="'+$col.attr('view_mode')+'"]').removeClass('is-active');
  602. }
  603. };
  604. // _ _ ___ _ _
  605. // /_\ (_)__ ___ __ | _ ) |___ __| |__ ___
  606. // / _ \ | / _` \ \ / | _ \ / _ \/ _| / /(_-<
  607. // /_/ \_\/ \__,_/_\_\ |___/_\___/\__|_\_\/__/
  608. // |__/
  609. // NOT USED (YET)
  610. // function refreshAllBlocks(){
  611. // var path = _origin + Drupal.url(_ajax_settings.blocksjson_path);
  612. // $.getJSON(path, {})
  613. // .done(function(data){
  614. // onAjaxBlockLoaded(data);
  615. // })
  616. // .fail(function(jqxhr, textStatus, error){
  617. // onAjaxBlockLoadError(jqxhr, textStatus, error);
  618. // });
  619. // };
  620. // function onAjaxBlockLoadError(jqxhr, textStatus, error){
  621. // console.warn('ajax block load failed: '+error, jqxhr.responseText);
  622. // };
  623. // function onAjaxBlockLoaded(data){
  624. // console.log('onAjaxBlockLoaded', data);
  625. // // TODO: update each blocks (exepted language switcher)
  626. // for (var blockname in data.blocks) {
  627. // var block = data.blocks[blockname];
  628. // console.log(blockname, block);
  629. // $(block.id).replaceWith(block.rendered);
  630. // }
  631. // };
  632. // _ _ _ _
  633. // | || (_)__| |_ ___ _ _ _ _
  634. // | __ | (_-< _/ _ \ '_| || |
  635. // |_||_|_/__/\__\___/_| \_, |
  636. // |__/
  637. function initHistory(){
  638. initFirstLoad();
  639. window.addEventListener('popstate', onHistoryPopState);
  640. };
  641. function initFirstLoad(){
  642. console.log('theme : initFirstLoad()');
  643. console.log('window.location', window.location);
  644. // var origin_sys_path = window.localStorage.getItem('edlp_origin_path');
  645. var edlp_origin = JSON.parse(window.localStorage.getItem('edlp_origin'));
  646. console.log('edlp_origin', edlp_origin);
  647. if(edlp_origin != null && edlp_origin.sys_path){
  648. // hash is used as viewmode for taxonomy term entrees load (index or notice)
  649. // and for audio contents (article|transcript)
  650. var hash = edlp_origin.hash.replace('#', '');
  651. // create history state
  652. var state = getSysPathState(edlp_origin.sys_path, hash);
  653. // add historic_index 0 to state
  654. state.historic_index = 0;
  655. // open entree tray in case of entree index|notice
  656. // (index or notice will be opened with ajaxLoadContent)
  657. // refactorized with new infos from edlp_origin
  658. // if(hash){
  659. if(edlp_origin.entity_type == "taxonomy_term"
  660. && edlp_origin.entity_bundle == "entrees"
  661. && hash){
  662. // var $link = $('[href="'+edlp_origin.url+'"][viewmode="'+hash+'"]');
  663. // var selector = $link.attr('selector') || null;
  664. // record the selector in the state for actions after ajaxContentLoaded
  665. state.selector = 'entree-'+hash+'-link-'+edlp_origin.entity_id; // entree-index-link-125
  666. // if(selector){
  667. // in case of entree link (actualy, selector is used only for entries links)
  668. // TODO: use a promise
  669. // TODO: but what if corpus ready before onAjaxLoaded >> use a promise !!
  670. if(_corpus_ready){
  671. _$corpus_canvas.trigger({
  672. type:'open-entree',
  673. // tid:$link.attr('tid')
  674. tid:edlp_origin.entity_id
  675. });
  676. }else{
  677. // else : EdlpCorpus will check when ready if entry item (notice or index) is already .is-active
  678. // .is-active class is added by onAjaxLoaded() (when content is loaded)
  679. // $('li.entree[tid="'+$link.attr('tid')+'"] a.term-link').addClass('is-active');
  680. $('li.entree[tid="'+edlp_origin.entity_id+'"] a.term-link').addClass('is-active');
  681. }
  682. // }
  683. }
  684. // check if audio link
  685. // only if not random link
  686. if(edlp_origin.audio_url){
  687. var node = {
  688. nid:edlp_origin.entity_id,
  689. audio_url:edlp_origin.audio_url
  690. };
  691. _audioPlayer.openDocument(node, 'history_first_load');
  692. // close home
  693. closeAllModals();
  694. if(hash == "" || hash == 'random'){
  695. console.log('first load hash', hash);
  696. // if hash is random, RandomPlayer will be started when playlist sent by corpus.js
  697. // if audio only record in state
  698. state.audio = true;
  699. state.node = node;
  700. if(!_is_mobile){
  701. // if not mobile we don't laod ajax content so we boot the home
  702. _$body.attr('booted', 'booted');
  703. }else{
  704. ajaxLoadContent(state);
  705. }
  706. }else{
  707. console.log('first load load content');
  708. // ajax load content for audio only if article or transcript
  709. ajaxLoadContent(state);
  710. }
  711. }
  712. // only if not entree path
  713. // only if not audio (without article or transcript) path
  714. else if(state.ajax_path){
  715. // load content through ajax
  716. // ajaxLoadContent(null, state.sys_path, state.ajax_path, selector);
  717. ajaxLoadContent(state);
  718. }
  719. if(state.entree_tid){
  720. openEntree(state.entree_tid);
  721. }
  722. // record history state
  723. history.replaceState(state, null, edlp_origin.url+edlp_origin.hash);
  724. // reset the storage
  725. window.localStorage.removeItem("edlp_origin");
  726. // window.localStorage.removeItem("edlp_origin_url");
  727. }else{
  728. // if(window.location.hash == "#random"){
  729. //
  730. // }
  731. history.replaceState({home:true}, null, window.location.pathname+window.location.hash);
  732. // initHome();
  733. initGrid();
  734. _$body.attr('booted', 'booted');
  735. }
  736. };
  737. function onHistoryPopState(e){
  738. console.log('onPopState',e.state);
  739. if(e.state.home){
  740. backToFrontPage(true);
  741. }
  742. else if (e.state.audio) {
  743. console.log('popstate audio : e.state', e.state);
  744. _audioPlayer.openDocument(e.state.node, 'popstate', e.state.historic_index);
  745. if(_is_mobile){
  746. ajaxLoadContent(e.state)
  747. }
  748. }
  749. else{
  750. if(e.state.entree_tid){
  751. openEntree(e.state.entree_tid);
  752. }
  753. if(e.state.ajax_path){
  754. e.state.url = null;
  755. // ajaxLoadContent(null, e.state.sys_path, e.state.ajax_path)
  756. ajaxLoadContent(e.state);
  757. }
  758. }
  759. };
  760. // _ _ _ _ _
  761. // /_\ (_)__ ___ _| | (_)_ _ | |__ ___
  762. // / _ \ | / _` \ \ / |__| | ' \| / /(_-<
  763. // /_/ \_\/ \__,_/_\_\____|_|_||_|_\_\/__/
  764. // |__/
  765. function initAjaxLinks(){
  766. // console.log('initAjaxLinks');
  767. $('a', '#block-mainnavigation')
  768. .add('a', '#block-mainnavigation-2')
  769. // .add('a', '.block.language-switcher-language-url')
  770. .add('a', '#block-footer.menu--footer')
  771. .add('a', '#block-productions')
  772. .add('a', 'article.node:not(.node--type-enregistrement) h2.node-title')
  773. // .add('a', 'article.node--type-evenement.node--view-mode-teaser .field--name-field-page-liee')
  774. .add('a', '.productions-subtree')
  775. .add('a', '.productions-parent')
  776. // .add('a.index-link, a.notice-link', '#block-edlpentreesblock')
  777. .add('a', '.field--name-field-son')
  778. .addClass('ajax-link');
  779. if(!_is_mobile){
  780. $('a.site-name', '#block-edlptheme-branding').addClass('ajax-link');
  781. }
  782. _$ajaxLinks = $('.ajax-link');
  783. activateAjaxLinks();
  784. };
  785. function activateAjaxLinks(){
  786. // $('.ajax-link:not(.ajax-enabled)')
  787. _$ajaxLinks.each(function(i,e){
  788. var $this = $(this);
  789. // avoid already ajaxified links
  790. if($this.is('.ajax-enable')) return;
  791. if($this.attr('data-drupal-link-system-path') || $this.is('[type^="audio"]')){
  792. $this.on('click', onClickAjaxLink).addClass('ajax-enable');
  793. }
  794. });
  795. };
  796. function onClickAjaxLink(e){
  797. e.preventDefault();
  798. var $link = $(this);
  799. // let the site-name link going through as it will shuffle the map if already active
  800. if($link.is('.is-active') && !$link.is('.site-name'))
  801. return false;
  802. // Audio links
  803. // launch audio player and stop here
  804. if($link.is('.audio-link')){
  805. // check if caller is lastdocs block
  806. caller = $link.parents('.lastdocs, .lastdocs-home').length ? 'lastdocs' : null;
  807. // check if caller is studio composition
  808. if(!caller){
  809. caller = $link.parents('.composition_ui').length ? 'studio-compo' : null;
  810. }
  811. // open audio player
  812. if(caller == 'studio-compo'){
  813. var index = $link.parents('.field__item').index();
  814. console.log('audio link caller', caller, index);
  815. // _compoPlayer.setIndex(index);
  816. _compoPlayer.start(index);
  817. }else{
  818. _audioPlayer
  819. .emmit('stop-shuffle')
  820. .openDocument({
  821. nid:$link.attr('nid'),
  822. audio_url:$link.attr('audio_url'),
  823. title:$link.find('.field--name-title').html()
  824. },
  825. caller);
  826. }
  827. return false;
  828. }
  829. // other sounds playing
  830. if($link.is('[type^="audio"]')){
  831. _audioPlayer
  832. .emmit('stop-shuffle')
  833. .openSound($link.attr('href'), $link.html());
  834. return false;
  835. }
  836. // NOT USED ( YET ? )
  837. // if($link.is('.language-link')){
  838. // TODO: change global site current language
  839. // load all blocks translated (exepted language switcher) ... :/
  840. // refreshAllBlocks();
  841. // TODO: use a promise to initAjaxLinks again after blocks updated
  842. // then let load the content
  843. // }
  844. // other links
  845. var sys_path = $(this).attr('data-drupal-link-system-path');
  846. // front page
  847. // just remove contents and stop here
  848. if(sys_path == '<front>'){
  849. if(!_is_mobile){
  850. if($link.is('.is-active') && _corpus_ready){
  851. _$corpus_canvas.trigger({'type':'shuffle-collection'});
  852. }else{
  853. backToFrontPage();
  854. }
  855. return false;
  856. }
  857. // else{
  858. // sys_path = edlp_mobile.mobile_home_path.replace(/^\//, '');
  859. // }
  860. }
  861. var view_mode = $link.attr('viewmode');
  862. var state = getSysPathState(sys_path, view_mode);
  863. state.url = $(this).attr('href');
  864. if(view_mode){
  865. state.url += "#"+view_mode;
  866. }
  867. // get context for navigation purpose
  868. // var contexts = state.url.match(/^.*\/(productions)\/.*/g);
  869. var contexts = /^.*\/(productions|documents|entrees|search)(\/.*)?/g.exec(state.url);
  870. console.log("onClickAjaxLink contexts", contexts);
  871. if(contexts){
  872. switch (contexts[1]) {
  873. case 'productions':
  874. // console.log("onClickAjaxLink is production");
  875. // if (typeof contexts[2] !== 'undefined') {
  876. state.context = "production"
  877. // }else{
  878. // state.context = "production-home"
  879. // }
  880. break;
  881. case 'entrees':
  882. switch(view_mode) {
  883. case 'index':
  884. state.context = "entree-index";
  885. break;
  886. case 'notice':
  887. state.context = "entree-notice";
  888. break;
  889. }
  890. break;
  891. case 'search':
  892. state.context = "search";
  893. break;
  894. case 'documents':
  895. // console.log("onClickAjaxLink is production");
  896. switch (view_mode) {
  897. case 'transcript':
  898. state.context = "document-transcript";
  899. break;
  900. case 'article':
  901. state.context = "document-article";
  902. break;
  903. default:
  904. state.context = "document";
  905. }
  906. // get the caller from pecedent context
  907. if(typeof _states_history[0] != "undefined"){
  908. if(_states_history[0].caller){
  909. state.caller = _states_history[0].caller
  910. }else{
  911. state.caller = _states_history[0].context
  912. }
  913. }else{
  914. state.caller = null;
  915. }
  916. break;
  917. }
  918. }else{
  919. state.context = null;
  920. // state.context = caller;
  921. }
  922. if($link.is('[selector]')){
  923. state.selector = $link.attr('selector');
  924. }
  925. $link.addClass('ajax-loading');
  926. // ajaxLoadContent(url, sys_path, state.ajax_path, selector);
  927. ajaxLoadContent(state);
  928. return false;
  929. };
  930. function refreshFavoritesLinks(){
  931. console.log("refreshFavoritesLinks", _states_history);
  932. // reload the active audioPlayer cartel
  933. _audioPlayer.reloadNode();
  934. // current content (index)
  935. if(_states_history[0].view_mode == 'index' || _states_history[0].sys_path == "docsindex"){
  936. ajaxLoadContent(_states_history[0]);
  937. }
  938. }
  939. // ___
  940. // / __|___ _ _ _ __ _ _ ___
  941. // | (__/ _ \ '_| '_ \ || (_-<
  942. // \___\___/_| | .__/\_,_/__/
  943. // |_|
  944. function onCorpusMapReady(e){
  945. //console.log('theme : onCorpusReady', e);
  946. _corpus_ready = true;
  947. _$corpus_canvas = $('canvas#corpus-map');
  948. _$corpus_canvas
  949. .on('corpus-cliked-on-map', function(e) {
  950. //console.log('theme : corpus-cliked-on-map');
  951. backToFrontPage();
  952. })
  953. .on('corpus-cliked-on-node', function(e) {
  954. //console.log('theme : corpus-cliked-on-node', e);
  955. _audioPlayer
  956. .emmit('stop-shuffle')
  957. // .setAutoOpenArticle(e.article)
  958. .openDocument(e.target_node);
  959. });
  960. _randomPlayer = new RandomPlayer(e.playlist);
  961. if (_is_expo) {
  962. initExpo();
  963. }
  964. // mainly for articles link
  965. initAjaxLinks();
  966. _$body.attr('corpus-map', 'ready');
  967. }
  968. function openEntree(tid){
  969. if(tid){
  970. closeAllModals();
  971. _$body.removeClass();//.addClass(body_classes.join(' '));
  972. // open entree
  973. if(_corpus_ready){
  974. _$corpus_canvas.trigger({
  975. type:'open-entree',
  976. tid:tid
  977. });
  978. }else{
  979. // else : EdlpCorpus will check when ready if entry item (notice or index) is already .is-active
  980. $('li.entree[tid="'+tid+'"] a.term-link').addClass('is-active');
  981. }
  982. }
  983. };
  984. function checkVisibleCorpusMapSpace(){
  985. var left_limit = 0, right_limit = 0;
  986. _$row.find('.col').each(function(i,e){
  987. var $col = $(this);
  988. var offset = $col.offset();
  989. console.log('$col', $col);
  990. switch(true){
  991. case $col.is('.float-right'):
  992. right_limit = Math.max(right_limit, Math.abs(offset.left-15-window.innerWidth));
  993. break;
  994. default:
  995. left_limit = Math.max(left_limit, offset.left+$col.width()+15);
  996. break;
  997. }
  998. });
  999. console.log('checkVisibleCorpusMapSpace left_limit:'+left_limit+" right_limit:"+right_limit);
  1000. if(_corpus_ready){
  1001. _$body.trigger({
  1002. type:'visible-space-changed',
  1003. left_limit:left_limit,
  1004. right_limit:right_limit
  1005. });
  1006. }else{
  1007. _corpus_promise.done(function(){
  1008. _$body.trigger({
  1009. type:'visible-space-changed',
  1010. left_limit:left_limit,
  1011. right_limit:right_limit
  1012. });
  1013. });
  1014. }
  1015. };
  1016. // _ _ _
  1017. // /_\ _ _ __| (_)___
  1018. // / _ \ || / _` | / _ \
  1019. // /_/ \_\_,_\__,_|_\___/
  1020. //
  1021. // https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement
  1022. // https://docs.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/samples/gg589528%28v%3dvs.85%29
  1023. // https://www.binarytides.com/using-html5-audio-element-javascript/
  1024. function AudioPlayer(){
  1025. var that = this;
  1026. this.fid;
  1027. this.audio = new Audio();
  1028. // audio events
  1029. this.audio_events = ["loadedmetadata","playing","pause","timeupdate","ended","error"]; // ,"canplay"
  1030. // UI dom objects
  1031. this.$container = $('<div id="audio-player">');
  1032. // btns
  1033. this.$btns = $('<div>').addClass('btns').appendTo(this.$container);
  1034. this.$previous = $('<div>').addClass('previous').appendTo(this.$btns);
  1035. this.$playpause = $('<div>').addClass('play-pause').appendTo(this.$btns);
  1036. this.$next = $('<div>').addClass('next').appendTo(this.$btns);
  1037. // timeline
  1038. this.$timelinecont= $('<div>').addClass('time-line-container').appendTo(this.$container);
  1039. this.$timeline = $('<div>').addClass('time-line').appendTo(this.$timelinecont);
  1040. this.$loader = $('<div>').addClass('loader').appendTo(this.$timeline);
  1041. this.$cursor = $('<div>').addClass('cursor').appendTo(this.$timeline);
  1042. // time
  1043. this.$time = $('<div>').addClass('time').appendTo(this.$container);
  1044. this.$currentTime = $('<div>').addClass('current-time').html('00:00').appendTo(this.$time);
  1045. this.$duration = $('<div>').addClass('duration').html('00:00').appendTo(this.$time);
  1046. // favoris
  1047. this.$fav = $('<div>').addClass('favoris').appendTo(this.$container);
  1048. // cartel
  1049. this.$cartel = $('<div>').addClass('cartel').appendTo(this.$container);
  1050. this.scndCartel_visible = 0;
  1051. this.cartelSwitchIntervalMS = 7000;
  1052. this.cartelSwitchInterval = false;
  1053. // hiding
  1054. this.visible = false;
  1055. this.hideTimer = false;
  1056. this.hideTimeMS = 15000;
  1057. // history
  1058. this.currentHistoricIndex = null;
  1059. this.historic = [];
  1060. this.shuffle_is_active = false;
  1061. // artciles
  1062. this.auto_open_article = false;
  1063. // object events
  1064. this.event_handlers = {
  1065. 'audio-open-document':[],
  1066. 'audio-play':[],
  1067. 'audio-pause':[],
  1068. 'audio-play-next':[],
  1069. 'audio-ended':[],
  1070. 'stop-shuffle':[]
  1071. };
  1072. this.init();
  1073. };
  1074. AudioPlayer.prototype = {
  1075. init(){
  1076. if(!_is_expo){
  1077. this.$container_parent = $('header[role="banner"] .region-header');
  1078. }else{
  1079. this.$container_parent = $('main[role="main"]');
  1080. }
  1081. // append ui to document
  1082. this.$container.appendTo(this.$container_parent);
  1083. // record timeline width
  1084. this.timeline_w = parseInt(this.$timeline.width());
  1085. // init seeking
  1086. this.$loader.on('click', this.seek.bind(this));
  1087. // init audio events
  1088. var fn = '';
  1089. for (var i = 0; i < this.audio_events.length; i++) {
  1090. fn = this.audio_events[i];
  1091. // capitalize first letter of event (only cosmetic :p )
  1092. fn = 'on'+fn.charAt(0).toUpperCase()+fn.slice(1);
  1093. this.audio.addEventListener(
  1094. this.audio_events[i],
  1095. this[fn].bind(this),
  1096. true);
  1097. }
  1098. // init btns events
  1099. this.$previous.on('click', this.playPrevious.bind(this));
  1100. this.$playpause.on('click', this.togglePlayPause.bind(this));
  1101. this.$next.on('click', this.playNext.bind(this));
  1102. },
  1103. openDocument(node, caller, historic_index){
  1104. console.log('AudioPlayer openDocument', node, caller, historic_index);
  1105. if(typeof node == 'undefined'
  1106. || typeof node.nid == 'undefined'
  1107. || typeof node.audio_url == 'undefined'){
  1108. console.warn('AudioPlayer openDocument() node is malformed', node);
  1109. return false;
  1110. }
  1111. // if we don't come from history popstate
  1112. if(typeof caller == 'undefined' || caller != 'popstate'){
  1113. console.log('');
  1114. this.historic.push(node);
  1115. this.currentHistoricIndex = this.historic.length-1;
  1116. // this.shuffle_mode = shuffle_mode || false;
  1117. // add the document opening to history to be able to share and play audio from any where
  1118. if(caller != "history_first_load"){
  1119. if(typeof node.document_url == 'undefined'){
  1120. console.warn("AudioPlayer openDocument missing document_url, can't push state to history", caller, node);
  1121. }else{
  1122. var state = {
  1123. audio:true,
  1124. node:{
  1125. nid:node.nid,
  1126. audio_url:node.audio_url,
  1127. document_url:node.document_url,
  1128. title:node.title || null,
  1129. },
  1130. historic_index : this.currentHistoricIndex,
  1131. };
  1132. // console.log('AudioPlayer pushstate', state);
  1133. var url = node.document_url + (caller == 'random' ? '#random' : '');
  1134. history.pushState(state, null, url);
  1135. }
  1136. }
  1137. }else{
  1138. // if the call commes from popstate, we update the current position of index
  1139. this.currentHistoricIndex = historic_index;
  1140. }
  1141. if(_$body.is('.path-frontpage') && caller !== 'lastdocs' && !_is_mobile){
  1142. closeAllModals();
  1143. }
  1144. // TODO: update language switcher for document url
  1145. // TODO: stop random player if playing from studio
  1146. this.emmit('audio-open-document', {caller:caller});
  1147. // piwik
  1148. // debugger;
  1149. if(typeof _paq !== 'undefined'){
  1150. // page tracking
  1151. // https://matomo.org/blog/2017/02/how-to-track-single-page-websites-using-piwik-analytics/
  1152. // _paq.push(['setCustomUrl', state.url]);
  1153. // _paq.push(['setDocumentTitle', data.title]);
  1154. // _paq.push(['trackPageView']);
  1155. // js event
  1156. // trackEvent(category, action, [name], [value])
  1157. if(typeof node.title != 'undefined'){
  1158. _paq.push(['trackEvent', 'Audio', 'play', node.title]);
  1159. }
  1160. }
  1161. this.launch();
  1162. },
  1163. launch(){
  1164. this.clearTimeOutToHide();
  1165. this.clearIntervalAutoCartelSwitch();
  1166. console.log('this.historic', this.historic);
  1167. console.log('this.currentHistoricIndex', this.currentHistoricIndex);
  1168. this.setSRC(this.historic[this.currentHistoricIndex].audio_url);
  1169. if(!_is_mobile){
  1170. this.loadNode(this.historic[this.currentHistoricIndex].nid);
  1171. }
  1172. // emmit new playing doc (e.g.: corpus map nowing that audio played from RandomPlayer)
  1173. try {
  1174. _$corpus_canvas.trigger({
  1175. 'type':'audio-node-opened',
  1176. 'nid':this.historic[this.currentHistoricIndex].nid
  1177. });
  1178. } catch (e) {
  1179. console.info('AudioPlayer : _$corpus_canvas does not exists, testing promise');
  1180. var that = this;
  1181. _corpus_promise.done(function(){
  1182. _$corpus_canvas.trigger({
  1183. 'type':'audio-node-opened',
  1184. 'nid':that.historic[that.currentHistoricIndex].nid
  1185. });
  1186. });
  1187. }
  1188. this.showHidePreviousBtn();
  1189. this.showHideNextBtn();
  1190. this.show();
  1191. },
  1192. openSound(url, title){
  1193. this.hide();
  1194. this.clearTimeOutToHide();
  1195. this.$cartel.html("");
  1196. this.setSRC(url);
  1197. this.show();
  1198. if(typeof _paq !== 'undefined'){
  1199. _paq.push(['trackEvent', 'Audio', 'play', url]);
  1200. }
  1201. },
  1202. // audio functions
  1203. setSRC(url){
  1204. console.log('AudioPlayer setSRC : url', url);
  1205. this.audio.src = url;
  1206. // need to trigger play right now to prevent safari blocking auto-play
  1207. this.play();
  1208. },
  1209. // audio is ready to play
  1210. onLoadedmetadata(){
  1211. var rem = parseInt(this.audio.duration, 10),
  1212. mins = Math.floor(rem/60,10),
  1213. secs = rem - mins*60;
  1214. this.$duration.html('<span>'+(mins<10 ? '0':'')+mins+':'+(secs<10 ? '0':'')+secs+'</span>');
  1215. this.updateLoadingBar();
  1216. },
  1217. updateLoadingBar(){
  1218. console.log("updateLoadingBar");
  1219. // var that = this;
  1220. // if (this.audio.readyState === 4){
  1221. if(this.audio.buffered.length>0){
  1222. // debugger;
  1223. this.$loader.css({
  1224. 'width':parseInt((100 * this.audio.buffered.end(0) / this.audio.duration), 10)+'%'
  1225. });
  1226. if( this.audio.buffered.end(0) < this.audio.duration ){
  1227. // loop through this function until file is fully loaded
  1228. window.requestAnimationFrame(this.updateLoadingBar.bind(this));
  1229. }else{
  1230. console.log('Audio fully loaded');
  1231. }
  1232. }else{
  1233. // as audio buffer is not ready, recall updateLoadingBar in next frame
  1234. window.requestAnimationFrame(this.updateLoadingBar.bind(this));
  1235. }
  1236. },
  1237. // onCanplay(){
  1238. // // this.play();
  1239. // },
  1240. onError(){
  1241. console.warn("Audio Error " + this.audio.error.code + "; details: " + this.audio.error.message);
  1242. },
  1243. play(){
  1244. this.clearTimeOutToHide();
  1245. // this.audio.play();
  1246. // making sound shorter for debuging purpose
  1247. // if(_is_expo){
  1248. // setTimeout(this.seekToEnd.bind(this), 20000);
  1249. // }
  1250. // 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
  1251. var promise = this.audio.play();
  1252. // console.log('promise', promise);
  1253. if (promise !== undefined) {
  1254. promise.catch(function(error){
  1255. // Auto-play was prevented
  1256. // Show a UI element to let the user manually start playback
  1257. console.warn('autoplay failed, ask for playing', error);
  1258. }).then(function(){
  1259. // Auto-play started
  1260. console.log('autoplay succeed');
  1261. });
  1262. }
  1263. },
  1264. playPrevious(){
  1265. if(this.currentHistoricIndex > 0){
  1266. this.currentHistoricIndex -= 1;
  1267. this.launch();
  1268. // TODO: update history state
  1269. }
  1270. },
  1271. playNext(){
  1272. if(this.currentHistoricIndex < this.historic.length-1){
  1273. this.currentHistoricIndex += 1;
  1274. this.launch();
  1275. // TODO: update history state
  1276. }else{
  1277. this.emmit('audio-play-next');
  1278. }
  1279. },
  1280. togglePlayPause(e){
  1281. if(this.audio.paused){
  1282. // this.audio.play();
  1283. this.play();
  1284. }else{
  1285. // this.audio.pause();
  1286. this.stop();
  1287. }
  1288. },
  1289. stop(){
  1290. // console.log('AudioPlayer stop()');
  1291. // debugger;
  1292. this.audio.pause();
  1293. // don't close player if article or transcript is open
  1294. if(!(_$body.is('.path-node-'+this.historic[this.currentHistoricIndex].nid)
  1295. && (_$body.is('.view-mode-article') || _$body.is('.view-mode-transcript')))){
  1296. this.timeOutToHide();
  1297. }
  1298. },
  1299. seek(e){
  1300. var seek = e.originalEvent.layerX / this.timeline_w * this.audio.duration
  1301. console.log("Audio seeking : seek", seek);
  1302. this.audio.currentTime = seek;
  1303. },
  1304. seekToEnd(){
  1305. if (this.audio.duration > 40) {
  1306. console.log("seekToEnd", this.audio.duration);
  1307. this.audio.currentTime = this.audio.duration - 20;
  1308. }
  1309. },
  1310. // audio events
  1311. onPlaying(){
  1312. this.$btns.addClass('is-playing');
  1313. this.emmit('audio-play');
  1314. },
  1315. onPause(){
  1316. this.$btns.removeClass('is-playing');
  1317. this.emmit('audio-pause');
  1318. },
  1319. onTimeupdate(){
  1320. // move cursor
  1321. this.$cursor.css({
  1322. 'left':(this.audio.currentTime/this.audio.duration * this.timeline_w)+"px"
  1323. });
  1324. // update time text display
  1325. var rem = parseInt(this.audio.currentTime, 10),
  1326. mins = Math.floor(rem/60,10),
  1327. secs = rem - mins*60;
  1328. this.$currentTime.html('<span>'+(mins<10 ? '0':'')+mins+':'+(secs<10 ? '0':'')+secs+'</span>');
  1329. },
  1330. onEnded(){
  1331. console.log('AudioPlayer onEnded()');
  1332. this.stop();
  1333. this.emmit('audio-ended');
  1334. },
  1335. // cartel functions
  1336. reloadNode(){
  1337. if(this.visible){
  1338. if(!_is_mobile){
  1339. console.log('reloadNode (cartel)');
  1340. this.loadNode(this.historic[this.currentHistoricIndex].nid);
  1341. }
  1342. }
  1343. },
  1344. loadNode(nid){
  1345. this.$cartel.addClass('loading');
  1346. var vm = 'player_cartel';
  1347. var ajax_path = _ajax_settings.entityjson_path+'/node/'+nid+'/'+vm;
  1348. var path = _origin + Drupal.url(ajax_path);
  1349. $.getJSON(path, {})
  1350. .done(this.onNodeLoaded.bind(this))
  1351. .fail(this.onNodeLoadFail.bind(this));
  1352. },
  1353. onNodeLoaded(data){
  1354. console.log('AudioPlayer node loaded');//, data);
  1355. this.$cartel.html(data.rendered).removeClass('loading');
  1356. _$body.trigger({'type':'new-audio-cartel-loaded'});
  1357. initAjaxLinks();
  1358. // cartel autoswitch
  1359. this.scndCartel_visible = 0;
  1360. this.$cartel.removeClass('second-visible');
  1361. if(!_is_expo){
  1362. // if second cartel has special info ?
  1363. if (this.$cartel.find('.second-cartel .col-left').children().length > 1
  1364. || this.$cartel.find('.second-cartel').children('.col-right').length){
  1365. // init cartel auto switch
  1366. this.cartelSwitchInterval = setInterval(this.switchCartel.bind(this), this.cartelSwitchIntervalMS);
  1367. }
  1368. // call drupal behaviours (for addtoany)
  1369. Drupal.attachBehaviors(this.$cartel);
  1370. }
  1371. // open automaticly tha article if needed
  1372. this.setAutoOpenArticle();
  1373. if(this.auto_open_article){
  1374. this.$cartel.find('a.link-article').trigger('click');
  1375. this.auto_open_article = false;
  1376. }
  1377. },
  1378. onNodeLoadFail(jqxhr, textStatus, error){
  1379. console.warn('AudioPlayer node load failed', jqxhr.responseText);
  1380. this.$cartel.removeClass('loading').html('');
  1381. },
  1382. setAutoOpenArticle(art){
  1383. this.auto_open_article = $('a.articles-link').is('.is-active');
  1384. return this;
  1385. },
  1386. // global
  1387. show(){
  1388. this.visible = true;
  1389. this.$container_parent.addClass('audio-player-visible');
  1390. this.$container.addClass('visible');
  1391. },
  1392. showHidePreviousBtn(){
  1393. if(this.historic.length > 1 && this.currentHistoricIndex > 0){
  1394. this.$previous.addClass('is-active');
  1395. }else{
  1396. this.$previous.removeClass('is-active');
  1397. }
  1398. },
  1399. showHideNextBtn(){
  1400. if(this.currentHistoricIndex < this.historic.length-1 || this.shuffle_is_active){
  1401. this.$next.addClass('is-active');
  1402. }else{
  1403. this.$next.removeClass('is-active');
  1404. }
  1405. },
  1406. timeOutToHide(){
  1407. // console.log('AudioPlayer timeOutToHide()');
  1408. this.clearTimeOutToHide();
  1409. this.hideTimer = setTimeout(this.hide.bind(this), this.hideTimeMS);
  1410. },
  1411. clearTimeOutToHide(){
  1412. // console.log('AudioPlayer clearTimeOutToHide()',this.hideTimer);
  1413. if(this.hideTimer){
  1414. clearTimeout(this.hideTimer);
  1415. this.hideTimer = false;
  1416. }
  1417. },
  1418. // cartel
  1419. switchCartel(){
  1420. // console.log("switchCartel", this.scndCartel_visible);
  1421. if (this.scndCartel_visible) {
  1422. // return to first cartel
  1423. this.$cartel.removeClass('second-visible');
  1424. this.scndCartel_visible = 0;
  1425. // kill the auto switch after one rotation
  1426. this.clearIntervalAutoCartelSwitch();
  1427. }else{
  1428. // switch to 2nd cartel
  1429. this.$cartel.addClass('second-visible');
  1430. this.scndCartel_visible = 1;
  1431. }
  1432. },
  1433. clearIntervalAutoCartelSwitch(){
  1434. if(this.cartelSwitchInterval){
  1435. clearInterval(this.cartelSwitchInterval);
  1436. this.cartelSwitchInterval = false;
  1437. }
  1438. },
  1439. hide(){
  1440. // console.log('AudioPlayer hide()');
  1441. this.visible = false;
  1442. this.$container_parent.removeClass('audio-player-visible');
  1443. this.$container.removeClass('visible');
  1444. // trigger highlighted node remove on corpus map
  1445. try {
  1446. _$corpus_canvas.trigger('audio-node-closed');
  1447. } catch (e) {
  1448. console.info('AudioPlayer hide() : _$corpus_canvas does not exists');
  1449. }
  1450. },
  1451. deActivateRandom(){
  1452. this.shuffle_is_active = false;
  1453. this.showHideNextBtn();
  1454. },
  1455. // object events
  1456. on(event_name, handler){
  1457. if(typeof this.event_handlers[event_name] == 'undefined'){
  1458. console.warn('AudioPlayer : event '+event_name+' does not exists');
  1459. }
  1460. this.event_handlers[event_name].push(handler);
  1461. return this;
  1462. },
  1463. emmit(event_name, args){
  1464. console.log('AudioPlayer emmit()', event_name, args, this.event_handlers[event_name]);
  1465. // console.log('AudioPlayer emmit() handlers', this.event_handlers[event_name]);
  1466. var handler;
  1467. var args = args || {};
  1468. for (var i = this.event_handlers[event_name].length-1; i >= 0 ; i--) {
  1469. handler = this.event_handlers[event_name][i];
  1470. // console.log('AudioPlayer emmit() loop handler', handler);
  1471. (function(handler, args){
  1472. setTimeout(function(){
  1473. // console.log('AudioPlayer emmit() timeout handler', handler);
  1474. handler(args);
  1475. }, 0);
  1476. }(handler, args));
  1477. }
  1478. return this;
  1479. },
  1480. }
  1481. // ___ _ ___ _
  1482. // | _ \__ _ _ _ __| |___ _ __ | _ \ |__ _ _ _ ___ _ _
  1483. // | / _` | ' \/ _` / _ \ ' \| _/ / _` | || / -_) '_|
  1484. // |_|_\__,_|_||_\__,_\___/_|_|_|_| |_\__,_|\_, \___|_|
  1485. // |__/
  1486. function RandomPlayer(playlist){
  1487. this.active = false;
  1488. this.playlist = playlist;
  1489. this.path = _base_url+drupalSettings.path.pathPrefix+'#random'
  1490. this.$btn = $('<a>')
  1491. .html('Shuffle')
  1492. .attr('href',this.path)
  1493. .attr('alt', drupalSettings.edlp_corpus.random_link_title)
  1494. .addClass('random-player-btn');
  1495. this.init();
  1496. };
  1497. RandomPlayer.prototype = {
  1498. init(){
  1499. // this.shuffle();
  1500. $('<div>')
  1501. .addClass('block random-player')
  1502. .append(this.$btn)
  1503. // .insertAfter('#block-userlogin, #block-studiolinkblock');
  1504. .prependTo('.region-footer-right');
  1505. // events
  1506. this.$btn.on('click', this.toggleActive.bind(this));
  1507. // attach an event on AudioPlayer
  1508. _audioPlayer
  1509. .on('audio-play-next', this.onAudioPlayNext.bind(this))
  1510. .on('audio-ended', this.onAudioPlayerEnded.bind(this))
  1511. .on('stop-shuffle', this.stop.bind(this));
  1512. _$corpus_canvas
  1513. .on('update-random-playlist', this.updatePlaylist.bind(this));
  1514. // provide a link to auto start random player
  1515. if(window.location.hash == '#random'){
  1516. this.start();
  1517. }
  1518. },
  1519. updatePlaylist(e){
  1520. if (!_is_expo) {
  1521. this.playlist = e.playlist;
  1522. this.shuffle();
  1523. }
  1524. },
  1525. shuffle(){
  1526. var tempPLaylist = [];
  1527. for (var i = this.playlist.length-1; i >= 0 ; i--) {
  1528. tempPLaylist.push(this.playlist[i]);
  1529. }
  1530. this.shuffledPlaylist = [];
  1531. while(tempPLaylist.length > 0){
  1532. var r = Math.floor(Math.random() * tempPLaylist.length);
  1533. this.shuffledPlaylist.push(tempPLaylist.splice(r,1)[0]);
  1534. }
  1535. //console.log('RandomPlayer, this.shuffledPlaylist', this.shuffledPlaylist);
  1536. },
  1537. toggleActive(e){
  1538. e.preventDefault();
  1539. if (this.active) {
  1540. this.stop();
  1541. }else{
  1542. this.start();
  1543. }
  1544. return false;
  1545. },
  1546. start(){
  1547. this.active = _audioPlayer.shuffle_is_active = true;
  1548. this.$btn.addClass('is-active');
  1549. this.shuffle();
  1550. this.next();
  1551. // piwik
  1552. if(typeof _paq !== 'undefined'){
  1553. // trackEvent(category, action, [name], [value])
  1554. _paq.push(['trackEvent', 'RandomPlayer', 'start']);
  1555. }
  1556. },
  1557. stop(){
  1558. this.active = false;
  1559. this.$btn.removeClass('is-active');
  1560. // stop audio player
  1561. // _audioPlayer.stop();
  1562. // remove hash
  1563. history.replaceState(history.state, null, window.location.pathname);
  1564. // tell to AudioPlayer to deactivate netx btn
  1565. _audioPlayer.deActivateRandom();
  1566. if(typeof _paq !== 'undefined'){
  1567. // trackEvent(category, action, [name], [value])
  1568. _paq.push(['trackEvent', 'RandomPlayer', 'stop']);
  1569. }
  1570. },
  1571. next(){
  1572. console.log('RandomPlayer next', this.active, this.shuffledPlaylist.length);
  1573. if(this.active){
  1574. if (this.shuffledPlaylist.length == 0) {
  1575. this.shuffle();
  1576. }
  1577. _audioPlayer.openDocument(this.shuffledPlaylist.splice(0,1)[0], 'random');
  1578. }
  1579. },
  1580. onAudioPlayNext(){
  1581. console.log('RandomPlayer : onAudioPlayNext()');
  1582. if(this.active){
  1583. this.next();
  1584. }
  1585. },
  1586. onAudioPlayerEnded(){
  1587. console.log('RandomPlayer : onAudioPlayerEnded()');
  1588. if(this.active){
  1589. this.next();
  1590. if(_is_expo){
  1591. _$corpus_canvas.trigger({'type':'scramble-collection'}); //shuffle-collection scramble-collection
  1592. }
  1593. }
  1594. }
  1595. };
  1596. // ___ ___ _
  1597. // / __|___ _ __ _ __ ___| _ \ |__ _ _ _ ___ _ _
  1598. // | (__/ _ \ ' \| '_ \/ _ \ _/ / _` | || / -_) '_|
  1599. // \___\___/_|_|_| .__/\___/_| |_\__,_|\_, \___|_|
  1600. // |_| |__/
  1601. function CompoPlayer(){
  1602. this.active = false;
  1603. this.playing = false;
  1604. this.paused = false;
  1605. this.playlist = [];
  1606. this.current_index = 0;
  1607. this.$composer = null;
  1608. this.$compo = null;
  1609. this.$controls = null;
  1610. this.init();
  1611. };
  1612. CompoPlayer.prototype = {
  1613. init(){
  1614. // console.log('CompoPlayer init()');
  1615. // attach an event on AudioPlayer
  1616. _audioPlayer
  1617. .on('audio-open-document', this.onAudioOpenDocument.bind(this))
  1618. .on('audio-play', this.onAudioPlayerPlay.bind(this))
  1619. .on('audio-pause', this.onAudioPlayerPause.bind(this))
  1620. .on('audio-ended', this.onAudioPlayerEnded.bind(this));
  1621. // .on('audio-play-next', this.onAudioPlayNext.bind(this));
  1622. // this.newCompo();
  1623. },
  1624. newCompo(){
  1625. console.log('CompoPlayer newCompo()');
  1626. // this.$compo = $('.composition_ui .composer .composition');
  1627. this.initControls();
  1628. },
  1629. initControls(){
  1630. //console.log('CompoPlayer initControls()');
  1631. this.$composer = $('.composition_ui .composer');
  1632. this.$compo = $('.composition_ui .composer .composition');
  1633. this.$controls = $('.composition_ui .composer .compo-player-controls');
  1634. if(!this.$controls.is('.ready') && this.$compo){
  1635. this.$previous = $('<div>').addClass('previous')
  1636. .on('click', this.prev.bind(this))
  1637. .appendTo(this.$controls);
  1638. this.$playpause = $('<div>').addClass('play-pause')
  1639. .on('click', this.togglePlayPause.bind(this))
  1640. .appendTo(this.$controls);
  1641. this.$next = $('<div>').addClass('next')
  1642. .on('click', this.next.bind(this))
  1643. .appendTo(this.$controls);
  1644. this.$controls.addClass('ready');
  1645. this.active = true;
  1646. // this.newCompo();
  1647. }
  1648. this.refresh();
  1649. },
  1650. refresh(){
  1651. // console.log('CompoPlayer refresh(), this', this);
  1652. this.stop();
  1653. // load new playlist
  1654. this.playlist = [];
  1655. var that = this;
  1656. $('.field--name-documents .field__item',this.$compo).each(function(i,el){
  1657. var $link = $('a.audio-link',this);
  1658. that.playlist.push({
  1659. item:$(this),
  1660. audio_url:$link.attr("audio_url"),
  1661. nid:$link.attr("nid"),
  1662. });
  1663. });
  1664. this.showHideControls();
  1665. },
  1666. togglePlayPause(){
  1667. // console.log('CompoPlayer togglePlayPause');
  1668. if (this.playing && !this.paused) {
  1669. this.pause();
  1670. }else{
  1671. if(this.playing && this.paused){
  1672. this.play();
  1673. }else{
  1674. this.start();
  1675. }
  1676. }
  1677. },
  1678. start(i){
  1679. //console.log('start');
  1680. // console.log('CompoPlayer start()');
  1681. this.current_index = i || 0;
  1682. this.playing = true;
  1683. this.play();
  1684. },
  1685. play(){
  1686. console.log('CompoPlayer play()', this.playlist[this.current_index]);
  1687. if(this.paused){
  1688. this.paused = false;
  1689. _audioPlayer.play();
  1690. }else{
  1691. console.log('CompoPlayer opendoc with audio player');
  1692. // _audioPlayer;
  1693. _audioPlayer.emmit('stop-shuffle').openDocument(this.playlist[this.current_index], this);
  1694. }
  1695. this.setActiveItem().showHideControls();
  1696. },
  1697. pause(){
  1698. //console.log('pause');
  1699. this.paused = true;
  1700. this.showHideControls();
  1701. _audioPlayer.stop();
  1702. },
  1703. next(){
  1704. console.log('CompoPlayer next()',this.playing);
  1705. if(this.playing){
  1706. this.current_index += 1;
  1707. if(this.current_index < this.playlist.length){
  1708. this.play();
  1709. }else{
  1710. this.stop();
  1711. }
  1712. }
  1713. },
  1714. prev(){
  1715. // console.log('CompoPlayer prev()');
  1716. if(this.playing){
  1717. this.current_index -= 1;
  1718. if(this.current_index >= 0){
  1719. this.play();
  1720. }else{
  1721. this.stop();
  1722. }
  1723. }
  1724. },
  1725. stop(){
  1726. if(this.playing){
  1727. _audioPlayer.stop();
  1728. }
  1729. this.reset();
  1730. },
  1731. reset(){
  1732. this.playing = false;
  1733. this.paused = false;
  1734. this.resetIndex();
  1735. },
  1736. resetIndex(){
  1737. this.current_index = 0;
  1738. this.showHideControls().resetActiveItems();
  1739. },
  1740. setActiveItem(){
  1741. this.resetActiveItems();
  1742. if(this.playing && this.current_index >= 0){
  1743. this.playlist[this.current_index].item.addClass('is-active');
  1744. }
  1745. // this call shoud not be here
  1746. this.showHideControls();
  1747. return this;
  1748. },
  1749. resetActiveItems(){
  1750. for (var n = 0; n < this.playlist.length; n++) {
  1751. // console.log('node',node);
  1752. this.playlist[n].item.removeClass('is-active');
  1753. }
  1754. return this;
  1755. },
  1756. showHideControls(){
  1757. // console.log('CompoPlayer showHideNextBtn(), playing:'+this.playing+', paused:'+this.paused);
  1758. // global playing
  1759. if(this.$controls){
  1760. if(this.playing && !this.paused){
  1761. this.$controls.addClass('is-playing');
  1762. }else{
  1763. this.$controls.removeClass('is-playing');
  1764. }
  1765. }
  1766. // playpause
  1767. if(this.$playpause){
  1768. if(this.playlist.length > 0){
  1769. this.$playpause.addClass('is-active');
  1770. }else{
  1771. this.$playpause.removeClass('is-active');
  1772. }
  1773. }
  1774. // next
  1775. if(this.$next){
  1776. if(this.playing && this.playlist.length > 1 && this.current_index < this.playlist.length -1){
  1777. this.$next.addClass('is-active');
  1778. }else{
  1779. this.$next.removeClass('is-active');
  1780. }
  1781. }
  1782. // previous
  1783. if(this.$previous){
  1784. if(this.playing && this.playlist.length > 1 && this.current_index > 0){
  1785. this.$previous.addClass('is-active');
  1786. }else{
  1787. this.$previous.removeClass('is-active');
  1788. }
  1789. }
  1790. return this;
  1791. },
  1792. deactivate(){
  1793. this.stop();
  1794. this.active = false;
  1795. },
  1796. // _audioPlayer events
  1797. onAudioOpenDocument(args){
  1798. console.log('Compo player onAudioOpenDocument', args);
  1799. if(args.caller !== this){
  1800. // console.log('CompoPlayer onAudioOpenDocument() called by other');
  1801. this.reset();
  1802. }
  1803. // else{
  1804. // // console.log('CompoPlayer onAudioOpenDocument() self calling');
  1805. // }
  1806. },
  1807. onAudioPlayerPlay(){
  1808. if(this.playing && this.paused){
  1809. this.paused = false;
  1810. this.showHideControls();
  1811. }
  1812. },
  1813. onAudioPlayerPause(){
  1814. if(this.playing && !this.paused){
  1815. this.paused = true;
  1816. this.showHideControls();
  1817. }
  1818. },
  1819. onAudioPlayerEnded(){
  1820. console.log('onAudioPlayerEnded');
  1821. if(this.playing){
  1822. // this paused shoudn't be true but i'm lazzy to find why it is ...
  1823. this.paused = false;
  1824. this.next();
  1825. }
  1826. },
  1827. // onAudioPlayNext(){
  1828. // this.next();
  1829. // }
  1830. };
  1831. // ___
  1832. // | __|_ ___ __ ___
  1833. // | _|\ \ / '_ \/ _ \
  1834. // |___/_\_\ .__/\___/
  1835. // |_|
  1836. function initExpo(){
  1837. console.log('initExpo', window.location.hash);
  1838. document.title = edlp.site_name;
  1839. if(window.location.hash == '#black'){
  1840. $('body').addClass('expo-black');
  1841. }
  1842. _$body.on('map-node-opened', checkExpoPlayerPositionning);
  1843. _randomPlayer.start();
  1844. initKeyboard();
  1845. }
  1846. function checkExpoPlayerPositionning(e){
  1847. console.log('checkExpoPlayerPositionning', e.node);
  1848. // optimized for 1280px width screen
  1849. switch(true){
  1850. case e.node.x > window.innerWidth-610 && e.node.y < 200:
  1851. _audioPlayer.$container.attr('pos', 'bottom-left');
  1852. break;
  1853. case e.node.x > window.innerWidth-610:
  1854. _audioPlayer.$container.attr('pos', 'top-left');
  1855. break;
  1856. case e.node.y < 200:
  1857. _audioPlayer.$container.attr('pos', 'bottom-right');
  1858. break;
  1859. default:
  1860. _audioPlayer.$container.attr('pos', 'top-right');
  1861. }
  1862. _audioPlayer.$container.css({
  1863. 'display':"block",
  1864. 'left':e.node.x+"px",
  1865. 'top':e.node.y+"px",
  1866. });
  1867. }
  1868. function initKeyboard(){
  1869. $(document).bind('keyup', 'alt+n', function(){
  1870. _randomPlayer.next();
  1871. });
  1872. }
  1873. // ___ _ _
  1874. // / __|_ _(_)__| |
  1875. // | (_ | '_| / _` |
  1876. // \___|_| |_\__,_|
  1877. function initGrid(){
  1878. console.log('theme : initGrid');
  1879. if(!_is_mobile){
  1880. checkGridBlockHeight();
  1881. _$row.find('.col').addClass('offfield');
  1882. }
  1883. if(false){
  1884. var $grid = $('.grid',_$row).masonry({
  1885. itemSelector:'.col',
  1886. columnWidth:'.col-2',
  1887. containerStyle: null,
  1888. resizeContainer:false,
  1889. // horizontalOrder: true,
  1890. transitionDuration:0,//'0.2s',
  1891. // stagger:30,
  1892. // disable initial layout
  1893. // initLayout: false,
  1894. });
  1895. // layout Masonry after each image loads
  1896. $grid.imagesLoaded().progress( function() {
  1897. $grid.masonry('layout');
  1898. });
  1899. $grid.imagesLoaded(function(){
  1900. $grid.masonry('layout');
  1901. // checkProductionBlockVisible();
  1902. });
  1903. // bind event
  1904. // $grid.masonry( 'on', 'layoutComplete', function() {
  1905. // console.log('layout is complete');
  1906. // });
  1907. $grid.on('layoutComplete', checkGridBlockVisible);
  1908. }else{
  1909. // setTimeout(checkGridBlockVisible, 100);
  1910. if(!_is_mobile){
  1911. checkGridBlockVisible();
  1912. }
  1913. }
  1914. };
  1915. function checkGridBlockHeight(){
  1916. // console.log('checkGridBlockHeight');
  1917. // if(_is_mobile) return;
  1918. var $r_h = _$row.height();
  1919. var $this;
  1920. // console.log($r_h);
  1921. $('.grid .col', _$row).each(function(i,e){
  1922. $this = $(this);
  1923. if(!$this.is('[init-height]')){
  1924. $this.attr('init-height', $this.outerHeight())
  1925. }
  1926. // console.log($(this).height(), $(this).innerHeight(), $(this).outerHeight());
  1927. // if($this.height() > $r_h){
  1928. // $this.height($r_h);
  1929. // }else{
  1930. // $this.height('auto');
  1931. // }
  1932. $this.height(Math.min($this.attr('init-height'), _$row.height()));
  1933. });
  1934. };
  1935. function checkGridBlockVisible(){
  1936. // console.log('checkGridBlockVisible');
  1937. // if(_is_mobile) return;
  1938. var $r_h = _$row.height();
  1939. var $this,pos;
  1940. $('.grid .col', _$row).each(function(i,e){
  1941. // $(this).on('load',function(event){
  1942. $this = $(this);
  1943. pos = $this.position();
  1944. // console.log(pos.top, $this.height(), pos.top+$this.height(), $r_h, $this);
  1945. if(pos.top+$this.height() <= $r_h){
  1946. $this.removeClass('offfield');
  1947. }else{
  1948. $this.addClass('offfield');
  1949. }
  1950. // });
  1951. });
  1952. // for (var i in items) {
  1953. // if(!items[i].isTransitioning){
  1954. // console.log('y+outerHeight', items[i].position.y+items[i].size.outerHeight);
  1955. // console.log('_$row.height()', _$row.height());
  1956. // if(items[i].position.y+items[i].size.outerHeight < _$row.height()){
  1957. // $(items[i].element).removeClass('offfield');
  1958. // }else{
  1959. // // $(items[i].element).addClass('offfield');
  1960. // }
  1961. // }
  1962. // }
  1963. }
  1964. // ___ _ _ _
  1965. // | _ \_ _ ___ __| |_ _ __| |_(_)___ _ _ ___
  1966. // | _/ '_/ _ \/ _` | || / _| _| / _ \ ' \(_-<
  1967. // |_| |_| \___/\__,_|\_,_\__|\__|_\___/_||_/__/
  1968. // function initProductions(){
  1969. // console.log('theme : initProductions');
  1970. //
  1971. // // _$row.find('.col').addClass('offfield');
  1972. // var $grid = $('.grid',_$row).masonry({
  1973. // itemSelector:'.col',
  1974. // columnWidth:'.col-2',
  1975. // containerStyle: null,
  1976. // resizeContainer:false,
  1977. // // horizontalOrder: true,
  1978. // transitionDuration:0,//'0.2s',
  1979. // // stagger:30,
  1980. // // disable initial layout
  1981. // // initLayout: false,
  1982. // });
  1983. //
  1984. // // layout Masonry after each image loads
  1985. // $grid.imagesLoaded().progress( function() {
  1986. // $grid.masonry('layout');
  1987. // });
  1988. //
  1989. // $grid.imagesLoaded(function(){
  1990. // $grid.masonry('layout');
  1991. // // checkProductionBlockVisible();
  1992. // });
  1993. //
  1994. // // bind event
  1995. // // $grid.masonry( 'on', 'layoutComplete', function() {
  1996. // // console.log('layout is complete');
  1997. // // });
  1998. // // $grid.on('layoutComplete', checkProductionBlockVisible);
  1999. // };
  2000. // ___ _ _ _ _
  2001. // / __|___| | |___ __| |_(_)___ _ _
  2002. // | (__/ _ \ | / -_) _| _| / _ \ ' \
  2003. // \___\___/_|_\___\__|\__|_\___/_||_|
  2004. // mobile version of collection
  2005. function initCollectionNav(){
  2006. console.log('initCollectionNav');
  2007. // taxonomy-term.vocabulary-entrees.home_mobile
  2008. $('.field--name-field-notice, .index', '.taxonomy-term.vocabulary-entrees.home_mobile')
  2009. .addClass('closed');
  2010. $('.field--name-field-notice>.field__label', '.taxonomy-term.vocabulary-entrees.home_mobile')
  2011. .on('click', onClickCollectionNotice);
  2012. $('.index>.field__label', '.taxonomy-term.vocabulary-entrees.home_mobile')
  2013. .on('click', onClickCollectionIndex);
  2014. };
  2015. function onClickCollectionNotice(e){
  2016. // console.log('onClickCollectionNotice');
  2017. // var $part = $(this).parent();//parents('.taxonomy-term');
  2018. toggleEntreeOpening($(this).parent(), 'notice');
  2019. };
  2020. function onClickCollectionIndex(e){
  2021. // console.log('onClickCollectionIndex');
  2022. // var $part = $(this).parent();//parents('.taxonomy-term');
  2023. toggleEntreeOpening($(this).parent(), 'index');
  2024. };
  2025. function toggleEntreeOpening($e, part){
  2026. $e.toggleClass('closed')
  2027. .parents('.taxonomy-term.vocabulary-entrees.home_mobile').toggleClass(part+'-opened');
  2028. }
  2029. // ___ _
  2030. // / __| ___ __ _ _ _ __| |_
  2031. // \__ \/ -_) _` | '_/ _| ' \
  2032. // |___/\___\__,_|_| \__|_||_|
  2033. function initSearch(){
  2034. // if($('#edit-entries input:checked', '#edlp-search-form').length){
  2035. // $('#edit-entries--wrapper', '#edlp-search-form').toggleClass('opened');
  2036. // }
  2037. $('#edit-entries--wrapper legend', '#edlp-search-form').on('click', function(){
  2038. $(this).parent().toggleClass('opened');
  2039. });
  2040. };
  2041. // ___ _ _ _
  2042. // | __|_ _ _ _ ___ __ _(_)__| |_ _ _ ___ _ __ ___ _ _| |_
  2043. // | _|| ' \| '_/ -_) _` | (_-< _| '_/ -_) ' \/ -_) ' \ _|
  2044. // |___|_||_|_| \___\__, |_/__/\__|_| \___|_|_|_\___|_||_\__|
  2045. // |___/
  2046. function initEnregistrementTranscript(){
  2047. console.log('initEnregistrementTranscript');
  2048. var $node = _$row.find('article.node--type-enregistrement.node--view-mode-transcript');
  2049. var $nav = $('<nav>').prependTo($node);
  2050. $node.find('.field--name-field-transcript-vo').addClass('visible').find('.field__label')
  2051. .clone().appendTo($nav).addClass('is-active')
  2052. .attr('field_target', '.field--name-field-transcript-vo');
  2053. $node.find('.field--name-field-transcript-trad').find('.field__label')
  2054. .clone().appendTo($nav)
  2055. .attr('field_target', '.field--name-field-transcript-trad');
  2056. $nav.find('.field__label').on('click', function(){
  2057. var $this = $(this).addClass('is-active');
  2058. $this.siblings('.is-active').removeClass('is-active');
  2059. $this.parents('article.node').find('.field.visible').removeClass('visible');
  2060. $this.parents('article.node').find($this.attr('field_target')).addClass('visible');
  2061. });
  2062. };
  2063. // ___ _ ___
  2064. // | __| _ ___ _ _| |_| _ \__ _ __ _ ___
  2065. // | _| '_/ _ \ ' \ _| _/ _` / _` / -_)
  2066. // |_||_| \___/_||_\__|_| \__,_\__, \___|
  2067. // |___/
  2068. function backToFrontPage(pop_state){
  2069. console.log('backToFrontPage', pop_state);
  2070. closeAllModals();
  2071. // assume we are going back to front page
  2072. $('body').removeClass().addClass('path-frontpage');
  2073. $('a[data-drupal-link-system-path="<front>"]').addClass('is-active');
  2074. // close entrees
  2075. if(_corpus_ready){
  2076. _$corpus_canvas.trigger({'type':'close-all-entree'});
  2077. _$corpus_canvas.trigger({'type':'scramble-collection'});
  2078. }
  2079. if(typeof pop_state == "undefined" || !pop_state){
  2080. console.log('backToFrontPage push state');
  2081. state = {
  2082. home:true,
  2083. context:"home",
  2084. caller:null
  2085. }
  2086. _states_history.unshift(state);
  2087. history.pushState(state, null, _base_url+drupalSettings.path.currentLanguage);
  2088. }
  2089. }
  2090. // function initHome(){
  2091. // addCloseModalBtnToCols();
  2092. // return;
  2093. // console.log('theme : initHome');
  2094. // var $grid = $('.grid',_$row).masonry({
  2095. // itemSelector:'.col',
  2096. // columnWidth:'.col-2',
  2097. // horizontalOrder: true,
  2098. // containerStyle: null,
  2099. // // disable initial layout
  2100. // // initLayout: false,
  2101. // });
  2102. // // bind event
  2103. // // $grid.masonry( 'on', 'layoutComplete', function() {
  2104. // // console.log('layout is complete');
  2105. // // });
  2106. //
  2107. // // layout Masonry after each image loads
  2108. // $grid.imagesLoaded().progress( function() {
  2109. // $grid.masonry('layout');
  2110. // });
  2111. //
  2112. // $grid.imagesLoaded(function(){
  2113. // $grid.masonry('layout');
  2114. // });
  2115. // }
  2116. // __ __ _ _
  2117. // | \/ |___ __| |__ _| |___
  2118. // | |\/| / _ \/ _` / _` | (_-<
  2119. // |_| |_\___/\__,_\__,_|_/__/
  2120. function closeAllModals(){
  2121. //console.log('theme : closeAllModals');
  2122. // TODO: animate the remove
  2123. _$row.html('');
  2124. _$ajaxLinks.removeClass('is-active');
  2125. _$body.trigger({'type':'all-modal-closed'});
  2126. // checkRowEmpty();
  2127. checkVisibleCorpusMapSpace();
  2128. };
  2129. function checkRowEmpty(){
  2130. console.log('checkRowEmpty');
  2131. // if row is empty and we are not in productions or entree notice|index call closeAllModals()
  2132. if(!$('.col', _$row).length){
  2133. if(!_$body.is('.entity-type-taxonomy_term.bundle-entrees')){
  2134. if(!_$body.is('.entity-type-node.bundle-page')){
  2135. // we weren't on production or entree, so go back to front page
  2136. // debugger;
  2137. if(_$body.is('.bundle-enregistrement.view-mode-article')
  2138. && $('a.articles-link').is('.is-active')){
  2139. console.log('Closing article while article index is active');
  2140. // if node article and articles is active, reload index
  2141. $('a.articles-link').removeClass('is-active').trigger('click');
  2142. }else{
  2143. backToFrontPage();
  2144. }
  2145. // if(!$('a.articles-link').is('.is-active')){
  2146. // // don't go back to front page if articles filter is on
  2147. // backToFrontPage();
  2148. // }else{
  2149. // }
  2150. }else{
  2151. // if we were on production page just scramble collection in case of map was filtered
  2152. if(_corpus_ready){
  2153. _$corpus_canvas.trigger({'type':'scramble-collection'});
  2154. }
  2155. // reload production home
  2156. $('a[data-drupal-link-system-path="productions"]', '#block-mainnavigation')
  2157. .removeClass('is-active').trigger('click');
  2158. }
  2159. }else{
  2160. // remove is-active class from index or notice entree links
  2161. $('.entree-content a.is-active').removeClass('is-active');
  2162. // TODO: remove the hash index or notice
  2163. }
  2164. }
  2165. };
  2166. init();
  2167. } // end EdlpTheme()
  2168. $(document).ready(function($) {
  2169. if(drupalSettings.path.isFront){
  2170. var edlptheme = new EdlpTheme();
  2171. }else{
  2172. $('body').attr('booted', 'booted');
  2173. }
  2174. });
  2175. })(jQuery, Drupal, drupalSettings);