2 // The URL path to the default glossary page in your instance.
3 // You should only need to change the "my-book" and "main-glossary"
4 // parts, keep the other parts and the general format the same.
5 const defaultGlossaryPage = '/books/my-book/page/main-glossary';
7 // Get a normalised URL path, check if it's a glossary page, and page the page content
8 const urlPath = window.location.pathname.replace(/^.*?\/books\//, '/books/');
9 const isGlossaryPage = urlPath.endsWith('/page/glossary') || urlPath.endsWith(defaultGlossaryPage);
10 const pageContentEl = document.querySelector('.page-content');
12 if (isGlossaryPage && pageContentEl) {
13 // Force re-index when viewing glossary pages
14 addTermMapToStorage(urlPath, domToTermMap(pageContentEl));
15 } else if (pageContentEl) {
16 // Get glossaries and highlight when viewing non-glossary pages
17 document.addEventListener('DOMContentLoaded', () => highlightTermsOnPage());
21 * Highlight glossary terms on the current page that's being viewed.
22 * In this, we get our combined glossary, then walk each text node to then check
23 * each word of the text against the glossary. Where exists, we split the text
24 * and insert a new glossary term span element in its place.
26 async function highlightTermsOnPage() {
27 const glossary = await getMergedGlossariesForPage(urlPath);
28 const trimRegex = /^[.?:"',;]|[.?:"',;]$/g;
29 const treeWalker = document.createTreeWalker(pageContentEl, NodeFilter.SHOW_TEXT);
30 while (treeWalker.nextNode()) {
31 const node = treeWalker.currentNode;
32 const words = node.textContent.split(' ');
33 const parent = node.parentNode;
35 let firstChange = true;
36 for (const word of words) {
37 const normalisedWord = word.toLowerCase().replace(trimRegex, '');
38 const glossaryVal = glossary[normalisedWord];
40 const preText = parsedWords.join(' ');
41 const preTextNode = new Text((firstChange ? '' : ' ') + preText + ' ');
42 parent.insertBefore(preTextNode, node)
43 const termEl = createGlossaryNode(word, glossaryVal);
44 parent.insertBefore(termEl, node);
45 node.textContent = node.textContent.replace(preText + ' ' + word, '');
51 parsedWords.push(word);
57 * Create the element for a glossary term.
58 * @param {string} term
59 * @param {string} description
62 function createGlossaryNode(term, description) {
63 const termEl = document.createElement('span');
64 termEl.setAttribute('data-term', description.trim());
65 termEl.setAttribute('class', 'glossary-term');
66 termEl.textContent = term;
71 * Get a merged glossary object for a given page.
72 * Combines the terms for a same-book & global glossary.
73 * @param {string} pagePath
74 * @returns {Promise<Object<string, string>>}
76 async function getMergedGlossariesForPage(pagePath) {
77 const [defaultGlossary, bookGlossary] = await Promise.all([
78 getGlossaryFromPath(defaultGlossaryPage),
79 getBookGlossary(pagePath),
82 return Object.assign({}, defaultGlossary, bookGlossary);
86 * Get the glossary for the book of page found at the given path.
87 * @param {string} pagePath
88 * @returns {Promise<Object<string, string>>}
90 async function getBookGlossary(pagePath) {
91 const bookPath = pagePath.split('/page/')[0];
92 const glossaryPath = bookPath + '/page/glossary';
93 return await getGlossaryFromPath(glossaryPath);
97 * Get/build a glossary from the given page path.
98 * Will fetch it from the localstorage cache first if existing.
99 * Otherwise, will attempt the load it by fetching the page.
101 * @returns {Promise<{}|any>}
103 async function getGlossaryFromPath(path) {
104 const key = 'bsglossary:' + path;
105 const storageVal = window.localStorage.getItem(key);
107 return JSON.parse(storageVal);
112 resp = await window.$http.get(path);
117 if (resp && resp.status === 200 && typeof resp.data === 'string') {
118 const doc = (new DOMParser).parseFromString(resp.data, 'text/html');
119 const contentEl = doc.querySelector('.page-content');
121 map = domToTermMap(contentEl);
125 addTermMapToStorage(path, map);
130 * Store a term map in storage for the given path.
131 * @param {string} urlPath
132 * @param {Object<string, string>} map
134 function addTermMapToStorage(urlPath, map) {
135 window.localStorage.setItem('bsglossary:' + urlPath, JSON.stringify(map));
139 * Convert the text of the given DOM into a map of definitions by term.
140 * @param {string} text
141 * @return {Object<string, string>}
143 function domToTermMap(dom) {
144 const textEls = Array.from(dom.querySelectorAll('p,h1,h2,h3,h4,h5,h6,blockquote'));
145 const text = textEls.map(el => el.textContent).join('\n');
147 const lines = text.split('\n');
148 for (const line of lines) {
149 const split = line.trim().split(':');
150 if (split.length > 1) {
151 map[split[0].trim().toLowerCase()] = split.slice(1).join(':');
159 * These are the styles for the glossary terms and definition popups.
160 * To keep things simple, the popups are not elements themselves, but
161 * pseudo ":after" elements on the terms, which gain their text via
162 * the "data-term" attribute on the term element.
164 .page-content .glossary-term {
165 text-decoration: underline;
166 text-decoration-style: dashed;
167 text-decoration-color: var(--color-link);
168 text-decoration-thickness: 1px;
172 .page-content .glossary-term:hover:after {
176 .page-content .glossary-term:after {
178 content: attr(data-term);
179 background-color: #FFF;
181 box-shadow: 0 1px 6px 0 rgba(0, 0, 0, 0.15);
182 padding: 0.5rem 1rem;
187 inset-inline-start: 0;
190 .dark-mode .page-content .glossary-term:after {
191 background-color: #000;