Merge commit '76f2664277e07a7d1b011fac236840c6e8e69fdd' into v4
This commit is contained in:
@ -20,4 +20,13 @@ document.addEventListener("nav", () => {
|
||||
if (currentTheme === "dark") {
|
||||
toggleSwitch.checked = true
|
||||
}
|
||||
|
||||
// Listen for changes in prefers-color-scheme
|
||||
const colorSchemeMediaQuery = window.matchMedia("(prefers-color-scheme: dark)")
|
||||
colorSchemeMediaQuery.addEventListener("change", (e) => {
|
||||
const newTheme = e.matches ? "dark" : "light"
|
||||
document.documentElement.setAttribute("saved-theme", newTheme)
|
||||
localStorage.setItem("theme", newTheme)
|
||||
toggleSwitch.checked = e.matches
|
||||
})
|
||||
})
|
||||
|
164
quartz/components/scripts/explorer.inline.ts
Normal file
164
quartz/components/scripts/explorer.inline.ts
Normal file
@ -0,0 +1,164 @@
|
||||
import { FolderState } from "../ExplorerNode"
|
||||
|
||||
// Current state of folders
|
||||
let explorerState: FolderState[]
|
||||
|
||||
const observer = new IntersectionObserver((entries) => {
|
||||
// If last element is observed, remove gradient of "overflow" class so element is visible
|
||||
const explorer = document.getElementById("explorer-ul")
|
||||
for (const entry of entries) {
|
||||
if (entry.isIntersecting) {
|
||||
explorer?.classList.add("no-background")
|
||||
} else {
|
||||
explorer?.classList.remove("no-background")
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
function toggleExplorer(this: HTMLElement) {
|
||||
// Toggle collapsed state of entire explorer
|
||||
this.classList.toggle("collapsed")
|
||||
const content = this.nextElementSibling as HTMLElement
|
||||
content.classList.toggle("collapsed")
|
||||
content.style.maxHeight = content.style.maxHeight === "0px" ? content.scrollHeight + "px" : "0px"
|
||||
}
|
||||
|
||||
function toggleFolder(evt: MouseEvent) {
|
||||
evt.stopPropagation()
|
||||
|
||||
// Element that was clicked
|
||||
const target = evt.target as HTMLElement
|
||||
|
||||
// Check if target was svg icon or button
|
||||
const isSvg = target.nodeName === "svg"
|
||||
|
||||
// corresponding <ul> element relative to clicked button/folder
|
||||
let childFolderContainer: HTMLElement
|
||||
|
||||
// <li> element of folder (stores folder-path dataset)
|
||||
let currentFolderParent: HTMLElement
|
||||
|
||||
// Get correct relative container and toggle collapsed class
|
||||
if (isSvg) {
|
||||
childFolderContainer = target.parentElement?.nextSibling as HTMLElement
|
||||
currentFolderParent = target.nextElementSibling as HTMLElement
|
||||
|
||||
childFolderContainer.classList.toggle("open")
|
||||
} else {
|
||||
childFolderContainer = target.parentElement?.parentElement?.nextElementSibling as HTMLElement
|
||||
currentFolderParent = target.parentElement as HTMLElement
|
||||
|
||||
childFolderContainer.classList.toggle("open")
|
||||
}
|
||||
if (!childFolderContainer) return
|
||||
|
||||
// Collapse folder container
|
||||
const isCollapsed = childFolderContainer.classList.contains("open")
|
||||
setFolderState(childFolderContainer, !isCollapsed)
|
||||
|
||||
// Save folder state to localStorage
|
||||
const clickFolderPath = currentFolderParent.dataset.folderpath as string
|
||||
|
||||
// Remove leading "/"
|
||||
const fullFolderPath = clickFolderPath.substring(1)
|
||||
toggleCollapsedByPath(explorerState, fullFolderPath)
|
||||
|
||||
const stringifiedFileTree = JSON.stringify(explorerState)
|
||||
localStorage.setItem("fileTree", stringifiedFileTree)
|
||||
}
|
||||
|
||||
function setupExplorer() {
|
||||
// Set click handler for collapsing entire explorer
|
||||
const explorer = document.getElementById("explorer")
|
||||
|
||||
// Get folder state from local storage
|
||||
const storageTree = localStorage.getItem("fileTree")
|
||||
|
||||
// Convert to bool
|
||||
const useSavedFolderState = explorer?.dataset.savestate === "true"
|
||||
|
||||
if (explorer) {
|
||||
// Get config
|
||||
const collapseBehavior = explorer.dataset.behavior
|
||||
|
||||
// Add click handlers for all folders (click handler on folder "label")
|
||||
if (collapseBehavior === "collapse") {
|
||||
Array.prototype.forEach.call(
|
||||
document.getElementsByClassName("folder-button"),
|
||||
function (item) {
|
||||
item.removeEventListener("click", toggleFolder)
|
||||
item.addEventListener("click", toggleFolder)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// Add click handler to main explorer
|
||||
explorer.removeEventListener("click", toggleExplorer)
|
||||
explorer.addEventListener("click", toggleExplorer)
|
||||
}
|
||||
|
||||
// Set up click handlers for each folder (click handler on folder "icon")
|
||||
Array.prototype.forEach.call(document.getElementsByClassName("folder-icon"), function (item) {
|
||||
item.removeEventListener("click", toggleFolder)
|
||||
item.addEventListener("click", toggleFolder)
|
||||
})
|
||||
|
||||
if (storageTree && useSavedFolderState) {
|
||||
// Get state from localStorage and set folder state
|
||||
explorerState = JSON.parse(storageTree)
|
||||
explorerState.map((folderUl) => {
|
||||
// grab <li> element for matching folder path
|
||||
const folderLi = document.querySelector(
|
||||
`[data-folderpath='/${folderUl.path}']`,
|
||||
) as HTMLElement
|
||||
|
||||
// Get corresponding content <ul> tag and set state
|
||||
if (folderLi) {
|
||||
const folderUL = folderLi.parentElement?.nextElementSibling
|
||||
if (folderUL) {
|
||||
setFolderState(folderUL as HTMLElement, folderUl.collapsed)
|
||||
}
|
||||
}
|
||||
})
|
||||
} else {
|
||||
// If tree is not in localStorage or config is disabled, use tree passed from Explorer as dataset
|
||||
explorerState = JSON.parse(explorer?.dataset.tree as string)
|
||||
}
|
||||
}
|
||||
|
||||
window.addEventListener("resize", setupExplorer)
|
||||
document.addEventListener("nav", () => {
|
||||
setupExplorer()
|
||||
|
||||
const explorerContent = document.getElementById("explorer-ul")
|
||||
// select pseudo element at end of list
|
||||
const lastItem = document.getElementById("explorer-end")
|
||||
|
||||
observer.disconnect()
|
||||
observer.observe(lastItem as Element)
|
||||
})
|
||||
|
||||
/**
|
||||
* Toggles the state of a given folder
|
||||
* @param folderElement <div class="folder-outer"> Element of folder (parent)
|
||||
* @param collapsed if folder should be set to collapsed or not
|
||||
*/
|
||||
function setFolderState(folderElement: HTMLElement, collapsed: boolean) {
|
||||
if (collapsed) {
|
||||
folderElement?.classList.remove("open")
|
||||
} else {
|
||||
folderElement?.classList.add("open")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Toggles visibility of a folder
|
||||
* @param array array of FolderState (`fileTree`, either get from local storage or data attribute)
|
||||
* @param path path to folder (e.g. 'advanced/more/more2')
|
||||
*/
|
||||
function toggleCollapsedByPath(array: FolderState[], path: string) {
|
||||
const entry = array.find((item) => item.path === path)
|
||||
if (entry) {
|
||||
entry.collapsed = !entry.collapsed
|
||||
}
|
||||
}
|
@ -42,19 +42,38 @@ async function renderGraph(container: string, fullSlug: FullSlug) {
|
||||
linkDistance,
|
||||
fontSize,
|
||||
opacityScale,
|
||||
removeTags,
|
||||
showTags,
|
||||
} = JSON.parse(graph.dataset["cfg"]!)
|
||||
|
||||
const data = await fetchData
|
||||
|
||||
const links: LinkData[] = []
|
||||
const tags: SimpleSlug[] = []
|
||||
|
||||
const validLinks = new Set(Object.keys(data).map((slug) => simplifySlug(slug as FullSlug)))
|
||||
|
||||
for (const [src, details] of Object.entries<ContentDetails>(data)) {
|
||||
const source = simplifySlug(src as FullSlug)
|
||||
const outgoing = details.links ?? []
|
||||
|
||||
for (const dest of outgoing) {
|
||||
if (dest in data) {
|
||||
if (validLinks.has(dest)) {
|
||||
links.push({ source, target: dest })
|
||||
}
|
||||
}
|
||||
|
||||
if (showTags) {
|
||||
const localTags = details.tags
|
||||
.filter((tag) => !removeTags.includes(tag))
|
||||
.map((tag) => simplifySlug(("tags/" + tag) as FullSlug))
|
||||
|
||||
tags.push(...localTags.filter((tag) => !tags.includes(tag)))
|
||||
|
||||
for (const tag of localTags) {
|
||||
links.push({ source, target: tag })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const neighbourhood = new Set<SimpleSlug>()
|
||||
@ -75,14 +94,18 @@ async function renderGraph(container: string, fullSlug: FullSlug) {
|
||||
}
|
||||
} else {
|
||||
Object.keys(data).forEach((id) => neighbourhood.add(simplifySlug(id as FullSlug)))
|
||||
if (showTags) tags.forEach((tag) => neighbourhood.add(tag))
|
||||
}
|
||||
|
||||
const graphData: { nodes: NodeData[]; links: LinkData[] } = {
|
||||
nodes: [...neighbourhood].map((url) => ({
|
||||
id: url,
|
||||
text: data[url]?.title ?? url,
|
||||
tags: data[url]?.tags ?? [],
|
||||
})),
|
||||
nodes: [...neighbourhood].map((url) => {
|
||||
const text = url.startsWith("tags/") ? "#" + url.substring(5) : data[url]?.title ?? url
|
||||
return {
|
||||
id: url,
|
||||
text: text,
|
||||
tags: data[url]?.tags ?? [],
|
||||
}
|
||||
}),
|
||||
links: links.filter((l) => neighbourhood.has(l.source) && neighbourhood.has(l.target)),
|
||||
}
|
||||
|
||||
@ -126,7 +149,7 @@ async function renderGraph(container: string, fullSlug: FullSlug) {
|
||||
const isCurrent = d.id === slug
|
||||
if (isCurrent) {
|
||||
return "var(--secondary)"
|
||||
} else if (visited.has(d.id)) {
|
||||
} else if (visited.has(d.id) || d.id.startsWith("tags/")) {
|
||||
return "var(--tertiary)"
|
||||
} else {
|
||||
return "var(--gray)"
|
||||
@ -230,9 +253,7 @@ async function renderGraph(container: string, fullSlug: FullSlug) {
|
||||
.attr("dx", 0)
|
||||
.attr("dy", (d) => -nodeRadius(d) + "px")
|
||||
.attr("text-anchor", "middle")
|
||||
.text(
|
||||
(d) => data[d.id]?.title || (d.id.charAt(1).toUpperCase() + d.id.slice(2)).replace("-", " "),
|
||||
)
|
||||
.text((d) => d.text)
|
||||
.style("opacity", (opacityScale - 1) / 3.75)
|
||||
.style("pointer-events", "none")
|
||||
.style("font-size", fontSize + "em")
|
||||
|
@ -28,8 +28,11 @@ async function mouseEnterHandler(
|
||||
})
|
||||
}
|
||||
|
||||
const hasAlreadyBeenFetched = () =>
|
||||
[...link.children].some((child) => child.classList.contains("popover"))
|
||||
|
||||
// dont refetch if there's already a popover
|
||||
if ([...link.children].some((child) => child.classList.contains("popover"))) {
|
||||
if (hasAlreadyBeenFetched()) {
|
||||
return setPosition(link.lastChild as HTMLElement)
|
||||
}
|
||||
|
||||
@ -49,6 +52,11 @@ async function mouseEnterHandler(
|
||||
console.error(err)
|
||||
})
|
||||
|
||||
// bailout if another popover exists
|
||||
if (hasAlreadyBeenFetched()) {
|
||||
return
|
||||
}
|
||||
|
||||
if (!contents) return
|
||||
const html = p.parseFromString(contents, "text/html")
|
||||
normalizeRelativeURLs(html, targetUrl)
|
||||
|
@ -1,4 +1,4 @@
|
||||
import { Document } from "flexsearch"
|
||||
import { Document, SimpleDocumentSearchResultSetUnit } from "flexsearch"
|
||||
import { ContentDetails } from "../../plugins/emitters/contentIndex"
|
||||
import { registerEscapeHandler, removeAllChildren } from "./util"
|
||||
import { FullSlug, resolveRelative } from "../../util/path"
|
||||
@ -8,12 +8,20 @@ interface Item {
|
||||
slug: FullSlug
|
||||
title: string
|
||||
content: string
|
||||
tags: string[]
|
||||
}
|
||||
|
||||
let index: Document<Item> | undefined = undefined
|
||||
|
||||
// Can be expanded with things like "term" in the future
|
||||
type SearchType = "basic" | "tags"
|
||||
|
||||
// Current searchType
|
||||
let searchType: SearchType = "basic"
|
||||
|
||||
const contextWindowWords = 30
|
||||
const numSearchResults = 5
|
||||
const numTagResults = 3
|
||||
function highlight(searchTerm: string, text: string, trim?: boolean) {
|
||||
// try to highlight longest tokens first
|
||||
const tokenizedTerms = searchTerm
|
||||
@ -74,6 +82,7 @@ document.addEventListener("nav", async (e: unknown) => {
|
||||
const searchIcon = document.getElementById("search-icon")
|
||||
const searchBar = document.getElementById("search-bar") as HTMLInputElement | null
|
||||
const results = document.getElementById("results-container")
|
||||
const resultCards = document.getElementsByClassName("result-card")
|
||||
const idDataMap = Object.keys(data) as FullSlug[]
|
||||
|
||||
function hideSearch() {
|
||||
@ -87,9 +96,12 @@ document.addEventListener("nav", async (e: unknown) => {
|
||||
if (results) {
|
||||
removeAllChildren(results)
|
||||
}
|
||||
|
||||
searchType = "basic" // reset search type after closing
|
||||
}
|
||||
|
||||
function showSearch() {
|
||||
function showSearch(searchTypeNew: SearchType) {
|
||||
searchType = searchTypeNew
|
||||
if (sidebar) {
|
||||
sidebar.style.zIndex = "1"
|
||||
}
|
||||
@ -98,36 +110,123 @@ document.addEventListener("nav", async (e: unknown) => {
|
||||
}
|
||||
|
||||
function shortcutHandler(e: HTMLElementEventMap["keydown"]) {
|
||||
if (e.key === "k" && (e.ctrlKey || e.metaKey)) {
|
||||
if (e.key === "k" && (e.ctrlKey || e.metaKey) && !e.shiftKey) {
|
||||
e.preventDefault()
|
||||
const searchBarOpen = container?.classList.contains("active")
|
||||
searchBarOpen ? hideSearch() : showSearch()
|
||||
searchBarOpen ? hideSearch() : showSearch("basic")
|
||||
} else if (e.shiftKey && (e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "k") {
|
||||
// Hotkey to open tag search
|
||||
e.preventDefault()
|
||||
const searchBarOpen = container?.classList.contains("active")
|
||||
searchBarOpen ? hideSearch() : showSearch("tags")
|
||||
|
||||
// add "#" prefix for tag search
|
||||
if (searchBar) searchBar.value = "#"
|
||||
} else if (e.key === "Enter") {
|
||||
const anchor = document.getElementsByClassName("result-card")[0] as HTMLInputElement | null
|
||||
if (anchor) {
|
||||
anchor.click()
|
||||
// If result has focus, navigate to that one, otherwise pick first result
|
||||
if (results?.contains(document.activeElement)) {
|
||||
const active = document.activeElement as HTMLInputElement
|
||||
active.click()
|
||||
} else {
|
||||
const anchor = document.getElementsByClassName("result-card")[0] as HTMLInputElement | null
|
||||
anchor?.click()
|
||||
}
|
||||
} else if (e.key === "ArrowDown") {
|
||||
e.preventDefault()
|
||||
// When first pressing ArrowDown, results wont contain the active element, so focus first element
|
||||
if (!results?.contains(document.activeElement)) {
|
||||
const firstResult = resultCards[0] as HTMLInputElement | null
|
||||
firstResult?.focus()
|
||||
} else {
|
||||
// If an element in results-container already has focus, focus next one
|
||||
const nextResult = document.activeElement?.nextElementSibling as HTMLInputElement | null
|
||||
nextResult?.focus()
|
||||
}
|
||||
} else if (e.key === "ArrowUp") {
|
||||
e.preventDefault()
|
||||
if (results?.contains(document.activeElement)) {
|
||||
// If an element in results-container already has focus, focus previous one
|
||||
const prevResult = document.activeElement?.previousElementSibling as HTMLInputElement | null
|
||||
prevResult?.focus()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function trimContent(content: string) {
|
||||
// works without escaping html like in `description.ts`
|
||||
const sentences = content.replace(/\s+/g, " ").split(".")
|
||||
let finalDesc = ""
|
||||
let sentenceIdx = 0
|
||||
|
||||
// Roughly estimate characters by (words * 5). Matches description length in `description.ts`.
|
||||
const len = contextWindowWords * 5
|
||||
while (finalDesc.length < len) {
|
||||
const sentence = sentences[sentenceIdx]
|
||||
if (!sentence) break
|
||||
finalDesc += sentence + "."
|
||||
sentenceIdx++
|
||||
}
|
||||
|
||||
// If more content would be available, indicate it by finishing with "..."
|
||||
if (finalDesc.length < content.length) {
|
||||
finalDesc += ".."
|
||||
}
|
||||
|
||||
return finalDesc
|
||||
}
|
||||
|
||||
const formatForDisplay = (term: string, id: number) => {
|
||||
const slug = idDataMap[id]
|
||||
return {
|
||||
id,
|
||||
slug,
|
||||
title: highlight(term, data[slug].title ?? ""),
|
||||
content: highlight(term, data[slug].content ?? "", true),
|
||||
title: searchType === "tags" ? data[slug].title : highlight(term, data[slug].title ?? ""),
|
||||
// if searchType is tag, display context from start of file and trim, otherwise use regular highlight
|
||||
content:
|
||||
searchType === "tags"
|
||||
? trimContent(data[slug].content)
|
||||
: highlight(term, data[slug].content ?? "", true),
|
||||
tags: highlightTags(term, data[slug].tags),
|
||||
}
|
||||
}
|
||||
|
||||
const resultToHTML = ({ slug, title, content }: Item) => {
|
||||
function highlightTags(term: string, tags: string[]) {
|
||||
if (tags && searchType === "tags") {
|
||||
// Find matching tags
|
||||
const termLower = term.toLowerCase()
|
||||
let matching = tags.filter((str) => str.includes(termLower))
|
||||
|
||||
// Substract matching from original tags, then push difference
|
||||
if (matching.length > 0) {
|
||||
let difference = tags.filter((x) => !matching.includes(x))
|
||||
|
||||
// Convert to html (cant be done later as matches/term dont get passed to `resultToHTML`)
|
||||
matching = matching.map((tag) => `<li><p class="match-tag">#${tag}</p></li>`)
|
||||
difference = difference.map((tag) => `<li><p>#${tag}</p></li>`)
|
||||
matching.push(...difference)
|
||||
}
|
||||
|
||||
// Only allow max of `numTagResults` in preview
|
||||
if (tags.length > numTagResults) {
|
||||
matching.splice(numTagResults)
|
||||
}
|
||||
|
||||
return matching
|
||||
} else {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
const resultToHTML = ({ slug, title, content, tags }: Item) => {
|
||||
const htmlTags = tags.length > 0 ? `<ul>${tags.join("")}</ul>` : ``
|
||||
const button = document.createElement("button")
|
||||
button.classList.add("result-card")
|
||||
button.id = slug
|
||||
button.innerHTML = `<h3>${title}</h3><p>${content}</p>`
|
||||
button.innerHTML = `<h3>${title}</h3>${htmlTags}<p>${content}</p>`
|
||||
button.addEventListener("click", () => {
|
||||
const targ = resolveRelative(currentSlug, slug)
|
||||
window.spaNavigate(new URL(targ, window.location.toString()))
|
||||
hideSearch()
|
||||
})
|
||||
return button
|
||||
}
|
||||
@ -147,15 +246,45 @@ document.addEventListener("nav", async (e: unknown) => {
|
||||
}
|
||||
|
||||
async function onType(e: HTMLElementEventMap["input"]) {
|
||||
const term = (e.target as HTMLInputElement).value
|
||||
const searchResults = (await index?.searchAsync(term, numSearchResults)) ?? []
|
||||
let term = (e.target as HTMLInputElement).value
|
||||
let searchResults: SimpleDocumentSearchResultSetUnit[]
|
||||
|
||||
if (term.toLowerCase().startsWith("#")) {
|
||||
searchType = "tags"
|
||||
} else {
|
||||
searchType = "basic"
|
||||
}
|
||||
|
||||
switch (searchType) {
|
||||
case "tags": {
|
||||
term = term.substring(1)
|
||||
searchResults =
|
||||
(await index?.searchAsync({ query: term, limit: numSearchResults, index: ["tags"] })) ??
|
||||
[]
|
||||
break
|
||||
}
|
||||
case "basic":
|
||||
default: {
|
||||
searchResults =
|
||||
(await index?.searchAsync({
|
||||
query: term,
|
||||
limit: numSearchResults,
|
||||
index: ["title", "content"],
|
||||
})) ?? []
|
||||
}
|
||||
}
|
||||
|
||||
const getByField = (field: string): number[] => {
|
||||
const results = searchResults.filter((x) => x.field === field)
|
||||
return results.length === 0 ? [] : ([...results[0].result] as number[])
|
||||
}
|
||||
|
||||
// order titles ahead of content
|
||||
const allIds: Set<number> = new Set([...getByField("title"), ...getByField("content")])
|
||||
const allIds: Set<number> = new Set([
|
||||
...getByField("title"),
|
||||
...getByField("content"),
|
||||
...getByField("tags"),
|
||||
])
|
||||
const finalResults = [...allIds].map((id) => formatForDisplay(term, id))
|
||||
displayResults(finalResults)
|
||||
}
|
||||
@ -166,15 +295,14 @@ document.addEventListener("nav", async (e: unknown) => {
|
||||
|
||||
document.addEventListener("keydown", shortcutHandler)
|
||||
prevShortcutHandler = shortcutHandler
|
||||
searchIcon?.removeEventListener("click", showSearch)
|
||||
searchIcon?.addEventListener("click", showSearch)
|
||||
searchIcon?.removeEventListener("click", () => showSearch("basic"))
|
||||
searchIcon?.addEventListener("click", () => showSearch("basic"))
|
||||
searchBar?.removeEventListener("input", onType)
|
||||
searchBar?.addEventListener("input", onType)
|
||||
|
||||
// setup index if it hasn't been already
|
||||
if (!index) {
|
||||
index = new Document({
|
||||
cache: true,
|
||||
charset: "latin:extra",
|
||||
optimize: true,
|
||||
encode: encoder,
|
||||
@ -189,22 +317,36 @@ document.addEventListener("nav", async (e: unknown) => {
|
||||
field: "content",
|
||||
tokenize: "reverse",
|
||||
},
|
||||
{
|
||||
field: "tags",
|
||||
tokenize: "reverse",
|
||||
},
|
||||
],
|
||||
},
|
||||
})
|
||||
|
||||
let id = 0
|
||||
for (const [slug, fileData] of Object.entries<ContentDetails>(data)) {
|
||||
await index.addAsync(id, {
|
||||
id,
|
||||
slug: slug as FullSlug,
|
||||
title: fileData.title,
|
||||
content: fileData.content,
|
||||
})
|
||||
id++
|
||||
}
|
||||
fillDocument(index, data)
|
||||
}
|
||||
|
||||
// register handlers
|
||||
registerEscapeHandler(container, hideSearch)
|
||||
})
|
||||
|
||||
/**
|
||||
* Fills flexsearch document with data
|
||||
* @param index index to fill
|
||||
* @param data data to fill index with
|
||||
*/
|
||||
async function fillDocument(index: Document<Item, false>, data: any) {
|
||||
let id = 0
|
||||
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,
|
||||
})
|
||||
id++
|
||||
}
|
||||
}
|
||||
|
@ -1,5 +1,6 @@
|
||||
import micromorph from "micromorph"
|
||||
import { FullSlug, RelativeURL, getFullSlug } from "../../util/path"
|
||||
import { normalizeRelativeURLs } from "./popover.inline"
|
||||
|
||||
// adapted from `micromorph`
|
||||
// https://github.com/natemoo-re/micromorph
|
||||
@ -18,8 +19,15 @@ const isLocalUrl = (href: string) => {
|
||||
return false
|
||||
}
|
||||
|
||||
const isSamePage = (url: URL): boolean => {
|
||||
const sameOrigin = url.origin === window.location.origin
|
||||
const samePath = url.pathname === window.location.pathname
|
||||
return sameOrigin && samePath
|
||||
}
|
||||
|
||||
const getOpts = ({ target }: Event): { url: URL; scroll?: boolean } | undefined => {
|
||||
if (!isElement(target)) return
|
||||
if (target.attributes.getNamedItem("target")?.value === "_blank") return
|
||||
const a = target.closest("a")
|
||||
if (!a) return
|
||||
if ("routerIgnore" in a.dataset) return
|
||||
@ -45,6 +53,8 @@ async function navigate(url: URL, isBack: boolean = false) {
|
||||
if (!contents) return
|
||||
|
||||
const html = p.parseFromString(contents, "text/html")
|
||||
normalizeRelativeURLs(html, url)
|
||||
|
||||
let title = html.querySelector("title")?.textContent
|
||||
if (title) {
|
||||
document.title = title
|
||||
@ -92,8 +102,16 @@ function createRouter() {
|
||||
if (typeof window !== "undefined") {
|
||||
window.addEventListener("click", async (event) => {
|
||||
const { url } = getOpts(event) ?? {}
|
||||
if (!url) return
|
||||
// dont hijack behaviour, just let browser act normally
|
||||
if (!url || event.ctrlKey || event.metaKey) return
|
||||
event.preventDefault()
|
||||
|
||||
if (isSamePage(url) && url.hash) {
|
||||
const el = document.getElementById(decodeURIComponent(url.hash.substring(1)))
|
||||
el?.scrollIntoView()
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
navigate(url, false)
|
||||
} catch (e) {
|
||||
|
@ -24,8 +24,9 @@ function toggleToc(this: HTMLElement) {
|
||||
function setupToc() {
|
||||
const toc = document.getElementById("toc")
|
||||
if (toc) {
|
||||
const collapsed = toc.classList.contains("collapsed")
|
||||
const content = toc.nextElementSibling as HTMLElement
|
||||
content.style.maxHeight = content.scrollHeight + "px"
|
||||
content.style.maxHeight = collapsed ? "0px" : content.scrollHeight + "px"
|
||||
toc.removeEventListener("click", toggleToc)
|
||||
toc.addEventListener("click", toggleToc)
|
||||
}
|
||||
|
Reference in New Issue
Block a user