Skip to content

Commit

Permalink
docs: update Quartz to 4.1.1 (#165)
Browse files Browse the repository at this point in the history
This version fix images issues.

Refs: #164
  • Loading branch information
JoffreyLGT authored Nov 21, 2023
1 parent 09bffaf commit d7b1229
Show file tree
Hide file tree
Showing 25 changed files with 319 additions and 91 deletions.
5 changes: 3 additions & 2 deletions docs/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 1 addition & 2 deletions docs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"name": "reagan-docs",
"description": "Documentation of Reagan: the e-commerce product classification platform.",
"private": true,
"version": "4.1.0",
"version": "4.1.1",
"type": "module",
"author": "Joffrey Lagut <joffreylagut.work@outlook.fr>",
"license": "GPL-V3",
Expand All @@ -24,7 +24,6 @@
"node": ">=18.14"
},
"keywords": [
"blog"
],
"bin": {
"quartz": "./quartz/bootstrap-cli.mjs"
Expand Down
5 changes: 5 additions & 0 deletions docs/quartz/cli/args.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,11 @@ export const SyncArgv = {
default: true,
describe: "create a git commit for your unsaved changes",
},
message: {
string: true,
alias: ["m"],
describe: "option to override the default Quartz commit message",
},
push: {
boolean: true,
default: true,
Expand Down
3 changes: 2 additions & 1 deletion docs/quartz/cli/handlers.js
Original file line number Diff line number Diff line change
Expand Up @@ -483,8 +483,9 @@ export async function handleSync(argv) {
dateStyle: "medium",
timeStyle: "short",
})
const commitMessage = argv.message ?? `Quartz sync: ${currentTimestamp}`
spawnSync("git", ["add", "."], { stdio: "inherit" })
spawnSync("git", ["commit", "-m", `Quartz sync: ${currentTimestamp}`], { stdio: "inherit" })
spawnSync("git", ["commit", "-m", commitMessage], { stdio: "inherit" })

if (contentStat.isSymbolicLink()) {
// put symlink back
Expand Down
66 changes: 36 additions & 30 deletions docs/quartz/components/Breadcrumbs.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,18 @@ interface BreadcrumbOptions {
* Wether to display breadcrumbs on root `index.md`
*/
hideOnRoot: boolean
/**
* Wether to display the current page in the breadcrumbs.
*/
showCurrentPage: boolean
}

const defaultOptions: BreadcrumbOptions = {
spacerSymbol: ">",
spacerSymbol: "",
rootName: "Home",
resolveFrontmatterTitle: false,
resolveFrontmatterTitle: true,
hideOnRoot: true,
showCurrentPage: true,
}

function formatCrumb(displayName: string, baseSlug: FullSlug, currentSlug: SimpleSlug): CrumbData {
Expand All @@ -41,25 +46,13 @@ function formatCrumb(displayName: string, baseSlug: FullSlug, currentSlug: Simpl
}
}

// given a folderName (e.g. "features"), search for the corresponding `index.md` file
function findCurrentFile(allFiles: QuartzPluginData[], folderName: string) {
return allFiles.find((file) => {
if (file.slug?.endsWith("index")) {
const folderParts = file.filePath?.split("/")
if (folderParts) {
const name = folderParts[folderParts?.length - 2]
if (name === folderName) {
return true
}
}
}
})
}

export default ((opts?: Partial<BreadcrumbOptions>) => {
// Merge options with defaults
const options: BreadcrumbOptions = { ...defaultOptions, ...opts }

// computed index of folder name to its associated file data
let folderIndex: Map<string, QuartzPluginData> | undefined

function Breadcrumbs({ fileData, allFiles, displayClass }: QuartzComponentProps) {
// Hide crumbs on root if enabled
if (options.hideOnRoot && fileData.slug === "index") {
Expand All @@ -70,36 +63,49 @@ export default ((opts?: Partial<BreadcrumbOptions>) => {
const firstEntry = formatCrumb(options.rootName, fileData.slug!, "/" as SimpleSlug)
const crumbs: CrumbData[] = [firstEntry]

if (!folderIndex && options.resolveFrontmatterTitle) {
folderIndex = new Map()
// construct the index for the first time
for (const file of allFiles) {
if (file.slug?.endsWith("index")) {
const folderParts = file.filePath?.split("/")
if (folderParts) {
const folderName = folderParts[folderParts?.length - 2]
folderIndex.set(folderName, file)
}
}
}
}

// Split slug into hierarchy/parts
const slugParts = fileData.slug?.split("/")
if (slugParts) {
// full path until current part
let currentPath = ""
for (let i = 0; i < slugParts.length - 1; i++) {
let currentTitle = slugParts[i]
let curPathSegment = slugParts[i]

// TODO: performance optimizations/memoizing
// Try to resolve frontmatter folder title
if (options?.resolveFrontmatterTitle) {
// try to find file for current path
const currentFile = findCurrentFile(allFiles, currentTitle)
if (currentFile) {
currentTitle = currentFile.frontmatter!.title
}
const currentFile = folderIndex?.get(curPathSegment)
if (currentFile) {
curPathSegment = currentFile.frontmatter!.title
}

// Add current slug to full path
currentPath += slugParts[i] + "/"

// Format and add current crumb
const crumb = formatCrumb(currentTitle, fileData.slug!, currentPath as SimpleSlug)
const crumb = formatCrumb(curPathSegment, fileData.slug!, currentPath as SimpleSlug)
crumbs.push(crumb)
}

// Add current file to crumb (can directly use frontmatter title)
crumbs.push({
displayName: fileData.frontmatter!.title,
path: "",
})
if (options.showCurrentPage) {
crumbs.push({
displayName: fileData.frontmatter!.title,
path: "",
})
}
}
return (
<nav class={`breadcrumb-container ${displayClass ?? ""}`} aria-label="breadcrumbs">
Expand Down
2 changes: 1 addition & 1 deletion docs/quartz/components/Footer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export default ((opts?: Options) => {
<footer class={`${displayClass ?? ""}`}>
<hr />
<p>
Documentation built with <a href="https://quartz.jzhao.xyz/">Quartz v{version}</a>, © {year}
Created with <a href="https://quartz.jzhao.xyz/">Quartz v{version}</a>, © {year}
</p>
<ul>
{Object.entries(links).map(([text, link]) => (
Expand Down
4 changes: 2 additions & 2 deletions docs/quartz/components/TableOfContents.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ function TableOfContents({ fileData, displayClass }: QuartzComponentProps) {

return (
<div class={`toc ${displayClass ?? ""}`}>
<button type="button" id="toc">
<button type="button" id="toc" class={fileData.collapseToc ? "collapsed" : ""}>
<h3>Table of Contents</h3>
<svg
xmlns="http://www.w3.org/2000/svg"
Expand Down Expand Up @@ -60,7 +60,7 @@ function LegacyTableOfContents({ fileData }: QuartzComponentProps) {
}

return (
<details id="toc" open>
<details id="toc" open={!fileData.collapseToc}>
<summary>
<h3>Table of Contents</h3>
</summary>
Expand Down
2 changes: 1 addition & 1 deletion docs/quartz/components/pages/TagContent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ function TagContent(props: QuartzComponentProps) {
return (
<div>
<h2>
<a class="internal tag-link" href={`./${tag}`}>
<a class="internal tag-link" href={`../tags/${tag}`}>
#{tag}
</a>
</h2>
Expand Down
81 changes: 70 additions & 11 deletions docs/quartz/components/renderPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import BodyConstructor from "./Body"
import { JSResourceToScriptElement, StaticResources } from "../util/resources"
import { FullSlug, RelativeURL, joinSegments } from "../util/path"
import { visit } from "unist-util-visit"
import { Root, Element } from "hast"
import { Root, Element, ElementContent } from "hast"

interface RenderComponents {
head: QuartzComponent
Expand Down Expand Up @@ -61,22 +61,81 @@ export function renderPage(
const classNames = (node.properties?.className ?? []) as string[]
if (classNames.includes("transclude")) {
const inner = node.children[0] as Element
const blockSlug = inner.properties?.["data-slug"] as FullSlug
const blockRef = node.properties!.dataBlock as string
const transcludeTarget = inner.properties?.["data-slug"] as FullSlug

// TODO: avoid this expensive find operation and construct an index ahead of time
let blockNode = componentData.allFiles.find((f) => f.slug === blockSlug)?.blocks?.[blockRef]
if (blockNode) {
if (blockNode.tagName === "li") {
blockNode = {
type: "element",
tagName: "ul",
children: [blockNode],
const page = componentData.allFiles.find((f) => f.slug === transcludeTarget)
if (!page) {
return
}

let blockRef = node.properties?.dataBlock as string | undefined
if (blockRef?.startsWith("^")) {
// block transclude
blockRef = blockRef.slice(1)
let blockNode = page.blocks?.[blockRef]
if (blockNode) {
if (blockNode.tagName === "li") {
blockNode = {
type: "element",
tagName: "ul",
children: [blockNode],
}
}

node.children = [
blockNode,
{
type: "element",
tagName: "a",
properties: { href: inner.properties?.href, class: ["internal"] },
children: [{ type: "text", value: `Link to original` }],
},
]
}
} else if (blockRef?.startsWith("#") && page.htmlAst) {
// header transclude
blockRef = blockRef.slice(1)
let startIdx = undefined
let endIdx = undefined
for (const [i, el] of page.htmlAst.children.entries()) {
if (el.type === "element" && el.tagName.match(/h[1-6]/)) {
if (endIdx) {
break
}

if (startIdx !== undefined) {
endIdx = i
} else if (el.properties?.id === blockRef) {
startIdx = i
}
}
}

if (startIdx === undefined) {
return
}

node.children = [
...(page.htmlAst.children.slice(startIdx, endIdx) as ElementContent[]),
{
type: "element",
tagName: "a",
properties: { href: inner.properties?.href, class: ["internal"] },
children: [{ type: "text", value: `Link to original` }],
},
]
} else if (page.htmlAst) {
// page transclude
node.children = [
blockNode,
{
type: "element",
tagName: "h1",
children: [
{ type: "text", value: page.frontmatter?.title ?? `Transclude of ${page.slug}` },
],
},
...(page.htmlAst.children as ElementContent[]),
{
type: "element",
tagName: "a",
Expand Down
13 changes: 7 additions & 6 deletions docs/quartz/components/scripts/explorer.inline.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,22 +120,23 @@ function setupExplorer() {
}
}
})
} else {
} else if (explorer?.dataset.tree) {
// 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)
explorerState = JSON.parse(explorer.dataset.tree)
}
}

window.addEventListener("resize", setupExplorer)
document.addEventListener("nav", () => {
setupExplorer()

const explorerContent = document.getElementById("explorer-ul")
observer.disconnect()

// select pseudo element at end of list
const lastItem = document.getElementById("explorer-end")

observer.disconnect()
observer.observe(lastItem as Element)
if (lastItem) {
observer.observe(lastItem)
}
})

/**
Expand Down
23 changes: 10 additions & 13 deletions docs/quartz/components/scripts/popover.inline.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,5 @@
import { computePosition, flip, inline, shift } from "@floating-ui/dom"

// from micromorph/src/utils.ts
// https://github.com/natemoo-re/micromorph/blob/main/src/utils.ts#L5
export function normalizeRelativeURLs(el: Element | Document, base: string | URL) {
const update = (el: Element, attr: string, base: string | URL) => {
el.setAttribute(attr, new URL(el.getAttribute(attr)!, base).pathname)
}

el.querySelectorAll('[href^="./"], [href^="../"]').forEach((item) => update(item, "href", base))

el.querySelectorAll('[src^="./"], [src^="../"]').forEach((item) => update(item, "src", base))
}
import { normalizeRelativeURLs } from "../../util/path"

const p = new DOMParser()
async function mouseEnterHandler(
Expand All @@ -28,8 +17,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)
}

Expand All @@ -49,6 +41,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)
Expand Down
Loading

0 comments on commit d7b1229

Please sign in to comment.