Merge branch 'jackyzha0:v4' into v4

This commit is contained in:
Erdem Özgen 2024-01-02 04:11:11 +03:00 committed by GitHub
commit cde7c3dc56
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
23 changed files with 296 additions and 166 deletions

View File

@ -20,12 +20,19 @@ Steps to reproduce the behavior:
**Expected behavior** **Expected behavior**
A clear and concise description of what you expected to happen. A clear and concise description of what you expected to happen.
**Screenshots** **Screenshots and Source**
If applicable, add screenshots to help explain your problem. If applicable, add screenshots to help explain your problem.
You can help speed up fixing the problem by either
1. providing a simple reproduction
2. linking to your Quartz repository where the problem can be observed
**Desktop (please complete the following information):** **Desktop (please complete the following information):**
- Device: [e.g. iPhone6] - Quartz Version: [e.g. v4.1.2]
- `node` Version: [e.g. v18.16]
- `npm` version: [e.g. v10.1.0]
- OS: [e.g. iOS] - OS: [e.g. iOS]
- Browser [e.g. chrome, safari] - Browser [e.g. chrome, safari]

View File

@ -179,6 +179,34 @@ Component.Explorer({
## Advanced examples ## Advanced examples
> [!tip]
> When writing more complicated functions, the `layout` file can start to look very cramped.
> You can fix this by defining your functions in another file.
>
> ```ts title="functions.ts"
> import { Options } from "./quartz/components/ExplorerNode"
> export const mapFn: Options["mapFn"] = (node) => {
> // implement your function here
> }
> export const filterFn: Options["filterFn"] = (node) => {
> // implement your function here
> }
> export const sortFn: Options["sortFn"] = (a, b) => {
> // implement your function here
> }
> ```
>
> You can then import them like this:
>
> ```ts title="quartz.layout.ts"
> import { mapFn, filterFn, sortFn } from "./functions.ts"
> Component.Explorer({
> mapFn: mapFn,
> filterFn: filterFn,
> sortFn: sortFn,
> })
> ```
### Add emoji prefix ### Add emoji prefix
To add emoji prefixes (📁 for folders, 📄 for files), you could use a map function like this: To add emoji prefixes (📁 for folders, 📄 for files), you could use a map function like this:
@ -216,30 +244,63 @@ Notice how we customized the `order` array here. This is done because the defaul
To fix this, we just changed around the order and apply the `sort` function before changing the display names in the `map` function. To fix this, we just changed around the order and apply the `sort` function before changing the display names in the `map` function.
> [!tip] ### Use `sort` with pre-defined sort order
> When writing more complicated functions, the `layout` file can start to look very cramped.
> You can fix this by defining your functions in another file. Here's another example where a map containing file/folder names (as slugs) is used to define the sort order of the explorer in quartz. All files/folders that aren't listed inside of `nameOrderMap` will appear at the top of that folders hierarchy level.
>
> ```ts title="functions.ts" It's also worth mentioning, that the smaller the number set in `nameOrderMap`, the higher up the entry will be in the explorer. Incrementing every folder/file by 100, makes ordering files in their folders a lot easier. Lastly, this example still allows you to use a `mapFn` or frontmatter titles to change display names, as it uses slugs for `nameOrderMap` (which is unaffected by display name changes).
> import { Options } from "./quartz/components/ExplorerNode"
> export const mapFn: Options["mapFn"] = (node) => { ```ts title="quartz.layout.ts"
> // implement your function here Component.Explorer({
> } sortFn: (a, b) => {
> export const filterFn: Options["filterFn"] = (node) => { const nameOrderMap: Record<string, number> = {
> // implement your function here "poetry-folder": 100,
> } "essay-folder": 200,
> export const sortFn: Options["sortFn"] = (a, b) => { "research-paper-file": 201,
> // implement your function here "dinosaur-fossils-file": 300,
> } "other-folder": 400,
> ``` }
>
> You can then import them like this: let orderA = 0
> let orderB = 0
> ```ts title="quartz.layout.ts"
> import { mapFn, filterFn, sortFn } from "./functions.ts" if (a.file && a.file.slug) {
> Component.Explorer({ orderA = nameOrderMap[a.file.slug] || 0
> mapFn: mapFn, } else if (a.name) {
> filterFn: filterFn, orderA = nameOrderMap[a.name] || 0
> sortFn: sortFn, }
> })
> ``` if (b.file && b.file.slug) {
orderB = nameOrderMap[b.file.slug] || 0
} else if (b.name) {
orderB = nameOrderMap[b.name] || 0
}
return orderA - orderB
},
})
```
For reference, this is how the quartz explorer window would look like with that example:
```
📖 Poetry Folder
📑 Essay Folder
⚗️ Research Paper File
🦴 Dinosaur Fossils File
🔮 Other Folder
```
And this is how the file structure would look like:
```
index.md
poetry-folder
index.md
essay-folder
index.md
research-paper-file.md
dinosaur-fossils-file.md
other-folder
index.md
```

View File

@ -21,5 +21,6 @@ Want to see what Quartz can do? Here are some cool community gardens:
- [Pedro MC Fernandes's Topo da Mente](https://www.pmcf.xyz/topo-da-mente/) - [Pedro MC Fernandes's Topo da Mente](https://www.pmcf.xyz/topo-da-mente/)
- [Mau Camargo's Notkesto](https://notes.camargomau.com/) - [Mau Camargo's Notkesto](https://notes.camargomau.com/)
- [Caicai's Novels](https://imoko.cc/blog/caicai/) - [Caicai's Novels](https://imoko.cc/blog/caicai/)
- [🌊 Collapsed Wave](https://collapsedwave.com/)
If you want to see your own on here, submit a [Pull Request adding yourself to this file](https://github.com/jackyzha0/quartz/blob/v4/docs/showcase.md)! If you want to see your own on here, submit a [Pull Request adding yourself to this file](https://github.com/jackyzha0/quartz/blob/v4/docs/showcase.md)!

19
package-lock.json generated
View File

@ -1,12 +1,12 @@
{ {
"name": "@jackyzha0/quartz", "name": "@jackyzha0/quartz",
"version": "4.1.3", "version": "4.1.4",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "@jackyzha0/quartz", "name": "@jackyzha0/quartz",
"version": "4.1.3", "version": "4.1.4",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@clack/prompts": "^0.7.0", "@clack/prompts": "^0.7.0",
@ -32,7 +32,6 @@
"mdast-util-to-hast": "^13.0.2", "mdast-util-to-hast": "^13.0.2",
"mdast-util-to-string": "^4.0.0", "mdast-util-to-string": "^4.0.0",
"micromorph": "^0.4.5", "micromorph": "^0.4.5",
"plausible-tracker": "^0.3.8",
"preact": "^10.19.3", "preact": "^10.19.3",
"preact-render-to-string": "^6.3.1", "preact-render-to-string": "^6.3.1",
"pretty-bytes": "^6.1.1", "pretty-bytes": "^6.1.1",
@ -52,6 +51,7 @@
"remark-parse": "^11.0.0", "remark-parse": "^11.0.0",
"remark-rehype": "^11.0.0", "remark-rehype": "^11.0.0",
"remark-smartypants": "^2.0.0", "remark-smartypants": "^2.0.0",
"rfdc": "^1.3.0",
"rimraf": "^5.0.5", "rimraf": "^5.0.5",
"serve-handler": "^6.1.5", "serve-handler": "^6.1.5",
"shikiji": "^0.9.9", "shikiji": "^0.9.9",
@ -4450,14 +4450,6 @@
"url": "https://github.com/sponsors/jonschlinkert" "url": "https://github.com/sponsors/jonschlinkert"
} }
}, },
"node_modules/plausible-tracker": {
"version": "0.3.8",
"resolved": "https://registry.npmjs.org/plausible-tracker/-/plausible-tracker-0.3.8.tgz",
"integrity": "sha512-lmOWYQ7s9KOUJ1R+YTOR3HrjdbxIS2Z4de0P/Jx2dQPteznJl2eX3tXxKClpvbfyGP59B5bbhW8ftN59HbbFSg==",
"engines": {
"node": ">=10"
}
},
"node_modules/preact": { "node_modules/preact": {
"version": "10.19.3", "version": "10.19.3",
"resolved": "https://registry.npmjs.org/preact/-/preact-10.19.3.tgz", "resolved": "https://registry.npmjs.org/preact/-/preact-10.19.3.tgz",
@ -5161,6 +5153,11 @@
"node": ">=0.10.0" "node": ">=0.10.0"
} }
}, },
"node_modules/rfdc": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/rfdc/-/rfdc-1.3.0.tgz",
"integrity": "sha512-V2hovdzFbOi77/WajaSMXk2OLm+xNIeQdMMuB7icj7bk6zi2F8GGAxigcnDFpJHbNyNcgyJDiP+8nOrY5cZGrA=="
},
"node_modules/rimraf": { "node_modules/rimraf": {
"version": "5.0.5", "version": "5.0.5",
"resolved": "https://registry.npmjs.org/rimraf/-/rimraf-5.0.5.tgz", "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-5.0.5.tgz",

View File

@ -2,7 +2,7 @@
"name": "@jackyzha0/quartz", "name": "@jackyzha0/quartz",
"description": "🌱 publish your digital garden and notes as a website", "description": "🌱 publish your digital garden and notes as a website",
"private": true, "private": true,
"version": "4.1.3", "version": "4.1.4",
"type": "module", "type": "module",
"author": "jackyzha0 <j.zhao2k19@gmail.com>", "author": "jackyzha0 <j.zhao2k19@gmail.com>",
"license": "MIT", "license": "MIT",
@ -57,7 +57,6 @@
"mdast-util-to-hast": "^13.0.2", "mdast-util-to-hast": "^13.0.2",
"mdast-util-to-string": "^4.0.0", "mdast-util-to-string": "^4.0.0",
"micromorph": "^0.4.5", "micromorph": "^0.4.5",
"plausible-tracker": "^0.3.8",
"preact": "^10.19.3", "preact": "^10.19.3",
"preact-render-to-string": "^6.3.1", "preact-render-to-string": "^6.3.1",
"pretty-bytes": "^6.1.1", "pretty-bytes": "^6.1.1",
@ -77,6 +76,7 @@
"remark-parse": "^11.0.0", "remark-parse": "^11.0.0",
"remark-rehype": "^11.0.0", "remark-rehype": "^11.0.0",
"remark-smartypants": "^2.0.0", "remark-smartypants": "^2.0.0",
"rfdc": "^1.3.0",
"rimraf": "^5.0.5", "rimraf": "^5.0.5",
"serve-handler": "^6.1.5", "serve-handler": "^6.1.5",
"shikiji": "^0.9.9", "shikiji": "^0.9.9",

View File

@ -37,7 +37,7 @@ export const defaultContentPageLayout: PageLayout = {
// components for pages that display lists of pages (e.g. tags or folders) // components for pages that display lists of pages (e.g. tags or folders)
export const defaultListPageLayout: PageLayout = { export const defaultListPageLayout: PageLayout = {
beforeBody: [Component.ArticleTitle()], beforeBody: [Component.Breadcrumbs(), Component.ArticleTitle()],
left: [ left: [
Component.PageTitle(), Component.PageTitle(),
Component.MobileOnly(Component.Spacer()), Component.MobileOnly(Component.Spacer()),

View File

@ -7,6 +7,7 @@ export type Analytics =
| null | null
| { | {
provider: "plausible" provider: "plausible"
host?: string
} }
| { | {
provider: "google" provider: "google"

View File

@ -113,7 +113,10 @@ export async function handleCreate(argv) {
} }
} }
await fs.promises.unlink(path.join(contentFolder, ".gitkeep")) const gitkeepPath = path.join(contentFolder, ".gitkeep")
if (fs.existsSync(gitkeepPath)) {
await fs.promises.unlink(gitkeepPath)
}
if (setupStrategy === "copy" || setupStrategy === "symlink") { if (setupStrategy === "copy" || setupStrategy === "symlink") {
let originalFolder = sourceDirectory let originalFolder = sourceDirectory

View File

@ -68,8 +68,9 @@ export default ((opts?: Partial<BreadcrumbOptions>) => {
// construct the index for the first time // construct the index for the first time
for (const file of allFiles) { for (const file of allFiles) {
if (file.slug?.endsWith("index")) { if (file.slug?.endsWith("index")) {
const folderParts = file.filePath?.split("/") const folderParts = file.slug?.split("/")
if (folderParts) { if (folderParts) {
// 2nd last to exclude the /index
const folderName = folderParts[folderParts?.length - 2] const folderName = folderParts[folderParts?.length - 2]
folderIndex.set(folderName, file) folderIndex.set(folderName, file)
} }
@ -88,7 +89,10 @@ export default ((opts?: Partial<BreadcrumbOptions>) => {
// Try to resolve frontmatter folder title // Try to resolve frontmatter folder title
const currentFile = folderIndex?.get(curPathSegment) const currentFile = folderIndex?.get(curPathSegment)
if (currentFile) { if (currentFile) {
curPathSegment = currentFile.frontmatter!.title const title = currentFile.frontmatter!.title
if (title !== "index") {
curPathSegment = title
}
} }
// Add current slug to full path // Add current slug to full path
@ -100,7 +104,7 @@ export default ((opts?: Partial<BreadcrumbOptions>) => {
} }
// Add current file to crumb (can directly use frontmatter title) // Add current file to crumb (can directly use frontmatter title)
if (options.showCurrentPage) { if (options.showCurrentPage && slugParts.at(-1) === "") {
crumbs.push({ crumbs.push({
displayName: fileData.frontmatter!.title, displayName: fileData.frontmatter!.title,
path: "", path: "",

View File

@ -18,7 +18,7 @@ function Darkmode({ displayClass }: QuartzComponentProps) {
x="0px" x="0px"
y="0px" y="0px"
viewBox="0 0 35 35" viewBox="0 0 35 35"
style="enable-background:new 0 0 35 35;" style="enable-background:new 0 0 35 35"
xmlSpace="preserve" xmlSpace="preserve"
> >
<title>Light mode</title> <title>Light mode</title>
@ -34,7 +34,7 @@ function Darkmode({ displayClass }: QuartzComponentProps) {
x="0px" x="0px"
y="0px" y="0px"
viewBox="0 0 100 100" viewBox="0 0 100 100"
style="enable-background='new 0 0 100 100'" style="enable-background:new 0 0 100 100"
xmlSpace="preserve" xmlSpace="preserve"
> >
<title>Dark mode</title> <title>Dark mode</title>

View File

@ -12,6 +12,9 @@ const defaultOptions = {
folderClickBehavior: "collapse", folderClickBehavior: "collapse",
folderDefaultState: "collapsed", folderDefaultState: "collapsed",
useSavedState: true, useSavedState: true,
mapFn: (node) => {
return node
},
sortFn: (a, b) => { sortFn: (a, b) => {
// Sort order: folders first, then files. Sort folders and files alphabetically // Sort order: folders first, then files. Sort folders and files alphabetically
if ((!a.file && !b.file) || (a.file && b.file)) { if ((!a.file && !b.file) || (a.file && b.file)) {
@ -22,6 +25,7 @@ const defaultOptions = {
sensitivity: "base", sensitivity: "base",
}) })
} }
if (a.file && !b.file) { if (a.file && !b.file) {
return 1 return 1
} else { } else {
@ -41,36 +45,25 @@ export default ((userOpts?: Partial<Options>) => {
let jsonTree: string let jsonTree: string
function constructFileTree(allFiles: QuartzPluginData[]) { function constructFileTree(allFiles: QuartzPluginData[]) {
if (!fileTree) { if (fileTree) {
return
}
// Construct tree from allFiles // Construct tree from allFiles
fileTree = new FileNode("") fileTree = new FileNode("")
allFiles.forEach((file) => fileTree.add(file, 1)) allFiles.forEach((file) => fileTree.add(file))
/**
* Keys of this object must match corresponding function name of `FileNode`,
* while values must be the argument that will be passed to the function.
*
* e.g. entry for FileNode.sort: `sort: opts.sortFn` (value is sort function from options)
*/
const functions = {
map: opts.mapFn,
sort: opts.sortFn,
filter: opts.filterFn,
}
// Execute all functions (sort, filter, map) that were provided (if none were provided, only default "sort" is applied) // Execute all functions (sort, filter, map) that were provided (if none were provided, only default "sort" is applied)
if (opts.order) { if (opts.order) {
// Order is important, use loop with index instead of order.map() // Order is important, use loop with index instead of order.map()
for (let i = 0; i < opts.order.length; i++) { for (let i = 0; i < opts.order.length; i++) {
const functionName = opts.order[i] const functionName = opts.order[i]
if (functions[functionName]) { if (functionName === "map") {
// for every entry in order, call matching function in FileNode and pass matching argument fileTree.map(opts.mapFn)
// e.g. i = 0; functionName = "filter" } else if (functionName === "sort") {
// converted to: (if opts.filterFn) => fileTree.filter(opts.filterFn) fileTree.sort(opts.sortFn)
} else if (functionName === "filter") {
// @ts-ignore fileTree.filter(opts.filterFn)
// typescript cant statically check these dynamic references, so manually make sure reference is valid and ignore warning
fileTree[functionName].call(fileTree, functions[functionName])
} }
} }
} }
@ -81,7 +74,6 @@ export default ((userOpts?: Partial<Options>) => {
// Stringify to pass json tree as data attribute ([data-tree]) // Stringify to pass json tree as data attribute ([data-tree])
jsonTree = JSON.stringify(folders) jsonTree = JSON.stringify(folders)
} }
}
function Explorer({ allFiles, displayClass, fileData }: QuartzComponentProps) { function Explorer({ allFiles, displayClass, fileData }: QuartzComponentProps) {
constructFileTree(allFiles) constructFileTree(allFiles)
@ -120,6 +112,7 @@ export default ((userOpts?: Partial<Options>) => {
</div> </div>
) )
} }
Explorer.css = explorerStyle Explorer.css = explorerStyle
Explorer.afterDOMLoaded = script Explorer.afterDOMLoaded = script
return Explorer return Explorer

View File

@ -1,6 +1,13 @@
// @ts-ignore // @ts-ignore
import { QuartzPluginData } from "../plugins/vfile" import { QuartzPluginData } from "../plugins/vfile"
import { resolveRelative } from "../util/path" import {
joinSegments,
resolveRelative,
clone,
simplifySlug,
SimpleSlug,
FilePath,
} from "../util/path"
type OrderEntries = "sort" | "filter" | "map" type OrderEntries = "sort" | "filter" | "map"
@ -10,9 +17,9 @@ export interface Options {
folderClickBehavior: "collapse" | "link" folderClickBehavior: "collapse" | "link"
useSavedState: boolean useSavedState: boolean
sortFn: (a: FileNode, b: FileNode) => number sortFn: (a: FileNode, b: FileNode) => number
filterFn?: (node: FileNode) => boolean filterFn: (node: FileNode) => boolean
mapFn?: (node: FileNode) => void mapFn: (node: FileNode) => void
order?: OrderEntries[] order: OrderEntries[]
} }
type DataWrapper = { type DataWrapper = {
@ -25,59 +32,74 @@ export type FolderState = {
collapsed: boolean collapsed: boolean
} }
function getPathSegment(fp: FilePath | undefined, idx: number): string | undefined {
if (!fp) {
return undefined
}
return fp.split("/").at(idx)
}
// Structure to add all files into a tree // Structure to add all files into a tree
export class FileNode { export class FileNode {
children: FileNode[] children: Array<FileNode>
name: string name: string // this is the slug segment
displayName: string displayName: string
file: QuartzPluginData | null file: QuartzPluginData | null
depth: number depth: number
constructor(name: string, file?: QuartzPluginData, depth?: number) { constructor(slugSegment: string, displayName?: string, file?: QuartzPluginData, depth?: number) {
this.children = [] this.children = []
this.name = name this.name = slugSegment
this.displayName = name this.displayName = displayName ?? file?.frontmatter?.title ?? slugSegment
this.file = file ? structuredClone(file) : null this.file = file ? clone(file) : null
this.depth = depth ?? 0 this.depth = depth ?? 0
} }
private insert(file: DataWrapper) { private insert(fileData: DataWrapper) {
if (file.path.length === 1) { if (fileData.path.length === 0) {
if (file.path[0] !== "index.md") {
this.children.push(new FileNode(file.file.frontmatter!.title, file.file, this.depth + 1))
} else {
const title = file.file.frontmatter?.title
if (title && title !== "index" && file.path[0] === "index.md") {
this.displayName = title
}
}
} else {
const next = file.path[0]
file.path = file.path.splice(1)
for (const child of this.children) {
if (child.name === next) {
child.insert(file)
return return
} }
const nextSegment = fileData.path[0]
// base case, insert here
if (fileData.path.length === 1) {
if (nextSegment === "") {
// index case (we are the root and we just found index.md), set our data appropriately
const title = fileData.file.frontmatter?.title
if (title && title !== "index") {
this.displayName = title
}
} else {
// direct child
this.children.push(new FileNode(nextSegment, undefined, fileData.file, this.depth + 1))
} }
const newChild = new FileNode(next, undefined, this.depth + 1) return
newChild.insert(file)
this.children.push(newChild)
} }
// find the right child to insert into
fileData.path = fileData.path.splice(1)
const child = this.children.find((c) => c.name === nextSegment)
if (child) {
child.insert(fileData)
return
}
const newChild = new FileNode(
nextSegment,
getPathSegment(fileData.file.relativePath, this.depth),
undefined,
this.depth + 1,
)
newChild.insert(fileData)
this.children.push(newChild)
} }
// Add new file to tree // Add new file to tree
add(file: QuartzPluginData, splice: number = 0) { add(file: QuartzPluginData) {
this.insert({ file, path: file.filePath!.split("/").splice(splice) }) this.insert({ file: file, path: simplifySlug(file.slug!).split("/") })
}
// Print tree structure (for debugging)
print(depth: number = 0) {
let folderChar = ""
if (!this.file) folderChar = "|"
console.log("-".repeat(depth), folderChar, this.name, this.depth)
this.children.forEach((e) => e.print(depth + 1))
} }
/** /**
@ -95,7 +117,6 @@ export class FileNode {
*/ */
map(mapFn: (node: FileNode) => void) { map(mapFn: (node: FileNode) => void) {
mapFn(this) mapFn(this)
this.children.forEach((child) => child.map(mapFn)) this.children.forEach((child) => child.map(mapFn))
} }
@ -110,16 +131,16 @@ export class FileNode {
const traverse = (node: FileNode, currentPath: string) => { const traverse = (node: FileNode, currentPath: string) => {
if (!node.file) { if (!node.file) {
const folderPath = currentPath + (currentPath ? "/" : "") + node.name const folderPath = joinSegments(currentPath, node.name)
if (folderPath !== "") { if (folderPath !== "") {
folderPaths.push({ path: folderPath, collapsed }) folderPaths.push({ path: folderPath, collapsed })
} }
node.children.forEach((child) => traverse(child, folderPath)) node.children.forEach((child) => traverse(child, folderPath))
} }
} }
traverse(this, "") traverse(this, "")
return folderPaths return folderPaths
} }
@ -147,14 +168,13 @@ export function ExplorerNode({ node, opts, fullPath, fileData }: ExplorerNodePro
const isDefaultOpen = opts.folderDefaultState === "open" const isDefaultOpen = opts.folderDefaultState === "open"
// Calculate current folderPath // Calculate current folderPath
let pathOld = fullPath ? fullPath : ""
let folderPath = "" let folderPath = ""
if (node.name !== "") { if (node.name !== "") {
folderPath = `${pathOld}/${node.name}` folderPath = joinSegments(fullPath ?? "", node.name)
} }
return ( return (
<li> <>
{node.file ? ( {node.file ? (
// Single file node // Single file node
<li key={node.file.slug}> <li key={node.file.slug}>
@ -163,7 +183,7 @@ export function ExplorerNode({ node, opts, fullPath, fileData }: ExplorerNodePro
</a> </a>
</li> </li>
) : ( ) : (
<div> <li>
{node.name !== "" && ( {node.name !== "" && (
// Node with entire folder // Node with entire folder
// Render svg button + folder name, then children // Render svg button + folder name, then children
@ -185,12 +205,16 @@ export function ExplorerNode({ node, opts, fullPath, fileData }: ExplorerNodePro
{/* render <a> tag if folderBehavior is "link", otherwise render <button> with collapse click event */} {/* render <a> tag if folderBehavior is "link", otherwise render <button> with collapse click event */}
<div key={node.name} data-folderpath={folderPath}> <div key={node.name} data-folderpath={folderPath}>
{folderBehavior === "link" ? ( {folderBehavior === "link" ? (
<a href={`${folderPath}`} data-for={node.name} class="folder-title"> <a
href={resolveRelative(fileData.slug!, folderPath as SimpleSlug)}
data-for={node.name}
class="folder-title"
>
{node.displayName} {node.displayName}
</a> </a>
) : ( ) : (
<button class="folder-button"> <button class="folder-button">
<p class="folder-title">{node.displayName}</p> <span class="folder-title">{node.displayName}</span>
</button> </button>
)} )}
</div> </div>
@ -217,8 +241,8 @@ export function ExplorerNode({ node, opts, fullPath, fileData }: ExplorerNodePro
))} ))}
</ul> </ul>
</div> </div>
</div>
)}
</li> </li>
)}
</>
) )
} }

View File

@ -59,8 +59,7 @@ function toggleFolder(evt: MouseEvent) {
// Save folder state to localStorage // Save folder state to localStorage
const clickFolderPath = currentFolderParent.dataset.folderpath as string const clickFolderPath = currentFolderParent.dataset.folderpath as string
// Remove leading "/" const fullFolderPath = clickFolderPath
const fullFolderPath = clickFolderPath.substring(1)
toggleCollapsedByPath(explorerState, fullFolderPath) toggleCollapsedByPath(explorerState, fullFolderPath)
const stringifiedFileTree = JSON.stringify(explorerState) const stringifiedFileTree = JSON.stringify(explorerState)
@ -108,9 +107,7 @@ function setupExplorer() {
explorerState = JSON.parse(storageTree) explorerState = JSON.parse(storageTree)
explorerState.map((folderUl) => { explorerState.map((folderUl) => {
// grab <li> element for matching folder path // grab <li> element for matching folder path
const folderLi = document.querySelector( const folderLi = document.querySelector(`[data-folderpath='${folderUl.path}']`) as HTMLElement
`[data-folderpath='/${folderUl.path}']`,
) as HTMLElement
// Get corresponding content <ul> tag and set state // Get corresponding content <ul> tag and set state
if (folderLi) { if (folderLi) {

View File

@ -1,3 +0,0 @@
import Plausible from "plausible-tracker"
const { trackPageview } = Plausible()
document.addEventListener("nav", () => trackPageview())

View File

@ -106,7 +106,7 @@ svg {
align-items: center; align-items: center;
font-family: var(--headerFont); font-family: var(--headerFont);
& p { & span {
font-size: 0.95rem; font-size: 0.95rem;
display: inline-block; display: inline-block;
color: var(--secondary); color: var(--secondary);

View File

@ -4,8 +4,6 @@ import { QuartzEmitterPlugin } from "../types"
// @ts-ignore // @ts-ignore
import spaRouterScript from "../../components/scripts/spa.inline" import spaRouterScript from "../../components/scripts/spa.inline"
// @ts-ignore // @ts-ignore
import plausibleScript from "../../components/scripts/plausible.inline"
// @ts-ignore
import popoverScript from "../../components/scripts/popover.inline" import popoverScript from "../../components/scripts/popover.inline"
import styles from "../../styles/custom.scss" import styles from "../../styles/custom.scss"
import popoverStyle from "../../components/styles/popover.scss" import popoverStyle from "../../components/styles/popover.scss"
@ -14,6 +12,7 @@ import { StaticResources } from "../../util/resources"
import { QuartzComponent } from "../../components/types" import { QuartzComponent } from "../../components/types"
import { googleFontHref, joinStyles } from "../../util/theme" import { googleFontHref, joinStyles } from "../../util/theme"
import { Features, transform } from "lightningcss" import { Features, transform } from "lightningcss"
import { transform as transpile } from "esbuild"
type ComponentResources = { type ComponentResources = {
css: string[] css: string[]
@ -56,9 +55,16 @@ function getComponentResources(ctx: BuildCtx): ComponentResources {
} }
} }
function joinScripts(scripts: string[]): string { async function joinScripts(scripts: string[]): Promise<string> {
// wrap with iife to prevent scope collision // wrap with iife to prevent scope collision
return scripts.map((script) => `(function () {${script}})();`).join("\n") const script = scripts.map((script) => `(function () {${script}})();`).join("\n")
// minify with esbuild
const res = await transpile(script, {
minify: true,
})
return res.code
} }
function addGlobalPageResources( function addGlobalPageResources(
@ -95,7 +101,20 @@ function addGlobalPageResources(
}); });
});`) });`)
} else if (cfg.analytics?.provider === "plausible") { } else if (cfg.analytics?.provider === "plausible") {
componentResources.afterDOMLoaded.push(plausibleScript) const plausibleHost = cfg.analytics.host ?? "https://plausible.io"
componentResources.afterDOMLoaded.push(`
const plausibleScript = document.createElement("script")
plausibleScript.src = "${plausibleHost}/js/script.manual.js"
plausibleScript.setAttribute("data-domain", location.hostname)
plausibleScript.defer = true
document.head.appendChild(plausibleScript)
window.plausible = window.plausible || function() { (window.plausible.q = window.plausible.q || []).push(arguments) }
document.addEventListener("nav", () => {
plausible("pageview")
})
`)
} else if (cfg.analytics?.provider === "umami") { } else if (cfg.analytics?.provider === "umami") {
componentResources.afterDOMLoaded.push(` componentResources.afterDOMLoaded.push(`
const umamiScript = document.createElement("script") const umamiScript = document.createElement("script")
@ -165,8 +184,11 @@ export const ComponentResources: QuartzEmitterPlugin<Options> = (opts?: Partial<
addGlobalPageResources(ctx, resources, componentResources) addGlobalPageResources(ctx, resources, componentResources)
const stylesheet = joinStyles(ctx.cfg.configuration.theme, ...componentResources.css, styles) const stylesheet = joinStyles(ctx.cfg.configuration.theme, ...componentResources.css, styles)
const prescript = joinScripts(componentResources.beforeDOMLoaded) const [prescript, postscript] = await Promise.all([
const postscript = joinScripts(componentResources.afterDOMLoaded) joinScripts(componentResources.beforeDOMLoaded),
joinScripts(componentResources.afterDOMLoaded),
])
const fps = await Promise.all([ const fps = await Promise.all([
emit({ emit({
slug: "index" as FullSlug, slug: "index" as FullSlug,

View File

@ -2,7 +2,7 @@ import { Root } from "hast"
import { GlobalConfiguration } from "../../cfg" import { GlobalConfiguration } from "../../cfg"
import { getDate } from "../../components/Date" import { getDate } from "../../components/Date"
import { escapeHTML } from "../../util/escape" import { escapeHTML } from "../../util/escape"
import { FilePath, FullSlug, SimpleSlug, simplifySlug } from "../../util/path" import { FilePath, FullSlug, SimpleSlug, joinSegments, simplifySlug } from "../../util/path"
import { QuartzEmitterPlugin } from "../types" import { QuartzEmitterPlugin } from "../types"
import { toHtml } from "hast-util-to-html" import { toHtml } from "hast-util-to-html"
import path from "path" import path from "path"
@ -37,7 +37,7 @@ const defaultOptions: Options = {
function generateSiteMap(cfg: GlobalConfiguration, idx: ContentIndex): string { function generateSiteMap(cfg: GlobalConfiguration, idx: ContentIndex): string {
const base = cfg.baseUrl ?? "" const base = cfg.baseUrl ?? ""
const createURLEntry = (slug: SimpleSlug, content: ContentDetails): string => `<url> const createURLEntry = (slug: SimpleSlug, content: ContentDetails): string => `<url>
<loc>https://${base}/${encodeURI(slug)}</loc> <loc>https://${joinSegments(base, encodeURI(slug))}</loc>
<lastmod>${content.date?.toISOString()}</lastmod> <lastmod>${content.date?.toISOString()}</lastmod>
</url>` </url>`
const urls = Array.from(idx) const urls = Array.from(idx)
@ -52,8 +52,8 @@ function generateRSSFeed(cfg: GlobalConfiguration, idx: ContentIndex, limit?: nu
const createURLEntry = (slug: SimpleSlug, content: ContentDetails): string => `<item> const createURLEntry = (slug: SimpleSlug, content: ContentDetails): string => `<item>
<title>${escapeHTML(content.title)}</title> <title>${escapeHTML(content.title)}</title>
<link>${root}/${encodeURI(slug)}</link> <link>${joinSegments(root, encodeURI(slug))}</link>
<guid>${root}/${encodeURI(slug)}</guid> <guid>${joinSegments(root, encodeURI(slug))}</guid>
<description>${content.richContent ?? content.description}</description> <description>${content.richContent ?? content.description}</description>
<pubDate>${content.date?.toUTCString()}</pubDate> <pubDate>${content.date?.toUTCString()}</pubDate>
</item>` </item>`

View File

@ -30,5 +30,6 @@ declare module "vfile" {
interface DataMap { interface DataMap {
slug: FullSlug slug: FullSlug
filePath: FilePath filePath: FilePath
relativePath: FilePath
} }
} }

View File

@ -49,13 +49,21 @@ export const FrontMatter: QuartzTransformerPlugin<Partial<Options> | undefined>
data.title = file.stem ?? "Untitled" data.title = file.stem ?? "Untitled"
} }
if (data.tags && !Array.isArray(data.tags)) { if (data.tags) {
// coerce to array
if (!Array.isArray(data.tags)) {
data.tags = data.tags data.tags = data.tags
.toString() .toString()
.split(oneLineTagDelim) .split(oneLineTagDelim)
.map((tag: string) => tag.trim()) .map((tag: string) => tag.trim())
} }
// remove all non-string tags
data.tags = data.tags
.filter((tag: unknown) => typeof tag === "string" || typeof tag === "number")
.map((tag: string | number) => tag.toString())
}
// slug them all!! // slug them all!!
data.tags = [...new Set(data.tags?.map((tag: string) => slugTag(tag)))] data.tags = [...new Set(data.tags?.map((tag: string) => slugTag(tag)))]

View File

@ -12,6 +12,7 @@ import {
import path from "path" import path from "path"
import { visit } from "unist-util-visit" import { visit } from "unist-util-visit"
import isAbsoluteUrl from "is-absolute-url" import isAbsoluteUrl from "is-absolute-url"
import { Root } from "hast"
interface Options { interface Options {
/** How to resolve Markdown paths */ /** How to resolve Markdown paths */
@ -19,12 +20,14 @@ interface Options {
/** Strips folders from a link so that it looks nice */ /** Strips folders from a link so that it looks nice */
prettyLinks: boolean prettyLinks: boolean
openLinksInNewTab: boolean openLinksInNewTab: boolean
lazyLoad: boolean
} }
const defaultOptions: Options = { const defaultOptions: Options = {
markdownLinkResolution: "absolute", markdownLinkResolution: "absolute",
prettyLinks: true, prettyLinks: true,
openLinksInNewTab: false, openLinksInNewTab: false,
lazyLoad: false,
} }
export const CrawlLinks: QuartzTransformerPlugin<Partial<Options> | undefined> = (userOpts) => { export const CrawlLinks: QuartzTransformerPlugin<Partial<Options> | undefined> = (userOpts) => {
@ -34,7 +37,7 @@ export const CrawlLinks: QuartzTransformerPlugin<Partial<Options> | undefined> =
htmlPlugins(ctx) { htmlPlugins(ctx) {
return [ return [
() => { () => {
return (tree, file) => { return (tree: Root, file) => {
const curSlug = simplifySlug(file.data.slug!) const curSlug = simplifySlug(file.data.slug!)
const outgoing: Set<SimpleSlug> = new Set() const outgoing: Set<SimpleSlug> = new Set()
@ -51,8 +54,8 @@ export const CrawlLinks: QuartzTransformerPlugin<Partial<Options> | undefined> =
typeof node.properties.href === "string" typeof node.properties.href === "string"
) { ) {
let dest = node.properties.href as RelativeURL let dest = node.properties.href as RelativeURL
node.properties.className ??= [] const classes = (node.properties.className ?? []) as string[]
node.properties.className.push(isAbsoluteUrl(dest) ? "external" : "internal") classes.push(isAbsoluteUrl(dest) ? "external" : "internal")
// Check if the link has alias text // Check if the link has alias text
if ( if (
@ -61,8 +64,9 @@ export const CrawlLinks: QuartzTransformerPlugin<Partial<Options> | undefined> =
node.children[0].value !== dest node.children[0].value !== dest
) { ) {
// Add the 'alias' class if the text content is not the same as the href // Add the 'alias' class if the text content is not the same as the href
node.properties.className.push("alias") classes.push("alias")
} }
node.properties.className = classes
if (opts.openLinksInNewTab) { if (opts.openLinksInNewTab) {
node.properties.target = "_blank" node.properties.target = "_blank"
@ -111,6 +115,10 @@ export const CrawlLinks: QuartzTransformerPlugin<Partial<Options> | undefined> =
node.properties && node.properties &&
typeof node.properties.src === "string" typeof node.properties.src === "string"
) { ) {
if (opts.lazyLoad) {
node.properties.loading = "lazy"
}
if (!isAbsoluteUrl(node.properties.src)) { if (!isAbsoluteUrl(node.properties.src)) {
let dest = node.properties.src as RelativeURL let dest = node.properties.src as RelativeURL
dest = node.properties.src = transformLink( dest = node.properties.src = transformLink(

View File

@ -125,7 +125,7 @@ const calloutLineRegex = new RegExp(/^> *\[\!\w+\][+-]?.*$/, "gm")
// #(...) -> capturing group, tag itself must start with # // #(...) -> capturing group, tag itself must start with #
// (?:[-_\p{L}\d\p{Z}])+ -> non-capturing group, non-empty string of (Unicode-aware) alpha-numeric characters and symbols, hyphens and/or underscores // (?:[-_\p{L}\d\p{Z}])+ -> non-capturing group, non-empty string of (Unicode-aware) alpha-numeric characters and symbols, hyphens and/or underscores
// (?:\/[-_\p{L}\d\p{Z}]+)*) -> non-capturing group, matches an arbitrary number of tag strings separated by "/" // (?:\/[-_\p{L}\d\p{Z}]+)*) -> non-capturing group, matches an arbitrary number of tag strings separated by "/"
const tagRegex = new RegExp(/(?:^| )#((?:[-_\p{L}\d])+(?:\/[-_\p{L}\d]+)*)/, "gu") const tagRegex = new RegExp(/(?:^| )#((?:[-_\p{L}\p{Emoji}\d])+(?:\/[-_\p{L}\p{Emoji}\d]+)*)/, "gu")
const blockReferenceRegex = new RegExp(/\^([A-Za-z0-9]+)$/, "g") const blockReferenceRegex = new RegExp(/\^([A-Za-z0-9]+)$/, "g")
export const ObsidianFlavoredMarkdown: QuartzTransformerPlugin<Partial<Options> | undefined> = ( export const ObsidianFlavoredMarkdown: QuartzTransformerPlugin<Partial<Options> | undefined> = (

View File

@ -91,8 +91,9 @@ export function createFileParser(ctx: BuildCtx, fps: FilePath[]) {
} }
// base data properties that plugins may use // base data properties that plugins may use
file.data.slug = slugifyFilePath(path.posix.relative(argv.directory, file.path) as FilePath) file.data.filePath = file.path as FilePath
file.data.filePath = fp file.data.relativePath = path.posix.relative(argv.directory, file.path) as FilePath
file.data.slug = slugifyFilePath(file.data.relativePath)
const ast = processor.parse(file) const ast = processor.parse(file)
const newAst = await processor.run(ast, file) const newAst = await processor.run(ast, file)

View File

@ -1,5 +1,9 @@
import { slug as slugAnchor } from "github-slugger" import { slug as slugAnchor } from "github-slugger"
import type { Element as HastElement } from "hast" import type { Element as HastElement } from "hast"
import rfdc from "rfdc"
export const clone = rfdc()
// this file must be isomorphic so it can't use node libs (e.g. path) // this file must be isomorphic so it can't use node libs (e.g. path)
export const QUARTZ = "quartz" export const QUARTZ = "quartz"
@ -121,7 +125,8 @@ const _rebaseHastElement = (
} }
} }
export function normalizeHastElement(el: HastElement, curBase: FullSlug, newBase: FullSlug) { export function normalizeHastElement(rawEl: HastElement, curBase: FullSlug, newBase: FullSlug) {
const el = clone(rawEl) // clone so we dont modify the original page
_rebaseHastElement(el, "src", curBase, newBase) _rebaseHastElement(el, "src", curBase, newBase)
_rebaseHastElement(el, "href", curBase, newBase) _rebaseHastElement(el, "href", curBase, newBase)
if (el.children) { if (el.children) {