-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhugo-academic.js
356 lines (306 loc) · 12.2 KB
/
hugo-academic.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
/*************************************************
* Academic: the personal website framework for Hugo.
* https://github.com/gcushen/hugo-academic
**************************************************/
(function($){
/* ---------------------------------------------------------------------------
* Responsive scrolling for URL hashes.
* --------------------------------------------------------------------------- */
// Dynamically get responsive navigation bar offset.
let $navbar = $('.navbar');
let navbar_offset = $navbar.innerHeight();
/**
* Responsive hash scrolling.
* Check for a URL hash as an anchor.
* If it exists on current page, scroll to it responsively.
* If `target` argument omitted (e.g. after event), assume it's the window's hash.
*/
function scrollToAnchor(target) {
// If `target` is undefined or HashChangeEvent object, set it to window's hash.
target = (typeof target === 'undefined' || typeof target === 'object') ? window.location.hash : target;
// Escape colons from IDs, such as those found in Markdown footnote links.
target = target.replace(/:/g, '\\:');
// If target element exists, scroll to it taking into account fixed navigation bar offset.
if($(target).length) {
$('body').addClass('scrolling');
$('html, body').animate({
scrollTop: $(target).offset().top - navbar_offset
}, 600, function () {
$('body').removeClass('scrolling');
});
}
}
// Make Scrollspy responsive.
function fixScrollspy() {
let $body = $('body');
let data = $body.data('bs.scrollspy');
if (data) {
data._config.offset = navbar_offset;
$body.data('bs.scrollspy', data);
$body.scrollspy('refresh');
}
}
// Check for hash change event and fix responsive offset for hash links (e.g. Markdown footnotes).
window.addEventListener("hashchange", scrollToAnchor);
/* ---------------------------------------------------------------------------
* Add smooth scrolling to all links inside the main navbar.
* --------------------------------------------------------------------------- */
$('#navbar-main li.nav-item a.nav-link').on('click', function(event) {
// Store requested URL hash.
let hash = this.hash;
// If we are on the homepage and the navigation bar link is to a homepage section.
if ( hash && $(hash).length && ($("#homepage").length > 0)) {
// Prevent default click behavior.
event.preventDefault();
// Use jQuery's animate() method for smooth page scrolling.
// The numerical parameter specifies the time (ms) taken to scroll to the specified hash.
$('html, body').animate({
scrollTop: $(hash).offset().top - navbar_offset
}, 800);
}
});
/* ---------------------------------------------------------------------------
* Smooth scrolling for Back To Top link.
* --------------------------------------------------------------------------- */
$('#back_to_top').on('click', function(event) {
event.preventDefault();
$('html, body').animate({
'scrollTop': 0
}, 800, function() {
window.location.hash = "";
});
});
/* ---------------------------------------------------------------------------
* Hide mobile collapsable menu on clicking a link.
* --------------------------------------------------------------------------- */
$(document).on('click', '.navbar-collapse.show', function(e) {
//get the <a> element that was clicked, even if the <span> element that is inside the <a> element is e.target
let targetElement = $(e.target).is('a') ? $(e.target) : $(e.target).parent();
if (targetElement.is('a') && targetElement.attr('class') != 'dropdown-toggle') {
$(this).collapse('hide');
}
});
/* ---------------------------------------------------------------------------
* Filter publications.
* --------------------------------------------------------------------------- */
let $grid_pubs = $('#container-publications');
$grid_pubs.isotope({
itemSelector: '.isotope-item',
percentPosition: true,
masonry: {
// Use Bootstrap compatible grid layout.
columnWidth: '.grid-sizer'
}
});
// Active publication filters.
let pubFilters = {};
// Flatten object by concatenating values.
function concatValues( obj ) {
let value = '';
for ( let prop in obj ) {
value += obj[ prop ];
}
return value;
}
$('.pub-filters').on( 'change', function() {
let $this = $(this);
// Get group key.
let filterGroup = $this[0].getAttribute('data-filter-group');
// Set filter for group.
pubFilters[ filterGroup ] = this.value;
// Combine filters.
let filterValues = concatValues( pubFilters );
// Activate filters.
$grid_pubs.isotope({ filter: filterValues });
// If filtering by publication type, update the URL hash to enable direct linking to results.
if (filterGroup == "pubtype") {
// Set hash URL to current filter.
let url = $(this).val();
if (url.substr(0, 9) == '.pubtype-') {
window.location.hash = url.substr(9);
} else {
window.location.hash = '';
}
}
});
// Filter publications according to hash in URL.
function filter_publications() {
let urlHash = window.location.hash.replace('#','');
let filterValue = '*';
// Check if hash is numeric.
if (urlHash != '' && !isNaN(urlHash)) {
filterValue = '.pubtype-' + urlHash;
}
// Set filter.
let filterGroup = 'pubtype';
pubFilters[ filterGroup ] = filterValue;
let filterValues = concatValues( pubFilters );
// Activate filters.
$grid_pubs.isotope({ filter: filterValues });
// Set selected option.
$('.pubtype-select').val(filterValue);
}
/* ---------------------------------------------------------------------------
* Google Maps or OpenStreetMap via Leaflet.
* --------------------------------------------------------------------------- */
function initMap () {
if ($('#map').length) {
let map_provider = $('#map-provider').val();
let lat = $('#map-lat').val();
let lng = $('#map-lng').val();
let zoom = parseInt($('#map-zoom').val());
let address = $('#map-dir').val();
let api_key = $('#map-api-key').val();
if ( map_provider == 1 ) {
let map = new GMaps({
div: '#map',
lat: lat,
lng: lng,
zoom: zoom,
zoomControl: true,
zoomControlOpt: {
style: 'SMALL',
position: 'TOP_LEFT'
},
panControl: false,
streetViewControl: false,
mapTypeControl: false,
overviewMapControl: false,
scrollwheel: true,
draggable: true
});
map.addMarker({
lat: lat,
lng: lng,
click: function (e) {
let url = 'https://www.google.com/maps/place/' + encodeURIComponent(address) + '/@' + lat + ',' + lng +'/';
window.open(url, '_blank')
},
title: address
})
} else {
let map = new L.map('map').setView([lat, lng], zoom);
if ( map_provider == 3 && api_key.length ) {
L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}', {
attribution: 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://mapbox.com">Mapbox</a>',
maxZoom: 18,
id: 'mapbox.streets',
accessToken: api_key
}).addTo(map);
} else {
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 19,
attribution: '© <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
}).addTo(map);
}
let marker = L.marker([lat, lng]).addTo(map);
let url = lat + ',' + lng +'#map='+ zoom +'/'+ lat +'/'+ lng +'&layers=N';
marker.bindPopup(address + '<p><a href="https://www.openstreetmap.org/directions?engine=osrm_car&route='+ url +'">Routing via OpenStreetMap</a></p>');
}
}
}
/* ---------------------------------------------------------------------------
* GitHub API.
* --------------------------------------------------------------------------- */
function printLatestRelease(selector, repo) {
$.getJSON('https://api.github.com/repos/' + repo + '/tags').done(function (json) {
let release = json[0];
$(selector).append(release.name);
}).fail(function( jqxhr, textStatus, error ) {
let err = textStatus + ", " + error;
console.log( "Request Failed: " + err );
});
}
/* ---------------------------------------------------------------------------
* On window load.
* --------------------------------------------------------------------------- */
$(window).on('load', function() {
if (window.location.hash) {
// When accessing homepage from another page and `#top` hash is set, show top of page (no hash).
if (window.location.hash == "#top") {
window.location.hash = ""
} else {
// If URL contains a hash, scroll to target ID taking into account responsive offset.
scrollToAnchor();
}
}
// Initialize Scrollspy.
let $body = $('body');
$body.scrollspy({offset: navbar_offset });
// Call `fixScrollspy` when window is resized.
let resizeTimer;
$(window).resize(function() {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(fixScrollspy, 200);
});
// Filter projects.
$('.projects-container').each(function(index, container) {
let $container = $(container);
let $section = $container.closest('section');
let layout = 'masonry';
if ($section.find('.isotope').hasClass('js-layout-row')) {
layout = 'fitRows';
}
$container.imagesLoaded(function() {
// Initialize Isotope after all images have loaded.
$container.isotope({
itemSelector: '.isotope-item',
layoutMode: layout,
filter: $section.find('.default-project-filter').text()
});
// Filter items when filter link is clicked.
$section.find('.project-filters a').click(function() {
let selector = $(this).attr('data-filter');
$container.isotope({filter: selector});
$(this).removeClass('active').addClass('active').siblings().removeClass('active all');
return false;
});
});
});
// Enable publication filter for publication index page.
if ($('.pub-filters-select')) {
filter_publications();
// Useful for changing hash manually (e.g. in development):
// window.addEventListener('hashchange', filter_publications, false);
}
// Load citation modal on 'Cite' click.
$('.js-cite-modal').click(function(e) {
e.preventDefault();
let filename = $(this).attr('data-filename');
let modal = $('#modal');
modal.find('.modal-body code').load( filename , function( response, status, xhr ) {
if ( status == 'error' ) {
let msg = "Error: ";
$('#modal-error').html( msg + xhr.status + " " + xhr.statusText );
} else {
$('.js-download-cite').attr('href', filename);
}
});
modal.modal('show');
});
// Copy citation text on 'Copy' click.
$('.js-copy-cite').click(function(e) {
e.preventDefault();
// Get selection.
let range = document.createRange();
let code_node = document.querySelector('#modal .modal-body');
range.selectNode(code_node);
window.getSelection().addRange(range);
try {
// Execute the copy command.
document.execCommand('copy');
} catch(e) {
console.log('Error: citation copy failed.');
}
// Remove selection.
window.getSelection().removeRange(range);
});
// Initialise Google Maps if necessary.
initMap();
// Fix Hugo's inbuilt Table of Contents.
$('#TableOfContents > ul > li > ul').unwrap().unwrap();
// Print latest Academic version if necessary.
if ($('#academic-release').length > 0)
printLatestRelease('#academic-release', $('#academic-release').data('repo'));
});
})(jQuery);