main.js 80 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370
  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-edlptheme-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. console.log('AudioPlayer onNodeLoaded', this.$cartel);
  1384. Drupal.attachBehaviors(this.$cartel.get(0));
  1385. }
  1386. // open automaticly tha article if needed
  1387. this.setAutoOpenArticle();
  1388. if(this.auto_open_article){
  1389. this.$cartel.find('a.link-article').trigger('click');
  1390. this.auto_open_article = false;
  1391. }
  1392. },
  1393. onNodeLoadFail(jqxhr, textStatus, error){
  1394. console.warn('AudioPlayer node load failed', jqxhr.responseText);
  1395. this.$cartel.removeClass('loading').html('');
  1396. },
  1397. setAutoOpenArticle(art){
  1398. this.auto_open_article = $('a.articles-link').is('.is-active');
  1399. return this;
  1400. },
  1401. // global
  1402. show(){
  1403. this.visible = true;
  1404. this.$container_parent.addClass('audio-player-visible');
  1405. this.$container.addClass('visible');
  1406. },
  1407. showHidePreviousBtn(){
  1408. if(this.historic.length > 1 && this.currentHistoricIndex > 0){
  1409. this.$previous.addClass('is-active');
  1410. }else{
  1411. this.$previous.removeClass('is-active');
  1412. }
  1413. },
  1414. showHideNextBtn(){
  1415. if(this.currentHistoricIndex < this.historic.length-1 || this.shuffle_is_active){
  1416. this.$next.addClass('is-active');
  1417. }else{
  1418. this.$next.removeClass('is-active');
  1419. }
  1420. },
  1421. timeOutToHide(){
  1422. // console.log('AudioPlayer timeOutToHide()');
  1423. this.clearTimeOutToHide();
  1424. this.hideTimer = setTimeout(this.hide.bind(this), this.hideTimeMS);
  1425. },
  1426. clearTimeOutToHide(){
  1427. // console.log('AudioPlayer clearTimeOutToHide()',this.hideTimer);
  1428. if(this.hideTimer){
  1429. clearTimeout(this.hideTimer);
  1430. this.hideTimer = false;
  1431. }
  1432. },
  1433. // cartel
  1434. switchCartel(){
  1435. // console.log("switchCartel", this.scndCartel_visible);
  1436. if (this.scndCartel_visible) {
  1437. // return to first cartel
  1438. this.$cartel.removeClass('second-visible');
  1439. this.scndCartel_visible = 0;
  1440. // kill the auto switch after one rotation
  1441. this.clearIntervalAutoCartelSwitch();
  1442. }else{
  1443. // switch to 2nd cartel
  1444. this.$cartel.addClass('second-visible');
  1445. this.scndCartel_visible = 1;
  1446. }
  1447. },
  1448. clearIntervalAutoCartelSwitch(){
  1449. if(this.cartelSwitchInterval){
  1450. clearInterval(this.cartelSwitchInterval);
  1451. this.cartelSwitchInterval = false;
  1452. }
  1453. },
  1454. hide(){
  1455. // console.log('AudioPlayer hide()');
  1456. this.visible = false;
  1457. this.$container_parent.removeClass('audio-player-visible');
  1458. this.$container.removeClass('visible');
  1459. // trigger highlighted node remove on corpus map
  1460. try {
  1461. _$corpus_canvas.trigger('audio-node-closed');
  1462. } catch (e) {
  1463. console.info('AudioPlayer hide() : _$corpus_canvas does not exists');
  1464. }
  1465. },
  1466. deActivateRandom(){
  1467. this.shuffle_is_active = false;
  1468. this.showHideNextBtn();
  1469. },
  1470. // object events
  1471. on(event_name, handler){
  1472. if(typeof this.event_handlers[event_name] == 'undefined'){
  1473. console.warn('AudioPlayer : event '+event_name+' does not exists');
  1474. }
  1475. this.event_handlers[event_name].push(handler);
  1476. return this;
  1477. },
  1478. emmit(event_name, args){
  1479. console.log('AudioPlayer emmit()', event_name, args, this.event_handlers[event_name]);
  1480. // console.log('AudioPlayer emmit() handlers', this.event_handlers[event_name]);
  1481. var handler;
  1482. var args = args || {};
  1483. for (var i = this.event_handlers[event_name].length-1; i >= 0 ; i--) {
  1484. handler = this.event_handlers[event_name][i];
  1485. // console.log('AudioPlayer emmit() loop handler', handler);
  1486. (function(handler, args){
  1487. setTimeout(function(){
  1488. // console.log('AudioPlayer emmit() timeout handler', handler);
  1489. handler(args);
  1490. }, 0);
  1491. }(handler, args));
  1492. }
  1493. return this;
  1494. },
  1495. }
  1496. // ___ _ ___ _
  1497. // | _ \__ _ _ _ __| |___ _ __ | _ \ |__ _ _ _ ___ _ _
  1498. // | / _` | ' \/ _` / _ \ ' \| _/ / _` | || / -_) '_|
  1499. // |_|_\__,_|_||_\__,_\___/_|_|_|_| |_\__,_|\_, \___|_|
  1500. // |__/
  1501. function RandomPlayer(playlist){
  1502. this.active = false;
  1503. this.playlist = playlist;
  1504. this.path = _base_url+drupalSettings.path.pathPrefix+'#random'
  1505. this.$btn = $('<a>')
  1506. .html('Shuffle')
  1507. .attr('href',this.path)
  1508. .attr('alt', drupalSettings.edlp_corpus.random_link_title)
  1509. .addClass('random-player-btn');
  1510. this.init();
  1511. };
  1512. RandomPlayer.prototype = {
  1513. init(){
  1514. // this.shuffle();
  1515. $('<div>')
  1516. .addClass('block random-player')
  1517. .append(this.$btn)
  1518. // .insertAfter('#block-userlogin, #block-studiolinkblock');
  1519. .prependTo('.region-footer-right');
  1520. // events
  1521. this.$btn.on('click', this.toggleActive.bind(this));
  1522. // attach an event on AudioPlayer
  1523. _audioPlayer
  1524. .on('audio-play-next', this.onAudioPlayNext.bind(this))
  1525. .on('audio-ended', this.onAudioPlayerEnded.bind(this))
  1526. .on('stop-shuffle', this.stop.bind(this));
  1527. _$corpus_canvas
  1528. .on('update-random-playlist', this.updatePlaylist.bind(this));
  1529. // provide a link to auto start random player
  1530. if(window.location.hash == '#random'){
  1531. this.start();
  1532. }
  1533. },
  1534. updatePlaylist(e){
  1535. if (!_is_expo) {
  1536. this.playlist = e.playlist;
  1537. this.shuffle();
  1538. }
  1539. },
  1540. shuffle(){
  1541. var tempPLaylist = [];
  1542. for (var i = this.playlist.length-1; i >= 0 ; i--) {
  1543. tempPLaylist.push(this.playlist[i]);
  1544. }
  1545. this.shuffledPlaylist = [];
  1546. while(tempPLaylist.length > 0){
  1547. var r = Math.floor(Math.random() * tempPLaylist.length);
  1548. this.shuffledPlaylist.push(tempPLaylist.splice(r,1)[0]);
  1549. }
  1550. //console.log('RandomPlayer, this.shuffledPlaylist', this.shuffledPlaylist);
  1551. },
  1552. toggleActive(e){
  1553. e.preventDefault();
  1554. if (this.active) {
  1555. this.stop();
  1556. }else{
  1557. this.start();
  1558. }
  1559. return false;
  1560. },
  1561. start(){
  1562. this.active = _audioPlayer.shuffle_is_active = true;
  1563. this.$btn.addClass('is-active');
  1564. this.shuffle();
  1565. this.next();
  1566. // piwik
  1567. if(typeof _paq !== 'undefined'){
  1568. // trackEvent(category, action, [name], [value])
  1569. _paq.push(['trackEvent', 'RandomPlayer', 'start']);
  1570. }
  1571. },
  1572. stop(){
  1573. this.active = false;
  1574. this.$btn.removeClass('is-active');
  1575. // stop audio player
  1576. // _audioPlayer.stop();
  1577. // remove hash
  1578. history.replaceState(history.state, null, window.location.pathname);
  1579. // tell to AudioPlayer to deactivate netx btn
  1580. _audioPlayer.deActivateRandom();
  1581. if(typeof _paq !== 'undefined'){
  1582. // trackEvent(category, action, [name], [value])
  1583. _paq.push(['trackEvent', 'RandomPlayer', 'stop']);
  1584. }
  1585. },
  1586. next(){
  1587. console.log('RandomPlayer next', this.active, this.shuffledPlaylist.length);
  1588. if(this.active){
  1589. if (this.shuffledPlaylist.length == 0) {
  1590. this.shuffle();
  1591. }
  1592. _audioPlayer.openDocument(this.shuffledPlaylist.splice(0,1)[0], 'random');
  1593. }
  1594. },
  1595. onAudioPlayNext(){
  1596. console.log('RandomPlayer : onAudioPlayNext()');
  1597. if(this.active){
  1598. this.next();
  1599. }
  1600. },
  1601. onAudioPlayerEnded(){
  1602. console.log('RandomPlayer : onAudioPlayerEnded()');
  1603. if(this.active){
  1604. this.next();
  1605. if(_is_expo){
  1606. _$corpus_canvas.trigger({'type':'scramble-collection'}); //shuffle-collection scramble-collection
  1607. }
  1608. }
  1609. }
  1610. };
  1611. // ___ ___ _
  1612. // / __|___ _ __ _ __ ___| _ \ |__ _ _ _ ___ _ _
  1613. // | (__/ _ \ ' \| '_ \/ _ \ _/ / _` | || / -_) '_|
  1614. // \___\___/_|_|_| .__/\___/_| |_\__,_|\_, \___|_|
  1615. // |_| |__/
  1616. function CompoPlayer(){
  1617. this.active = false;
  1618. this.playing = false;
  1619. this.paused = false;
  1620. this.playlist = [];
  1621. this.current_index = 0;
  1622. this.$composer = null;
  1623. this.$compo = null;
  1624. this.$controls = null;
  1625. this.init();
  1626. };
  1627. CompoPlayer.prototype = {
  1628. init(){
  1629. // console.log('CompoPlayer init()');
  1630. // attach an event on AudioPlayer
  1631. _audioPlayer
  1632. .on('audio-open-document', this.onAudioOpenDocument.bind(this))
  1633. .on('audio-play', this.onAudioPlayerPlay.bind(this))
  1634. .on('audio-pause', this.onAudioPlayerPause.bind(this))
  1635. .on('audio-ended', this.onAudioPlayerEnded.bind(this));
  1636. // .on('audio-play-next', this.onAudioPlayNext.bind(this));
  1637. // this.newCompo();
  1638. },
  1639. newCompo(){
  1640. console.log('CompoPlayer newCompo()');
  1641. // this.$compo = $('.composition_ui .composer .composition');
  1642. this.initControls();
  1643. },
  1644. initControls(){
  1645. //console.log('CompoPlayer initControls()');
  1646. this.$composer = $('.composition_ui .composer');
  1647. this.$compo = $('.composition_ui .composer .composition');
  1648. this.$controls = $('.composition_ui .composer .compo-player-controls');
  1649. if(!this.$controls.is('.ready') && this.$compo){
  1650. this.$previous = $('<div>').addClass('previous')
  1651. .on('click', this.prev.bind(this))
  1652. .appendTo(this.$controls);
  1653. this.$playpause = $('<div>').addClass('play-pause')
  1654. .on('click', this.togglePlayPause.bind(this))
  1655. .appendTo(this.$controls);
  1656. this.$next = $('<div>').addClass('next')
  1657. .on('click', this.next.bind(this))
  1658. .appendTo(this.$controls);
  1659. this.$controls.addClass('ready');
  1660. this.active = true;
  1661. // this.newCompo();
  1662. }
  1663. this.refresh();
  1664. },
  1665. refresh(){
  1666. // console.log('CompoPlayer refresh(), this', this);
  1667. this.stop();
  1668. // load new playlist
  1669. this.playlist = [];
  1670. var that = this;
  1671. $('.field--name-documents .field__item',this.$compo).each(function(i,el){
  1672. var $link = $('a.audio-link',this);
  1673. that.playlist.push({
  1674. item:$(this),
  1675. audio_url:$link.attr("audio_url"),
  1676. nid:$link.attr("nid"),
  1677. });
  1678. });
  1679. this.showHideControls();
  1680. },
  1681. togglePlayPause(){
  1682. // console.log('CompoPlayer togglePlayPause');
  1683. if (this.playing && !this.paused) {
  1684. this.pause();
  1685. }else{
  1686. if(this.playing && this.paused){
  1687. this.play();
  1688. }else{
  1689. this.start();
  1690. }
  1691. }
  1692. },
  1693. start(i){
  1694. //console.log('start');
  1695. // console.log('CompoPlayer start()');
  1696. this.current_index = i || 0;
  1697. this.playing = true;
  1698. this.play();
  1699. },
  1700. play(){
  1701. console.log('CompoPlayer play()', this.playlist[this.current_index]);
  1702. if(this.paused){
  1703. this.paused = false;
  1704. _audioPlayer.play();
  1705. }else{
  1706. console.log('CompoPlayer opendoc with audio player');
  1707. // _audioPlayer;
  1708. _audioPlayer.emmit('stop-shuffle').openDocument(this.playlist[this.current_index], this);
  1709. }
  1710. this.setActiveItem().showHideControls();
  1711. },
  1712. pause(){
  1713. //console.log('pause');
  1714. this.paused = true;
  1715. this.showHideControls();
  1716. _audioPlayer.stop();
  1717. },
  1718. next(){
  1719. console.log('CompoPlayer next()',this.playing);
  1720. if(this.playing){
  1721. this.current_index += 1;
  1722. if(this.current_index < this.playlist.length){
  1723. this.play();
  1724. }else{
  1725. this.stop();
  1726. }
  1727. }
  1728. },
  1729. prev(){
  1730. // console.log('CompoPlayer prev()');
  1731. if(this.playing){
  1732. this.current_index -= 1;
  1733. if(this.current_index >= 0){
  1734. this.play();
  1735. }else{
  1736. this.stop();
  1737. }
  1738. }
  1739. },
  1740. stop(){
  1741. if(this.playing){
  1742. _audioPlayer.stop();
  1743. }
  1744. this.reset();
  1745. },
  1746. reset(){
  1747. this.playing = false;
  1748. this.paused = false;
  1749. this.resetIndex();
  1750. },
  1751. resetIndex(){
  1752. this.current_index = 0;
  1753. this.showHideControls().resetActiveItems();
  1754. },
  1755. setActiveItem(){
  1756. this.resetActiveItems();
  1757. if(this.playing && this.current_index >= 0){
  1758. this.playlist[this.current_index].item.addClass('is-active');
  1759. }
  1760. // this call shoud not be here
  1761. this.showHideControls();
  1762. return this;
  1763. },
  1764. resetActiveItems(){
  1765. for (var n = 0; n < this.playlist.length; n++) {
  1766. // console.log('node',node);
  1767. this.playlist[n].item.removeClass('is-active');
  1768. }
  1769. return this;
  1770. },
  1771. showHideControls(){
  1772. // console.log('CompoPlayer showHideNextBtn(), playing:'+this.playing+', paused:'+this.paused);
  1773. // global playing
  1774. if(this.$controls){
  1775. if(this.playing && !this.paused){
  1776. this.$controls.addClass('is-playing');
  1777. }else{
  1778. this.$controls.removeClass('is-playing');
  1779. }
  1780. }
  1781. // playpause
  1782. if(this.$playpause){
  1783. if(this.playlist.length > 0){
  1784. this.$playpause.addClass('is-active');
  1785. }else{
  1786. this.$playpause.removeClass('is-active');
  1787. }
  1788. }
  1789. // next
  1790. if(this.$next){
  1791. if(this.playing && this.playlist.length > 1 && this.current_index < this.playlist.length -1){
  1792. this.$next.addClass('is-active');
  1793. }else{
  1794. this.$next.removeClass('is-active');
  1795. }
  1796. }
  1797. // previous
  1798. if(this.$previous){
  1799. if(this.playing && this.playlist.length > 1 && this.current_index > 0){
  1800. this.$previous.addClass('is-active');
  1801. }else{
  1802. this.$previous.removeClass('is-active');
  1803. }
  1804. }
  1805. return this;
  1806. },
  1807. deactivate(){
  1808. this.stop();
  1809. this.active = false;
  1810. },
  1811. // _audioPlayer events
  1812. onAudioOpenDocument(args){
  1813. console.log('Compo player onAudioOpenDocument', args);
  1814. if(args.caller !== this){
  1815. // console.log('CompoPlayer onAudioOpenDocument() called by other');
  1816. this.reset();
  1817. }
  1818. // else{
  1819. // // console.log('CompoPlayer onAudioOpenDocument() self calling');
  1820. // }
  1821. },
  1822. onAudioPlayerPlay(){
  1823. if(this.playing && this.paused){
  1824. this.paused = false;
  1825. this.showHideControls();
  1826. }
  1827. },
  1828. onAudioPlayerPause(){
  1829. if(this.playing && !this.paused){
  1830. this.paused = true;
  1831. this.showHideControls();
  1832. }
  1833. },
  1834. onAudioPlayerEnded(){
  1835. console.log('onAudioPlayerEnded');
  1836. if(this.playing){
  1837. // this paused shoudn't be true but i'm lazzy to find why it is ...
  1838. this.paused = false;
  1839. this.next();
  1840. }
  1841. },
  1842. // onAudioPlayNext(){
  1843. // this.next();
  1844. // }
  1845. };
  1846. // ___
  1847. // | __|_ ___ __ ___
  1848. // | _|\ \ / '_ \/ _ \
  1849. // |___/_\_\ .__/\___/
  1850. // |_|
  1851. function initExpo(){
  1852. console.log('initExpo', window.location.hash);
  1853. document.title = edlp.site_name;
  1854. if(window.location.hash == '#black'){
  1855. $('body').addClass('expo-black');
  1856. }
  1857. _$body.on('map-node-opened', checkExpoPlayerPositionning);
  1858. _randomPlayer.start();
  1859. initKeyboard();
  1860. }
  1861. function checkExpoPlayerPositionning(e){
  1862. console.log('checkExpoPlayerPositionning', e.node);
  1863. // optimized for 1280px width screen
  1864. switch(true){
  1865. case e.node.x > window.innerWidth-610 && e.node.y < 200:
  1866. _audioPlayer.$container.attr('pos', 'bottom-left');
  1867. break;
  1868. case e.node.x > window.innerWidth-610:
  1869. _audioPlayer.$container.attr('pos', 'top-left');
  1870. break;
  1871. case e.node.y < 200:
  1872. _audioPlayer.$container.attr('pos', 'bottom-right');
  1873. break;
  1874. default:
  1875. _audioPlayer.$container.attr('pos', 'top-right');
  1876. }
  1877. _audioPlayer.$container.css({
  1878. 'display':"block",
  1879. 'left':e.node.x+"px",
  1880. 'top':e.node.y+"px",
  1881. });
  1882. }
  1883. function initKeyboard(){
  1884. $(document).bind('keyup', 'alt+n', function(){
  1885. _randomPlayer.next();
  1886. });
  1887. }
  1888. // ___ _ _
  1889. // / __|_ _(_)__| |
  1890. // | (_ | '_| / _` |
  1891. // \___|_| |_\__,_|
  1892. function initGrid(){
  1893. console.log('theme : initGrid');
  1894. if(!_is_mobile){
  1895. checkGridBlockHeight();
  1896. _$row.find('.col').addClass('offfield');
  1897. }
  1898. if(false){
  1899. var $grid = $('.grid',_$row).masonry({
  1900. itemSelector:'.col',
  1901. columnWidth:'.col-2',
  1902. containerStyle: null,
  1903. resizeContainer:false,
  1904. // horizontalOrder: true,
  1905. transitionDuration:0,//'0.2s',
  1906. // stagger:30,
  1907. // disable initial layout
  1908. // initLayout: false,
  1909. });
  1910. // layout Masonry after each image loads
  1911. $grid.imagesLoaded().progress( function() {
  1912. $grid.masonry('layout');
  1913. });
  1914. $grid.imagesLoaded(function(){
  1915. $grid.masonry('layout');
  1916. // checkProductionBlockVisible();
  1917. });
  1918. // bind event
  1919. // $grid.masonry( 'on', 'layoutComplete', function() {
  1920. // console.log('layout is complete');
  1921. // });
  1922. $grid.on('layoutComplete', checkGridBlockVisible);
  1923. }else{
  1924. // setTimeout(checkGridBlockVisible, 100);
  1925. if(!_is_mobile){
  1926. checkGridBlockVisible();
  1927. }
  1928. }
  1929. };
  1930. function checkGridBlockHeight(){
  1931. // console.log('checkGridBlockHeight');
  1932. // if(_is_mobile) return;
  1933. var $r_h = _$row.height();
  1934. var $this;
  1935. // console.log($r_h);
  1936. $('.grid .col', _$row).each(function(i,e){
  1937. $this = $(this);
  1938. if(!$this.is('[init-height]')){
  1939. $this.attr('init-height', $this.outerHeight())
  1940. }
  1941. // console.log($(this).height(), $(this).innerHeight(), $(this).outerHeight());
  1942. // if($this.height() > $r_h){
  1943. // $this.height($r_h);
  1944. // }else{
  1945. // $this.height('auto');
  1946. // }
  1947. $this.height(Math.min($this.attr('init-height'), _$row.height()));
  1948. });
  1949. };
  1950. function checkGridBlockVisible(){
  1951. // console.log('checkGridBlockVisible');
  1952. // if(_is_mobile) return;
  1953. var $r_h = _$row.height();
  1954. var $this,pos;
  1955. $('.grid .col', _$row).each(function(i,e){
  1956. // $(this).on('load',function(event){
  1957. $this = $(this);
  1958. pos = $this.position();
  1959. // console.log(pos.top, $this.height(), pos.top+$this.height(), $r_h, $this);
  1960. if(pos.top+$this.height() <= $r_h){
  1961. $this.removeClass('offfield');
  1962. }else{
  1963. $this.addClass('offfield');
  1964. }
  1965. // });
  1966. });
  1967. // for (var i in items) {
  1968. // if(!items[i].isTransitioning){
  1969. // console.log('y+outerHeight', items[i].position.y+items[i].size.outerHeight);
  1970. // console.log('_$row.height()', _$row.height());
  1971. // if(items[i].position.y+items[i].size.outerHeight < _$row.height()){
  1972. // $(items[i].element).removeClass('offfield');
  1973. // }else{
  1974. // // $(items[i].element).addClass('offfield');
  1975. // }
  1976. // }
  1977. // }
  1978. }
  1979. // ___ _ _ _
  1980. // | _ \_ _ ___ __| |_ _ __| |_(_)___ _ _ ___
  1981. // | _/ '_/ _ \/ _` | || / _| _| / _ \ ' \(_-<
  1982. // |_| |_| \___/\__,_|\_,_\__|\__|_\___/_||_/__/
  1983. // function initProductions(){
  1984. // console.log('theme : initProductions');
  1985. //
  1986. // // _$row.find('.col').addClass('offfield');
  1987. // var $grid = $('.grid',_$row).masonry({
  1988. // itemSelector:'.col',
  1989. // columnWidth:'.col-2',
  1990. // containerStyle: null,
  1991. // resizeContainer:false,
  1992. // // horizontalOrder: true,
  1993. // transitionDuration:0,//'0.2s',
  1994. // // stagger:30,
  1995. // // disable initial layout
  1996. // // initLayout: false,
  1997. // });
  1998. //
  1999. // // layout Masonry after each image loads
  2000. // $grid.imagesLoaded().progress( function() {
  2001. // $grid.masonry('layout');
  2002. // });
  2003. //
  2004. // $grid.imagesLoaded(function(){
  2005. // $grid.masonry('layout');
  2006. // // checkProductionBlockVisible();
  2007. // });
  2008. //
  2009. // // bind event
  2010. // // $grid.masonry( 'on', 'layoutComplete', function() {
  2011. // // console.log('layout is complete');
  2012. // // });
  2013. // // $grid.on('layoutComplete', checkProductionBlockVisible);
  2014. // };
  2015. // ___ _ _ _ _
  2016. // / __|___| | |___ __| |_(_)___ _ _
  2017. // | (__/ _ \ | / -_) _| _| / _ \ ' \
  2018. // \___\___/_|_\___\__|\__|_\___/_||_|
  2019. // mobile version of collection
  2020. function initCollectionNav(){
  2021. console.log('initCollectionNav');
  2022. // taxonomy-term.vocabulary-entrees.home_mobile
  2023. $('.field--name-field-notice, .index', '.taxonomy-term.vocabulary-entrees.home_mobile')
  2024. .addClass('closed');
  2025. $('.field--name-field-notice>.field__label', '.taxonomy-term.vocabulary-entrees.home_mobile')
  2026. .on('click', onClickCollectionNotice);
  2027. $('.index>.field__label', '.taxonomy-term.vocabulary-entrees.home_mobile')
  2028. .on('click', onClickCollectionIndex);
  2029. };
  2030. function onClickCollectionNotice(e){
  2031. // console.log('onClickCollectionNotice');
  2032. // var $part = $(this).parent();//parents('.taxonomy-term');
  2033. toggleEntreeOpening($(this).parent(), 'notice');
  2034. };
  2035. function onClickCollectionIndex(e){
  2036. // console.log('onClickCollectionIndex');
  2037. // var $part = $(this).parent();//parents('.taxonomy-term');
  2038. toggleEntreeOpening($(this).parent(), 'index');
  2039. };
  2040. function toggleEntreeOpening($e, part){
  2041. $e.toggleClass('closed')
  2042. .parents('.taxonomy-term.vocabulary-entrees.home_mobile').toggleClass(part+'-opened');
  2043. }
  2044. // ___ _
  2045. // / __| ___ __ _ _ _ __| |_
  2046. // \__ \/ -_) _` | '_/ _| ' \
  2047. // |___/\___\__,_|_| \__|_||_|
  2048. function initSearch(){
  2049. // if($('#edit-entries input:checked', '#edlp-search-form').length){
  2050. // $('#edit-entries--wrapper', '#edlp-search-form').toggleClass('opened');
  2051. // }
  2052. $('#edit-entries--wrapper legend', '#edlp-search-form').on('click', function(){
  2053. $(this).parent().toggleClass('opened');
  2054. });
  2055. };
  2056. // ___ _ _ _
  2057. // | __|_ _ _ _ ___ __ _(_)__| |_ _ _ ___ _ __ ___ _ _| |_
  2058. // | _|| ' \| '_/ -_) _` | (_-< _| '_/ -_) ' \/ -_) ' \ _|
  2059. // |___|_||_|_| \___\__, |_/__/\__|_| \___|_|_|_\___|_||_\__|
  2060. // |___/
  2061. function initEnregistrementTranscript(){
  2062. console.log('initEnregistrementTranscript');
  2063. var $node = _$row.find('article.node--type-enregistrement.node--view-mode-transcript');
  2064. var $nav = $('<nav>').prependTo($node);
  2065. $node.find('.field--name-field-transcript-vo').addClass('visible').find('.field__label')
  2066. .clone().appendTo($nav).addClass('is-active')
  2067. .attr('field_target', '.field--name-field-transcript-vo');
  2068. $node.find('.field--name-field-transcript-trad').find('.field__label')
  2069. .clone().appendTo($nav)
  2070. .attr('field_target', '.field--name-field-transcript-trad');
  2071. $nav.find('.field__label').on('click', function(){
  2072. var $this = $(this).addClass('is-active');
  2073. $this.siblings('.is-active').removeClass('is-active');
  2074. $this.parents('article.node').find('.field.visible').removeClass('visible');
  2075. $this.parents('article.node').find($this.attr('field_target')).addClass('visible');
  2076. });
  2077. };
  2078. // ___ _ ___
  2079. // | __| _ ___ _ _| |_| _ \__ _ __ _ ___
  2080. // | _| '_/ _ \ ' \ _| _/ _` / _` / -_)
  2081. // |_||_| \___/_||_\__|_| \__,_\__, \___|
  2082. // |___/
  2083. function backToFrontPage(pop_state){
  2084. console.log('backToFrontPage', pop_state);
  2085. if(!_is_mobile){
  2086. closeAllModals();
  2087. // assume we are going back to front page
  2088. $('body').removeClass().addClass('path-frontpage');
  2089. $('a[data-drupal-link-system-path="<front>"]').addClass('is-active');
  2090. // close entrees
  2091. if(_corpus_ready){
  2092. _$corpus_canvas.trigger({'type':'close-all-entree'});
  2093. _$corpus_canvas.trigger({'type':'scramble-collection'});
  2094. }
  2095. if(typeof pop_state == "undefined" || !pop_state){
  2096. console.log('backToFrontPage push state');
  2097. state = {
  2098. home:true,
  2099. context:"home",
  2100. caller:null
  2101. }
  2102. _states_history.unshift(state);
  2103. history.pushState(state, null, _base_url+drupalSettings.path.currentLanguage);
  2104. }
  2105. }else{
  2106. // if mobile reload the front page
  2107. ajaxLoadContent({home: true, ajax_path: 'home_m/ajax', sys_path: 'frontpage'});
  2108. }
  2109. }
  2110. // function initHome(){
  2111. // addCloseModalBtnToCols();
  2112. // return;
  2113. // console.log('theme : initHome');
  2114. // var $grid = $('.grid',_$row).masonry({
  2115. // itemSelector:'.col',
  2116. // columnWidth:'.col-2',
  2117. // horizontalOrder: true,
  2118. // containerStyle: null,
  2119. // // disable initial layout
  2120. // // initLayout: false,
  2121. // });
  2122. // // bind event
  2123. // // $grid.masonry( 'on', 'layoutComplete', function() {
  2124. // // console.log('layout is complete');
  2125. // // });
  2126. //
  2127. // // layout Masonry after each image loads
  2128. // $grid.imagesLoaded().progress( function() {
  2129. // $grid.masonry('layout');
  2130. // });
  2131. //
  2132. // $grid.imagesLoaded(function(){
  2133. // $grid.masonry('layout');
  2134. // });
  2135. // }
  2136. // __ __ _ _
  2137. // | \/ |___ __| |__ _| |___
  2138. // | |\/| / _ \/ _` / _` | (_-<
  2139. // |_| |_\___/\__,_\__,_|_/__/
  2140. function closeAllModals(){
  2141. //console.log('theme : closeAllModals');
  2142. // TODO: animate the remove
  2143. _$row.html('');
  2144. _$ajaxLinks.removeClass('is-active');
  2145. _$body.trigger({'type':'all-modal-closed'});
  2146. // checkRowEmpty();
  2147. checkVisibleCorpusMapSpace();
  2148. };
  2149. function checkRowEmpty(){
  2150. console.log('checkRowEmpty');
  2151. // if row is empty and we are not in productions or entree notice|index call closeAllModals()
  2152. if(!$('.col', _$row).length){
  2153. if(!_$body.is('.entity-type-taxonomy_term.bundle-entrees')){
  2154. if(!_$body.is('.entity-type-node.bundle-page')){
  2155. // we weren't on production or entree, so go back to front page
  2156. // debugger;
  2157. if(_$body.is('.bundle-enregistrement.view-mode-article')
  2158. && $('a.articles-link').is('.is-active')){
  2159. console.log('Closing article while article index is active');
  2160. // if node article and articles is active, reload index
  2161. $('a.articles-link').removeClass('is-active').trigger('click');
  2162. }else{
  2163. backToFrontPage();
  2164. }
  2165. // if(!$('a.articles-link').is('.is-active')){
  2166. // // don't go back to front page if articles filter is on
  2167. // backToFrontPage();
  2168. // }else{
  2169. // }
  2170. }else{
  2171. // if we were on production page just scramble collection in case of map was filtered
  2172. if(_corpus_ready){
  2173. _$corpus_canvas.trigger({'type':'scramble-collection'});
  2174. }
  2175. // reload production home
  2176. $('a[data-drupal-link-system-path="productions"]', '#block-mainnavigation')
  2177. .removeClass('is-active').trigger('click');
  2178. }
  2179. }else{
  2180. // remove is-active class from index or notice entree links
  2181. $('.entree-content a.is-active').removeClass('is-active');
  2182. // TODO: remove the hash index or notice
  2183. }
  2184. }
  2185. };
  2186. init();
  2187. } // end EdlpTheme()
  2188. $(document).ready(function($) {
  2189. if(drupalSettings.path.isFront){
  2190. var edlptheme = new EdlpTheme();
  2191. }else{
  2192. $('body').attr('booted', 'booted');
  2193. }
  2194. });
  2195. })(jQuery, Drupal, drupalSettings);