]> BookStack Code Mirror - hacks/blob - content/dynamic-glossary/head.html
Added glossary hack
[hacks] / content / dynamic-glossary / head.html
1 <script type="module">
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';
6
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');
11
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());
18     }
19
20     /**
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.
25      */
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;
34             let parsedWords = [];
35             let firstChange = true;
36             for (const word of words) {
37                 const normalisedWord = word.toLowerCase().replace(trimRegex, '');
38                 const glossaryVal = glossary[normalisedWord];
39                 if (glossaryVal) {
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, '');
46                     parsedWords = [];
47                     firstChange = false;
48                     continue;
49                 }
50
51                 parsedWords.push(word);
52             }
53         }
54     }
55
56     /**
57      * Create the element for a glossary term.
58      * @param {string} term
59      * @param {string} description
60      * @returns {Element}
61      */
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;
67         return termEl;
68     }
69
70     /**
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>>}
75      */
76     async function getMergedGlossariesForPage(pagePath) {
77         const [defaultGlossary, bookGlossary] = await Promise.all([
78             getGlossaryFromPath(defaultGlossaryPage),
79             getBookGlossary(pagePath),
80         ]);
81
82         return Object.assign({}, defaultGlossary, bookGlossary);
83     }
84
85     /**
86      * Get the glossary for the book of page found at the given path.
87      * @param {string} pagePath
88      * @returns {Promise<Object<string, string>>}
89      */
90     async function getBookGlossary(pagePath) {
91         const bookPath = pagePath.split('/page/')[0];
92         const glossaryPath = bookPath + '/page/glossary';
93         return await getGlossaryFromPath(glossaryPath);
94     }
95
96     /**
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.
100      * @param path
101      * @returns {Promise<{}|any>}
102      */
103     async function getGlossaryFromPath(path) {
104         const key = 'bsglossary:' + path;
105         const storageVal = window.localStorage.getItem(key);
106         if (storageVal) {
107             return JSON.parse(storageVal);
108         }
109
110         let resp = null;
111         try {
112             resp = await window.$http.get(path);
113         } catch (err) {
114         }
115
116         let map = {};
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');
120             if (contentEl) {
121                 map = domToTermMap(contentEl);
122             }
123         }
124
125         addTermMapToStorage(path, map);
126         return map;
127     }
128
129     /**
130      * Store a term map in storage for the given path.
131      * @param {string} urlPath
132      * @param {Object<string, string>} map
133      */
134     function addTermMapToStorage(urlPath, map) {
135         window.localStorage.setItem('bsglossary:' + urlPath, JSON.stringify(map));
136     }
137
138     /**
139      * Convert the text of the given DOM into a map of definitions by term.
140      * @param {string} text
141      * @return {Object<string, string>}
142      */
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');
146         const map = {};
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(':');
152             }
153         }
154         return map;
155     }
156 </script>
157 <style>
158     /**
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.
163      */
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;
169         position: relative;
170         cursor: help;
171     }
172     .page-content .glossary-term:hover:after {
173         display: block;
174     }
175
176     .page-content .glossary-term:after {
177         position: absolute;
178         content: attr(data-term);
179         background-color: #FFF;
180         width: 200px;
181         box-shadow: 0 1px 6px 0 rgba(0, 0, 0, 0.15);
182         padding: 0.5rem 1rem;
183         font-size: 12px;
184         border-radius: 3px;
185         z-index: 20;
186         top: 2em;
187         inset-inline-start: 0;
188         display: none;
189     }
190     .dark-mode .page-content .glossary-term:after {
191         background-color: #000;
192     }
193 </style>