main.js 79 KB

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