From eb23cbe8da4ce90bf6a34f7e92148babc9a3049b Mon Sep 17 00:00:00 2001
From: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Date: Thu, 15 Aug 2024 08:25:07 +0000
Subject: [PATCH] chore(deps): bump rehype-citation from 2.0.0 to 2.1.1 (#1341)
---
quartz/components/scripts/search.inline.ts | 214 +++++++++++++++++++++++++++-------------------------
1 files changed, 111 insertions(+), 103 deletions(-)
diff --git a/quartz/components/scripts/search.inline.ts b/quartz/components/scripts/search.inline.ts
index c960f5e..73e64b3 100644
--- a/quartz/components/scripts/search.inline.ts
+++ b/quartz/components/scripts/search.inline.ts
@@ -15,10 +15,31 @@
type SearchType = "basic" | "tags"
let searchType: SearchType = "basic"
let currentSearchTerm: string = ""
-let index: FlexSearch.Document<Item> | undefined = undefined
-const p = new DOMParser()
const encoder = (str: string) => str.toLowerCase().split(/([^a-z]|[^\x00-\x7F])/)
+let index = new FlexSearch.Document<Item>({
+ charset: "latin:extra",
+ encode: encoder,
+ document: {
+ id: "id",
+ tag: "tags",
+ index: [
+ {
+ field: "title",
+ tokenize: "forward",
+ },
+ {
+ field: "content",
+ tokenize: "forward",
+ },
+ {
+ field: "tags",
+ tokenize: "forward",
+ },
+ ],
+ },
+})
+const p = new DOMParser()
const fetchContentCache: Map<FullSlug, Element[]> = new Map()
const contextWindowWords = 30
const numSearchResults = 8
@@ -76,14 +97,15 @@
})
.join(" ")
- return `${startIndex === 0 ? "" : "..."}${slice}${endIndex === tokenizedText.length - 1 ? "" : "..."
- }`
+ return `${startIndex === 0 ? "" : "..."}${slice}${
+ endIndex === tokenizedText.length - 1 ? "" : "..."
+ }`
}
-function highlightHTML(searchTerm: string, innerHTML: string) {
+function highlightHTML(searchTerm: string, el: HTMLElement) {
const p = new DOMParser()
const tokenizedTerms = tokenizeTerm(searchTerm)
- const html = p.parseFromString(innerHTML, "text/html")
+ const html = p.parseFromString(el.innerHTML, "text/html")
const createHighlightSpan = (text: string) => {
const span = document.createElement("span")
@@ -126,7 +148,7 @@
const data = await fetchData
const container = document.getElementById("search-container")
const sidebar = container?.closest(".sidebar") as HTMLElement
- const searchIcon = document.getElementById("search-icon")
+ const searchButton = document.getElementById("search-button")
const searchBar = document.getElementById("search-bar") as HTMLInputElement | null
const searchLayout = document.getElementById("search-layout")
const idDataMap = Object.keys(data) as FullSlug[]
@@ -142,13 +164,11 @@
let previewInner: HTMLDivElement | undefined = undefined
const results = document.createElement("div")
results.id = "results-container"
- results.style.flexBasis = enablePreview ? "min(30%, 450px)" : "100%"
appendLayout(results)
if (enablePreview) {
preview = document.createElement("div")
preview.id = "preview-container"
- preview.style.flexBasis = "100%"
appendLayout(preview)
}
@@ -167,10 +187,12 @@
removeAllChildren(preview)
}
if (searchLayout) {
- searchLayout.style.visibility = "hidden"
+ searchLayout.classList.remove("display-results")
}
searchType = "basic" // reset search type after closing
+
+ searchButton?.focus()
}
function showSearch(searchTypeNew: SearchType) {
@@ -207,7 +229,7 @@
// If search is active, then we will render the first result and display accordingly
if (!container?.classList.contains("active")) return
- else if (e.key === "Enter") {
+ if (e.key === "Enter") {
// If result has focus, navigate to that one, otherwise pick first result
if (results?.contains(document.activeElement)) {
const active = document.activeElement as HTMLInputElement
@@ -229,9 +251,9 @@
: (document.activeElement as HTMLInputElement | null)
const prevResult = currentResult?.previousElementSibling as HTMLInputElement | null
currentResult?.classList.remove("focus")
- await displayPreview(prevResult)
prevResult?.focus()
- currentHover = prevResult
+ if (prevResult) currentHover = prevResult
+ await displayPreview(prevResult)
}
} else if (e.key === "ArrowDown" || e.key === "Tab") {
e.preventDefault()
@@ -243,19 +265,9 @@
: (document.getElementsByClassName("result-card")[0] as HTMLInputElement | null)
const secondResult = firstResult?.nextElementSibling as HTMLInputElement | null
firstResult?.classList.remove("focus")
- await displayPreview(secondResult)
secondResult?.focus()
- currentHover = secondResult
- } else {
- // If an element in results-container already has focus, focus next one
- const active = currentHover
- ? currentHover
- : (document.activeElement as HTMLInputElement | null)
- active?.classList.remove("focus")
- const nextResult = active?.nextElementSibling as HTMLInputElement | null
- await displayPreview(nextResult)
- nextResult?.focus()
- currentHover = nextResult
+ if (secondResult) currentHover = secondResult
+ await displayPreview(secondResult)
}
}
}
@@ -276,13 +288,15 @@
return []
}
- return tags.map(tag => {
- if (tag.toLowerCase().includes(term.toLowerCase())) {
- return `<li><p class="match-tag">#${tag}</p></li>`
- } else {
- return `<li><p>#${tag}</p></li>`
- }
- }).slice(0, numTagResults)
+ return tags
+ .map((tag) => {
+ if (tag.toLowerCase().includes(term.toLowerCase())) {
+ return `<li><p class="match-tag">#${tag}</p></li>`
+ } else {
+ return `<li><p>#${tag}</p></li>`
+ }
+ })
+ .slice(0, numTagResults)
}
function resolveUrl(slug: FullSlug): URL {
@@ -295,40 +309,29 @@
itemTile.classList.add("result-card")
itemTile.id = slug
itemTile.href = resolveUrl(slug).toString()
- itemTile.innerHTML = `<h3>${title}</h3>${htmlTags}<p class="preview">${content}</p>`
+ itemTile.innerHTML = `<h3>${title}</h3>${htmlTags}${
+ enablePreview && window.innerWidth > 600 ? "" : `<p>${content}</p>`
+ }`
+ itemTile.addEventListener("click", (event) => {
+ if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) return
+ hideSearch()
+ })
+
+ const handler = (event: MouseEvent) => {
+ if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) return
+ hideSearch()
+ }
async function onMouseEnter(ev: MouseEvent) {
if (!ev.target) return
- currentHover?.classList.remove('focus')
- currentHover?.blur()
const target = ev.target as HTMLInputElement
await displayPreview(target)
- currentHover = target
- currentHover.classList.add("focus")
}
- async function onMouseLeave(ev: MouseEvent) {
- if (!ev.target) return
- const target = ev.target as HTMLElement
- target.classList.remove("focus")
- }
-
- const events = [
- ["mouseenter", onMouseEnter],
- ["mouseleave", onMouseLeave],
- [
- "click",
- (event: MouseEvent) => {
- if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) return
- hideSearch()
- },
- ],
- ] as const
-
- events.forEach(([event, handler]) => {
- itemTile.addEventListener(event, handler)
- window.addCleanup(() => itemTile.removeEventListener(event, handler))
- })
+ itemTile.addEventListener("mouseenter", onMouseEnter)
+ window.addCleanup(() => itemTile.removeEventListener("mouseenter", onMouseEnter))
+ itemTile.addEventListener("click", handler)
+ window.addCleanup(() => itemTile.removeEventListener("click", handler))
return itemTile
}
@@ -382,33 +385,56 @@
async function displayPreview(el: HTMLElement | null) {
if (!searchLayout || !enablePreview || !el || !preview) return
const slug = el.id as FullSlug
- el.classList.add("focus")
+ const innerDiv = await fetchContent(slug).then((contents) =>
+ contents.flatMap((el) => [...highlightHTML(currentSearchTerm, el as HTMLElement).children]),
+ )
previewInner = document.createElement("div")
previewInner.classList.add("preview-inner")
- const innerDiv = await fetchContent(slug).then((contents) =>
- contents.map((el) => highlightHTML(currentSearchTerm, el.innerHTML)),
- )
previewInner.append(...innerDiv)
preview.replaceChildren(previewInner)
// scroll to longest
- const highlights = [...preview.querySelectorAll(".highlight")].sort((a, b) => b.innerHTML.length - a.innerHTML.length)
- highlights[0]?.scrollIntoView()
+ const highlights = [...preview.querySelectorAll(".highlight")].sort(
+ (a, b) => b.innerHTML.length - a.innerHTML.length,
+ )
+ highlights[0]?.scrollIntoView({ block: "start" })
}
async function onType(e: HTMLElementEventMap["input"]) {
if (!searchLayout || !index) return
currentSearchTerm = (e.target as HTMLInputElement).value
- searchLayout.style.visibility = currentSearchTerm === "" ? "hidden" : "visible"
+ searchLayout.classList.toggle("display-results", currentSearchTerm !== "")
searchType = currentSearchTerm.startsWith("#") ? "tags" : "basic"
let searchResults: FlexSearch.SimpleDocumentSearchResultSetUnit[]
if (searchType === "tags") {
- searchResults = await index.searchAsync({
- query: currentSearchTerm.substring(1),
- limit: numSearchResults,
- index: ["tags"],
- })
+ currentSearchTerm = currentSearchTerm.substring(1).trim()
+ const separatorIndex = currentSearchTerm.indexOf(" ")
+ if (separatorIndex != -1) {
+ // search by title and content index and then filter by tag (implemented in flexsearch)
+ const tag = currentSearchTerm.substring(0, separatorIndex)
+ const query = currentSearchTerm.substring(separatorIndex + 1).trim()
+ searchResults = await index.searchAsync({
+ query: query,
+ // return at least 10000 documents, so it is enough to filter them by tag (implemented in flexsearch)
+ limit: Math.max(numSearchResults, 10000),
+ index: ["title", "content"],
+ tag: tag,
+ })
+ for (let searchResult of searchResults) {
+ searchResult.result = searchResult.result.slice(0, numSearchResults)
+ }
+ // set search type to basic and remove tag from term for proper highlightning and scroll
+ searchType = "basic"
+ currentSearchTerm = query
+ } else {
+ // default search by tags index
+ searchResults = await index.searchAsync({
+ query: currentSearchTerm,
+ limit: numSearchResults,
+ index: ["tags"],
+ })
+ }
} else if (searchType === "basic") {
searchResults = await index.searchAsync({
query: currentSearchTerm,
@@ -434,13 +460,13 @@
document.addEventListener("keydown", shortcutHandler)
window.addCleanup(() => document.removeEventListener("keydown", shortcutHandler))
- searchIcon?.addEventListener("click", () => showSearch("basic"))
- window.addCleanup(() => searchIcon?.removeEventListener("click", () => showSearch("basic")))
+ searchButton?.addEventListener("click", () => showSearch("basic"))
+ window.addCleanup(() => searchButton?.removeEventListener("click", () => showSearch("basic")))
searchBar?.addEventListener("input", onType)
window.addCleanup(() => searchBar?.removeEventListener("input", onType))
- index ??= await fillDocument(data)
registerEscapeHandler(container, hideSearch)
+ await fillDocument(data)
})
/**
@@ -449,37 +475,19 @@
* @param data data to fill index with
*/
async function fillDocument(data: { [key: FullSlug]: ContentDetails }) {
- const index = new FlexSearch.Document<Item>({
- charset: "latin:extra",
- encode: encoder,
- document: {
- id: "id",
- index: [
- {
- field: "title",
- tokenize: "forward",
- },
- {
- field: "content",
- tokenize: "forward",
- },
- {
- field: "tags",
- tokenize: "forward",
- },
- ],
- },
- })
let id = 0
+ const promises: Array<Promise<unknown>> = []
for (const [slug, fileData] of Object.entries<ContentDetails>(data)) {
- await index.addAsync(id++, {
- id,
- slug: slug as FullSlug,
- title: fileData.title,
- content: fileData.content,
- tags: fileData.tags,
- })
+ promises.push(
+ index.addAsync(id++, {
+ id,
+ slug: slug as FullSlug,
+ title: fileData.title,
+ content: fileData.content,
+ tags: fileData.tags,
+ }),
+ )
}
- return index
+ return await Promise.all(promises)
}
--
Gitblit v1.10.0