Emile Bangma
2024-03-04 bcb5b2df09cb8c8fc0736ec476b2486f9b4643be
quartz/components/scripts/popover.inline.ts
@@ -37,29 +37,55 @@
  targetUrl.hash = ""
  targetUrl.search = ""
  const contents = await fetch(`${targetUrl}`)
    .then((res) => res.text())
    .catch((err) => {
      console.error(err)
    })
  const response = await fetch(`${targetUrl}`).catch((err) => {
    console.error(err)
  })
  // bailout if another popover exists
  if (hasAlreadyBeenFetched()) {
    return
  }
  if (!contents) return
  const html = p.parseFromString(contents, "text/html")
  normalizeRelativeURLs(html, targetUrl)
  const elts = [...html.getElementsByClassName("popover-hint")]
  if (elts.length === 0) return
  if (!response) return
  const [contentType] = response.headers.get("Content-Type")!.split(";")
  const [contentTypeCategory, typeInfo] = contentType.split("/")
  const popoverElement = document.createElement("div")
  popoverElement.classList.add("popover")
  const popoverInner = document.createElement("div")
  popoverInner.classList.add("popover-inner")
  popoverElement.appendChild(popoverInner)
  elts.forEach((elt) => popoverInner.appendChild(elt))
  popoverInner.dataset.contentType = contentType ?? undefined
  switch (contentTypeCategory) {
    case "image":
      const img = document.createElement("img")
      img.src = targetUrl.toString()
      img.alt = targetUrl.pathname
      popoverInner.appendChild(img)
      break
    case "application":
      switch (typeInfo) {
        case "pdf":
          const pdf = document.createElement("iframe")
          pdf.src = targetUrl.toString()
          popoverInner.appendChild(pdf)
          break
        default:
          break
      }
      break
    default:
      const contents = await response.text()
      const html = p.parseFromString(contents, "text/html")
      normalizeRelativeURLs(html, targetUrl)
      const elts = [...html.getElementsByClassName("popover-hint")]
      if (elts.length === 0) return
      elts.forEach((elt) => popoverInner.appendChild(elt))
  }
  setPosition(popoverElement)
  link.appendChild(popoverElement)