main.js 80 KB

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