-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlibguides.js
More file actions
502 lines (486 loc) · 22.9 KB
/
libguides.js
File metadata and controls
502 lines (486 loc) · 22.9 KB
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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
// ============================================================================
// GUIDES GROUP: ACCESSIBILITY CSS OVERRIDES
// These styles are injected on Guides group pages, where the main libguides-css
// stylesheet is intentionally stripped so the CMS default styles apply.
// Edit ONLY this block when adding/changing accessibility overrides.
// Injection logic is in the DOMContentLoaded handler below.
// ============================================================================
const GUIDES_ACCESSIBILITY_CSS = `
/* LibGuide Footer */
.s-lib-footer {
font-size: 1em !important;
}
.s-lg-no-val, .s-lg-text-greyout, .s-lib-greyout {
color: #555 !important;
}
.s-lg-content-more-info {
font-size: 1em !important;}
`;
// context hacks
document.addEventListener("DOMContentLoaded", function(event) {
if (document.getElementById("s-lg-admin-command-bar")) {
var admin = true;
console.log("‼️ ADMIN");
// remove elements that conflict with the LibGuides admin UI
document.getElementById("libguides-css").remove();
document.getElementById("bootstrap-css").remove();
// display admin-only content (elements have style="display:none" set)
// see https://stackoverflow.com/a/54819633 regarding fancy syntax
[...document.getElementsByClassName("c3-admin-show")].forEach(e => e.removeAttribute("style"));
// ensure all details elements are open
[...document.querySelectorAll("details")].forEach(e => e.open = true);
// expand all details elements inside the WYSIWYG editor
const body = document.getElementsByTagName("body")[0];
const config = { childList: true, subtree: true };
const observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (document.getElementById("cke_s-lg-editor-content")) {
// jQuery
// add custom CSS to WYSIWYG editor inside iframe
var head = $(".cke_wysiwyg_frame").contents().find("head");
var css = '<style>.cke_editable details > summary { display: list-item; cursor: pointer; } .cke_editable summary > h3 { display: inline-block; }</style>';
$(head).append(css);
// /jQuery
const iframe = document.querySelector(".cke_wysiwyg_frame");
iframe.addEventListener("load", () => {
const childDoc = iframe.contentDocument;
[...childDoc.querySelectorAll("details")].forEach(e => e.open = true);
});
}
});
});
observer.observe(body, config);
// customize admin ui for Digital Exhibits Thumbnails page;
// remove hardcoded navigation elements, widen columns
let digital_exhibits_introduction_row = document.querySelector(".digital-exhibits-thumbnails #c3-introduction-row");
if (digital_exhibits_introduction_row) {
digital_exhibits_introduction_row.firstElementChild.classList.add("col-md-12");
digital_exhibits_introduction_row.firstElementChild.classList.remove("col-md-6");
digital_exhibits_introduction_row.lastElementChild.remove();
}
}
else {
var _public = true;
console.log("‼️ PUBLIC");
// Initialize Bootstrap 5 tooltips (Bootstrap provided by Springshare)
var tooltipTriggerList = document.querySelectorAll('[data-bs-toggle="tooltip"]');
tooltipTriggerList.forEach(function(tooltipTriggerEl) {
new bootstrap.Tooltip(tooltipTriggerEl);
});
// Remove Website CSS from `Guides` Group content.
if (document.getElementById("s-lib-bc-group")) {
if (document.getElementById("s-lib-bc-group").textContent == "Guides") {
document.getElementById("libguides-css").remove();
const style = document.createElement("style");
style.id = "guides-accessibility-css";
style.textContent = GUIDES_ACCESSIBILITY_CSS;
document.head.appendChild(style);
}
}
// remove scroll-to-top javascript
if (document.getElementById("s-lib-scroll-top")) {
document.getElementById("s-lib-scroll-top").remove();
}
if (document.getElementById("footer-wrapper")) {
// move the breadcrumbs to the footer
document.getElementById("footer-breadcrumbs").appendChild(document.getElementById("s-lib-bc"));
// this javascript code for the hours widget cannot be added alongside the
// HTML, instead it must be entered in a CSS/JS-specific field
var s_lc_tdh_3271_0 = new $.LibCalTodayHours( $("#s_lc_tdh_3271_0"), { iid: 3271, lid: 0 });
// grab tokenized login link and rebuild elsewhere
const login_link = document.createElement("a");
login_link.setAttribute("href", document.getElementById("s-lib-footer-login-link").getElementsByTagName("a")[0].getAttribute("href"));
login_link.setAttribute("aria-label", "Staff Login");
login_link.innerHTML = `<i class="fa fa-sign-in" aria-hidden="true"></i>`;
document.getElementById("footer-login").appendChild(login_link);
}
// update page title
const page_name = document.getElementById("s-lib-bc-page").textContent;
const site_name = "Caltech Library";
if (document.getElementById("s-lib-bc-group")) {
const group_name = document.getElementById("s-lib-bc-group").textContent;
if (document.body.classList.contains("c3-asc")) {
document.title = `${page_name} - ${group_name} - ${site_name}`;
}
else {
document.title = `${page_name} - ${site_name}`;
}
}
else {
document.title = `${page_name} - ${site_name}`;
}
// site search alert
if (document.getElementById("s-lg-srch-cols")) {
const search_alert = document.createElement("div");
search_alert.id = "search-alert";
search_alert.classList.add("alert", "alert-warning", "alert-dismissible");
search_alert.setAttribute("role", "alert");
search_alert.innerHTML = '<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>Looking for a book, journal, database, or other resource? Try <a href="/libsearch">LibSearch</a> instead. You can also browse our <a href="/az.php">Databases List</a> or <a href="https://libanswers.caltech.edu/">FAQs</a>.';
let parent = document.getElementById("s-lg-srch-cols").parentNode;
let target = document.getElementById("s-lg-srch-cols");
parent.insertBefore(search_alert, target);
}
}
if (document.getElementById("tpl-web")) {
if (document.getElementById("s-lg-guide-tabs") && !document.getElementById("s-lg-guide-tabs").firstElementChild.firstElementChild.classList.contains("active")) {
var content = true;
console.log("‼️ CONTENT");
// hide landing-only elements from content pages
[...document.getElementsByClassName("c3-content-hide")].forEach(e => e.classList.add("d-none"));
}
else {
var landing = true;
console.log("‼️ LANDING");
// hide content-only elements from landing pages
[...document.getElementsByClassName("c3-landing-hide")].forEach(e => e.classList.add("d-none"));
}
}
if (document.getElementById("s-lg-blog-content")) {
var blog = true;
console.log("‼️ BLOG");
}
// COMPLEX CONDITIONS
if (_public && document.getElementById("tpl-a-home")) {
console.log("‼️ ARCHIVES HOME");
const widget = document.getElementById("s-lg-widget-1653629897969");
const config = { childList: true, subtree: true };
const observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
observer.disconnect();
console.log(mutation.type);
var items = widget.getElementsByTagName("ul")[0].getElementsByTagName("li");
for (var i = 0; i < items.length; i++) {
items[i].setAttribute("id", `blogpost${[i]}`);
console.log(items[i]);
let title_link = items[i].getElementsByTagName("a")[0];
console.log(title_link);
let post_date = items[i].getElementsByTagName("span")[0];
console.log(post_date);
let first_img = items[i].getElementsByTagName("img")[0];
console.log(first_img);
// TODO account for no p
// TODO account for br inside p
let first_p = items[i].getElementsByTagName("p")[0];
console.log(first_p);
let p_images = first_p.getElementsByTagName("img");
while(p_images.length > 0) {
p_images[0].parentNode.removeChild(p_images[0]);
}
// create element
items[i].innerHTML = "";
title_link.removeAttribute("target");
items[i].innerHTML += `<h3>${title_link.outerHTML}</h3>`;
items[i].innerHTML += `<div class="text-secondary">${post_date.textContent}</div>`;
if (first_img) {
first_img.removeAttribute("align");
first_img.removeAttribute("border");
first_img.removeAttribute("height");
first_img.removeAttribute("hspace");
first_img.removeAttribute("style");
first_img.removeAttribute("vspace");
first_img.removeAttribute("width");
first_img.classList.add("blogpost-img");
items[i].innerHTML += first_img.outerHTML;
}
items[i].innerHTML += `<p>${first_p.innerHTML}</p>`;
items[i].innerHTML += `<a href="${title_link.href}" class="read-more">Read More . . .</a>`;
}
// NOTE images are not loaded by the end of the mutation observation
// apply classes based on image size, orientation, and aspect ratio
[...document.getElementsByClassName("blogpost-img")].forEach(e => e.addEventListener("load", function () {
console.log(e.naturalWidth);
console.log(e.naturalHeight);
if (e.naturalWidth <= 240) {
e.classList.add("img-xs");
}
else if (e.naturalWidth <= 535) {
e.classList.add("img-sm");
}
if (e.naturalWidth / e.naturalHeight < 4/3) {
e.classList.add("img-narrow");
}
}));
});
});
observer.observe(widget, config);
}
else if (admin && landing) {}
else if (admin && content) {}
// else if (admin && blog) {} // custom <HEAD> code not added on blog admin
else if (_public && landing) {
// identify public-facing landing pages to CSS
document.body.classList.add("c3-landing");
// Digital Exhibits Thumbnails
if (document.querySelector("#tpl-web.digital-exhibits-thumbnails")) {
// TODO implement for all landing pages
// wrap link from figcaption around figure
[...document.getElementsByTagName("figure")].forEach(e => {
let link = document.createElement("a");
link.innerHTML = e.outerHTML;
link.setAttribute("href", e.getElementsByTagName("a")[0].href)
e.parentElement.insertBefore(link, e);
e.remove();
});
// remove link from figcaption
[...document.getElementsByTagName("figcaption")].forEach(e => {
e.innerHTML = e.innerText;
});
}
}
else if (_public && content) {
document.body.classList.add("c3-content");
// remove the 'active' class from a dropdown parent if a child is active
if (document.getElementById("c3-sidenav").getElementsByClassName("active dropdown")[0]) {
if (document.getElementById("c3-sidenav").getElementsByClassName("active dropdown")[0].getElementsByClassName("active")[1]) {
document.getElementById("c3-sidenav").getElementsByClassName("active dropdown")[0].classList.remove("active");
}
}
// expand nested lists by removing dropdown classes
[...document.getElementById("c3-sidenav").getElementsByClassName("dropdown")].forEach(e => e.classList.remove("dropdown", "clearfix"));
[...document.getElementById("c3-sidenav").getElementsByClassName("float-start")].forEach(e => e.classList.remove("float-start"));
[...document.getElementById("c3-sidenav").getElementsByClassName("dropdown-menu")].forEach(e => e.classList.remove("dropdown-menu"));
[...document.getElementById("c3-sidenav").getElementsByClassName("dropdown-toggle")].forEach(e => e.remove());
[...document.getElementById("c3-sidenav").getElementsByClassName("d-inline-flex")].forEach(e => e.classList.remove("d-inline-flex"));
// save link for use if needed
const link = document.querySelector(".c3-asc #c3-sidenav > ul > li:first-of-type a");
// remove landing page links in Archives sidebar (jQuery)
$(".c3-asc #c3-sidenav > ul > li:first-of-type a").contents().unwrap();
// add custom sidebar menu title for Research Collections
const sidenav = document.getElementById("c3-sidenav");
const config = { attributes: true };
const observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
observer.disconnect();
// NOTE custom guide classes added via admin ui
// TODO refactor as DRY code
if (document.querySelector("#c3-sidenav.g1230812 > ul")) {
// first link was unwrapped; rewrap with the link (jQuery)
$("#c3-sidenav.g1230812 > ul > li:first-of-type span").wrap(link);
// add the new custom element
const sidenav_title = document.createElement("li");
sidenav_title.textContent = "Research Collections";
document.querySelector("#c3-sidenav.g1230812 > ul").insertAdjacentElement('afterbegin', sidenav_title);
}
if (document.querySelector("#c3-sidenav.g1230813 > ul")) {
// first link was unwrapped; rewrap with the link (jQuery)
$("#c3-sidenav.g1230813 > ul > li:first-of-type span").wrap(link);
// add the new custom element
const sidenav_title = document.createElement("li");
sidenav_title.textContent = "Explore Exhibits";
document.querySelector("#c3-sidenav.g1230813 > ul").insertAdjacentElement('afterbegin', sidenav_title);
}
});
});
observer.observe(sidenav, config);
}
else if (_public && blog) {
// NOTE unsure if this script will always run before main blog script;
// #s-lg-blog-content is initially empty on the /blog page, but on blog
// post pages it is populated with #s-lg-blog-posts and more
/**
* Removes a Comments link and its preceding text node.
*
* We want to remove the link to Comments and its preceding text node
* containing a horizontal bar character (` | `). The markup is different
* depending on whether the post contains subject tags or not.
*
* Example without subjects:
* ```html
* <h2 class="s-lg-blog-header">Post Title</h2>
* <span>by Post Author on <span>[Post Date]</span> | <a href="/example#comments">Comments</a></span><br>
* ```
*
* Example with subjects:
* ```html
* <h2 class="s-lg-blog-header">Post Title</h2>
* <span>by Post Author on <span>[Post Date]</span> in <a>Subject 1</a>, <a>Subject 2</a>, <a>Subject 3</a></span> | <a href="/example#comments">Comments</a><br>
* ```
*
* @param {node} node The span element immediately following the .s-lg-blog-header element.
*/
function removeCommentsLink(node) {
if (node.nextSibling.nodeName === "BR") {
if (node.lastChild.previousSibling.nodeName === "#text" && node.lastChild.previousSibling.nodeValue === " | ") {
node.lastChild.previousSibling.remove();
}
else if (node.lastChild.nodeName === "A" && node.lastChild.href.endsWith("#comments")) {
node.lastChild.remove();
}
}
else if (node.nextSibling.nodeName === "#text" && node.nextSibling.nodeValue === " | ") {
// console.log(node.nextSibling);
if (node.nextSibling.nextSibling.nodeName === "A" && node.nextSibling.nextSibling.href.endsWith("#comments")) {
// console.log(node.nextSibling.nextSibling);
node.nextSibling.nextSibling.remove();
// console.log(node.nextSibling);
node.nextSibling.remove();
}
}
}
if (document.getElementById("s-lg-blog-posts")) {
console.log("‼️ BLOG POST");
document.body.classList.add("blog-post");
// console.log(document.getElementById("s-lg-blog-posts").querySelector(".s-lg-blog-header + span"));
removeCommentsLink(document.getElementById("s-lg-blog-posts").querySelector(".s-lg-blog-header + span"));
}
else {
console.log("‼️ BLOG LANDING");
// /blog landing content is populated by another script
const blog_content = document.getElementById("s-lg-blog-content");
const config = { childList: true, subtree: true };
const observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
observer.disconnect();
// console.log(mutation.type);
const blog_posts = document.getElementById("s-lg-blog-posts").getElementsByClassName("row");
for (var i = 0; i < blog_posts.length; i++) {
// console.log(blog_posts[i]);
blog_posts[i].querySelectorAll(".s-lg-blog-header + span").forEach(node => removeCommentsLink(node));
}
});
});
observer.observe(blog_content, config);
}
}
// Transform new Springshare blog metadata (removes icons, reformats to "by Author on Date | Subjects")
if (document.querySelector(".posts-container .blog-post")) {
console.log("‼️ NEW BLOG FORMAT");
document.querySelectorAll(".blog-post").forEach(post => {
const metaContainer = post.querySelector(".d-flex.flex-wrap.align-items-center.gap-2");
if (!metaContainer) return;
// Extract date
const dateEl = metaContainer.querySelector(".blog-public-custom-calendar-icon")?.parentElement?.querySelector("span");
const date = dateEl?.textContent?.trim() || "";
// Extract author
const authorEl = metaContainer.querySelector(".blog-public-custom-user-profile-icon")?.parentElement?.querySelector("span");
const author = authorEl?.textContent?.trim() || "";
// Extract subjects (preserve links)
const subjectsContainer = metaContainer.querySelector(".subjects-container");
let subjectsHTML = "";
let hasSubjects = false;
if (subjectsContainer) {
const subjectLinks = subjectsContainer.querySelectorAll("a");
if (subjectLinks.length > 0) {
hasSubjects = true;
// Clean up commas from link text and rebuild with proper separators
const cleanedLinks = Array.from(subjectLinks).map(a => {
const clone = a.cloneNode(true);
clone.textContent = clone.textContent.trim().replace(/,$/, "");
return clone.outerHTML;
});
subjectsHTML = cleanedLinks.join(", ");
}
}
// Rebuild metadata
metaContainer.innerHTML = `<span class="blog-meta-text text-secondary">by ${author} on ${date}${hasSubjects ? " | " + subjectsHTML : ""}</span>`;
metaContainer.classList.remove("gap-2", "gap-sm-4");
});
}
});
// keep menu open upon non-link click within
$(document).ready(function() {
$('.megatoggle').on({
"click": function(e) { // handles click event
// if megamenu or any child of megamenu is clicked
if ($(e.target).is('.megamenu') || $(e.target).parents().is('.megamenu')) {
this.closable = false // do not close it
return;
} else {
this.closable = true; // else close it
}
},
"hide.bs.dropdown": function() {
return this.closable;
} // save state
});
});
/* ============================================================================
LIBRARY HOME BLOG WIDGET
Widget ID: s-lg-widget-1770820610259
Transforms blog widget on library homepage into card layout
============================================================================ */
(function() {
function transformLibraryBlogWidget() {
const widget = document.getElementById("s-lg-widget-1770820610259");
if (!widget) return;
// Check if widget has content (ul with li items)
const ul = widget.getElementsByTagName("ul")[0];
if (!ul) return;
const items = ul.getElementsByTagName("li");
if (!items.length) return;
console.log("‼️ LIBRARY HOME BLOG WIDGET - transforming");
for (var i = 0; i < items.length; i++) {
items[i].setAttribute("id", `lib-blogpost${i}`);
let title_link = items[i].getElementsByTagName("a")[0];
let post_date = items[i].getElementsByTagName("span")[0];
let first_img = items[i].getElementsByTagName("img")[0];
// Find first paragraph with actual text content (not just an image)
let paragraphs = items[i].getElementsByTagName("p");
let text_p = null;
for (var j = 0; j < paragraphs.length; j++) {
// Check if paragraph has text content beyond just whitespace
let textContent = paragraphs[j].textContent.trim();
if (textContent.length > 0) {
text_p = paragraphs[j].cloneNode(true);
// Remove images from the cloned paragraph
let p_images = text_p.getElementsByTagName("img");
while(p_images.length > 0) {
p_images[0].parentNode.removeChild(p_images[0]);
}
break;
}
}
// Rebuild element
items[i].innerHTML = "";
title_link.removeAttribute("target");
items[i].innerHTML += `<h3>${title_link.outerHTML}</h3>`;
if (post_date) {
items[i].innerHTML += `<div class="post-date text-secondary">${post_date.textContent}</div>`;
}
if (first_img) {
first_img.removeAttribute("align");
first_img.removeAttribute("border");
first_img.removeAttribute("height");
first_img.removeAttribute("hspace");
first_img.removeAttribute("style");
first_img.removeAttribute("vspace");
first_img.removeAttribute("width");
first_img.classList.add("lib-blogpost-img");
items[i].innerHTML += first_img.outerHTML;
}
if (text_p) {
// Truncate to ~400 characters at word boundary
let text = text_p.textContent;
if (text.length > 400) {
text = text.substring(0, 400);
text = text.substring(0, text.lastIndexOf(' ')) + '...';
}
items[i].innerHTML += `<p>${text}</p>`;
}
items[i].innerHTML += `<a href="${title_link.href}" class="read-more">View Full Post</a>`;
}
// Change "View More Results" to "View More Posts"
const moreLink = widget.querySelector('.s-lg-widget-list-more-results a');
if (moreLink) {
moreLink.textContent = 'View More Posts';
moreLink.removeAttribute('target');
}
}
// Poll for widget to appear and have content
var checkCount = 0;
var checkInterval = setInterval(function() {
checkCount++;
const widget = document.getElementById("s-lg-widget-1770820610259");
const ul = widget && widget.getElementsByTagName("ul")[0];
if (ul && ul.getElementsByTagName("li").length > 0) {
clearInterval(checkInterval);
transformLibraryBlogWidget();
}
if (checkCount > 50) { // Stop after 5 seconds
clearInterval(checkInterval);
}
}, 100);
})();
/* ============================================================================
END LIBRARY HOME BLOG WIDGET
============================================================================ */