|
| 1 | +/* |
| 2 | + filters elements on page based on url or search box. |
| 3 | + syntax: term1 term2 "full phrase 1" "full phrase 2" "tag: tag 1" |
| 4 | + match if: all terms AND at least one phrase AND at least one tag |
| 5 | +*/ |
| 6 | +{ |
| 7 | + // elements to filter |
| 8 | + const elementSelector = ".card, .citation, .post-excerpt"; |
| 9 | + // search box element |
| 10 | + const searchBoxSelector = ".search-box"; |
| 11 | + // results info box element |
| 12 | + const infoBoxSelector = ".search-info"; |
| 13 | + // tags element |
| 14 | + const tagSelector = ".tag"; |
| 15 | + |
| 16 | + // split search query into terms, phrases, and tags |
| 17 | + const splitQuery = (query) => { |
| 18 | + // split into parts, preserve quotes |
| 19 | + const parts = query.match(/"[^"]*"|\S+/g) || []; |
| 20 | + |
| 21 | + // bins |
| 22 | + const terms = []; |
| 23 | + const phrases = []; |
| 24 | + const tags = []; |
| 25 | + |
| 26 | + // put parts into bins |
| 27 | + for (let part of parts) { |
| 28 | + if (part.startsWith('"')) { |
| 29 | + part = part.replaceAll('"', "").trim(); |
| 30 | + if (part.startsWith("tag:")) |
| 31 | + tags.push(normalizeTag(part.replace(/tag:\s*/, ""))); |
| 32 | + else phrases.push(part.toLowerCase()); |
| 33 | + } else terms.push(part.toLowerCase()); |
| 34 | + } |
| 35 | + |
| 36 | + return { terms, phrases, tags }; |
| 37 | + }; |
| 38 | + |
| 39 | + // normalize tag string for comparison |
| 40 | + window.normalizeTag = (tag) => |
| 41 | + tag.trim().toLowerCase().replaceAll(/\s+/g, "-"); |
| 42 | + |
| 43 | + // get data attribute contents of element and children |
| 44 | + const getAttr = (element, attr) => |
| 45 | + [element, ...element.querySelectorAll(`[data-${attr}]`)] |
| 46 | + .map((element) => element.dataset[attr]) |
| 47 | + .join(" "); |
| 48 | + |
| 49 | + // determine if element should show up in results based on query |
| 50 | + const elementMatches = (element, { terms, phrases, tags }) => { |
| 51 | + // tag elements within element |
| 52 | + const tagElements = [...element.querySelectorAll(".tag")]; |
| 53 | + |
| 54 | + // check if text content exists in element |
| 55 | + const hasText = (string) => |
| 56 | + ( |
| 57 | + element.innerText + |
| 58 | + getAttr(element, "tooltip") + |
| 59 | + getAttr(element, "search") |
| 60 | + ) |
| 61 | + .toLowerCase() |
| 62 | + .includes(string); |
| 63 | + // check if text matches a tag in element |
| 64 | + const hasTag = (string) => |
| 65 | + tagElements.some((tag) => normalizeTag(tag.innerText) === string); |
| 66 | + |
| 67 | + // match logic |
| 68 | + return ( |
| 69 | + (terms.every(hasText) || !terms.length) && |
| 70 | + (phrases.some(hasText) || !phrases.length) && |
| 71 | + (tags.some(hasTag) || !tags.length) |
| 72 | + ); |
| 73 | + }; |
| 74 | + |
| 75 | + // loop through elements, hide/show based on query, and return results info |
| 76 | + const filterElements = (parts) => { |
| 77 | + let elements = document.querySelectorAll(elementSelector); |
| 78 | + |
| 79 | + // results info |
| 80 | + let x = 0; |
| 81 | + let n = elements.length; |
| 82 | + let tags = parts.tags; |
| 83 | + |
| 84 | + // filter elements |
| 85 | + for (const element of elements) { |
| 86 | + if (elementMatches(element, parts)) { |
| 87 | + element.style.display = ""; |
| 88 | + x++; |
| 89 | + } else element.style.display = "none"; |
| 90 | + } |
| 91 | + |
| 92 | + return [x, n, tags]; |
| 93 | + }; |
| 94 | + |
| 95 | + // highlight search terms |
| 96 | + const highlightMatches = async ({ terms, phrases }) => { |
| 97 | + // make sure Mark library available |
| 98 | + if (typeof Mark === "undefined") return; |
| 99 | + |
| 100 | + // reset |
| 101 | + new Mark(document.body).unmark(); |
| 102 | + |
| 103 | + // limit number of highlights to avoid slowdown |
| 104 | + let counter = 0; |
| 105 | + const filter = () => counter++ < 100; |
| 106 | + |
| 107 | + // highlight terms and phrases |
| 108 | + new Mark(elementSelector) |
| 109 | + .mark(terms, { separateWordSearch: true, filter }) |
| 110 | + .mark(phrases, { separateWordSearch: false, filter }); |
| 111 | + }; |
| 112 | + |
| 113 | + // update search box based on query |
| 114 | + const updateSearchBox = (query = "") => { |
| 115 | + const boxes = document.querySelectorAll(searchBoxSelector); |
| 116 | + |
| 117 | + for (const box of boxes) { |
| 118 | + const input = box.querySelector("input"); |
| 119 | + const button = box.querySelector("button"); |
| 120 | + const icon = box.querySelector("button i"); |
| 121 | + input.value = query; |
| 122 | + icon.className = input.value.length |
| 123 | + ? "icon fa-solid fa-xmark" |
| 124 | + : "icon fa-solid fa-magnifying-glass"; |
| 125 | + button.disabled = input.value.length ? false : true; |
| 126 | + } |
| 127 | + }; |
| 128 | + |
| 129 | + // update info box based on query and results |
| 130 | + const updateInfoBox = (query, x, n) => { |
| 131 | + const boxes = document.querySelectorAll(infoBoxSelector); |
| 132 | + |
| 133 | + if (query.trim()) { |
| 134 | + // show all info boxes |
| 135 | + boxes.forEach((info) => (info.style.display = "")); |
| 136 | + |
| 137 | + // info template |
| 138 | + let info = ""; |
| 139 | + info += `Showing ${x.toLocaleString()} of ${n.toLocaleString()} results<br>`; |
| 140 | + info += "<a href='./'>Clear search</a>"; |
| 141 | + |
| 142 | + // set info HTML string |
| 143 | + boxes.forEach((el) => (el.innerHTML = info)); |
| 144 | + } |
| 145 | + // if nothing searched |
| 146 | + else { |
| 147 | + // hide all info boxes |
| 148 | + boxes.forEach((info) => (info.style.display = "none")); |
| 149 | + } |
| 150 | + }; |
| 151 | + |
| 152 | + // update tags based on query |
| 153 | + const updateTags = (query) => { |
| 154 | + const { tags } = splitQuery(query); |
| 155 | + document.querySelectorAll(tagSelector).forEach((tag) => { |
| 156 | + // set active if tag is in query |
| 157 | + if (tags.includes(normalizeTag(tag.innerText))) |
| 158 | + tag.setAttribute("data-active", ""); |
| 159 | + else tag.removeAttribute("data-active"); |
| 160 | + }); |
| 161 | + }; |
| 162 | + |
| 163 | + // run search with query |
| 164 | + const runSearch = (query = "") => { |
| 165 | + const parts = splitQuery(query); |
| 166 | + const [x, n] = filterElements(parts); |
| 167 | + updateSearchBox(query); |
| 168 | + updateInfoBox(query, x, n); |
| 169 | + updateTags(query); |
| 170 | + highlightMatches(parts); |
| 171 | + }; |
| 172 | + |
| 173 | + // update url based on query |
| 174 | + const updateUrl = (query = "") => { |
| 175 | + const url = new URL(window.location); |
| 176 | + let params = new URLSearchParams(url.search); |
| 177 | + params.set("search", query); |
| 178 | + url.search = params.toString(); |
| 179 | + window.history.replaceState(null, null, url); |
| 180 | + }; |
| 181 | + |
| 182 | + // search based on url param |
| 183 | + const searchFromUrl = () => { |
| 184 | + const query = |
| 185 | + new URLSearchParams(window.location.search).get("search") || ""; |
| 186 | + runSearch(query); |
| 187 | + }; |
| 188 | + |
| 189 | + // return func that runs after delay |
| 190 | + const debounce = (callback, delay = 250) => { |
| 191 | + let timeout; |
| 192 | + return (...args) => { |
| 193 | + window.clearTimeout(timeout); |
| 194 | + timeout = window.setTimeout(() => callback(...args), delay); |
| 195 | + }; |
| 196 | + }; |
| 197 | + |
| 198 | + // when user types into search box |
| 199 | + const debouncedRunSearch = debounce(runSearch, 1000); |
| 200 | + window.onSearchInput = (target) => { |
| 201 | + debouncedRunSearch(target.value); |
| 202 | + updateUrl(target.value); |
| 203 | + }; |
| 204 | + |
| 205 | + // when user clears search box with button |
| 206 | + window.onSearchClear = () => { |
| 207 | + runSearch(); |
| 208 | + updateUrl(); |
| 209 | + }; |
| 210 | + |
| 211 | + // after page loads |
| 212 | + window.addEventListener("load", searchFromUrl); |
| 213 | + // after tags load |
| 214 | + window.addEventListener("tagsfetched", searchFromUrl); |
| 215 | +} |
0 commit comments