|
| 1 | +import { Controller } from "@hotwired/stimulus"; |
| 2 | +import lunr from "lunr"; |
| 3 | + |
| 4 | +export default class extends Controller { |
| 5 | + static targets = ["search", "dialog", "results", "resultTemplate", "data"]; |
| 6 | + |
| 7 | + connect() { |
| 8 | + this._allowOpening(); |
| 9 | + } |
| 10 | + |
| 11 | + disconnect() { |
| 12 | + document.removeEventListener("keydown", this.keydownOpen); |
| 13 | + document.removeEventListener("click", this.clickClose, { once: true }); |
| 14 | + } |
| 15 | + |
| 16 | + open() { |
| 17 | + if (this.searchTarget.open) return; |
| 18 | + this._allowClosing(); |
| 19 | + this._initSearch(); |
| 20 | + this.searchTarget.showModal(); |
| 21 | + } |
| 22 | + |
| 23 | + search = debounce(this._search, 200); |
| 24 | + |
| 25 | + _allowOpening() { |
| 26 | + this.keydownOpen = (event) => { |
| 27 | + if (this.searchTarget.open || event.key !== "/") return; |
| 28 | + event.preventDefault(); |
| 29 | + this.open(); |
| 30 | + }; |
| 31 | + |
| 32 | + document.addEventListener("keydown", this.keydownOpen); |
| 33 | + } |
| 34 | + |
| 35 | + _allowClosing() { |
| 36 | + this.clickClose = (event) => { |
| 37 | + if (this.dialogTarget.contains(event.target)) return; |
| 38 | + this.searchTarget.close(); |
| 39 | + }; |
| 40 | + |
| 41 | + document.addEventListener("click", this.clickClose, { once: true }); |
| 42 | + } |
| 43 | + |
| 44 | + _initSearch() { |
| 45 | + if (this.documents) { |
| 46 | + this.searchTarget.classList.add("loaded"); |
| 47 | + return; |
| 48 | + } |
| 49 | + this._createSearchIndex(); |
| 50 | + this.searchTarget.classList.add("loaded"); |
| 51 | + } |
| 52 | + |
| 53 | + _createSearchIndex() { |
| 54 | + const documents = this._getDocuments(); |
| 55 | + if (documents.length === 0) return; |
| 56 | + this.documents = documents; |
| 57 | + this.searchIndex = lunr(function () { |
| 58 | + this.ref("title"); |
| 59 | + this.field("title", { boost: 5 }); |
| 60 | + this.field("text"); |
| 61 | + this.metadataWhitelist = ["position"]; |
| 62 | + documents.forEach(function (doc) { |
| 63 | + this.add(doc); |
| 64 | + }, this); |
| 65 | + }); |
| 66 | + } |
| 67 | + |
| 68 | + _getDocuments() { |
| 69 | + const searchData = JSON.parse(this.dataTarget.textContent); |
| 70 | + if (searchData.length === 0) { |
| 71 | + console.warn( |
| 72 | + [ |
| 73 | + "The search data is not present in the HTML.", |
| 74 | + "If you are in development, run `bundle exec rails hotdocs:index`.", |
| 75 | + "If you are in production, assets compilation should have taken care of it.", |
| 76 | + ].join(" ") |
| 77 | + ); |
| 78 | + } |
| 79 | + return searchData.map((data) => { |
| 80 | + const div = document.createElement("div"); |
| 81 | + div.innerHTML = data.html; |
| 82 | + return { ...data, text: div.innerText }; |
| 83 | + }); |
| 84 | + } |
| 85 | + |
| 86 | + _search(event) { |
| 87 | + if (!this.searchIndex) return; |
| 88 | + const query = event.target.value; |
| 89 | + const results = this.searchIndex.search(query).slice(0, 10); |
| 90 | + this._displayResults(results); |
| 91 | + } |
| 92 | + |
| 93 | + _displayResults(results) { |
| 94 | + this.resultsTarget.innerHTML = null; |
| 95 | + |
| 96 | + results.forEach((result) => { |
| 97 | + const matches = Object.keys(result.matchData.metadata); |
| 98 | + const excerpt = this._withExcerpt(matches, result)[0]; |
| 99 | + if (!excerpt) return; |
| 100 | + this.resultsTarget.appendChild(this._createResultElement(excerpt)); |
| 101 | + }); |
| 102 | + } |
| 103 | + |
| 104 | + _withExcerpt(matches, result) { |
| 105 | + return matches.flatMap((match) => { |
| 106 | + return Object.keys(result.matchData.metadata[match]).map((key) => { |
| 107 | + const position = result.matchData.metadata[match][key].position[0]; |
| 108 | + const [sliceStart, sliceLength] = key === "text" ? position : [0, 0]; |
| 109 | + const doc = this.documents.find((doc) => doc.title === result.ref); |
| 110 | + const excerpt = this._excerpt(doc.text, sliceStart, sliceLength); |
| 111 | + return { ...doc, excerpt }; |
| 112 | + }); |
| 113 | + }); |
| 114 | + } |
| 115 | + |
| 116 | + _excerpt(doc, sliceStart, sliceLength) { |
| 117 | + const startPos = Math.max(sliceStart - 80, 0); |
| 118 | + const endPos = Math.min(sliceStart + sliceLength + 80, doc.length); |
| 119 | + return [ |
| 120 | + startPos > 0 ? "..." : "", |
| 121 | + doc.slice(startPos, sliceStart), |
| 122 | + "<strong>" + |
| 123 | + escapeHtmlEntities(doc.slice(sliceStart, sliceStart + sliceLength)) + |
| 124 | + "</strong>", |
| 125 | + doc.slice(sliceStart + sliceLength, endPos), |
| 126 | + endPos < doc.length ? "..." : "", |
| 127 | + ].join(""); |
| 128 | + } |
| 129 | + |
| 130 | + _createResultElement(excerpt) { |
| 131 | + const clone = this.resultTemplateTarget.content.cloneNode(true); |
| 132 | + const li = clone.querySelector("li"); |
| 133 | + li.querySelector("h1").innerHTML = `${excerpt.parent} > ${excerpt.title}`; |
| 134 | + li.querySelector("a").innerHTML = excerpt.excerpt; |
| 135 | + li.querySelector("a").href = excerpt.url; |
| 136 | + return clone; |
| 137 | + } |
| 138 | +} |
| 139 | + |
| 140 | +function debounce(func, wait) { |
| 141 | + let timeoutId; |
| 142 | + |
| 143 | + return function (...args) { |
| 144 | + clearTimeout(timeoutId); |
| 145 | + timeoutId = setTimeout(() => func.apply(this, args), wait); |
| 146 | + }; |
| 147 | +} |
| 148 | + |
| 149 | +function escapeHtmlEntities(string) { |
| 150 | + return String(string) |
| 151 | + .replace(/&/g, "&") |
| 152 | + .replace(/</g, "<") |
| 153 | + .replace(/>/g, ">") |
| 154 | + .replace(/"/g, """); |
| 155 | +} |
0 commit comments