Jacky Zhao
2023-08-21 bb93ac1c83fd8d13593f7f9688de02eba60de913
quartz/components/scripts/search.inline.ts
@@ -1,11 +1,11 @@
import { Document } from "flexsearch"
import { ContentDetails } from "../../plugins/emitters/contentIndex"
import { registerEscapeHandler, removeAllChildren } from "./util"
import { CanonicalSlug, getClientSlug, resolveRelative } from "../../path"
import { FullSlug, resolveRelative } from "../../util/path"
interface Item {
  id: number
  slug: CanonicalSlug
  slug: FullSlug
  title: string
  content: string
}
@@ -64,6 +64,7 @@
}
const encoder = (str: string) => str.toLowerCase().split(/([^a-z]|[^\x00-\x7F])/)
let prevShortcutHandler: ((e: HTMLElementEventMap["keydown"]) => void) | undefined = undefined
document.addEventListener("nav", async (e: unknown) => {
  const currentSlug = (e as CustomEventMap["nav"]).detail.url
@@ -73,7 +74,7 @@
  const searchIcon = document.getElementById("search-icon")
  const searchBar = document.getElementById("search-bar") as HTMLInputElement | null
  const results = document.getElementById("results-container")
  const idDataMap = Object.keys(data) as CanonicalSlug[]
  const idDataMap = Object.keys(data) as FullSlug[]
  function hideSearch() {
    container?.classList.remove("active")
@@ -126,7 +127,7 @@
    button.innerHTML = `<h3>${title}</h3><p>${content}</p>`
    button.addEventListener("click", () => {
      const targ = resolveRelative(currentSlug, slug)
      window.spaNavigate(new URL(targ, getClientSlug(window)))
      window.spaNavigate(new URL(targ, window.location.toString()))
    })
    return button
  }
@@ -148,7 +149,6 @@
  async function onType(e: HTMLElementEventMap["input"]) {
    const term = (e.target as HTMLInputElement).value
    const searchResults = (await index?.searchAsync(term, numSearchResults)) ?? []
    console.log(searchResults)
    const getByField = (field: string): number[] => {
      const results = searchResults.filter((x) => x.field === field)
      return results.length === 0 ? [] : ([...results[0].result] as number[])
@@ -160,8 +160,12 @@
    displayResults(finalResults)
  }
  document.removeEventListener("keydown", shortcutHandler)
  if (prevShortcutHandler) {
    document.removeEventListener("keydown", prevShortcutHandler)
  }
  document.addEventListener("keydown", shortcutHandler)
  prevShortcutHandler = shortcutHandler
  searchIcon?.removeEventListener("click", showSearch)
  searchIcon?.addEventListener("click", showSearch)
  searchBar?.removeEventListener("input", onType)
@@ -193,7 +197,7 @@
    for (const [slug, fileData] of Object.entries<ContentDetails>(data)) {
      await index.addAsync(id, {
        id,
        slug: slug as CanonicalSlug,
        slug: slug as FullSlug,
        title: fileData.title,
        content: fileData.content,
      })