1
0
forked from GitHub/quartz

Compare commits

..

1 Commits

Author SHA1 Message Date
Aaron Pham
3e9be39851
fix(og): make sure to replace space in fonts with +
Signed-off-by: Aaron Pham <contact@aarnphm.xyz>
2025-01-17 07:52:03 -05:00
126 changed files with 4364 additions and 6877 deletions

View File

@ -45,7 +45,7 @@ jobs:
run: npm test run: npm test
- name: Ensure Quartz builds, check bundle info - name: Ensure Quartz builds, check bundle info
run: npx quartz build --bundleInfo -d docs run: npx quartz build --bundleInfo
publish-tag: publish-tag:
if: ${{ github.repository == 'jackyzha0/quartz' && github.ref == 'refs/heads/v4' }} if: ${{ github.repository == 'jackyzha0/quartz' && github.ref == 'refs/heads/v4' }}

View File

@ -25,7 +25,7 @@ jobs:
with: with:
fetch-depth: 1 fetch-depth: 1
- name: Inject slug/short variables - name: Inject slug/short variables
uses: rlespinasse/github-slug-action@v5.1.0 uses: rlespinasse/github-slug-action@v5.0.0
- name: Set up QEMU - name: Set up QEMU
uses: docker/setup-qemu-action@v3 uses: docker/setup-qemu-action@v3
- name: Set up Docker Buildx - name: Set up Docker Buildx
@ -37,7 +37,7 @@ jobs:
network=host network=host
- name: Install cosign - name: Install cosign
if: github.event_name != 'pull_request' if: github.event_name != 'pull_request'
uses: sigstore/cosign-installer@v3.8.1 uses: sigstore/cosign-installer@v3.7.0
- name: Login to GitHub Container Registry - name: Login to GitHub Container Registry
uses: docker/login-action@v3 uses: docker/login-action@v3
if: github.event_name != 'pull_request' if: github.event_name != 'pull_request'

View File

@ -1,10 +1,10 @@
FROM node:22-slim AS builder FROM node:20-slim AS builder
WORKDIR /usr/src/app WORKDIR /usr/src/app
COPY package.json . COPY package.json .
COPY package-lock.json* . COPY package-lock.json* .
RUN npm ci RUN npm ci
FROM node:22-slim FROM node:20-slim
WORKDIR /usr/src/app WORKDIR /usr/src/app
COPY --from=builder /usr/src/app/ /usr/src/app/ COPY --from=builder /usr/src/app/ /usr/src/app/
COPY . . COPY . .

160
action.sh
View File

@ -1,160 +0,0 @@
#!/bin/bash
# To fetch and use this script in a GitHub action:
#
# curl -s -S https://raw.githubusercontent.com/saberzero1/quartz-themes/master/action.sh | bash -s -- <THEME_NAME>
RED='\033[0;31m'
YELLOW='\033[1;33m'
GREEN='\033[0;32m'
BLUE='\033[1;34m'
NC='\033[0m'
echo_err() { echo -e "${RED}$1${NC}"; }
echo_warn() { echo -e "${YELLOW}$1${NC}"; }
echo_ok() { echo -e "${GREEN}$1${NC}"; }
echo_info() { echo -e "${BLUE}$1${NC}"; }
THEME_DIR="themes"
QUARTZ_STYLES_DIR="quartz/styles"
if test -f ${QUARTZ_STYLES_DIR}/custom.scss; then
echo_ok "Quartz root succesfully detected..."
THEME_DIR="${QUARTZ_STYLES_DIR}/${THEME_DIR}"
else
echo_warn "Quartz root not detected, checking if we are in the styles directory..."
if test -f custom.scss; then
echo_ok "Styles directory detected..."
else
echo_err "Cannot detect Quartz repository. Are you in the correct working directory?" 1>&2
exit 1
fi
fi
echo -e "Input theme: ${BLUE}$*${NC}"
echo "Parsing input theme..."
# Concat parameters
result=""
for param in "$@"; do
if [ -n "$result" ]; then
result="$result-"
fi
result="$result$param"
done
if "$result" = ""; then
echo_warn "No theme provided, defaulting to Tokyo Night..."
result="tokyo-night"
fi
# Convert to lowercase
THEME=$(echo "$result" | tr '[:upper:]' '[:lower:]')
echo -e "Theme ${BLUE}$*${NC} parsed to $(echo_info ${THEME})"
echo "Validating theme..."
GITHUB_URL_BASE="https://raw.githubusercontent.com/saberzero1/quartz-themes/master/__CONVERTER/"
GITHUB_OUTPUT_DIR="__OUTPUT/"
GITHUB_OVERRIDE_DIR="__OVERRIDES/"
GITHUB_THEME_DIR="${THEME}/"
CSS_INDEX_URL="${GITHUB_URL_BASE}${GITHUB_OUTPUT_DIR}${GITHUB_THEME_DIR}_index.scss"
CSS_FONT_URL="${GITHUB_URL_BASE}${GITHUB_OUTPUT_DIR}${GITHUB_THEME_DIR}_fonts.scss"
CSS_DARK_URL="${GITHUB_URL_BASE}${GITHUB_OUTPUT_DIR}${GITHUB_THEME_DIR}_dark.scss"
CSS_LIGHT_URL="${GITHUB_URL_BASE}${GITHUB_OUTPUT_DIR}${GITHUB_THEME_DIR}_light.scss"
CSS_OVERRIDE_URL="${GITHUB_URL_BASE}${GITHUB_OVERRIDE_DIR}${GITHUB_THEME_DIR}_index.scss"
README_URL="${GITHUB_URL_BASE}${GITHUB_OVERRIDE_DIR}${GITHUB_THEME_DIR}README.md"
PULSE=$(curl -o /dev/null --silent -lw '%{http_code}' "${CSS_INDEX_URL}")
if [ "${PULSE}" = "200" ]; then
echo_ok "Theme '${THEME}' found. Preparing to fetch files..."
else
if [ "${PULSE}" = "404" ]; then
echo_err "Theme '${THEME}' not found. Please check the compatibility list." 1>&2
exit 1
else
echo_err "Something weird happened. If this issue persists, please open an Issue on GitHub." !>&2
exit 1
fi
fi
echo "Cleaning theme directory..."
rm -rf ${THEME_DIR}
echo "Creating theme directory..."
mkdir -p ${THEME_DIR}/overrides
echo "Fetching theme files..."
curl -s -S -o ${THEME_DIR}/_index.scss "${CSS_INDEX_URL}"
curl -s -S -o ${THEME_DIR}/_fonts.scss "${CSS_FONT_URL}"
curl -s -S -o ${THEME_DIR}/_dark.scss "${CSS_DARK_URL}"
curl -s -S -o ${THEME_DIR}/_light.scss "${CSS_LIGHT_URL}"
curl -s -S -o ${THEME_DIR}/overrides/_index.scss "${CSS_OVERRIDE_URL}"
echo "Fetching README file..."
curl -s -S -o ${THEME_DIR}/README.md "${README_URL}"
echo "Checking theme files..."
if test -f ${THEME_DIR}/_index.scss; then
echo_ok "_index.scss exists"
else
echo_err "_index.scss missing" 1>&2
exit 1
fi
if test -f ${THEME_DIR}/_fonts.scss; then
echo_ok "_fonts.scss exists"
else
echo_err "_fonts.scss missing" 1>&2
exit 1
fi
if test -f ${THEME_DIR}/_dark.scss; then
echo_ok "_dark.scss exists"
else
echo_err "_dark.scss missing" 1>&2
exit 1
fi
if test -f ${THEME_DIR}/_light.scss; then
echo_ok "_light.scss exists"
else
echo_err "_light.scss missing" 1>&2
exit 1
fi
if test -f ${THEME_DIR}/overrides/_index.scss; then
echo_ok "overrides/_index.scss exists"
else
echo_err "overrides/_index.scss missing" 1>&2
exit 1
fi
if test -f ${THEME_DIR}/README.md; then
echo_ok "README file exists"
else
echo_warn "README file missing"
fi
echo "Verifying setup..."
if grep -q '^@use "./themes";' ${THEME_DIR}/../custom.scss; then
# Import already present in custom.scss
echo_warn "Theme import line already present in custom.scss. Skipping..."
else
# Add `@use "./themes";` import to custom.scss
sed -ir 's#@use "./base.scss";#@use "./base.scss";\n@use "./themes";#' ${THEME_DIR}/../custom.scss
echo_info "Added import line to custom.scss..."
fi
echo_ok "Finished fetching and applying theme '${THEME}'."

View File

@ -161,18 +161,6 @@ document.addEventListener("nav", () => {
}) })
``` ```
You can also add the equivalent of a `beforeunload` event for [[SPA Routing]] via the `prenav` event.
```ts
document.addEventListener("prenav", () => {
// executed after an SPA navigation is triggered but
// before the page is replaced
// one usage pattern is to store things in sessionStorage
// in the prenav and then conditionally load then in the consequent
// nav
})
```
It is best practice to track any event handlers via `window.addCleanup` to prevent memory leaks. It is best practice to track any event handlers via `window.addCleanup` to prevent memory leaks.
This will get called on page navigation. This will get called on page navigation.

View File

@ -25,11 +25,10 @@ The following sections will go into detail for what methods can be implemented f
- `BuildCtx` is defined in `quartz/ctx.ts`. It consists of - `BuildCtx` is defined in `quartz/ctx.ts`. It consists of
- `argv`: The command line arguments passed to the Quartz [[build]] command - `argv`: The command line arguments passed to the Quartz [[build]] command
- `cfg`: The full Quartz [[configuration]] - `cfg`: The full Quartz [[configuration]]
- `allSlugs`: a list of all the valid content slugs (see [[paths]] for more information on what a slug is) - `allSlugs`: a list of all the valid content slugs (see [[paths]] for more information on what a `ServerSlug` is)
- `StaticResources` is defined in `quartz/resources.tsx`. It consists of - `StaticResources` is defined in `quartz/resources.tsx`. It consists of
- `css`: a list of CSS style definitions that should be loaded. A CSS style is described with the `CSSResource` type which is also defined in `quartz/resources.tsx`. It accepts either a source URL or the inline content of the stylesheet. - `css`: a list of CSS style definitions that should be loaded. A CSS style is described with the `CSSResource` type which is also defined in `quartz/resources.tsx`. It accepts either a source URL or the inline content of the stylesheet.
- `js`: a list of scripts that should be loaded. A script is described with the `JSResource` type which is also defined in `quartz/resources.tsx`. It allows you to define a load time (either before or after the DOM has been loaded), whether it should be a module, and either the source URL or the inline content of the script. - `js`: a list of scripts that should be loaded. A script is described with the `JSResource` type which is also defined in `quartz/resources.tsx`. It allows you to define a load time (either before or after the DOM has been loaded), whether it should be a module, and either the source URL or the inline content of the script.
- `additionalHead`: a list of JSX elements or functions that return JSX elements to be added to the `<head>` tag of the page. Functions receive the page's data as an argument and can conditionally render elements.
## Transformers ## Transformers
@ -38,7 +37,7 @@ Transformers **map** over content, taking a Markdown file and outputting modifie
```ts ```ts
export type QuartzTransformerPluginInstance = { export type QuartzTransformerPluginInstance = {
name: string name: string
textTransform?: (ctx: BuildCtx, src: string) => string textTransform?: (ctx: BuildCtx, src: string | Buffer) => string | Buffer
markdownPlugins?: (ctx: BuildCtx) => PluggableList markdownPlugins?: (ctx: BuildCtx) => PluggableList
htmlPlugins?: (ctx: BuildCtx) => PluggableList htmlPlugins?: (ctx: BuildCtx) => PluggableList
externalResources?: (ctx: BuildCtx) => Partial<StaticResources> externalResources?: (ctx: BuildCtx) => Partial<StaticResources>
@ -100,6 +99,8 @@ export const Latex: QuartzTransformerPlugin<Options> = (opts?: Options) => {
}, },
], ],
} }
} else {
return {}
} }
}, },
} }
@ -221,26 +222,12 @@ export type QuartzEmitterPlugin<Options extends OptionType = undefined> = (
export type QuartzEmitterPluginInstance = { export type QuartzEmitterPluginInstance = {
name: string name: string
emit( emit(ctx: BuildCtx, content: ProcessedContent[], resources: StaticResources): Promise<FilePath[]>
ctx: BuildCtx,
content: ProcessedContent[],
resources: StaticResources,
): Promise<FilePath[]> | AsyncGenerator<FilePath>
partialEmit?(
ctx: BuildCtx,
content: ProcessedContent[],
resources: StaticResources,
changeEvents: ChangeEvent[],
): Promise<FilePath[]> | AsyncGenerator<FilePath> | null
getQuartzComponents(ctx: BuildCtx): QuartzComponent[] getQuartzComponents(ctx: BuildCtx): QuartzComponent[]
} }
``` ```
An emitter plugin must define a `name` field, an `emit` function, and a `getQuartzComponents` function. It can optionally implement a `partialEmit` function for incremental builds. An emitter plugin must define a `name` field, an `emit` function, and a `getQuartzComponents` function. `emit` is responsible for looking at all the parsed and filtered content and then appropriately creating files and returning a list of paths to files the plugin created.
- `emit` is responsible for looking at all the parsed and filtered content and then appropriately creating files and returning a list of paths to files the plugin created.
- `partialEmit` is an optional function that enables incremental builds. It receives information about which files have changed (`changeEvents`) and can selectively rebuild only the necessary files. This is useful for optimizing build times in development mode. If `partialEmit` is undefined, it will default to the `emit` function.
- `getQuartzComponents` declares which Quartz components the emitter uses to construct its pages.
Creating new files can be done via regular Node [fs module](https://nodejs.org/api/fs.html) (i.e. `fs.cp` or `fs.writeFile`) or via the `write` function in `quartz/plugins/emitters/helpers.ts` if you are creating files that contain text. `write` has the following signature: Creating new files can be done via regular Node [fs module](https://nodejs.org/api/fs.html) (i.e. `fs.cp` or `fs.writeFile`) or via the `write` function in `quartz/plugins/emitters/helpers.ts` if you are creating files that contain text. `write` has the following signature:
@ -249,7 +236,7 @@ export type WriteOptions = (data: {
// the build context // the build context
ctx: BuildCtx ctx: BuildCtx
// the name of the file to emit (not including the file extension) // the name of the file to emit (not including the file extension)
slug: FullSlug slug: ServerSlug
// the file extension // the file extension
ext: `.${string}` | "" ext: `.${string}` | ""
// the file content to add // the file content to add

View File

@ -35,8 +35,6 @@ Some common frontmatter fields that are natively supported by Quartz:
- `draft`: Whether to publish the page or not. This is one way to make [[private pages|pages private]] in Quartz. - `draft`: Whether to publish the page or not. This is one way to make [[private pages|pages private]] in Quartz.
- `date`: A string representing the day the note was published. Normally uses `YYYY-MM-DD` format. - `date`: A string representing the day the note was published. Normally uses `YYYY-MM-DD` format.
See [[Frontmatter]] for a complete list of frontmatter.
## Syncing your Content ## Syncing your Content
When your Quartz is at a point you're happy with, you can save your changes to GitHub. When your Quartz is at a point you're happy with, you can save your changes to GitHub.

View File

@ -41,12 +41,11 @@ This part of the configuration concerns anything that can affect the whole site.
- `ignorePatterns`: a list of [glob](<https://en.wikipedia.org/wiki/Glob_(programming)>) patterns that Quartz should ignore and not search through when looking for files inside the `content` folder. See [[private pages]] for more details. - `ignorePatterns`: a list of [glob](<https://en.wikipedia.org/wiki/Glob_(programming)>) patterns that Quartz should ignore and not search through when looking for files inside the `content` folder. See [[private pages]] for more details.
- `defaultDateType`: whether to use created, modified, or published as the default date to display on pages and page listings. - `defaultDateType`: whether to use created, modified, or published as the default date to display on pages and page listings.
- `theme`: configure how the site looks. - `theme`: configure how the site looks.
- `cdnCaching`: if `true` (default), use Google CDN to cache the fonts. This will generally be faster. Disable (`false`) this if you want Quartz to download the fonts to be self-contained. - `cdnCaching`: If `true` (default), use Google CDN to cache the fonts. This will generally will be faster. Disable (`false`) this if you want Quartz to download the fonts to be self-contained.
- `typography`: what fonts to use. Any font available on [Google Fonts](https://fonts.google.com/) works here. - `typography`: what fonts to use. Any font available on [Google Fonts](https://fonts.google.com/) works here.
- `title`: font for the title of the site (optional, same as `header` by default) - `header`: Font to use for headers
- `header`: font to use for headers - `code`: Font for inline and block quotes.
- `code`: font for inline and block quotes - `body`: Font for everything
- `body`: font for everything
- `colors`: controls the theming of the site. - `colors`: controls the theming of the site.
- `light`: page background - `light`: page background
- `lightgray`: borders - `lightgray`: borders
@ -109,25 +108,3 @@ Some plugins are included by default in the [`quartz.config.ts`](https://github.
You can see a list of all plugins and their configuration options [[tags/plugin|here]]. You can see a list of all plugins and their configuration options [[tags/plugin|here]].
If you'd like to make your own plugins, see the [[making plugins|making custom plugins]] guide. If you'd like to make your own plugins, see the [[making plugins|making custom plugins]] guide.
## Fonts
Fonts can be specified as a `string` or a `FontSpecification`:
```ts
// string
typography: {
header: "Schibsted Grotesk",
...
}
// FontSpecification
typography: {
header: {
name: "Schibsted Grotesk",
weights: [400, 700],
includeItalic: true,
},
...
}
```

View File

@ -1,31 +0,0 @@
---
title: Citations
tags:
- feature/transformer
---
Quartz uses [rehype-citation](https://github.com/timlrx/rehype-citation) to support parsing of a BibTex bibliography file.
Under the default configuration, a citation key `[@templeton2024scaling]` will be exported as `(Templeton et al., 2024)`.
> [!example]- BibTex file
>
> ```bib title="bibliography.bib"
> @article{templeton2024scaling,
> title={Scaling Monosemanticity: Extracting Interpretable Features from Claude 3 Sonnet},
> author={Templeton, Adly and Conerly, Tom and Marcus, Jonathan and Lindsey, Jack and Bricken, Trenton and Chen, Brian and Pearce, Adam and Citro, Craig and Ameisen, Emmanuel and Jones, Andy and Cunningham, Hoagy and Turner, Nicholas L and McDougall, Callum and MacDiarmid, Monte and Freeman, C. Daniel and Sumers, Theodore R. and Rees, Edward and Batson, Joshua and Jermyn, Adam and Carter, Shan and Olah, Chris and Henighan, Tom},
> year={2024},
> journal={Transformer Circuits Thread},
> url={https://transformer-circuits.pub/2024/scaling-monosemanticity/index.html}
> }
> ```
> [!note] Behaviour of references
>
> By default, the references will be included at the end of the file. To control where the references to be included, uses `[^ref]`
>
> Refer to `rehype-citation` docs for more information.
## Customization
Citation parsing is a functionality of the [[plugins/Citations|Citation]] plugin. **This plugin is not enabled by default**. See the plugin page for customization options.

View File

@ -3,5 +3,5 @@ Quartz comes shipped with a Docker image that will allow you to preview your Qua
You can run the below one-liner to run Quartz in Docker. You can run the below one-liner to run Quartz in Docker.
```sh ```sh
docker run --rm -itp 8080:8080 -p 3001:3001 -v ./content:/usr/src/app/content $(docker build -q .) docker run --rm -itp 8080:8080 $(docker build -q .)
``` ```

View File

@ -1,10 +1,5 @@
Quartz emits an RSS feed for all the content on your site by generating an `index.xml` file that RSS readers can subscribe to. Because of the RSS spec, this requires the `baseUrl` property in your [[configuration]] to be set properly for RSS readers to pick it up properly. Quartz emits an RSS feed for all the content on your site by generating an `index.xml` file that RSS readers can subscribe to. Because of the RSS spec, this requires the `baseUrl` property in your [[configuration]] to be set properly for RSS readers to pick it up properly.
> [!info]
> After deploying, the generated RSS link will be available at `https://${baseUrl}/index.xml` by default.
>
> The `index.xml` path can be customized by passing the `rssSlug` option to the [[ContentIndex]] plugin.
## Configuration ## Configuration
This functionality is provided by the [[ContentIndex]] plugin. See the plugin page for customization options. This functionality is provided by the [[ContentIndex]] plugin. See the plugin page for customization options.

View File

@ -27,10 +27,12 @@ Component.Explorer({
folderClickBehavior: "collapse", // what happens when you click a folder ("link" to navigate to folder page on click or "collapse" to collapse folder on click) folderClickBehavior: "collapse", // what happens when you click a folder ("link" to navigate to folder page on click or "collapse" to collapse folder on click)
folderDefaultState: "collapsed", // default state of folders ("collapsed" or "open") folderDefaultState: "collapsed", // default state of folders ("collapsed" or "open")
useSavedState: true, // whether to use local storage to save "state" (which folders are opened) of explorer useSavedState: true, // whether to use local storage to save "state" (which folders are opened) of explorer
// omitted but shown later // Sort order: folders first, then files. Sort folders and files alphabetically
sortFn: ..., sortFn: (a, b) => {
filterFn: ..., ... // default implementation shown later
mapFn: ..., },
filterFn: filterFn: (node) => node.name !== "tags", // filters out 'tags' folder
mapFn: undefined,
// what order to apply functions in // what order to apply functions in
order: ["filter", "map", "sort"], order: ["filter", "map", "sort"],
}) })
@ -52,23 +54,17 @@ Want to customize it even more?
## Advanced customization ## Advanced customization
This component allows you to fully customize all of its behavior. You can pass a custom `sort`, `filter` and `map` function. This component allows you to fully customize all of its behavior. You can pass a custom `sort`, `filter` and `map` function.
All functions you can pass work with the `FileTrieNode` class, which has the following properties: All functions you can pass work with the `FileNode` class, which has the following properties:
```ts title="quartz/components/Explorer.tsx" ```ts title="quartz/components/ExplorerNode.tsx" {2-5}
class FileTrieNode { export class FileNode {
isFolder: boolean children: FileNode[] // children of current node
children: Array<FileTrieNode> name: string // last part of slug
data: ContentDetails | null displayName: string // what actually should be displayed in the explorer
} file: QuartzPluginData | null // if node is a file, this is the file's metadata. See `QuartzPluginData` for more detail
``` depth: number // depth of current node
```ts title="quartz/plugins/emitters/contentIndex.tsx" ... // rest of implementation
export type ContentDetails = {
slug: FullSlug
title: string
links: SimpleSlug[]
tags: string[]
content: string
} }
``` ```
@ -78,14 +74,15 @@ Every function you can pass is optional. By default, only a `sort` function will
// Sort order: folders first, then files. Sort folders and files alphabetically // Sort order: folders first, then files. Sort folders and files alphabetically
Component.Explorer({ Component.Explorer({
sortFn: (a, b) => { sortFn: (a, b) => {
if ((!a.isFolder && !b.isFolder) || (a.isFolder && b.isFolder)) { if ((!a.file && !b.file) || (a.file && b.file)) {
// sensitivity: "base": Only strings that differ in base letters compare as unequal. Examples: a ≠ b, a = á, a = A
// numeric: true: Whether numeric collation should be used, such that "1" < "2" < "10"
return a.displayName.localeCompare(b.displayName, undefined, { return a.displayName.localeCompare(b.displayName, undefined, {
numeric: true, numeric: true,
sensitivity: "base", sensitivity: "base",
}) })
} }
if (a.file && !b.file) {
if (!a.isFolder && b.isFolder) {
return 1 return 1
} else { } else {
return -1 return -1
@ -103,23 +100,41 @@ For more information on how to use `sort`, `filter` and `map`, you can check [Ar
Type definitions look like this: Type definitions look like this:
```ts ```ts
type SortFn = (a: FileTrieNode, b: FileTrieNode) => number sortFn: (a: FileNode, b: FileNode) => number
type FilterFn = (node: FileTrieNode) => boolean filterFn: (node: FileNode) => boolean
type MapFn = (node: FileTrieNode) => void mapFn: (node: FileNode) => void
``` ```
> [!tip]
> You can check if a `FileNode` is a folder or a file like this:
>
> ```ts
> if (node.file) {
> // node is a file
> } else {
> // node is a folder
> }
> ```
## Basic examples ## Basic examples
These examples show the basic usage of `sort`, `map` and `filter`. These examples show the basic usage of `sort`, `map` and `filter`.
### Use `sort` to put files first ### Use `sort` to put files first
Using this example, the explorer will alphabetically sort everything. Using this example, the explorer will alphabetically sort everything, but put all **files** above all **folders**.
```ts title="quartz.layout.ts" ```ts title="quartz.layout.ts"
Component.Explorer({ Component.Explorer({
sortFn: (a, b) => { sortFn: (a, b) => {
return a.displayName.localeCompare(b.displayName) if ((!a.file && !b.file) || (a.file && b.file)) {
return a.displayName.localeCompare(b.displayName)
}
if (a.file && !b.file) {
return -1
} else {
return 1
}
}, },
}) })
``` ```
@ -131,43 +146,43 @@ Using this example, the display names of all `FileNodes` (folders + files) will
```ts title="quartz.layout.ts" ```ts title="quartz.layout.ts"
Component.Explorer({ Component.Explorer({
mapFn: (node) => { mapFn: (node) => {
return (node.displayName = node.displayName.toUpperCase()) node.displayName = node.displayName.toUpperCase()
}, },
}) })
``` ```
### Remove list of elements (`filter`) ### Remove list of elements (`filter`)
Using this example, you can remove elements from your explorer by providing an array of folders/files to exclude. Using this example, you can remove elements from your explorer by providing an array of folders/files using the `omit` set.
Note that this example filters on the title but you can also do it via slug or any other field available on `FileTrieNode`.
```ts title="quartz.layout.ts" ```ts title="quartz.layout.ts"
Component.Explorer({ Component.Explorer({
filterFn: (node) => { filterFn: (node) => {
// set containing names of everything you want to filter out // set containing names of everything you want to filter out
const omit = new Set(["authoring content", "tags", "hosting"]) const omit = new Set(["authoring content", "tags", "hosting"])
return !omit.has(node.data.title.toLowerCase()) return !omit.has(node.name.toLowerCase())
}, },
}) })
``` ```
You can customize this by changing the entries of the `omit` set. Simply add all folder or file names you want to remove.
### Remove files by tag ### Remove files by tag
You can access the tags of a file by `node.data.tags`. You can access the frontmatter of a file by `node.file?.frontmatter?`. This allows you to filter out files based on their frontmatter, for example by their tags.
```ts title="quartz.layout.ts" ```ts title="quartz.layout.ts"
Component.Explorer({ Component.Explorer({
filterFn: (node) => { filterFn: (node) => {
// exclude files with the tag "explorerexclude" // exclude files with the tag "explorerexclude"
return node.data.tags.includes("explorerexclude") !== true return node.file?.frontmatter?.tags?.includes("explorerexclude") !== true
}, },
}) })
``` ```
### Show every element in explorer ### Show every element in explorer
By default, the explorer will filter out the `tags` folder. To override the default filter function that removes the `tags` folder from the explorer, you can set the filter function to `undefined`.
To override the default filter function, you can set the filter function to `undefined`.
```ts title="quartz.layout.ts" ```ts title="quartz.layout.ts"
Component.Explorer({ Component.Explorer({
@ -179,12 +194,10 @@ Component.Explorer({
> [!tip] > [!tip]
> When writing more complicated functions, the `layout` file can start to look very cramped. > When writing more complicated functions, the `layout` file can start to look very cramped.
> You can fix this by defining your sort functions outside of the component > You can fix this by defining your functions in another file.
> and passing it in.
> >
> ```ts title="quartz.layout.ts" > ```ts title="functions.ts"
> import { Options } from "./quartz/components/ExplorerNode" > import { Options } from "./quartz/components/ExplorerNode"
>
> export const mapFn: Options["mapFn"] = (node) => { > export const mapFn: Options["mapFn"] = (node) => {
> // implement your function here > // implement your function here
> } > }
@ -194,12 +207,16 @@ Component.Explorer({
> export const sortFn: Options["sortFn"] = (a, b) => { > export const sortFn: Options["sortFn"] = (a, b) => {
> // implement your function here > // 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({ > Component.Explorer({
> // ... your other options > mapFn: mapFn,
> mapFn, > filterFn: filterFn,
> filterFn, > sortFn: sortFn,
> sortFn,
> }) > })
> ``` > ```
@ -210,11 +227,93 @@ To add emoji prefixes (📁 for folders, 📄 for files), you could use a map fu
```ts title="quartz.layout.ts" ```ts title="quartz.layout.ts"
Component.Explorer({ Component.Explorer({
mapFn: (node) => { mapFn: (node) => {
if (node.isFolder) { // dont change name of root node
node.displayName = "📁 " + node.displayName if (node.depth > 0) {
} else { // set emoji for file/folder
node.displayName = "📄 " + node.displayName if (node.file) {
node.displayName = "📄 " + node.displayName
} else {
node.displayName = "📁 " + node.displayName
}
} }
}, },
}) })
``` ```
### Putting it all together
In this example, we're going to customize the explorer by using functions from examples above to [[#Add emoji prefix | add emoji prefixes]], [[#remove-list-of-elements-filter| filter out some folders]] and [[#use-sort-to-put-files-first | sort with files above folders]].
```ts title="quartz.layout.ts"
Component.Explorer({
filterFn: sampleFilterFn,
mapFn: sampleMapFn,
sortFn: sampleSortFn,
order: ["filter", "sort", "map"],
})
```
Notice how we customized the `order` array here. This is done because the default order applies the `sort` function last. While this normally works well, it would cause unintended behavior here, since we changed the first characters of all display names. In our example, `sort` would be applied based off the emoji prefix instead of the first _real_ character.
To fix this, we just changed around the order and apply the `sort` function before changing the display names in the `map` function.
### Use `sort` with pre-defined sort order
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.
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).
```ts title="quartz.layout.ts"
Component.Explorer({
sortFn: (a, b) => {
const nameOrderMap: Record<string, number> = {
"poetry-folder": 100,
"essay-folder": 200,
"research-paper-file": 201,
"dinosaur-fossils-file": 300,
"other-folder": 400,
}
let orderA = 0
let orderB = 0
if (a.file && a.file.slug) {
orderA = nameOrderMap[a.file.slug] || 0
} else if (a.name) {
orderA = nameOrderMap[a.name] || 0
}
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

@ -36,7 +36,6 @@ Component.Graph({
opacityScale: 1, // how quickly do we fade out the labels when zooming out? opacityScale: 1, // how quickly do we fade out the labels when zooming out?
removeTags: [], // what tags to remove from the graph removeTags: [], // what tags to remove from the graph
showTags: true, // whether to show tags in the graph showTags: true, // whether to show tags in the graph
enableRadial: false, // whether to constrain the graph, similar to Obsidian
}, },
globalGraph: { globalGraph: {
drag: true, drag: true,
@ -50,7 +49,6 @@ Component.Graph({
opacityScale: 1, opacityScale: 1,
removeTags: [], // what tags to remove from the graph removeTags: [], // what tags to remove from the graph
showTags: true, // whether to show tags in the graph showTags: true, // whether to show tags in the graph
enableRadial: true, // whether to constrain the graph, similar to Obsidian
}, },
}) })
``` ```

View File

@ -2,18 +2,400 @@
title: "Social Media Preview Cards" title: "Social Media Preview Cards"
--- ---
A lot of social media platforms can display a rich preview for your website when sharing a link (most notably, a cover image, a title and a description). A lot of social media platforms can display a rich preview for your website when sharing a link (most notably, a cover image, a title and a description). Quartz automatically handles most of this for you with reasonable defaults, but for more control, you can customize these by setting [[social images#Frontmatter Properties]].
Quartz can also dynamically generate and use new cover images for every page to be used in link previews on social media for you. To get started with this, set `generateSocialImages: true` in `quartz.config.ts`.
Quartz can also dynamically generate and use new cover images for every page to be used in link previews on social media for you.
## Showcase ## Showcase
After enabling the [[CustomOgImages]] emitter plugin, the social media link preview for [[authoring content | Authoring Content]] looks like this: After enabling `generateSocialImages` in `quartz.config.ts`, the social media link preview for [[authoring content | Authoring Content]] looks like this:
| Light | Dark | | Light | Dark |
| ----------------------------------- | ---------------------------------- | | ----------------------------------- | ---------------------------------- |
| ![[social-image-preview-light.png]] | ![[social-image-preview-dark.png]] | | ![[social-image-preview-light.png]] | ![[social-image-preview-dark.png]] |
## Configuration For testing, it is recommended to use [opengraph.xyz](https://www.opengraph.xyz/) to see what the link to your page will look like on various platforms (more info under [[social images#local testing]]).
This functionality is provided by the [[CustomOgImages]] plugin. See the plugin page for customization options. ## Customization
You can customize how images will be generated in the quartz config.
For example, here's what the default configuration looks like if you set `generateSocialImages: true`:
```typescript title="quartz.config.ts"
generateSocialImages: {
colorScheme: "lightMode", // what colors to use for generating image, same as theme colors from config, valid values are "darkMode" and "lightMode"
width: 1200, // width to generate with (in pixels)
height: 630, // height to generate with (in pixels)
excludeRoot: false, // wether to exclude "/" index path to be excluded from auto generated images (false = use auto, true = use default og image)
}
```
---
### Frontmatter Properties
> [!tip] Hint
>
> Overriding social media preview properties via frontmatter still works even if `generateSocialImages` is disabled.
The following properties can be used to customize your link previews:
| Property | Alias | Summary |
| ------------------- | ---------------- | ----------------------------------- |
| `socialDescription` | `description` | Description to be used for preview. |
| `socialImage` | `image`, `cover` | Link to preview image. |
The `socialImage` property should contain a link to an image relative to `quartz/static`. If you have a folder for all your images in `quartz/static/my-images`, an example for `socialImage` could be `"my-images/cover.png"`.
> [!info] Info
>
> The priority for what image will be used for the cover image looks like the following: `frontmatter property > generated image (if enabled) > default image`.
>
> The default image (`quartz/static/og-image.png`) will only be used as a fallback if nothing else is set. If `generateSocialImages` is enabled, it will be treated as the new default per page, but can be overwritten by setting the `socialImage` frontmatter property for that page.
---
### Fully customized image generation
You can fully customize how the images being generated look by passing your own component to `generateSocialImages.imageStructure`. This component takes html/css + some page metadata/config options and converts it to an image using [satori](https://github.com/vercel/satori). Vercel provides an [online playground](https://og-playground.vercel.app/) that can be used to preview how your html/css looks like as a picture. This is ideal for prototyping your custom design.
It is recommended to write your own image components in `quartz/util/og.tsx` or any other `.tsx` file, as passing them to the config won't work otherwise. An example of the default image component can be found in `og.tsx` in `defaultImage()`.
> [!tip] Hint
>
> Satori only supports a subset of all valid CSS properties. All supported properties can be found in their [documentation](https://github.com/vercel/satori#css).
Your custom image component should have the `SocialImageOptions["imageStructure"]` type, to make development easier for you. Using a component of this type, you will be passed the following variables:
```ts
imageStructure: (
cfg: GlobalConfiguration, // global Quartz config (useful for getting theme colors and other info)
userOpts: UserOpts, // options passed to `generateSocialImage`
title: string, // title of current page
description: string, // description of current page
fonts: SatoriOptions["fonts"], // header + body font
) => JSXInternal.Element
```
Now, you can let your creativity flow and design your own image component! For reference and some cool tips, you can check how the markup for the default image looks.
> [!example] Examples
>
> Here are some examples for markup you may need to get started:
>
> - Get a theme color
>
> `cfg.theme.colors[colorScheme].<colorName>`, where `<colorName>` corresponds to a key in `ColorScheme` (defined at the top of `quartz/util/theme.ts`)
>
> - Use the page title/description
>
> `<p>{title}</p>`/`<p>{description}</p>`
>
> - Use a font family
>
> Detailed in the Fonts chapter below
---
### Fonts
You will also be passed an array containing a header and a body font (where the first entry is header and the second is body). The fonts matches the ones selected in `theme.typography.header` and `theme.typography.body` from `quartz.config.ts` and will be passed in the format required by [`satori`](https://github.com/vercel/satori). To use them in CSS, use the `.name` property (e.g. `fontFamily: fonts[1].name` to use the "body" font family).
An example of a component using the header font could look like this:
```tsx title="socialImage.tsx"
export const myImage: SocialImageOptions["imageStructure"] = (...) => {
return <p style={{ fontFamily: fonts[0].name }}>Cool Header!</p>
}
```
> [!example]- Local fonts
>
> For cases where you use a local fonts under `static` folder, make sure to set the correct `@font-face` in `custom.scss`
>
> ```scss title="custom.scss"
> @font-face {
> font-family: "Newsreader";
> font-style: normal;
> font-weight: normal;
> font-display: swap;
> src: url("/static/Newsreader.woff2") format("woff2");
> }
> ```
>
> Then in `quartz/util/og.tsx`, you can load the satori fonts like so:
>
> ```tsx title="quartz/util/og.tsx"
> const headerFont = joinSegments("static", "Newsreader.woff2")
> const bodyFont = joinSegments("static", "Newsreader.woff2")
>
> export async function getSatoriFont(cfg: GlobalConfiguration): Promise<SatoriOptions["fonts"]> {
> const headerWeight: FontWeight = 700
> const bodyWeight: FontWeight = 400
>
> const url = new URL(`https://${cfg.baseUrl ?? "example.com"}`)
>
> const [header, body] = await Promise.all(
> [headerFont, bodyFont].map((font) =>
> fetch(`${url.toString()}/${font}`).then((res) => res.arrayBuffer()),
> ),
> )
>
> return [
> { name: cfg.theme.typography.header, data: header, weight: headerWeight, style: "normal" },
> { name: cfg.theme.typography.body, data: body, weight: bodyWeight, style: "normal" },
> ]
> }
> ```
>
> This font then can be used with your custom structure
### Local testing
To test how the full preview of your page is going to look even before deploying, you can forward the port you're serving quartz on. In VSCode, this can easily be achieved following [this guide](https://code.visualstudio.com/docs/editor/port-forwarding) (make sure to set `Visibility` to `public` if testing on external tools like [opengraph.xyz](https://www.opengraph.xyz/)).
If you have `generateSocialImages` enabled, you can check out all generated images under `public/static/social-images`.
## Technical info
Images will be generated as `.webp` files, which helps to keep images small (the average image takes ~`19kB`). They are also compressed further using [sharp](https://sharp.pixelplumbing.com/).
When using images, the appropriate [Open Graph](https://ogp.me/) and [Twitter](https://developer.twitter.com/en/docs/twitter-for-websites/cards/guides/getting-started) meta tags will be set to ensure they work and look as expected.
## Examples
Besides the template for the default image generation (found under `quartz/util/og.tsx`), you can also add your own! To do this, you can either edit the source code of that file (not recommended) or create a new one (e.g. `customSocialImage.tsx`, source shown below).
After adding that file, you can update `quartz.config.ts` to use your image generation template as follows:
```ts
// Import component at start of file
import { customImage } from "./quartz/util/customSocialImage.tsx"
// In main config
const config: QuartzConfig = {
...
generateSocialImages: {
...
imageStructure: customImage, // tells quartz to use your component when generating images
},
}
```
The following example will generate images that look as follows:
| Light | Dark |
| ------------------------------------------ | ----------------------------------------- |
| ![[custom-social-image-preview-light.png]] | ![[custom-social-image-preview-dark.png]] |
This example (and the default template) use colors and fonts from your theme specified in the quartz config. Fonts get passed in as a prop, where `fonts[0]` will contain the header font and `fonts[1]` will contain the body font (more info in the [[#fonts]] section).
```tsx
import { SatoriOptions } from "satori/wasm"
import { GlobalConfiguration } from "../cfg"
import { SocialImageOptions, UserOpts } from "./imageHelper"
import { QuartzPluginData } from "../plugins/vfile"
export const customImage: SocialImageOptions["imageStructure"] = (
cfg: GlobalConfiguration,
userOpts: UserOpts,
title: string,
description: string,
fonts: SatoriOptions["fonts"],
fileData: QuartzPluginData,
) => {
// How many characters are allowed before switching to smaller font
const fontBreakPoint = 22
const useSmallerFont = title.length > fontBreakPoint
const { colorScheme } = userOpts
return (
<div
style={{
display: "flex",
flexDirection: "row",
justifyContent: "flex-start",
alignItems: "center",
height: "100%",
width: "100%",
}}
>
<div
style={{
display: "flex",
alignItems: "center",
justifyContent: "center",
height: "100%",
width: "100%",
backgroundColor: cfg.theme.colors[colorScheme].light,
flexDirection: "column",
gap: "2.5rem",
paddingTop: "2rem",
paddingBottom: "2rem",
}}
>
<p
style={{
color: cfg.theme.colors[colorScheme].dark,
fontSize: useSmallerFont ? 70 : 82,
marginLeft: "4rem",
textAlign: "center",
marginRight: "4rem",
fontFamily: fonts[0].name,
}}
>
{title}
</p>
<p
style={{
color: cfg.theme.colors[colorScheme].dark,
fontSize: 44,
marginLeft: "8rem",
marginRight: "8rem",
lineClamp: 3,
fontFamily: fonts[1].name,
}}
>
{description}
</p>
</div>
<div
style={{
height: "100%",
width: "2vw",
position: "absolute",
backgroundColor: cfg.theme.colors[colorScheme].tertiary,
opacity: 0.85,
}}
/>
</div>
)
}
```
> [!example]- Advanced example
>
> The following example includes a customized social image with a custom background and formatted date.
>
> ```typescript title="custom-og.tsx"
> export const og: SocialImageOptions["Component"] = (
> cfg: GlobalConfiguration,
> fileData: QuartzPluginData,
> { colorScheme }: Options,
> title: string,
> description: string,
> fonts: SatoriOptions["fonts"],
> ) => {
> let created: string | undefined
> let reading: string | undefined
> if (fileData.dates) {
> created = formatDate(getDate(cfg, fileData)!, cfg.locale)
> }
> const { minutes, text: _timeTaken, words: _words } = readingTime(fileData.text!)
> reading = i18n(cfg.locale).components.contentMeta.readingTime({
> minutes: Math.ceil(minutes),
> })
>
> const Li = [created, reading]
>
> return (
> <div
> style={{
> position: "relative",
> display: "flex",
> flexDirection: "row",
> alignItems: "flex-start",
> height: "100%",
> width: "100%",
> backgroundImage: `url("https://${cfg.baseUrl}/static/og-image.jpeg")`,
> backgroundSize: "100% 100%",
> }}
> >
> <div
> style={{
> position: "absolute",
> top: 0,
> left: 0,
> right: 0,
> bottom: 0,
> background: "radial-gradient(circle at center, transparent, rgba(0, 0, 0, 0.4) 70%)",
> }}
> />
> <div
> style={{
> display: "flex",
> height: "100%",
> width: "100%",
> flexDirection: "column",
> justifyContent: "flex-start",
> alignItems: "flex-start",
> gap: "1.5rem",
> paddingTop: "4rem",
> paddingBottom: "4rem",
> marginLeft: "4rem",
> }}
> >
> <img
> src={`"https://${cfg.baseUrl}/static/icon.jpeg"`}
> style={{
> position: "relative",
> backgroundClip: "border-box",
> borderRadius: "6rem",
> }}
> width={80}
> />
> <div
> style={{
> display: "flex",
> flexDirection: "column",
> textAlign: "left",
> fontFamily: fonts[0].name,
> }}
> >
> <h2
> style={{
> color: cfg.theme.colors[colorScheme].light,
> fontSize: "3rem",
> fontWeight: 700,
> marginRight: "4rem",
> fontFamily: fonts[0].name,
> }}
> >
> {title}
> </h2>
> <ul
> style={{
> color: cfg.theme.colors[colorScheme].gray,
> gap: "1rem",
> fontSize: "1.5rem",
> fontFamily: fonts[1].name,
> }}
> >
> {Li.map((item, index) => {
> if (item) {
> return <li key={index}>{item}</li>
> }
> })}
> </ul>
> </div>
> <p
> style={{
> color: cfg.theme.colors[colorScheme].light,
> fontSize: "1.5rem",
> overflow: "hidden",
> marginRight: "8rem",
> textOverflow: "ellipsis",
> display: "-webkit-box",
> WebkitLineClamp: 7,
> WebkitBoxOrient: "vertical",
> lineClamp: 7,
> fontFamily: fonts[1].name,
> }}
> >
> {description}
> </p>
> </div>
> </div>
> )
> }
> ```

View File

@ -31,13 +31,13 @@ If you prefer instructions in a video format you can try following Nicole van de
## 🔧 Features ## 🔧 Features
- [[Obsidian compatibility]], [[full-text search]], [[graph view]], note transclusion, [[wikilinks]], [[backlinks]], [[features/Latex|Latex]], [[syntax highlighting]], [[popover previews]], [[Docker Support]], [[i18n|internationalization]], [[comments]] and [many more](./features/) right out of the box - [[Obsidian compatibility]], [[full-text search]], [[graph view]], note transclusion, [[wikilinks]], [[backlinks]], [[features/Latex|Latex]], [[syntax highlighting]], [[popover previews]], [[Docker Support]], [[i18n|internationalization]], [[comments]] and [many more](./features) right out of the box
- Hot-reload on configuration edits and incremental rebuilds for content edits - Hot-reload for both configuration and content
- Simple JSX layouts and [[creating components|page components]] - Simple JSX layouts and [[creating components|page components]]
- [[SPA Routing|Ridiculously fast page loads]] and tiny bundle sizes - [[SPA Routing|Ridiculously fast page loads]] and tiny bundle sizes
- Fully-customizable parsing, filtering, and page generation through [[making plugins|plugins]] - Fully-customizable parsing, filtering, and page generation through [[making plugins|plugins]]
For a comprehensive list of features, visit the [features page](./features/). You can read more about the _why_ behind these features on the [[philosophy]] page and a technical overview on the [[architecture]] page. For a comprehensive list of features, visit the [features page](/features). You can read more about the _why_ behind these features on the [[philosophy]] page and a technical overview on the [[architecture]] page.
### 🚧 Troubleshooting + Updating ### 🚧 Troubleshooting + Updating

View File

@ -1,62 +0,0 @@
---
title: Higher-Order Layout Components
---
Quartz provides several higher-order components that help with layout composition and responsive design. These components wrap other components to add additional functionality or modify their behavior.
## `Flex` Component
The `Flex` component creates a [flexible box layout](https://developer.mozilla.org/en-US/docs/Web/CSS/flex) that can arrange child components in various ways. It's particularly useful for creating responsive layouts and organizing components in rows or columns.
```typescript
type FlexConfig = {
components: {
Component: QuartzComponent
grow?: boolean // whether component should grow to fill space
shrink?: boolean // whether component should shrink if needed
basis?: string // initial main size of the component
order?: number // order in flex container
align?: "start" | "end" | "center" | "stretch" // cross-axis alignment
justify?: "start" | "end" | "center" | "between" | "around" // main-axis alignment
}[]
direction?: "row" | "row-reverse" | "column" | "column-reverse"
wrap?: "nowrap" | "wrap" | "wrap-reverse"
gap?: string
}
```
### Example Usage
```typescript
Component.Flex({
components: [
{
Component: Component.Search(),
grow: true, // Search will grow to fill available space
},
{ Component: Component.Darkmode() }, // Darkmode keeps its natural size
],
direction: "row",
gap: "1rem",
})
```
## `MobileOnly` Component
The `MobileOnly` component is a wrapper that makes its child component only visible on mobile devices. This is useful for creating responsive layouts where certain components should only appear on smaller screens.
### Example Usage
```typescript
Component.MobileOnly(Component.Spacer())
```
## `DesktopOnly` Component
The `DesktopOnly` component is the counterpart to `MobileOnly`. It makes its child component only visible on desktop devices. This helps create responsive layouts where certain components should only appear on larger screens.
### Example Usage
```typescript
Component.DesktopOnly(Component.TableOfContents())
```

View File

@ -35,9 +35,7 @@ These correspond to following parts of the page:
Quartz **components**, like plugins, can take in additional properties as configuration options. If you're familiar with React terminology, you can think of them as Higher-order Components. Quartz **components**, like plugins, can take in additional properties as configuration options. If you're familiar with React terminology, you can think of them as Higher-order Components.
See [a list of all the components](component.md) for all available components along with their configuration options. Additionally, Quartz provides several built-in higher-order components for layout composition - see [[layout-components]] for more details. See [a list of all the components](component.md) for all available components along with their configuration options. You can also checkout the guide on [[creating components]] if you're interested in further customizing the behaviour of Quartz.
You can also checkout the guide on [[creating components]] if you're interested in further customizing the behaviour of Quartz.
### Layout breakpoints ### Layout breakpoints

View File

@ -1,24 +0,0 @@
---
title: "Citations"
tags:
- plugin/transformer
---
This plugin adds Citation support to Quartz.
> [!note]
> For information on how to add, remove or configure plugins, see the [[configuration#Plugins|Configuration]] page.
This plugin accepts the following configuration options:
- `bibliographyFile`: the path to the bibliography file. Defaults to `./bibliography.bib`. This is relative to git source of your vault.
- `suppressBibliography`: whether to suppress the bibliography at the end of the document. Defaults to `false`.
- `linkCitations`: whether to link citations to the bibliography. Defaults to `false`.
- `csl`: the citation style to use. Defaults to `apa`. Reference [rehype-citation](https://rehype-citation.netlify.app/custom-csl) for more options.
- `prettyLink`: whether to use pretty links for citations. Defaults to `true`.
## API
- Category: Transformer
- Function name: `Plugin.Citations()`.
- Source: [`quartz/plugins/transformers/citations.ts`](https://github.com/jackyzha0/quartz/blob/v4/quartz/plugins/transformers/citations.ts).

View File

@ -17,7 +17,6 @@ This plugin accepts the following configuration options:
- `enableRSS`: If `true` (default), produces an RSS feed (`index.xml`) with recent content updates. - `enableRSS`: If `true` (default), produces an RSS feed (`index.xml`) with recent content updates.
- `rssLimit`: Defines the maximum number of entries to include in the RSS feed, helping to focus on the most recent or relevant content. Defaults to `10`. - `rssLimit`: Defines the maximum number of entries to include in the RSS feed, helping to focus on the most recent or relevant content. Defaults to `10`.
- `rssFullHtml`: If `true`, the RSS feed includes full HTML content. Otherwise it includes just summaries. - `rssFullHtml`: If `true`, the RSS feed includes full HTML content. Otherwise it includes just summaries.
- `rssSlug`: Slug to the generated RSS feed XML file. Defaults to `"index"`.
- `includeEmptyFiles`: If `true` (default), content files with no body text are included in the generated index and resources. - `includeEmptyFiles`: If `true` (default), content files with no body text are included in the generated index and resources.
## API ## API

View File

@ -13,8 +13,6 @@ This plugin accepts the following configuration options:
- `priority`: The data sources to consult for date information. Highest priority first. Possible values are `"frontmatter"`, `"git"`, and `"filesystem"`. Defaults to `["frontmatter", "git", "filesystem"]`. - `priority`: The data sources to consult for date information. Highest priority first. Possible values are `"frontmatter"`, `"git"`, and `"filesystem"`. Defaults to `["frontmatter", "git", "filesystem"]`.
When loading the frontmatter, the value of [[Frontmatter#List]] is used.
> [!warning] > [!warning]
> If you rely on `git` for dates, make sure `defaultDateType` is set to `modified` in `quartz.config.ts`. > If you rely on `git` for dates, make sure `defaultDateType` is set to `modified` in `quartz.config.ts`.
> >

View File

@ -1,360 +0,0 @@
---
title: Custom OG Images
tags:
- feature/emitter
---
The Custom OG Images emitter plugin generates social media preview images for your pages. It uses [satori](https://github.com/vercel/satori) to convert HTML/CSS into images, allowing you to create beautiful and consistent social media preview cards for your content.
> [!note]
> For information on how to add, remove or configure plugins, see the [[configuration#Plugins|Configuration]] page.
## Features
- Automatically generates social media preview images for each page
- Supports both light and dark mode themes
- Customizable through frontmatter properties
- Fallback to default image when needed
- Full control over image design through custom components
## Configuration
> [!info] Info
>
> The `baseUrl` property in your [[configuration]] must be set properly for social images to work correctly, as they require absolute paths.
This plugin accepts the following configuration options:
```typescript title="quartz.config.ts"
import { CustomOgImages } from "./quartz/plugins/emitters/ogImage"
const config: QuartzConfig = {
plugins: {
emitters: [
CustomOgImages({
colorScheme: "lightMode", // what colors to use for generating image, same as theme colors from config, valid values are "darkMode" and "lightMode"
width: 1200, // width to generate with (in pixels)
height: 630, // height to generate with (in pixels)
excludeRoot: false, // wether to exclude "/" index path to be excluded from auto generated images (false = use auto, true = use default og image)
imageStructure: defaultImage, // custom image component to use
}),
],
},
}
```
### Configuration Options
| Option | Type | Default | Description |
| ---------------- | --------- | ------------ | ----------------------------------------------------------------- |
| `colorScheme` | string | "lightMode" | Theme to use for generating images ("darkMode" or "lightMode") |
| `width` | number | 1200 | Width of the generated image in pixels |
| `height` | number | 630 | Height of the generated image in pixels |
| `excludeRoot` | boolean | false | Whether to exclude the root index page from auto-generated images |
| `imageStructure` | component | defaultImage | Custom component to use for image generation |
## Frontmatter Properties
The following properties can be used to customize your link previews:
| Property | Alias | Summary |
| ------------------- | ---------------- | ----------------------------------- |
| `socialDescription` | `description` | Description to be used for preview. |
| `socialImage` | `image`, `cover` | Link to preview image. |
The `socialImage` property should contain a link to an image relative to `quartz/static`. If you have a folder for all your images in `quartz/static/my-images`, an example for `socialImage` could be `"my-images/cover.png"`.
> [!info] Info
>
> The priority for what image will be used for the cover image looks like the following: `frontmatter property > generated image (if enabled) > default image`.
>
> The default image (`quartz/static/og-image.png`) will only be used as a fallback if nothing else is set. If the Custom OG Images emitter plugin is enabled, it will be treated as the new default per page, but can be overwritten by setting the `socialImage` frontmatter property for that page.
## Customization
You can fully customize how the images being generated look by passing your own component to `imageStructure`. This component takes JSX + some page metadata/config options and converts it to an image using [satori](https://github.com/vercel/satori). Vercel provides an [online playground](https://og-playground.vercel.app/) that can be used to preview how your JSX looks like as a picture. This is ideal for prototyping your custom design.
### Fonts
You will also be passed an array containing a header and a body font (where the first entry is header and the second is body). The fonts matches the ones selected in `theme.typography.header` and `theme.typography.body` from `quartz.config.ts` and will be passed in the format required by [`satori`](https://github.com/vercel/satori). To use them in CSS, use the `.name` property (e.g. `fontFamily: fonts[1].name` to use the "body" font family).
An example of a component using the header font could look like this:
```tsx title="socialImage.tsx"
export const myImage: SocialImageOptions["imageStructure"] = (...) => {
return <p style={{ fontFamily: fonts[0].name }}>Cool Header!</p>
}
```
> [!example]- Local fonts
>
> For cases where you use a local fonts under `static` folder, make sure to set the correct `@font-face` in `custom.scss`
>
> ```scss title="custom.scss"
> @font-face {
> font-family: "Newsreader";
> font-style: normal;
> font-weight: normal;
> font-display: swap;
> src: url("/static/Newsreader.woff2") format("woff2");
> }
> ```
>
> Then in `quartz/util/og.tsx`, you can load the Satori fonts like so:
>
> ```tsx title="quartz/util/og.tsx"
> import { joinSegments, QUARTZ } from "../path"
> import fs from "fs"
> import path from "path"
>
> const newsreaderFontPath = joinSegments(QUARTZ, "static", "Newsreader.woff2")
> export async function getSatoriFonts(headerFont: FontSpecification, bodyFont: FontSpecification) {
> // ... rest of implementation remains same
> const fonts: SatoriOptions["fonts"] = [
> ...headerFontData.map((data, idx) => ({
> name: headerFontName,
> data,
> weight: headerWeights[idx],
> style: "normal" as const,
> })),
> ...bodyFontData.map((data, idx) => ({
> name: bodyFontName,
> data,
> weight: bodyWeights[idx],
> style: "normal" as const,
> })),
> {
> name: "Newsreader",
> data: await fs.promises.readFile(path.resolve(newsreaderFontPath)),
> weight: 400,
> style: "normal" as const,
> },
> ]
>
> return fonts
> }
> ```
>
> This font then can be used with your custom structure.
## Examples
Here are some example image components you can use as a starting point:
### Basic Example
This example will generate images that look as follows:
| Light | Dark |
| ------------------------------------------ | ----------------------------------------- |
| ![[custom-social-image-preview-light.png]] | ![[custom-social-image-preview-dark.png]] |
```tsx
import { SatoriOptions } from "satori/wasm"
import { GlobalConfiguration } from "../cfg"
import { SocialImageOptions, UserOpts } from "./imageHelper"
import { QuartzPluginData } from "../plugins/vfile"
export const customImage: SocialImageOptions["imageStructure"] = (
cfg: GlobalConfiguration,
userOpts: UserOpts,
title: string,
description: string,
fonts: SatoriOptions["fonts"],
fileData: QuartzPluginData,
) => {
// How many characters are allowed before switching to smaller font
const fontBreakPoint = 22
const useSmallerFont = title.length > fontBreakPoint
const { colorScheme } = userOpts
return (
<div
style={{
display: "flex",
flexDirection: "row",
justifyContent: "flex-start",
alignItems: "center",
height: "100%",
width: "100%",
}}
>
<div
style={{
display: "flex",
alignItems: "center",
justifyContent: "center",
height: "100%",
width: "100%",
backgroundColor: cfg.theme.colors[colorScheme].light,
flexDirection: "column",
gap: "2.5rem",
paddingTop: "2rem",
paddingBottom: "2rem",
}}
>
<p
style={{
color: cfg.theme.colors[colorScheme].dark,
fontSize: useSmallerFont ? 70 : 82,
marginLeft: "4rem",
textAlign: "center",
marginRight: "4rem",
fontFamily: fonts[0].name,
}}
>
{title}
</p>
<p
style={{
color: cfg.theme.colors[colorScheme].dark,
fontSize: 44,
marginLeft: "8rem",
marginRight: "8rem",
lineClamp: 3,
fontFamily: fonts[1].name,
}}
>
{description}
</p>
</div>
<div
style={{
height: "100%",
width: "2vw",
position: "absolute",
backgroundColor: cfg.theme.colors[colorScheme].tertiary,
opacity: 0.85,
}}
/>
</div>
)
}
```
### Advanced Example
The following example includes a customized social image with a custom background and formatted date:
```typescript title="custom-og.tsx"
export const og: SocialImageOptions["Component"] = (
cfg: GlobalConfiguration,
fileData: QuartzPluginData,
{ colorScheme }: Options,
title: string,
description: string,
fonts: SatoriOptions["fonts"],
) => {
let created: string | undefined
let reading: string | undefined
if (fileData.dates) {
created = formatDate(getDate(cfg, fileData)!, cfg.locale)
}
const { minutes, text: _timeTaken, words: _words } = readingTime(fileData.text!)
reading = i18n(cfg.locale).components.contentMeta.readingTime({
minutes: Math.ceil(minutes),
})
const Li = [created, reading]
return (
<div
style={{
position: "relative",
display: "flex",
flexDirection: "row",
alignItems: "flex-start",
height: "100%",
width: "100%",
backgroundImage: `url("https://${cfg.baseUrl}/static/og-image.jpeg")`,
backgroundSize: "100% 100%",
}}
>
<div
style={{
position: "absolute",
top: 0,
left: 0,
right: 0,
bottom: 0,
background: "radial-gradient(circle at center, transparent, rgba(0, 0, 0, 0.4) 70%)",
}}
/>
<div
style={{
display: "flex",
height: "100%",
width: "100%",
flexDirection: "column",
justifyContent: "flex-start",
alignItems: "flex-start",
gap: "1.5rem",
paddingTop: "4rem",
paddingBottom: "4rem",
marginLeft: "4rem",
}}
>
<img
src={`"https://${cfg.baseUrl}/static/icon.jpeg"`}
style={{
position: "relative",
backgroundClip: "border-box",
borderRadius: "6rem",
}}
width={80}
/>
<div
style={{
display: "flex",
flexDirection: "column",
textAlign: "left",
fontFamily: fonts[0].name,
}}
>
<h2
style={{
color: cfg.theme.colors[colorScheme].light,
fontSize: "3rem",
fontWeight: 700,
marginRight: "4rem",
fontFamily: fonts[0].name,
}}
>
{title}
</h2>
<ul
style={{
color: cfg.theme.colors[colorScheme].gray,
gap: "1rem",
fontSize: "1.5rem",
fontFamily: fonts[1].name,
}}
>
{Li.map((item, index) => {
if (item) {
return <li key={index}>{item}</li>
}
})}
</ul>
</div>
<p
style={{
color: cfg.theme.colors[colorScheme].light,
fontSize: "1.5rem",
overflow: "hidden",
marginRight: "8rem",
textOverflow: "ellipsis",
display: "-webkit-box",
WebkitLineClamp: 7,
WebkitBoxOrient: "vertical",
lineClamp: 7,
fontFamily: fonts[1].name,
}}
>
{description}
</p>
</div>
</div>
)
}
```

View File

@ -17,54 +17,6 @@ This plugin accepts the following configuration options:
> [!warning] > [!warning]
> This plugin must not be removed, otherwise Quartz will break. > This plugin must not be removed, otherwise Quartz will break.
## List
Quartz supports the following frontmatter:
- title
- `title`
- description
- `description`
- permalink
- `permalink`
- comments
- `comments`
- lang
- `lang`
- publish
- `publish`
- draft
- `draft`
- enableToc
- `enableToc`
- tags
- `tags`
- `tag`
- aliases
- `aliases`
- `alias`
- cssclasses
- `cssclasses`
- `cssclass`
- socialDescription
- `socialDescription`
- socialImage
- `socialImage`
- `image`
- `cover`
- created
- `created`
- `date`
- modified
- `modified`
- `lastmod`
- `updated`
- `last-modified`
- published
- `published`
- `publishDate`
- `date`
## API ## API
- Category: Transformer - Category: Transformer

View File

@ -32,3 +32,5 @@ Want to see what Quartz can do? Here are some cool community gardens:
- [🌓 Projects & Privacy - FOSS, tech, law](https://be-far.com) - [🌓 Projects & Privacy - FOSS, tech, law](https://be-far.com)
- [Zen Browser Docs](https://docs.zen-browser.app) - [Zen Browser Docs](https://docs.zen-browser.app)
- [🪴8cat life](https://8cat.life) - [🪴8cat life](https://8cat.life)
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)!

2
index.d.ts vendored
View File

@ -5,10 +5,8 @@ declare module "*.scss" {
// dom custom event // dom custom event
interface CustomEventMap { interface CustomEventMap {
prenav: CustomEvent<{}>
nav: CustomEvent<{ url: FullSlug }> nav: CustomEvent<{ url: FullSlug }>
themechange: CustomEvent<{ theme: "light" | "dark" }> themechange: CustomEvent<{ theme: "light" | "dark" }>
} }
type ContentIndex = Record<FullSlug, ContentDetails>
declare const fetchData: Promise<ContentIndex> declare const fetchData: Promise<ContentIndex>

1622
package-lock.json generated

File diff suppressed because it is too large Load Diff

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.5.0", "version": "4.4.0",
"type": "module", "type": "module",
"author": "jackyzha0 <j.zhao2k19@gmail.com>", "author": "jackyzha0 <j.zhao2k19@gmail.com>",
"license": "MIT", "license": "MIT",
@ -16,12 +16,12 @@
"docs": "npx quartz build --serve -d docs", "docs": "npx quartz build --serve -d docs",
"check": "tsc --noEmit && npx prettier . --check", "check": "tsc --noEmit && npx prettier . --check",
"format": "npx prettier . --write", "format": "npx prettier . --write",
"test": "tsx --test", "test": "tsx ./quartz/util/path.test.ts && tsx ./quartz/depgraph.test.ts",
"profile": "0x -D prof ./quartz/bootstrap-cli.mjs build --concurrency=1" "profile": "0x -D prof ./quartz/bootstrap-cli.mjs build --concurrency=1"
}, },
"engines": { "engines": {
"npm": ">=9.3.1", "npm": ">=9.3.1",
"node": ">=20" "node": "20 || >=22"
}, },
"keywords": [ "keywords": [
"site generator", "site generator",
@ -35,12 +35,11 @@
"quartz": "./quartz/bootstrap-cli.mjs" "quartz": "./quartz/bootstrap-cli.mjs"
}, },
"dependencies": { "dependencies": {
"@clack/prompts": "^0.10.0", "@clack/prompts": "^0.9.0",
"@floating-ui/dom": "^1.6.13", "@floating-ui/dom": "^1.6.12",
"@myriaddreamin/rehype-typst": "^0.5.4", "@myriaddreamin/rehype-typst": "^0.5.4",
"@napi-rs/simple-git": "0.1.19", "@napi-rs/simple-git": "0.1.19",
"@tweenjs/tween.js": "^25.0.0", "@tweenjs/tween.js": "^25.0.0",
"ansi-truncate": "^1.2.0",
"async-mutex": "^0.5.0", "async-mutex": "^0.5.0",
"chalk": "^5.4.1", "chalk": "^5.4.1",
"chokidar": "^4.0.3", "chokidar": "^4.0.3",
@ -49,46 +48,45 @@
"esbuild-sass-plugin": "^3.3.1", "esbuild-sass-plugin": "^3.3.1",
"flexsearch": "0.7.43", "flexsearch": "0.7.43",
"github-slugger": "^2.0.0", "github-slugger": "^2.0.0",
"globby": "^14.1.0", "globby": "^14.0.2",
"gray-matter": "^4.0.3", "gray-matter": "^4.0.3",
"hast-util-to-html": "^9.0.5", "hast-util-to-html": "^9.0.4",
"hast-util-to-jsx-runtime": "^2.3.6", "hast-util-to-jsx-runtime": "^2.3.2",
"hast-util-to-string": "^3.0.1", "hast-util-to-string": "^3.0.1",
"is-absolute-url": "^4.0.1", "is-absolute-url": "^4.0.1",
"js-yaml": "^4.1.0", "js-yaml": "^4.1.0",
"lightningcss": "^1.29.2", "lightningcss": "^1.28.2",
"mdast-util-find-and-replace": "^3.0.2", "mdast-util-find-and-replace": "^3.0.1",
"mdast-util-to-hast": "^13.2.0", "mdast-util-to-hast": "^13.2.0",
"mdast-util-to-string": "^4.0.0", "mdast-util-to-string": "^4.0.0",
"micromorph": "^0.4.5", "micromorph": "^0.4.5",
"minimatch": "^10.0.1", "pixi.js": "^8.6.6",
"pixi.js": "^8.8.1", "preact": "^10.25.4",
"preact": "^10.26.4", "preact-render-to-string": "^6.5.12",
"preact-render-to-string": "^6.5.13",
"pretty-bytes": "^6.1.1", "pretty-bytes": "^6.1.1",
"pretty-time": "^1.1.0", "pretty-time": "^1.1.0",
"reading-time": "^1.5.0", "reading-time": "^1.5.0",
"rehype-autolink-headings": "^7.1.0", "rehype-autolink-headings": "^7.1.0",
"rehype-citation": "^2.2.2", "rehype-citation": "^2.2.2",
"rehype-katex": "^7.0.1", "rehype-katex": "^7.0.1",
"rehype-mathjax": "^7.1.0", "rehype-mathjax": "^6.0.0",
"rehype-pretty-code": "^0.14.0", "rehype-pretty-code": "^0.14.0",
"rehype-raw": "^7.0.0", "rehype-raw": "^7.0.0",
"rehype-slug": "^6.0.0", "rehype-slug": "^6.0.0",
"remark": "^15.0.1", "remark": "^15.0.1",
"remark-breaks": "^4.0.0", "remark-breaks": "^4.0.0",
"remark-frontmatter": "^5.0.0", "remark-frontmatter": "^5.0.0",
"remark-gfm": "^4.0.1", "remark-gfm": "^4.0.0",
"remark-math": "^6.0.0", "remark-math": "^6.0.0",
"remark-parse": "^11.0.0", "remark-parse": "^11.0.0",
"remark-rehype": "^11.1.1", "remark-rehype": "^11.1.1",
"remark-smartypants": "^3.0.2", "remark-smartypants": "^3.0.2",
"rfdc": "^1.4.1", "rfdc": "^1.4.1",
"rimraf": "^6.0.1", "rimraf": "^6.0.1",
"satori": "^0.12.1", "satori": "^0.12.0",
"serve-handler": "^6.1.6", "serve-handler": "^6.1.6",
"sharp": "^0.33.5", "sharp": "^0.33.5",
"shiki": "^1.26.2", "shiki": "^1.24.4",
"source-map-support": "^0.5.21", "source-map-support": "^0.5.21",
"to-vfile": "^8.0.0", "to-vfile": "^8.0.0",
"toml": "^3.0.0", "toml": "^3.0.0",
@ -96,21 +94,22 @@
"unist-util-visit": "^5.0.0", "unist-util-visit": "^5.0.0",
"vfile": "^6.0.3", "vfile": "^6.0.3",
"workerpool": "^9.2.0", "workerpool": "^9.2.0",
"ws": "^8.18.1", "ws": "^8.18.0",
"yargs": "^17.7.2" "yargs": "^17.7.2"
}, },
"devDependencies": { "devDependencies": {
"@types/cli-spinner": "^0.2.3",
"@types/d3": "^7.4.3", "@types/d3": "^7.4.3",
"@types/hast": "^3.0.4", "@types/hast": "^3.0.4",
"@types/js-yaml": "^4.0.9", "@types/js-yaml": "^4.0.9",
"@types/node": "^22.13.10", "@types/node": "^22.10.2",
"@types/pretty-time": "^1.1.5", "@types/pretty-time": "^1.1.5",
"@types/source-map-support": "^0.5.10", "@types/source-map-support": "^0.5.10",
"@types/ws": "^8.18.0", "@types/ws": "^8.5.13",
"@types/yargs": "^17.0.33", "@types/yargs": "^17.0.33",
"esbuild": "^0.25.1", "esbuild": "^0.24.2",
"prettier": "^3.5.3", "prettier": "^3.4.2",
"tsx": "^4.19.3", "tsx": "^4.19.2",
"typescript": "^5.8.2" "typescript": "^5.7.2"
} }
} }

View File

@ -2,30 +2,31 @@ import { QuartzConfig } from "./quartz/cfg"
import * as Plugin from "./quartz/plugins" import * as Plugin from "./quartz/plugins"
/** /**
* Quartz 4 Configuration * Quartz 4.0 Configuration
* *
* See https://quartz.jzhao.xyz/configuration for more information. * See https://quartz.jzhao.xyz/configuration for more information.
*/ */
const config: QuartzConfig = { const config: QuartzConfig = {
configuration: { configuration: {
pageTitle: "isuckatcode.lol", pageTitle: "🪴 Quartz 4.0",
pageTitleSuffix: " | isuckatcode.lol", pageTitleSuffix: "",
enableSPA: true, enableSPA: true,
enablePopovers: true, enablePopovers: true,
analytics: { analytics: {
provider: "plausible", provider: "plausible",
}, },
locale: "en-US", locale: "en-US",
baseUrl: "isuckatcode.lol", baseUrl: "quartz.jzhao.xyz",
ignorePatterns: ["private", "templates", ".obsidian"], ignorePatterns: ["private", "templates", ".obsidian"],
defaultDateType: "created", defaultDateType: "created",
generateSocialImages: false,
theme: { theme: {
fontOrigin: "googleFonts", fontOrigin: "googleFonts",
cdnCaching: true, cdnCaching: true,
typography: { typography: {
header: "Courier Prime", header: "Schibsted Grotesk",
body: "Roboto", body: "Source Sans Pro",
code: "Courier Prime", code: "IBM Plex Mono",
}, },
colors: { colors: {
lightMode: { lightMode: {
@ -57,7 +58,7 @@ const config: QuartzConfig = {
transformers: [ transformers: [
Plugin.FrontMatter(), Plugin.FrontMatter(),
Plugin.CreatedModifiedDate({ Plugin.CreatedModifiedDate({
priority: ["frontmatter", "git", "filesystem"], priority: ["frontmatter", "filesystem"],
}), }),
Plugin.SyntaxHighlighting({ Plugin.SyntaxHighlighting({
theme: { theme: {
@ -87,8 +88,6 @@ const config: QuartzConfig = {
Plugin.Assets(), Plugin.Assets(),
Plugin.Static(), Plugin.Static(),
Plugin.NotFoundPage(), Plugin.NotFoundPage(),
// Comment out CustomOgImages to speed up build time
Plugin.CustomOgImages(),
], ],
}, },
} }

View File

@ -25,16 +25,9 @@ export const defaultContentPageLayout: PageLayout = {
left: [ left: [
Component.PageTitle(), Component.PageTitle(),
Component.MobileOnly(Component.Spacer()), Component.MobileOnly(Component.Spacer()),
Component.Flex({ Component.Search(),
components: [ Component.Darkmode(),
{ Component.DesktopOnly(Component.Explorer()),
Component: Component.Search(),
grow: true,
},
{ Component: Component.Darkmode() },
],
}),
Component.Explorer(),
], ],
right: [ right: [
Component.Graph(), Component.Graph(),
@ -49,16 +42,9 @@ export const defaultListPageLayout: PageLayout = {
left: [ left: [
Component.PageTitle(), Component.PageTitle(),
Component.MobileOnly(Component.Spacer()), Component.MobileOnly(Component.Spacer()),
Component.Flex({ Component.Search(),
components: [ Component.Darkmode(),
{ Component.DesktopOnly(Component.Explorer()),
Component: Component.Search(),
grow: true,
},
{ Component: Component.Darkmode() },
],
}),
Component.Explorer(),
], ],
right: [], right: [],
} }

View File

@ -1,4 +1,4 @@
#!/usr/bin/env -S node --no-deprecation #!/usr/bin/env node
import yargs from "yargs" import yargs from "yargs"
import { hideBin } from "yargs/helpers" import { hideBin } from "yargs/helpers"
import { import {

View File

@ -9,7 +9,7 @@ import { parseMarkdown } from "./processors/parse"
import { filterContent } from "./processors/filter" import { filterContent } from "./processors/filter"
import { emitContent } from "./processors/emit" import { emitContent } from "./processors/emit"
import cfg from "../quartz.config" import cfg from "../quartz.config"
import { FilePath, joinSegments, slugifyFilePath } from "./util/path" import { FilePath, FullSlug, joinSegments, slugifyFilePath } from "./util/path"
import chokidar from "chokidar" import chokidar from "chokidar"
import { ProcessedContent } from "./plugins/vfile" import { ProcessedContent } from "./plugins/vfile"
import { Argv, BuildCtx } from "./util/ctx" import { Argv, BuildCtx } from "./util/ctx"
@ -17,39 +17,37 @@ import { glob, toPosixPath } from "./util/glob"
import { trace } from "./util/trace" import { trace } from "./util/trace"
import { options } from "./util/sourcemap" import { options } from "./util/sourcemap"
import { Mutex } from "async-mutex" import { Mutex } from "async-mutex"
import DepGraph from "./depgraph"
import { getStaticResourcesFromPlugins } from "./plugins" import { getStaticResourcesFromPlugins } from "./plugins"
import { randomIdNonSecure } from "./util/random"
import { ChangeEvent } from "./plugins/types"
import { minimatch } from "minimatch"
type ContentMap = Map< type Dependencies = Record<string, DepGraph<FilePath> | null>
FilePath,
| {
type: "markdown"
content: ProcessedContent
}
| {
type: "other"
}
>
type BuildData = { type BuildData = {
ctx: BuildCtx ctx: BuildCtx
ignored: GlobbyFilterFunction ignored: GlobbyFilterFunction
mut: Mutex mut: Mutex
contentMap: ContentMap initialSlugs: FullSlug[]
changesSinceLastBuild: Record<FilePath, ChangeEvent["type"]> // TODO merge contentMap and trackedAssets
contentMap: Map<FilePath, ProcessedContent>
trackedAssets: Set<FilePath>
toRebuild: Set<FilePath>
toRemove: Set<FilePath>
lastBuildMs: number lastBuildMs: number
dependencies: Dependencies
}
type FileEvent = "add" | "change" | "delete"
function newBuildId() {
return Math.random().toString(36).substring(2, 8)
} }
async function buildQuartz(argv: Argv, mut: Mutex, clientRefresh: () => void) { async function buildQuartz(argv: Argv, mut: Mutex, clientRefresh: () => void) {
const ctx: BuildCtx = { const ctx: BuildCtx = {
buildId: randomIdNonSecure(), buildId: newBuildId(),
argv, argv,
cfg, cfg,
allSlugs: [], allSlugs: [],
allFiles: [],
incremental: false,
} }
const perf = new PerfTimer() const perf = new PerfTimer()
@ -72,70 +70,64 @@ async function buildQuartz(argv: Argv, mut: Mutex, clientRefresh: () => void) {
perf.addEvent("glob") perf.addEvent("glob")
const allFiles = await glob("**/*.*", argv.directory, cfg.configuration.ignorePatterns) const allFiles = await glob("**/*.*", argv.directory, cfg.configuration.ignorePatterns)
const markdownPaths = allFiles.filter((fp) => fp.endsWith(".md")).sort() const fps = allFiles.filter((fp) => fp.endsWith(".md")).sort()
console.log( console.log(
`Found ${markdownPaths.length} input files from \`${argv.directory}\` in ${perf.timeSince("glob")}`, `Found ${fps.length} input files from \`${argv.directory}\` in ${perf.timeSince("glob")}`,
) )
const filePaths = markdownPaths.map((fp) => joinSegments(argv.directory, fp) as FilePath) const filePaths = fps.map((fp) => joinSegments(argv.directory, fp) as FilePath)
ctx.allFiles = allFiles
ctx.allSlugs = allFiles.map((fp) => slugifyFilePath(fp as FilePath)) ctx.allSlugs = allFiles.map((fp) => slugifyFilePath(fp as FilePath))
const parsedFiles = await parseMarkdown(ctx, filePaths) const parsedFiles = await parseMarkdown(ctx, filePaths)
const filteredContent = filterContent(ctx, parsedFiles) const filteredContent = filterContent(ctx, parsedFiles)
const dependencies: Record<string, DepGraph<FilePath> | null> = {}
// Only build dependency graphs if we're doing a fast rebuild
if (argv.fastRebuild) {
const staticResources = getStaticResourcesFromPlugins(ctx)
for (const emitter of cfg.plugins.emitters) {
dependencies[emitter.name] =
(await emitter.getDependencyGraph?.(ctx, filteredContent, staticResources)) ?? null
}
}
await emitContent(ctx, filteredContent) await emitContent(ctx, filteredContent)
console.log(chalk.green(`Done processing ${markdownPaths.length} files in ${perf.timeSince()}`)) console.log(chalk.green(`Done processing ${fps.length} files in ${perf.timeSince()}`))
release() release()
if (argv.watch) { if (argv.serve) {
ctx.incremental = true return startServing(ctx, mut, parsedFiles, clientRefresh, dependencies)
return startWatching(ctx, mut, parsedFiles, clientRefresh)
} }
} }
// setup watcher for rebuilds // setup watcher for rebuilds
async function startWatching( async function startServing(
ctx: BuildCtx, ctx: BuildCtx,
mut: Mutex, mut: Mutex,
initialContent: ProcessedContent[], initialContent: ProcessedContent[],
clientRefresh: () => void, clientRefresh: () => void,
dependencies: Dependencies, // emitter name: dep graph
) { ) {
const { argv, allFiles } = ctx const { argv } = ctx
const contentMap: ContentMap = new Map()
for (const filePath of allFiles) {
contentMap.set(filePath, {
type: "other",
})
}
// cache file parse results
const contentMap = new Map<FilePath, ProcessedContent>()
for (const content of initialContent) { for (const content of initialContent) {
const [_tree, vfile] = content const [_tree, vfile] = content
contentMap.set(vfile.data.relativePath!, { contentMap.set(vfile.data.filePath!, content)
type: "markdown",
content,
})
} }
const gitIgnoredMatcher = await isGitIgnored()
const buildData: BuildData = { const buildData: BuildData = {
ctx, ctx,
mut, mut,
dependencies,
contentMap, contentMap,
ignored: (path) => { ignored: await isGitIgnored(),
if (gitIgnoredMatcher(path)) return true initialSlugs: ctx.allSlugs,
const pathStr = path.toString() toRebuild: new Set<FilePath>(),
for (const pattern of cfg.configuration.ignorePatterns) { toRemove: new Set<FilePath>(),
if (minimatch(pathStr, pattern)) { trackedAssets: new Set<FilePath>(),
return true
}
}
return false
},
changesSinceLastBuild: {},
lastBuildMs: 0, lastBuildMs: 0,
} }
@ -145,37 +137,34 @@ async function startWatching(
ignoreInitial: true, ignoreInitial: true,
}) })
const changes: ChangeEvent[] = [] const buildFromEntry = argv.fastRebuild ? partialRebuildFromEntrypoint : rebuildFromEntrypoint
watcher watcher
.on("add", (fp) => { .on("add", (fp) => buildFromEntry(fp as string, "add", clientRefresh, buildData))
if (buildData.ignored(fp)) return .on("change", (fp) => buildFromEntry(fp as string, "change", clientRefresh, buildData))
changes.push({ path: fp as FilePath, type: "add" }) .on("unlink", (fp) => buildFromEntry(fp as string, "delete", clientRefresh, buildData))
void rebuild(changes, clientRefresh, buildData)
})
.on("change", (fp) => {
if (buildData.ignored(fp)) return
changes.push({ path: fp as FilePath, type: "change" })
void rebuild(changes, clientRefresh, buildData)
})
.on("unlink", (fp) => {
if (buildData.ignored(fp)) return
changes.push({ path: fp as FilePath, type: "delete" })
void rebuild(changes, clientRefresh, buildData)
})
return async () => { return async () => {
await watcher.close() await watcher.close()
} }
} }
async function rebuild(changes: ChangeEvent[], clientRefresh: () => void, buildData: BuildData) { async function partialRebuildFromEntrypoint(
const { ctx, contentMap, mut, changesSinceLastBuild } = buildData filepath: string,
action: FileEvent,
clientRefresh: () => void,
buildData: BuildData, // note: this function mutates buildData
) {
const { ctx, ignored, dependencies, contentMap, mut, toRemove } = buildData
const { argv, cfg } = ctx const { argv, cfg } = ctx
const buildId = randomIdNonSecure() // don't do anything for gitignored files
if (ignored(filepath)) {
return
}
const buildId = newBuildId()
ctx.buildId = buildId ctx.buildId = buildId
buildData.lastBuildMs = new Date().getTime() buildData.lastBuildMs = new Date().getTime()
const numChangesInBuild = changes.length
const release = await mut.acquire() const release = await mut.acquire()
// if there's another build after us, release and let them do it // if there's another build after us, release and let them do it
@ -185,105 +174,242 @@ async function rebuild(changes: ChangeEvent[], clientRefresh: () => void, buildD
} }
const perf = new PerfTimer() const perf = new PerfTimer()
perf.addEvent("rebuild")
console.log(chalk.yellow("Detected change, rebuilding...")) console.log(chalk.yellow("Detected change, rebuilding..."))
// update changesSinceLastBuild // UPDATE DEP GRAPH
for (const change of changes) { const fp = joinSegments(argv.directory, toPosixPath(filepath)) as FilePath
changesSinceLastBuild[change.path] = change.type
}
const staticResources = getStaticResourcesFromPlugins(ctx) const staticResources = getStaticResourcesFromPlugins(ctx)
const pathsToParse: FilePath[] = [] let processedFiles: ProcessedContent[] = []
for (const [fp, type] of Object.entries(changesSinceLastBuild)) {
if (type === "delete" || path.extname(fp) !== ".md") continue
const fullPath = joinSegments(argv.directory, toPosixPath(fp)) as FilePath
pathsToParse.push(fullPath)
}
const parsed = await parseMarkdown(ctx, pathsToParse) switch (action) {
for (const content of parsed) { case "add":
contentMap.set(content[1].data.relativePath!, { // add to cache when new file is added
type: "markdown", processedFiles = await parseMarkdown(ctx, [fp])
content, processedFiles.forEach(([tree, vfile]) => contentMap.set(vfile.data.filePath!, [tree, vfile]))
})
}
// update state using changesSinceLastBuild // update the dep graph by asking all emitters whether they depend on this file
// we do this weird play of add => compute change events => remove for (const emitter of cfg.plugins.emitters) {
// so that partialEmitters can do appropriate cleanup based on the content of deleted files const emitterGraph =
for (const [file, change] of Object.entries(changesSinceLastBuild)) { (await emitter.getDependencyGraph?.(ctx, processedFiles, staticResources)) ?? null
if (change === "delete") {
// universal delete case
contentMap.delete(file as FilePath)
}
// manually track non-markdown files as processed files only if (emitterGraph) {
// contains markdown files const existingGraph = dependencies[emitter.name]
if (change === "add" && path.extname(file) !== ".md") { if (existingGraph !== null) {
contentMap.set(file as FilePath, { existingGraph.mergeGraph(emitterGraph)
type: "other", } else {
}) // might be the first time we're adding a mardown file
} dependencies[emitter.name] = emitterGraph
} }
}
const changeEvents: ChangeEvent[] = Object.entries(changesSinceLastBuild).map(([fp, type]) => {
const path = fp as FilePath
const processedContent = contentMap.get(path)
if (processedContent?.type === "markdown") {
const [_tree, file] = processedContent.content
return {
type,
path,
file,
} }
} break
case "change":
// invalidate cache when file is changed
processedFiles = await parseMarkdown(ctx, [fp])
processedFiles.forEach(([tree, vfile]) => contentMap.set(vfile.data.filePath!, [tree, vfile]))
return { // only content files can have added/removed dependencies because of transclusions
type, if (path.extname(fp) === ".md") {
path, for (const emitter of cfg.plugins.emitters) {
} // get new dependencies from all emitters for this file
}) const emitterGraph =
(await emitter.getDependencyGraph?.(ctx, processedFiles, staticResources)) ?? null
// update allFiles and then allSlugs with the consistent view of content map // only update the graph if the emitter plugin uses the changed file
ctx.allFiles = Array.from(contentMap.keys()) // eg. Assets plugin ignores md files, so we skip updating the graph
ctx.allSlugs = ctx.allFiles.map((fp) => slugifyFilePath(fp as FilePath)) if (emitterGraph?.hasNode(fp)) {
const processedFiles = Array.from(contentMap.values()) // merge the new dependencies into the dep graph
.filter((file) => file.type === "markdown") dependencies[emitter.name]?.updateIncomingEdgesForNode(emitterGraph, fp)
.map((file) => file.content) }
}
}
break
case "delete":
toRemove.add(fp)
break
}
if (argv.verbose) {
console.log(`Updated dependency graphs in ${perf.timeSince()}`)
}
// EMIT
perf.addEvent("rebuild")
let emittedFiles = 0 let emittedFiles = 0
for (const emitter of cfg.plugins.emitters) { for (const emitter of cfg.plugins.emitters) {
// Try to use partialEmit if available, otherwise assume the output is static const depGraph = dependencies[emitter.name]
const emitFn = emitter.partialEmit ?? emitter.emit
const emitted = await emitFn(ctx, processedFiles, staticResources, changeEvents) // emitter hasn't defined a dependency graph. call it with all processed files
if (emitted === null) { if (depGraph === null) {
if (argv.verbose) {
console.log(
`Emitter ${emitter.name} doesn't define a dependency graph. Calling it with all files...`,
)
}
const files = [...contentMap.values()].filter(
([_node, vfile]) => !toRemove.has(vfile.data.filePath!),
)
const emittedFps = await emitter.emit(ctx, files, staticResources)
if (ctx.argv.verbose) {
for (const file of emittedFps) {
console.log(`[emit:${emitter.name}] ${file}`)
}
}
emittedFiles += emittedFps.length
continue continue
} }
if (Symbol.asyncIterator in emitted) { // only call the emitter if it uses this file
// Async generator case if (depGraph.hasNode(fp)) {
for await (const file of emitted) { // re-emit using all files that are needed for the downstream of this file
emittedFiles++ // eg. for ContentIndex, the dep graph could be:
if (ctx.argv.verbose) { // a.md --> contentIndex.json
console.log(`[emit:${emitter.name}] ${file}`) // b.md ------^
} //
} // if a.md changes, we need to re-emit contentIndex.json,
} else { // and supply [a.md, b.md] to the emitter
// Array case const upstreams = [...depGraph.getLeafNodeAncestors(fp)] as FilePath[]
emittedFiles += emitted.length
const upstreamContent = upstreams
// filter out non-markdown files
.filter((file) => contentMap.has(file))
// if file was deleted, don't give it to the emitter
.filter((file) => !toRemove.has(file))
.map((file) => contentMap.get(file)!)
const emittedFps = await emitter.emit(ctx, upstreamContent, staticResources)
if (ctx.argv.verbose) { if (ctx.argv.verbose) {
for (const file of emitted) { for (const file of emittedFps) {
console.log(`[emit:${emitter.name}] ${file}`) console.log(`[emit:${emitter.name}] ${file}`)
} }
} }
emittedFiles += emittedFps.length
} }
} }
console.log(`Emitted ${emittedFiles} files to \`${argv.output}\` in ${perf.timeSince("rebuild")}`) console.log(`Emitted ${emittedFiles} files to \`${argv.output}\` in ${perf.timeSince("rebuild")}`)
// CLEANUP
const destinationsToDelete = new Set<FilePath>()
for (const file of toRemove) {
// remove from cache
contentMap.delete(file)
Object.values(dependencies).forEach((depGraph) => {
// remove the node from dependency graphs
depGraph?.removeNode(file)
// remove any orphan nodes. eg if a.md is deleted, a.html is orphaned and should be removed
const orphanNodes = depGraph?.removeOrphanNodes()
orphanNodes?.forEach((node) => {
// only delete files that are in the output directory
if (node.startsWith(argv.output)) {
destinationsToDelete.add(node)
}
})
})
}
await rimraf([...destinationsToDelete])
console.log(chalk.green(`Done rebuilding in ${perf.timeSince()}`)) console.log(chalk.green(`Done rebuilding in ${perf.timeSince()}`))
changes.splice(0, numChangesInBuild)
toRemove.clear()
release()
clientRefresh() clientRefresh()
}
async function rebuildFromEntrypoint(
fp: string,
action: FileEvent,
clientRefresh: () => void,
buildData: BuildData, // note: this function mutates buildData
) {
const { ctx, ignored, mut, initialSlugs, contentMap, toRebuild, toRemove, trackedAssets } =
buildData
const { argv } = ctx
// don't do anything for gitignored files
if (ignored(fp)) {
return
}
// dont bother rebuilding for non-content files, just track and refresh
fp = toPosixPath(fp)
const filePath = joinSegments(argv.directory, fp) as FilePath
if (path.extname(fp) !== ".md") {
if (action === "add" || action === "change") {
trackedAssets.add(filePath)
} else if (action === "delete") {
trackedAssets.delete(filePath)
}
clientRefresh()
return
}
if (action === "add" || action === "change") {
toRebuild.add(filePath)
} else if (action === "delete") {
toRemove.add(filePath)
}
const buildId = newBuildId()
ctx.buildId = buildId
buildData.lastBuildMs = new Date().getTime()
const release = await mut.acquire()
// there's another build after us, release and let them do it
if (ctx.buildId !== buildId) {
release()
return
}
const perf = new PerfTimer()
console.log(chalk.yellow("Detected change, rebuilding..."))
try {
const filesToRebuild = [...toRebuild].filter((fp) => !toRemove.has(fp))
const parsedContent = await parseMarkdown(ctx, filesToRebuild)
for (const content of parsedContent) {
const [_tree, vfile] = content
contentMap.set(vfile.data.filePath!, content)
}
for (const fp of toRemove) {
contentMap.delete(fp)
}
const parsedFiles = [...contentMap.values()]
const filteredContent = filterContent(ctx, parsedFiles)
// re-update slugs
const trackedSlugs = [...new Set([...contentMap.keys(), ...toRebuild, ...trackedAssets])]
.filter((fp) => !toRemove.has(fp))
.map((fp) => slugifyFilePath(path.posix.relative(argv.directory, fp) as FilePath))
ctx.allSlugs = [...new Set([...initialSlugs, ...trackedSlugs])]
// TODO: we can probably traverse the link graph to figure out what's safe to delete here
// instead of just deleting everything
await rimraf(path.join(argv.output, ".*"), { glob: true })
await emitContent(ctx, filteredContent)
console.log(chalk.green(`Done rebuilding in ${perf.timeSince()}`))
} catch (err) {
console.log(chalk.yellow(`Rebuild failed. Waiting on a change to fix the error...`))
if (argv.verbose) {
console.log(chalk.red(err))
}
}
clientRefresh()
toRebuild.clear()
toRemove.clear()
release() release()
} }

View File

@ -2,6 +2,7 @@ import { ValidDateType } from "./components/Date"
import { QuartzComponent } from "./components/types" import { QuartzComponent } from "./components/types"
import { ValidLocale } from "./i18n" import { ValidLocale } from "./i18n"
import { PluginTypes } from "./plugins/types" import { PluginTypes } from "./plugins/types"
import { SocialImageOptions } from "./util/og"
import { Theme } from "./util/theme" import { Theme } from "./util/theme"
export type Analytics = export type Analytics =
@ -60,6 +61,10 @@ export interface GlobalConfiguration {
* Quartz will avoid using this as much as possible and use relative URLs most of the time * Quartz will avoid using this as much as possible and use relative URLs most of the time
*/ */
baseUrl?: string baseUrl?: string
/**
* Whether to generate social images (Open Graph and Twitter standard) for link previews
*/
generateSocialImages: boolean | Partial<SocialImageOptions>
theme: Theme theme: Theme
/** /**
* Allow to translate the date in the language of your choice. * Allow to translate the date in the language of your choice.

View File

@ -71,10 +71,10 @@ export const BuildArgv = {
default: false, default: false,
describe: "run a local server to live-preview your Quartz", describe: "run a local server to live-preview your Quartz",
}, },
watch: { fastRebuild: {
boolean: true, boolean: true,
default: false, default: false,
describe: "watch for changes and rebuild automatically", describe: "[experimental] rebuild only the changed files",
}, },
baseDir: { baseDir: {
string: true, string: true,

View File

@ -33,15 +33,6 @@ import {
cwd, cwd,
} from "./constants.js" } from "./constants.js"
/**
* Resolve content directory path
* @param contentPath path to resolve
*/
function resolveContentPath(contentPath) {
if (path.isAbsolute(contentPath)) return path.relative(cwd, contentPath)
return path.join(cwd, contentPath)
}
/** /**
* Handles `npx quartz create` * Handles `npx quartz create`
* @param {*} argv arguments for `create` * @param {*} argv arguments for `create`
@ -49,7 +40,7 @@ function resolveContentPath(contentPath) {
export async function handleCreate(argv) { export async function handleCreate(argv) {
console.log() console.log()
intro(chalk.bgGreen.black(` Quartz v${version} `)) intro(chalk.bgGreen.black(` Quartz v${version} `))
const contentFolder = resolveContentPath(argv.directory) const contentFolder = path.join(cwd, argv.directory)
let setupStrategy = argv.strategy?.toLowerCase() let setupStrategy = argv.strategy?.toLowerCase()
let linkResolutionStrategy = argv.links?.toLowerCase() let linkResolutionStrategy = argv.links?.toLowerCase()
const sourceDirectory = argv.source const sourceDirectory = argv.source
@ -225,10 +216,6 @@ See the [documentation](https://quartz.jzhao.xyz) for how to get started.
* @param {*} argv arguments for `build` * @param {*} argv arguments for `build`
*/ */
export async function handleBuild(argv) { export async function handleBuild(argv) {
if (argv.serve) {
argv.watch = true
}
console.log(chalk.bgGreen.black(`\n Quartz v${version} \n`)) console.log(chalk.bgGreen.black(`\n Quartz v${version} \n`))
const ctx = await esbuild.context({ const ctx = await esbuild.context({
entryPoints: [fp], entryPoints: [fp],
@ -335,10 +322,9 @@ export async function handleBuild(argv) {
clientRefresh() clientRefresh()
} }
let clientRefresh = () => {}
if (argv.serve) { if (argv.serve) {
const connections = [] const connections = []
clientRefresh = () => connections.forEach((conn) => conn.send("rebuild")) const clientRefresh = () => connections.forEach((conn) => conn.send("rebuild"))
if (argv.baseDir !== "" && !argv.baseDir.startsWith("/")) { if (argv.baseDir !== "" && !argv.baseDir.startsWith("/")) {
argv.baseDir = "/" + argv.baseDir argv.baseDir = "/" + argv.baseDir
@ -438,7 +424,6 @@ export async function handleBuild(argv) {
return serve() return serve()
}) })
server.listen(argv.port) server.listen(argv.port)
const wss = new WebSocketServer({ port: argv.wsPort }) const wss = new WebSocketServer({ port: argv.wsPort })
wss.on("connection", (ws) => connections.push(ws)) wss.on("connection", (ws) => connections.push(ws))
@ -447,27 +432,16 @@ export async function handleBuild(argv) {
`Started a Quartz server listening at http://localhost:${argv.port}${argv.baseDir}`, `Started a Quartz server listening at http://localhost:${argv.port}${argv.baseDir}`,
), ),
) )
} else { console.log("hint: exit with ctrl+c")
await build(clientRefresh) const paths = await globby(["**/*.ts", "**/*.tsx", "**/*.scss", "package.json"])
ctx.dispose()
}
if (argv.watch) {
const paths = await globby([
"**/*.ts",
"quartz/cli/*.js",
"quartz/static/**/*",
"**/*.tsx",
"**/*.scss",
"package.json",
])
chokidar chokidar
.watch(paths, { ignoreInitial: true }) .watch(paths, { ignoreInitial: true })
.on("add", () => build(clientRefresh)) .on("add", () => build(clientRefresh))
.on("change", () => build(clientRefresh)) .on("change", () => build(clientRefresh))
.on("unlink", () => build(clientRefresh)) .on("unlink", () => build(clientRefresh))
} else {
console.log(chalk.grey("hint: exit with ctrl+c")) await build(() => {})
ctx.dispose()
} }
} }
@ -476,7 +450,7 @@ export async function handleBuild(argv) {
* @param {*} argv arguments for `update` * @param {*} argv arguments for `update`
*/ */
export async function handleUpdate(argv) { export async function handleUpdate(argv) {
const contentFolder = resolveContentPath(argv.directory) const contentFolder = path.join(cwd, argv.directory)
console.log(chalk.bgGreen.black(`\n Quartz v${version} \n`)) console.log(chalk.bgGreen.black(`\n Quartz v${version} \n`))
console.log("Backing up your content") console.log("Backing up your content")
execSync( execSync(
@ -528,7 +502,7 @@ export async function handleUpdate(argv) {
* @param {*} argv arguments for `restore` * @param {*} argv arguments for `restore`
*/ */
export async function handleRestore(argv) { export async function handleRestore(argv) {
const contentFolder = resolveContentPath(argv.directory) const contentFolder = path.join(cwd, argv.directory)
await popContentFolder(contentFolder) await popContentFolder(contentFolder)
} }
@ -537,7 +511,7 @@ export async function handleRestore(argv) {
* @param {*} argv arguments for `sync` * @param {*} argv arguments for `sync`
*/ */
export async function handleSync(argv) { export async function handleSync(argv) {
const contentFolder = resolveContentPath(argv.directory) const contentFolder = path.join(cwd, argv.directory)
console.log(chalk.bgGreen.black(`\n Quartz v${version} \n`)) console.log(chalk.bgGreen.black(`\n Quartz v${version} \n`))
console.log("Backing up your content") console.log("Backing up your content")

View File

@ -3,7 +3,6 @@ import style from "./styles/backlinks.scss"
import { resolveRelative, simplifySlug } from "../util/path" import { resolveRelative, simplifySlug } from "../util/path"
import { i18n } from "../i18n" import { i18n } from "../i18n"
import { classNames } from "../util/lang" import { classNames } from "../util/lang"
import OverflowListFactory from "./OverflowList"
interface BacklinksOptions { interface BacklinksOptions {
hideWhenEmpty: boolean hideWhenEmpty: boolean
@ -15,7 +14,6 @@ const defaultOptions: BacklinksOptions = {
export default ((opts?: Partial<BacklinksOptions>) => { export default ((opts?: Partial<BacklinksOptions>) => {
const options: BacklinksOptions = { ...defaultOptions, ...opts } const options: BacklinksOptions = { ...defaultOptions, ...opts }
const { OverflowList, overflowListAfterDOMLoaded } = OverflowListFactory()
const Backlinks: QuartzComponent = ({ const Backlinks: QuartzComponent = ({
fileData, fileData,
@ -31,7 +29,7 @@ export default ((opts?: Partial<BacklinksOptions>) => {
return ( return (
<div class={classNames(displayClass, "backlinks")}> <div class={classNames(displayClass, "backlinks")}>
<h3>{i18n(cfg.locale).components.backlinks.title}</h3> <h3>{i18n(cfg.locale).components.backlinks.title}</h3>
<OverflowList> <ul class="overflow">
{backlinkFiles.length > 0 ? ( {backlinkFiles.length > 0 ? (
backlinkFiles.map((f) => ( backlinkFiles.map((f) => (
<li> <li>
@ -43,13 +41,12 @@ export default ((opts?: Partial<BacklinksOptions>) => {
) : ( ) : (
<li>{i18n(cfg.locale).components.backlinks.noBacklinksFound}</li> <li>{i18n(cfg.locale).components.backlinks.noBacklinksFound}</li>
)} )}
</OverflowList> </ul>
</div> </div>
) )
} }
Backlinks.css = style Backlinks.css = style
Backlinks.afterDOMLoaded = overflowListAfterDOMLoaded
return Backlinks return Backlinks
}) satisfies QuartzComponentConstructor }) satisfies QuartzComponentConstructor

View File

@ -102,7 +102,7 @@ export default ((opts?: Partial<BreadcrumbOptions>) => {
// Add current slug to full path // Add current slug to full path
currentPath = joinSegments(currentPath, slugParts[i]) currentPath = joinSegments(currentPath, slugParts[i])
const includeTrailingSlash = !isTagPath || i < slugParts.length - 1 const includeTrailingSlash = !isTagPath || i < 1
// Format and add current crumb // Format and add current crumb
const crumb = formatCrumb( const crumb = formatCrumb(

View File

@ -1,4 +1,6 @@
// @ts-ignore // @ts-ignore: this is safe, we don't want to actually make darkmode.inline.ts a module as
// modules are automatically deferred and we don't want that to happen for critical beforeDOMLoads
// see: https://v8.dev/features/modules#defer
import darkmodeScript from "./scripts/darkmode.inline" import darkmodeScript from "./scripts/darkmode.inline"
import styles from "./styles/darkmode.scss" import styles from "./styles/darkmode.scss"
import { QuartzComponent, QuartzComponentConstructor, QuartzComponentProps } from "./types" import { QuartzComponent, QuartzComponentConstructor, QuartzComponentProps } from "./types"
@ -7,12 +9,12 @@ import { classNames } from "../util/lang"
const Darkmode: QuartzComponent = ({ displayClass, cfg }: QuartzComponentProps) => { const Darkmode: QuartzComponent = ({ displayClass, cfg }: QuartzComponentProps) => {
return ( return (
<button class={classNames(displayClass, "darkmode")}> <button class={classNames(displayClass, "darkmode")} id="darkmode">
<svg <svg
xmlns="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg"
xmlnsXlink="http://www.w3.org/1999/xlink" xmlnsXlink="http://www.w3.org/1999/xlink"
version="1.1" version="1.1"
class="dayIcon" id="dayIcon"
x="0px" x="0px"
y="0px" y="0px"
viewBox="0 0 35 35" viewBox="0 0 35 35"
@ -27,7 +29,7 @@ const Darkmode: QuartzComponent = ({ displayClass, cfg }: QuartzComponentProps)
xmlns="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg"
xmlnsXlink="http://www.w3.org/1999/xlink" xmlnsXlink="http://www.w3.org/1999/xlink"
version="1.1" version="1.1"
class="nightIcon" id="nightIcon"
x="0px" x="0px"
y="0px" y="0px"
viewBox="0 0 100 100" viewBox="0 0 100 100"

View File

@ -1,14 +1,18 @@
import { QuartzComponent, QuartzComponentConstructor, QuartzComponentProps } from "./types" import { QuartzComponent, QuartzComponentConstructor, QuartzComponentProps } from "./types"
export default ((component: QuartzComponent) => { export default ((component?: QuartzComponent) => {
const Component = component if (component) {
const DesktopOnly: QuartzComponent = (props: QuartzComponentProps) => { const Component = component
return <Component displayClass="desktop-only" {...props} /> const DesktopOnly: QuartzComponent = (props: QuartzComponentProps) => {
} return <Component displayClass="desktop-only" {...props} />
}
DesktopOnly.displayName = component.displayName DesktopOnly.displayName = component.displayName
DesktopOnly.afterDOMLoaded = component?.afterDOMLoaded DesktopOnly.afterDOMLoaded = component?.afterDOMLoaded
DesktopOnly.beforeDOMLoaded = component?.beforeDOMLoaded DesktopOnly.beforeDOMLoaded = component?.beforeDOMLoaded
DesktopOnly.css = component?.css DesktopOnly.css = component?.css
return DesktopOnly return DesktopOnly
}) satisfies QuartzComponentConstructor<QuartzComponent> } else {
return () => <></>
}
}) satisfies QuartzComponentConstructor

View File

@ -1,37 +1,24 @@
import { QuartzComponent, QuartzComponentConstructor, QuartzComponentProps } from "./types" import { QuartzComponent, QuartzComponentConstructor, QuartzComponentProps } from "./types"
import style from "./styles/explorer.scss" import explorerStyle from "./styles/explorer.scss"
// @ts-ignore // @ts-ignore
import script from "./scripts/explorer.inline" import script from "./scripts/explorer.inline"
import { ExplorerNode, FileNode, Options } from "./ExplorerNode"
import { QuartzPluginData } from "../plugins/vfile"
import { classNames } from "../util/lang" import { classNames } from "../util/lang"
import { i18n } from "../i18n" import { i18n } from "../i18n"
import { FileTrieNode } from "../util/fileTrie"
import OverflowListFactory from "./OverflowList"
import { concatenateResources } from "../util/resources"
type OrderEntries = "sort" | "filter" | "map" // Options interface defined in `ExplorerNode` to avoid circular dependency
const defaultOptions = {
export interface Options { folderClickBehavior: "collapse",
title?: string
folderDefaultState: "collapsed" | "open"
folderClickBehavior: "collapse" | "link"
useSavedState: boolean
sortFn: (a: FileTrieNode, b: FileTrieNode) => number
filterFn: (node: FileTrieNode) => boolean
mapFn: (node: FileTrieNode) => void
order: OrderEntries[]
}
const defaultOptions: Options = {
folderDefaultState: "collapsed", folderDefaultState: "collapsed",
folderClickBehavior: "link",
useSavedState: true, useSavedState: true,
mapFn: (node) => { mapFn: (node) => {
return node return node
}, },
sortFn: (a, b) => { sortFn: (a, b) => {
// Sort order: folders first, then files. Sort folders and files alphabeticall // Sort order: folders first, then files. Sort folders and files alphabetically
if ((!a.isFolder && !b.isFolder) || (a.isFolder && b.isFolder)) { if ((!a.file && !b.file) || (a.file && b.file)) {
// numeric: true: Whether numeric collation should be used, such that "1" < "2" < "10" // numeric: true: Whether numeric collation should be used, such that "1" < "2" < "10"
// sensitivity: "base": Only strings that differ in base letters compare as unequal. Examples: a ≠ b, a = á, a = A // sensitivity: "base": Only strings that differ in base letters compare as unequal. Examples: a ≠ b, a = á, a = A
return a.displayName.localeCompare(b.displayName, undefined, { return a.displayName.localeCompare(b.displayName, undefined, {
@ -40,65 +27,74 @@ const defaultOptions: Options = {
}) })
} }
if (!a.isFolder && b.isFolder) { if (a.file && !b.file) {
return 1 return 1
} else { } else {
return -1 return -1
} }
}, },
filterFn: (node) => node.slugSegment !== "tags", filterFn: (node) => node.name !== "tags",
order: ["filter", "map", "sort"], order: ["filter", "map", "sort"],
} } satisfies Options
export type FolderState = {
path: string
collapsed: boolean
}
export default ((userOpts?: Partial<Options>) => { export default ((userOpts?: Partial<Options>) => {
// Parse config
const opts: Options = { ...defaultOptions, ...userOpts } const opts: Options = { ...defaultOptions, ...userOpts }
const { OverflowList, overflowListAfterDOMLoaded } = OverflowListFactory()
const Explorer: QuartzComponent = ({ cfg, displayClass }: QuartzComponentProps) => { // memoized
let fileTree: FileNode
let jsonTree: string
let lastBuildId: string = ""
function constructFileTree(allFiles: QuartzPluginData[]) {
// Construct tree from allFiles
fileTree = new FileNode("")
allFiles.forEach((file) => fileTree.add(file))
// Execute all functions (sort, filter, map) that were provided (if none were provided, only default "sort" is applied)
if (opts.order) {
// Order is important, use loop with index instead of order.map()
for (let i = 0; i < opts.order.length; i++) {
const functionName = opts.order[i]
if (functionName === "map") {
fileTree.map(opts.mapFn)
} else if (functionName === "sort") {
fileTree.sort(opts.sortFn)
} else if (functionName === "filter") {
fileTree.filter(opts.filterFn)
}
}
}
// Get all folders of tree. Initialize with collapsed state
// Stringify to pass json tree as data attribute ([data-tree])
const folders = fileTree.getFolderPaths(opts.folderDefaultState === "collapsed")
jsonTree = JSON.stringify(folders)
}
const Explorer: QuartzComponent = ({
ctx,
cfg,
allFiles,
displayClass,
fileData,
}: QuartzComponentProps) => {
if (ctx.buildId !== lastBuildId) {
lastBuildId = ctx.buildId
constructFileTree(allFiles)
}
return ( return (
<div <div class={classNames(displayClass, "explorer")}>
class={classNames(displayClass, "explorer")}
data-behavior={opts.folderClickBehavior}
data-collapsed={opts.folderDefaultState}
data-savestate={opts.useSavedState}
data-data-fns={JSON.stringify({
order: opts.order,
sortFn: opts.sortFn.toString(),
filterFn: opts.filterFn.toString(),
mapFn: opts.mapFn.toString(),
})}
>
<button <button
type="button" type="button"
class="explorer-toggle mobile-explorer hide-until-loaded" id="explorer"
data-mobile={true} data-behavior={opts.folderClickBehavior}
data-collapsed={opts.folderDefaultState}
data-savestate={opts.useSavedState}
data-tree={jsonTree}
aria-controls="explorer-content" aria-controls="explorer-content"
> aria-expanded={opts.folderDefaultState === "open"}
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
class="lucide-menu"
>
<line x1="4" x2="20" y1="12" y2="12" />
<line x1="4" x2="20" y1="6" y2="6" />
<line x1="4" x2="20" y1="18" y2="18" />
</svg>
</button>
<button
type="button"
class="title-button explorer-toggle desktop-explorer"
data-mobile={false}
aria-expanded={true}
> >
<h2>{opts.title ?? i18n(cfg.locale).components.explorer.title}</h2> <h2>{opts.title ?? i18n(cfg.locale).components.explorer.title}</h2>
<svg <svg
@ -116,47 +112,17 @@ export default ((userOpts?: Partial<Options>) => {
<polyline points="6 9 12 15 18 9"></polyline> <polyline points="6 9 12 15 18 9"></polyline>
</svg> </svg>
</button> </button>
<div class="explorer-content" aria-expanded={false}> <div id="explorer-content">
<OverflowList class="explorer-ul" /> <ul class="overflow" id="explorer-ul">
<ExplorerNode node={fileTree} opts={opts} fileData={fileData} />
<li id="explorer-end" />
</ul>
</div> </div>
<template id="template-file">
<li>
<a href="#"></a>
</li>
</template>
<template id="template-folder">
<li>
<div class="folder-container">
<svg
xmlns="http://www.w3.org/2000/svg"
width="12"
height="12"
viewBox="5 8 14 8"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
class="folder-icon"
>
<polyline points="6 9 12 15 18 9"></polyline>
</svg>
<div>
<button class="folder-button">
<span class="folder-title"></span>
</button>
</div>
</div>
<div class="folder-outer">
<ul class="content"></ul>
</div>
</li>
</template>
</div> </div>
) )
} }
Explorer.css = style Explorer.css = explorerStyle
Explorer.afterDOMLoaded = concatenateResources(script, overflowListAfterDOMLoaded) Explorer.afterDOMLoaded = script
return Explorer return Explorer
}) satisfies QuartzComponentConstructor }) satisfies QuartzComponentConstructor

View File

@ -0,0 +1,242 @@
// @ts-ignore
import { QuartzPluginData } from "../plugins/vfile"
import {
joinSegments,
resolveRelative,
clone,
simplifySlug,
SimpleSlug,
FilePath,
} from "../util/path"
type OrderEntries = "sort" | "filter" | "map"
export interface Options {
title?: string
folderDefaultState: "collapsed" | "open"
folderClickBehavior: "collapse" | "link"
useSavedState: boolean
sortFn: (a: FileNode, b: FileNode) => number
filterFn: (node: FileNode) => boolean
mapFn: (node: FileNode) => void
order: OrderEntries[]
}
type DataWrapper = {
file: QuartzPluginData
path: string[]
}
export type FolderState = {
path: string
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
export class FileNode {
children: Array<FileNode>
name: string // this is the slug segment
displayName: string
file: QuartzPluginData | null
depth: number
constructor(slugSegment: string, displayName?: string, file?: QuartzPluginData, depth?: number) {
this.children = []
this.name = slugSegment
this.displayName = displayName ?? file?.frontmatter?.title ?? slugSegment
this.file = file ? clone(file) : null
this.depth = depth ?? 0
}
private insert(fileData: DataWrapper) {
if (fileData.path.length === 0) {
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))
}
return
}
// 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(file: QuartzPluginData) {
this.insert({ file: file, path: simplifySlug(file.slug!).split("/") })
}
/**
* Filter FileNode tree. Behaves similar to `Array.prototype.filter()`, but modifies tree in place
* @param filterFn function to filter tree with
*/
filter(filterFn: (node: FileNode) => boolean) {
this.children = this.children.filter(filterFn)
this.children.forEach((child) => child.filter(filterFn))
}
/**
* Filter FileNode tree. Behaves similar to `Array.prototype.map()`, but modifies tree in place
* @param mapFn function to use for mapping over tree
*/
map(mapFn: (node: FileNode) => void) {
mapFn(this)
this.children.forEach((child) => child.map(mapFn))
}
/**
* Get folder representation with state of tree.
* Intended to only be called on root node before changes to the tree are made
* @param collapsed default state of folders (collapsed by default or not)
* @returns array containing folder state for tree
*/
getFolderPaths(collapsed: boolean): FolderState[] {
const folderPaths: FolderState[] = []
const traverse = (node: FileNode, currentPath: string) => {
if (!node.file) {
const folderPath = joinSegments(currentPath, node.name)
if (folderPath !== "") {
folderPaths.push({ path: folderPath, collapsed })
}
node.children.forEach((child) => traverse(child, folderPath))
}
}
traverse(this, "")
return folderPaths
}
// Sort order: folders first, then files. Sort folders and files alphabetically
/**
* Sorts tree according to sort/compare function
* @param sortFn compare function used for `.sort()`, also used recursively for children
*/
sort(sortFn: (a: FileNode, b: FileNode) => number) {
this.children = this.children.sort(sortFn)
this.children.forEach((e) => e.sort(sortFn))
}
}
type ExplorerNodeProps = {
node: FileNode
opts: Options
fileData: QuartzPluginData
fullPath?: string
}
export function ExplorerNode({ node, opts, fullPath, fileData }: ExplorerNodeProps) {
// Get options
const folderBehavior = opts.folderClickBehavior
const isDefaultOpen = opts.folderDefaultState === "open"
// Calculate current folderPath
const folderPath = node.name !== "" ? joinSegments(fullPath ?? "", node.name) : ""
const href = resolveRelative(fileData.slug!, folderPath as SimpleSlug) + "/"
return (
<>
{node.file ? (
// Single file node
<li key={node.file.slug}>
<a href={resolveRelative(fileData.slug!, node.file.slug!)} data-for={node.file.slug}>
{node.displayName}
</a>
</li>
) : (
<li>
{node.name !== "" && (
// Node with entire folder
// Render svg button + folder name, then children
<div class="folder-container">
<svg
xmlns="http://www.w3.org/2000/svg"
width="12"
height="12"
viewBox="5 8 14 8"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
class="folder-icon"
>
<polyline points="6 9 12 15 18 9"></polyline>
</svg>
{/* render <a> tag if folderBehavior is "link", otherwise render <button> with collapse click event */}
<div key={node.name} data-folderpath={folderPath}>
{folderBehavior === "link" ? (
<a href={href} data-for={node.name} class="folder-title">
{node.displayName}
</a>
) : (
<button class="folder-button">
<span class="folder-title">{node.displayName}</span>
</button>
)}
</div>
</div>
)}
{/* Recursively render children of folder */}
<div class={`folder-outer ${node.depth === 0 || isDefaultOpen ? "open" : ""}`}>
<ul
// Inline style for left folder paddings
style={{
paddingLeft: node.name !== "" ? "1.4rem" : "0",
}}
class="content"
data-folderul={folderPath}
>
{node.children.map((childNode, i) => (
<ExplorerNode
node={childNode}
key={i}
opts={opts}
fullPath={folderPath}
fileData={fileData}
/>
))}
</ul>
</div>
</li>
)}
</>
)
}

View File

@ -1,55 +0,0 @@
import { concatenateResources } from "../util/resources"
import { QuartzComponent, QuartzComponentConstructor, QuartzComponentProps } from "./types"
type FlexConfig = {
components: {
Component: QuartzComponent
grow?: boolean
shrink?: boolean
basis?: string
order?: number
align?: "start" | "end" | "center" | "stretch"
justify?: "start" | "end" | "center" | "between" | "around"
}[]
direction?: "row" | "row-reverse" | "column" | "column-reverse"
wrap?: "nowrap" | "wrap" | "wrap-reverse"
gap?: string
}
export default ((config: FlexConfig) => {
const Flex: QuartzComponent = (props: QuartzComponentProps) => {
const direction = config.direction ?? "row"
const wrap = config.wrap ?? "nowrap"
const gap = config.gap ?? "1rem"
return (
<div style={`display: flex; flex-direction: ${direction}; flex-wrap: ${wrap}; gap: ${gap};`}>
{config.components.map((c) => {
const grow = c.grow ? 1 : 0
const shrink = (c.shrink ?? true) ? 1 : 0
const basis = c.basis ?? "auto"
const order = c.order ?? 0
const align = c.align ?? "center"
const justify = c.justify ?? "center"
return (
<div
style={`flex-grow: ${grow}; flex-shrink: ${shrink}; flex-basis: ${basis}; order: ${order}; align-self: ${align}; justify-self: ${justify};`}
>
<c.Component {...props} />
</div>
)
})}
</div>
)
}
Flex.afterDOMLoaded = concatenateResources(
...config.components.map((c) => c.Component.afterDOMLoaded),
)
Flex.beforeDOMLoaded = concatenateResources(
...config.components.map((c) => c.Component.beforeDOMLoaded),
)
Flex.css = concatenateResources(...config.components.map((c) => c.Component.css))
return Flex
}) satisfies QuartzComponentConstructor<FlexConfig>

View File

@ -18,7 +18,6 @@ export interface D3Config {
removeTags: string[] removeTags: string[]
showTags: boolean showTags: boolean
focusOnHover?: boolean focusOnHover?: boolean
enableRadial?: boolean
} }
interface GraphOptions { interface GraphOptions {
@ -40,7 +39,6 @@ const defaultOptions: GraphOptions = {
showTags: true, showTags: true,
removeTags: [], removeTags: [],
focusOnHover: false, focusOnHover: false,
enableRadial: false,
}, },
globalGraph: { globalGraph: {
drag: true, drag: true,
@ -48,18 +46,17 @@ const defaultOptions: GraphOptions = {
depth: -1, depth: -1,
scale: 0.9, scale: 0.9,
repelForce: 0.5, repelForce: 0.5,
centerForce: 0.2, centerForce: 0.3,
linkDistance: 30, linkDistance: 30,
fontSize: 0.6, fontSize: 0.6,
opacityScale: 1, opacityScale: 1,
showTags: true, showTags: true,
removeTags: [], removeTags: [],
focusOnHover: true, focusOnHover: true,
enableRadial: true,
}, },
} }
export default ((opts?: Partial<GraphOptions>) => { export default ((opts?: GraphOptions) => {
const Graph: QuartzComponent = ({ displayClass, cfg }: QuartzComponentProps) => { const Graph: QuartzComponent = ({ displayClass, cfg }: QuartzComponentProps) => {
const localGraph = { ...defaultOptions.localGraph, ...opts?.localGraph } const localGraph = { ...defaultOptions.localGraph, ...opts?.localGraph }
const globalGraph = { ...defaultOptions.globalGraph, ...opts?.globalGraph } const globalGraph = { ...defaultOptions.globalGraph, ...opts?.globalGraph }
@ -67,8 +64,8 @@ export default ((opts?: Partial<GraphOptions>) => {
<div class={classNames(displayClass, "graph")}> <div class={classNames(displayClass, "graph")}>
<h3>{i18n(cfg.locale).components.graph.title}</h3> <h3>{i18n(cfg.locale).components.graph.title}</h3>
<div class="graph-outer"> <div class="graph-outer">
<div class="graph-container" data-cfg={JSON.stringify(localGraph)}></div> <div id="graph-container" data-cfg={JSON.stringify(localGraph)}></div>
<button class="global-graph-icon" aria-label="Global Graph"> <button id="global-graph-icon" aria-label="Global Graph">
<svg <svg
version="1.1" version="1.1"
xmlns="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg"
@ -95,8 +92,8 @@ export default ((opts?: Partial<GraphOptions>) => {
</svg> </svg>
</button> </button>
</div> </div>
<div class="global-graph-outer"> <div id="global-graph-outer">
<div class="global-graph-container" data-cfg={JSON.stringify(globalGraph)}></div> <div id="global-graph-container" data-cfg={JSON.stringify(globalGraph)}></div>
</div> </div>
</div> </div>
) )

View File

@ -1,41 +1,159 @@
import { i18n } from "../i18n" import { i18n } from "../i18n"
import { FullSlug, getFileExtension, joinSegments, pathToRoot } from "../util/path" import { FullSlug, joinSegments, pathToRoot } from "../util/path"
import { CSSResourceToStyleElement, JSResourceToScriptElement } from "../util/resources" import { CSSResourceToStyleElement, JSResourceToScriptElement } from "../util/resources"
import { googleFontHref, googleFontSubsetHref } from "../util/theme" import { googleFontHref } from "../util/theme"
import { QuartzComponent, QuartzComponentConstructor, QuartzComponentProps } from "./types" import { QuartzComponent, QuartzComponentConstructor, QuartzComponentProps } from "./types"
import satori, { SatoriOptions } from "satori"
import fs from "fs"
import sharp from "sharp"
import { ImageOptions, SocialImageOptions, getSatoriFont, defaultImage } from "../util/og"
import { unescapeHTML } from "../util/escape" import { unescapeHTML } from "../util/escape"
import { CustomOgImagesEmitterName } from "../plugins/emitters/ogImage"
/**
* Generates social image (OG/twitter standard) and saves it as `.webp` inside the public folder
* @param opts options for generating image
*/
async function generateSocialImage(
{ cfg, description, fileName, fontsPromise, title, fileData }: ImageOptions,
userOpts: SocialImageOptions,
imageDir: string,
) {
const fonts = await fontsPromise
const { width, height } = userOpts
// JSX that will be used to generate satori svg
const imageComponent = userOpts.imageStructure(cfg, userOpts, title, description, fonts, fileData)
const svg = await satori(imageComponent, { width, height, fonts })
// Convert svg directly to webp (with additional compression)
const compressed = await sharp(Buffer.from(svg)).webp({ quality: 40 }).toBuffer()
// Write to file system
const filePath = joinSegments(imageDir, `${fileName}.${extension}`)
fs.writeFileSync(filePath, compressed)
}
const extension = "webp"
const defaultOptions: SocialImageOptions = {
colorScheme: "lightMode",
width: 1200,
height: 630,
imageStructure: defaultImage,
excludeRoot: false,
}
export default (() => { export default (() => {
let fontsPromise: Promise<SatoriOptions["fonts"]>
let fullOptions: SocialImageOptions
const Head: QuartzComponent = ({ const Head: QuartzComponent = ({
cfg, cfg,
fileData, fileData,
externalResources, externalResources,
ctx, ctx,
}: QuartzComponentProps) => { }: QuartzComponentProps) => {
// Initialize options if not set
if (!fullOptions) {
if (typeof cfg.generateSocialImages !== "boolean") {
fullOptions = { ...defaultOptions, ...cfg.generateSocialImages }
} else {
fullOptions = defaultOptions
}
}
// Memoize google fonts
if (!fontsPromise && cfg.generateSocialImages) {
fontsPromise = getSatoriFont(cfg.theme.typography.header, cfg.theme.typography.body)
}
const slug = fileData.filePath
// since "/" is not a valid character in file names, replace with "-"
const fileName = slug?.replaceAll("/", "-")
// Get file description (priority: frontmatter > fileData > default)
const fdDescription =
fileData.description?.trim() ?? i18n(cfg.locale).propertyDefaults.description
const titleSuffix = cfg.pageTitleSuffix ?? "" const titleSuffix = cfg.pageTitleSuffix ?? ""
const title = const title =
(fileData.frontmatter?.title ?? i18n(cfg.locale).propertyDefaults.title) + titleSuffix (fileData.frontmatter?.title ?? i18n(cfg.locale).propertyDefaults.title) + titleSuffix
const description = let description = ""
fileData.frontmatter?.socialDescription ?? if (fdDescription) {
fileData.frontmatter?.description ?? description = unescapeHTML(fdDescription)
unescapeHTML(fileData.description?.trim() ?? i18n(cfg.locale).propertyDefaults.description) }
const { css, js, additionalHead } = externalResources if (fileData.frontmatter?.socialDescription) {
description = fileData.frontmatter?.socialDescription as string
} else if (fileData.frontmatter?.description) {
description = fileData.frontmatter?.description
}
const fileDir = joinSegments(ctx.argv.output, "static", "social-images")
if (cfg.generateSocialImages) {
// Generate folders for social images (if they dont exist yet)
if (!fs.existsSync(fileDir)) {
fs.mkdirSync(fileDir, { recursive: true })
}
if (fileName) {
// Generate social image (happens async)
generateSocialImage(
{
title,
description,
fileName,
fileDir,
fileExt: extension,
fontsPromise,
cfg,
fileData,
},
fullOptions,
fileDir,
)
}
}
const { css, js } = externalResources
const url = new URL(`https://${cfg.baseUrl ?? "example.com"}`) const url = new URL(`https://${cfg.baseUrl ?? "example.com"}`)
const path = url.pathname as FullSlug const path = url.pathname as FullSlug
const baseDir = fileData.slug === "404" ? path : pathToRoot(fileData.slug!) const baseDir = fileData.slug === "404" ? path : pathToRoot(fileData.slug!)
const iconPath = joinSegments(baseDir, "static/icon.png") const iconPath = joinSegments(baseDir, "static/icon.png")
const ogImageDefaultPath = `https://${cfg.baseUrl}/static/og-image.png`
// "static/social-images/slug-filename.md.webp"
const ogImageGeneratedPath = `https://${cfg.baseUrl}/${fileDir.replace(
`${ctx.argv.output}/`,
"",
)}/${fileName}.${extension}`
// Use default og image if filePath doesnt exist (for autogenerated paths with no .md file)
const useDefaultOgImage = fileName === undefined || !cfg.generateSocialImages
// Path to og/social image (priority: frontmatter > generated image (if enabled) > default image)
let ogImagePath = useDefaultOgImage ? ogImageDefaultPath : ogImageGeneratedPath
// TODO: could be improved to support external images in the future
// Aliases for image and cover handled in `frontmatter.ts`
const frontmatterImgUrl = fileData.frontmatter?.socialImage
// Override with default og image if config option is set
if (fileData.slug === "index") {
ogImagePath = ogImageDefaultPath
}
// Override with frontmatter url if existing
if (frontmatterImgUrl) {
ogImagePath = `https://${cfg.baseUrl}/static/${frontmatterImgUrl}`
}
// Url of current page // Url of current page
const socialUrl = const socialUrl =
fileData.slug === "404" ? url.toString() : joinSegments(url.toString(), fileData.slug!) fileData.slug === "404" ? url.toString() : joinSegments(url.toString(), fileData.slug!)
const usesCustomOgImage = ctx.cfg.plugins.emitters.some(
(e) => e.name === CustomOgImagesEmitterName,
)
const ogImageDefaultPath = `https://${cfg.baseUrl}/static/og-image.png`
return ( return (
<head> <head>
<title>{title}</title> <title>{title}</title>
@ -45,14 +163,11 @@ export default (() => {
<link rel="preconnect" href="https://fonts.googleapis.com" /> <link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" /> <link rel="preconnect" href="https://fonts.gstatic.com" />
<link rel="stylesheet" href={googleFontHref(cfg.theme)} /> <link rel="stylesheet" href={googleFontHref(cfg.theme)} />
{cfg.theme.typography.title && (
<link rel="stylesheet" href={googleFontSubsetHref(cfg.theme, cfg.pageTitle)} />
)}
</> </>
)} )}
<link rel="preconnect" href="https://cdnjs.cloudflare.com" crossOrigin="anonymous" /> <link rel="preconnect" href="https://cdnjs.cloudflare.com" crossOrigin={"anonymous"} />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
{/* OG/Twitter meta tags */}
<meta name="og:site_name" content={cfg.pageTitle}></meta> <meta name="og:site_name" content={cfg.pageTitle}></meta>
<meta property="og:title" content={title} /> <meta property="og:title" content={title} />
<meta property="og:type" content="website" /> <meta property="og:type" content="website" />
@ -60,43 +175,32 @@ export default (() => {
<meta name="twitter:title" content={title} /> <meta name="twitter:title" content={title} />
<meta name="twitter:description" content={description} /> <meta name="twitter:description" content={description} />
<meta property="og:description" content={description} /> <meta property="og:description" content={description} />
<meta property="og:image:type" content={`image/${extension}`} />
<meta property="og:image:alt" content={description} /> <meta property="og:image:alt" content={description} />
{/* Dont set width and height if unknown (when using custom frontmatter image) */}
{!usesCustomOgImage && ( {!frontmatterImgUrl && (
<> <>
<meta property="og:image" content={ogImageDefaultPath} /> <meta property="og:image:width" content={fullOptions.width.toString()} />
<meta property="og:image:url" content={ogImageDefaultPath} /> <meta property="og:image:height" content={fullOptions.height.toString()} />
<meta name="twitter:image" content={ogImageDefaultPath} />
<meta
property="og:image:type"
content={`image/${getFileExtension(ogImageDefaultPath) ?? "png"}`}
/>
</> </>
)} )}
<meta property="og:image:url" content={ogImagePath} />
{cfg.baseUrl && ( {cfg.baseUrl && (
<> <>
<meta name="twitter:image" content={ogImagePath} />
<meta property="og:image" content={ogImagePath} />
<meta property="twitter:domain" content={cfg.baseUrl}></meta> <meta property="twitter:domain" content={cfg.baseUrl}></meta>
<meta property="og:url" content={socialUrl}></meta> <meta property="og:url" content={socialUrl}></meta>
<meta property="twitter:url" content={socialUrl}></meta> <meta property="twitter:url" content={socialUrl}></meta>
</> </>
)} )}
<link rel="icon" href={iconPath} /> <link rel="icon" href={iconPath} />
<meta name="description" content={description} /> <meta name="description" content={description} />
<meta name="generator" content="Quartz" /> <meta name="generator" content="Quartz" />
{css.map((resource) => CSSResourceToStyleElement(resource, true))} {css.map((resource) => CSSResourceToStyleElement(resource, true))}
{js {js
.filter((resource) => resource.loadTime === "beforeDOMReady") .filter((resource) => resource.loadTime === "beforeDOMReady")
.map((res) => JSResourceToScriptElement(res, true))} .map((res) => JSResourceToScriptElement(res, true))}
{additionalHead.map((resource) => {
if (typeof resource === "function") {
return resource(fileData)
} else {
return resource
}
})}
</head> </head>
) )
} }

View File

@ -1,14 +1,18 @@
import { QuartzComponent, QuartzComponentConstructor, QuartzComponentProps } from "./types" import { QuartzComponent, QuartzComponentConstructor, QuartzComponentProps } from "./types"
export default ((component: QuartzComponent) => { export default ((component?: QuartzComponent) => {
const Component = component if (component) {
const MobileOnly: QuartzComponent = (props: QuartzComponentProps) => { const Component = component
return <Component displayClass="mobile-only" {...props} /> const MobileOnly: QuartzComponent = (props: QuartzComponentProps) => {
} return <Component displayClass="mobile-only" {...props} />
}
MobileOnly.displayName = component.displayName MobileOnly.displayName = component.displayName
MobileOnly.afterDOMLoaded = component?.afterDOMLoaded MobileOnly.afterDOMLoaded = component?.afterDOMLoaded
MobileOnly.beforeDOMLoaded = component?.beforeDOMLoaded MobileOnly.beforeDOMLoaded = component?.beforeDOMLoaded
MobileOnly.css = component?.css MobileOnly.css = component?.css
return MobileOnly return MobileOnly
}) satisfies QuartzComponentConstructor<QuartzComponent> } else {
return () => <></>
}
}) satisfies QuartzComponentConstructor

View File

@ -1,48 +0,0 @@
import { JSX } from "preact"
import { randomIdNonSecure } from "../util/random"
const OverflowList = ({
children,
...props
}: JSX.HTMLAttributes<HTMLUListElement> & { id: string }) => {
return (
<ul {...props} class={[props.class, "overflow"].filter(Boolean).join(" ")} id={props.id}>
{children}
<li class="overflow-end" />
</ul>
)
}
export default () => {
const id = randomIdNonSecure()
return {
OverflowList: (props: JSX.HTMLAttributes<HTMLUListElement>) => (
<OverflowList {...props} id={id} />
),
overflowListAfterDOMLoaded: `
document.addEventListener("nav", (e) => {
const observer = new IntersectionObserver((entries) => {
for (const entry of entries) {
const parentUl = entry.target.parentElement
if (!parentUl) return
if (entry.isIntersecting) {
parentUl.classList.remove("gradient-active")
} else {
parentUl.classList.add("gradient-active")
}
}
})
const ul = document.getElementById("${id}")
if (!ul) return
const end = ul.querySelector(".overflow-end")
if (!end) return
observer.observe(end)
window.addCleanup(() => observer.disconnect())
})
`,
}
}

View File

@ -1,4 +1,4 @@
import { FullSlug, isFolderPath, resolveRelative } from "../util/path" import { FullSlug, resolveRelative } from "../util/path"
import { QuartzPluginData } from "../plugins/vfile" import { QuartzPluginData } from "../plugins/vfile"
import { Date, getDate } from "./Date" import { Date, getDate } from "./Date"
import { QuartzComponent, QuartzComponentProps } from "./types" import { QuartzComponent, QuartzComponentProps } from "./types"
@ -8,13 +8,6 @@ export type SortFn = (f1: QuartzPluginData, f2: QuartzPluginData) => number
export function byDateAndAlphabetical(cfg: GlobalConfiguration): SortFn { export function byDateAndAlphabetical(cfg: GlobalConfiguration): SortFn {
return (f1, f2) => { return (f1, f2) => {
// Sort folders first
const f1IsFolder = isFolderPath(f1.slug ?? "")
const f2IsFolder = isFolderPath(f2.slug ?? "")
if (f1IsFolder && !f2IsFolder) return -1
if (!f1IsFolder && f2IsFolder) return 1
// If both are folders or both are files, sort by date/alphabetical
if (f1.dates && f2.dates) { if (f1.dates && f2.dates) {
// sort descending // sort descending
return getDate(cfg, f2)!.getTime() - getDate(cfg, f1)!.getTime() return getDate(cfg, f2)!.getTime() - getDate(cfg, f1)!.getTime()

View File

@ -17,7 +17,6 @@ PageTitle.css = `
.page-title { .page-title {
font-size: 1.75rem; font-size: 1.75rem;
margin: 0; margin: 0;
font-family: var(--titleFont);
} }
` `

View File

@ -19,7 +19,7 @@ export default ((userOpts?: Partial<SearchOptions>) => {
const searchPlaceholder = i18n(cfg.locale).components.search.searchBarPlaceholder const searchPlaceholder = i18n(cfg.locale).components.search.searchBarPlaceholder
return ( return (
<div class={classNames(displayClass, "search")}> <div class={classNames(displayClass, "search")}>
<button class="search-button"> <button class="search-button" id="search-button">
<p>{i18n(cfg.locale).components.search.title}</p> <p>{i18n(cfg.locale).components.search.title}</p>
<svg role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 19.9 19.7"> <svg role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 19.9 19.7">
<title>Search</title> <title>Search</title>
@ -29,17 +29,17 @@ export default ((userOpts?: Partial<SearchOptions>) => {
</g> </g>
</svg> </svg>
</button> </button>
<div class="search-container"> <div id="search-container">
<div class="search-space"> <div id="search-space">
<input <input
autocomplete="off" autocomplete="off"
class="search-bar" id="search-bar"
name="search" name="search"
type="text" type="text"
aria-label={searchPlaceholder} aria-label={searchPlaceholder}
placeholder={searchPlaceholder} placeholder={searchPlaceholder}
/> />
<div class="search-layout" data-preview={opts.enablePreview}></div> <div id="search-layout" data-preview={opts.enablePreview}></div>
</div> </div>
</div> </div>
</div> </div>

View File

@ -6,8 +6,6 @@ import { classNames } from "../util/lang"
// @ts-ignore // @ts-ignore
import script from "./scripts/toc.inline" import script from "./scripts/toc.inline"
import { i18n } from "../i18n" import { i18n } from "../i18n"
import OverflowListFactory from "./OverflowList"
import { concatenateResources } from "../util/resources"
interface Options { interface Options {
layout: "modern" | "legacy" layout: "modern" | "legacy"
@ -17,70 +15,42 @@ const defaultOptions: Options = {
layout: "modern", layout: "modern",
} }
export default ((opts?: Partial<Options>) => { const TableOfContents: QuartzComponent = ({
const layout = opts?.layout ?? defaultOptions.layout fileData,
const { OverflowList, overflowListAfterDOMLoaded } = OverflowListFactory() displayClass,
const TableOfContents: QuartzComponent = ({ cfg,
fileData, }: QuartzComponentProps) => {
displayClass, if (!fileData.toc) {
cfg, return null
}: QuartzComponentProps) => {
if (!fileData.toc) {
return null
}
return (
<div class={classNames(displayClass, "toc")}>
<button
type="button"
class={fileData.collapseToc ? "collapsed toc-header" : "toc-header"}
aria-controls="toc-content"
aria-expanded={!fileData.collapseToc}
>
<h3>{i18n(cfg.locale).components.tableOfContents.title}</h3>
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
class="fold"
>
<polyline points="6 9 12 15 18 9"></polyline>
</svg>
</button>
<div class={fileData.collapseToc ? "collapsed toc-content" : "toc-content"}>
<OverflowList>
{fileData.toc.map((tocEntry) => (
<li key={tocEntry.slug} class={`depth-${tocEntry.depth}`}>
<a href={`#${tocEntry.slug}`} data-for={tocEntry.slug}>
{tocEntry.text}
</a>
</li>
))}
</OverflowList>
</div>
</div>
)
} }
TableOfContents.css = modernStyle return (
TableOfContents.afterDOMLoaded = concatenateResources(script, overflowListAfterDOMLoaded) <div class={classNames(displayClass, "toc")}>
<button
const LegacyTableOfContents: QuartzComponent = ({ fileData, cfg }: QuartzComponentProps) => { type="button"
if (!fileData.toc) { id="toc"
return null class={fileData.collapseToc ? "collapsed" : ""}
} aria-controls="toc-content"
return ( aria-expanded={!fileData.collapseToc}
<details class="toc" open={!fileData.collapseToc}> >
<summary> <h3>{i18n(cfg.locale).components.tableOfContents.title}</h3>
<h3>{i18n(cfg.locale).components.tableOfContents.title}</h3> <svg
</summary> xmlns="http://www.w3.org/2000/svg"
<ul> width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
class="fold"
>
<polyline points="6 9 12 15 18 9"></polyline>
</svg>
</button>
<div id="toc-content" class={fileData.collapseToc ? "collapsed" : ""}>
<ul class="overflow">
{fileData.toc.map((tocEntry) => ( {fileData.toc.map((tocEntry) => (
<li key={tocEntry.slug} class={`depth-${tocEntry.depth}`}> <li key={tocEntry.slug} class={`depth-${tocEntry.depth}`}>
<a href={`#${tocEntry.slug}`} data-for={tocEntry.slug}> <a href={`#${tocEntry.slug}`} data-for={tocEntry.slug}>
@ -89,10 +59,37 @@ export default ((opts?: Partial<Options>) => {
</li> </li>
))} ))}
</ul> </ul>
</details> </div>
) </div>
} )
LegacyTableOfContents.css = legacyStyle }
TableOfContents.css = modernStyle
TableOfContents.afterDOMLoaded = script
const LegacyTableOfContents: QuartzComponent = ({ fileData, cfg }: QuartzComponentProps) => {
if (!fileData.toc) {
return null
}
return (
<details id="toc" open={!fileData.collapseToc}>
<summary>
<h3>{i18n(cfg.locale).components.tableOfContents.title}</h3>
</summary>
<ul>
{fileData.toc.map((tocEntry) => (
<li key={tocEntry.slug} class={`depth-${tocEntry.depth}`}>
<a href={`#${tocEntry.slug}`} data-for={tocEntry.slug}>
{tocEntry.text}
</a>
</li>
))}
</ul>
</details>
)
}
LegacyTableOfContents.css = legacyStyle
export default ((opts?: Partial<Options>) => {
const layout = opts?.layout ?? defaultOptions.layout
return layout === "modern" ? TableOfContents : LegacyTableOfContents return layout === "modern" ? TableOfContents : LegacyTableOfContents
}) satisfies QuartzComponentConstructor }) satisfies QuartzComponentConstructor

View File

@ -20,7 +20,6 @@ import MobileOnly from "./MobileOnly"
import RecentNotes from "./RecentNotes" import RecentNotes from "./RecentNotes"
import Breadcrumbs from "./Breadcrumbs" import Breadcrumbs from "./Breadcrumbs"
import Comments from "./Comments" import Comments from "./Comments"
import Flex from "./Flex"
export { export {
ArticleTitle, ArticleTitle,
@ -45,5 +44,4 @@ export {
NotFound, NotFound,
Breadcrumbs, Breadcrumbs,
Comments, Comments,
Flex,
} }

View File

@ -1,9 +1,8 @@
import { ComponentChildren } from "preact"
import { htmlToJsx } from "../../util/jsx" import { htmlToJsx } from "../../util/jsx"
import { QuartzComponent, QuartzComponentConstructor, QuartzComponentProps } from "../types" import { QuartzComponent, QuartzComponentConstructor, QuartzComponentProps } from "../types"
const Content: QuartzComponent = ({ fileData, tree }: QuartzComponentProps) => { const Content: QuartzComponent = ({ fileData, tree }: QuartzComponentProps) => {
const content = htmlToJsx(fileData.filePath!, tree) as ComponentChildren const content = htmlToJsx(fileData.filePath!, tree)
const classes: string[] = fileData.frontmatter?.cssclasses ?? [] const classes: string[] = fileData.frontmatter?.cssclasses ?? []
const classString = ["popover-hint", ...classes].join(" ") const classString = ["popover-hint", ...classes].join(" ")
return <article class={classString}>{content}</article> return <article class={classString}>{content}</article>

View File

@ -1,14 +1,14 @@
import { QuartzComponent, QuartzComponentConstructor, QuartzComponentProps } from "../types" import { QuartzComponent, QuartzComponentConstructor, QuartzComponentProps } from "../types"
import path from "path"
import style from "../styles/listPage.scss" import style from "../styles/listPage.scss"
import { PageList, SortFn } from "../PageList" import { byDateAndAlphabetical, PageList, SortFn } from "../PageList"
import { stripSlashes, simplifySlug, joinSegments, FullSlug } from "../../util/path"
import { Root } from "hast" import { Root } from "hast"
import { htmlToJsx } from "../../util/jsx" import { htmlToJsx } from "../../util/jsx"
import { i18n } from "../../i18n" import { i18n } from "../../i18n"
import { QuartzPluginData } from "../../plugins/vfile" import { QuartzPluginData } from "../../plugins/vfile"
import { ComponentChildren } from "preact"
import { concatenateResources } from "../../util/resources"
import { FileTrieNode } from "../../util/fileTrie"
interface FolderContentOptions { interface FolderContentOptions {
/** /**
* Whether to display number of folders * Whether to display number of folders
@ -25,88 +25,51 @@ const defaultOptions: FolderContentOptions = {
export default ((opts?: Partial<FolderContentOptions>) => { export default ((opts?: Partial<FolderContentOptions>) => {
const options: FolderContentOptions = { ...defaultOptions, ...opts } const options: FolderContentOptions = { ...defaultOptions, ...opts }
let trie: FileTrieNode<
QuartzPluginData & {
slug: string
title: string
filePath: string
}
>
const FolderContent: QuartzComponent = (props: QuartzComponentProps) => { const FolderContent: QuartzComponent = (props: QuartzComponentProps) => {
const { tree, fileData, allFiles, cfg } = props const { tree, fileData, allFiles, cfg } = props
const folderSlug = stripSlashes(simplifySlug(fileData.slug!))
const folderParts = folderSlug.split(path.posix.sep)
if (!trie) { const allPagesInFolder: QuartzPluginData[] = []
trie = new FileTrieNode([]) const allPagesInSubfolders: Map<FullSlug, QuartzPluginData[]> = new Map()
allFiles.forEach((file) => {
if (file.frontmatter) {
trie.add({
...file,
slug: file.slug!,
title: file.frontmatter.title,
filePath: file.filePath!,
})
}
})
}
const folder = trie.findNode(fileData.slug!.split("/")) allFiles.forEach((file) => {
if (!folder) { const fileSlug = stripSlashes(simplifySlug(file.slug!))
return null const prefixed = fileSlug.startsWith(folderSlug) && fileSlug !== folderSlug
} const fileParts = fileSlug.split(path.posix.sep)
const isDirectChild = fileParts.length === folderParts.length + 1
const allPagesInFolder: QuartzPluginData[] = if (!prefixed) {
folder.children return
.map((node) => { }
// regular file, proceed
if (node.data) {
return node.data
}
if (node.isFolder && options.showSubfolders) { if (isDirectChild) {
// folders that dont have data need synthetic files allPagesInFolder.push(file)
const getMostRecentDates = (): QuartzPluginData["dates"] => { } else if (options.showSubfolders) {
let maybeDates: QuartzPluginData["dates"] | undefined = undefined const subfolderSlug = joinSegments(
for (const child of node.children) { ...fileParts.slice(0, folderParts.length + 1),
if (child.data?.dates) { ) as FullSlug
// compare all dates and assign to maybeDates if its more recent or its not set const pagesInFolder = allPagesInSubfolders.get(subfolderSlug) || []
if (!maybeDates) { allPagesInSubfolders.set(subfolderSlug, [...pagesInFolder, file])
maybeDates = { ...child.data.dates } }
} else { })
if (child.data.dates.created > maybeDates.created) {
maybeDates.created = child.data.dates.created
}
if (child.data.dates.modified > maybeDates.modified) { allPagesInSubfolders.forEach((files, subfolderSlug) => {
maybeDates.modified = child.data.dates.modified const hasIndex = allPagesInFolder.some(
} (file) => subfolderSlug === stripSlashes(simplifySlug(file.slug!)),
)
if (child.data.dates.published > maybeDates.published) { if (!hasIndex) {
maybeDates.published = child.data.dates.published const subfolderDates = files.sort(byDateAndAlphabetical(cfg))[0].dates
} const subfolderTitle = subfolderSlug.split(path.posix.sep).at(-1)!
} allPagesInFolder.push({
} slug: subfolderSlug,
} dates: subfolderDates,
return ( frontmatter: { title: subfolderTitle, tags: ["folder"] },
maybeDates ?? {
created: new Date(),
modified: new Date(),
published: new Date(),
}
)
}
return {
slug: node.slug,
dates: getMostRecentDates(),
frontmatter: {
title: node.displayName,
tags: [],
},
}
}
}) })
.filter((page) => page !== undefined) ?? [] }
})
const cssClasses: string[] = fileData.frontmatter?.cssclasses ?? [] const cssClasses: string[] = fileData.frontmatter?.cssclasses ?? []
const classes = cssClasses.join(" ") const classes = cssClasses.join(" ")
const listProps = { const listProps = {
@ -115,11 +78,10 @@ export default ((opts?: Partial<FolderContentOptions>) => {
allFiles: allPagesInFolder, allFiles: allPagesInFolder,
} }
const content = ( const content =
(tree as Root).children.length === 0 (tree as Root).children.length === 0
? fileData.description ? fileData.description
: htmlToJsx(fileData.filePath!, tree) : htmlToJsx(fileData.filePath!, tree)
) as ComponentChildren
return ( return (
<div class="popover-hint"> <div class="popover-hint">
@ -140,6 +102,6 @@ export default ((opts?: Partial<FolderContentOptions>) => {
) )
} }
FolderContent.css = concatenateResources(style, PageList.css) FolderContent.css = style + PageList.css
return FolderContent return FolderContent
}) satisfies QuartzComponentConstructor }) satisfies QuartzComponentConstructor

View File

@ -6,8 +6,6 @@ import { QuartzPluginData } from "../../plugins/vfile"
import { Root } from "hast" import { Root } from "hast"
import { htmlToJsx } from "../../util/jsx" import { htmlToJsx } from "../../util/jsx"
import { i18n } from "../../i18n" import { i18n } from "../../i18n"
import { ComponentChildren } from "preact"
import { concatenateResources } from "../../util/resources"
interface TagContentOptions { interface TagContentOptions {
sort?: SortFn sort?: SortFn
@ -35,11 +33,10 @@ export default ((opts?: Partial<TagContentOptions>) => {
(file.frontmatter?.tags ?? []).flatMap(getAllSegmentPrefixes).includes(tag), (file.frontmatter?.tags ?? []).flatMap(getAllSegmentPrefixes).includes(tag),
) )
const content = ( const content =
(tree as Root).children.length === 0 (tree as Root).children.length === 0
? fileData.description ? fileData.description
: htmlToJsx(fileData.filePath!, tree) : htmlToJsx(fileData.filePath!, tree)
) as ComponentChildren
const cssClasses: string[] = fileData.frontmatter?.cssclasses ?? [] const cssClasses: string[] = fileData.frontmatter?.cssclasses ?? []
const classes = cssClasses.join(" ") const classes = cssClasses.join(" ")
if (tag === "/") { if (tag === "/") {
@ -125,6 +122,6 @@ export default ((opts?: Partial<TagContentOptions>) => {
} }
} }
TagContent.css = concatenateResources(style, PageList.css) TagContent.css = style + PageList.css
return TagContent return TagContent
}) satisfies QuartzComponentConstructor }) satisfies QuartzComponentConstructor

View File

@ -3,12 +3,15 @@ import { QuartzComponent, QuartzComponentProps } from "./types"
import HeaderConstructor from "./Header" import HeaderConstructor from "./Header"
import BodyConstructor from "./Body" import BodyConstructor from "./Body"
import { JSResourceToScriptElement, StaticResources } from "../util/resources" import { JSResourceToScriptElement, StaticResources } from "../util/resources"
import { FullSlug, RelativeURL, joinSegments, normalizeHastElement } from "../util/path" import { clone, FullSlug, RelativeURL, joinSegments, normalizeHastElement } from "../util/path"
import { clone } from "../util/clone"
import { visit } from "unist-util-visit" import { visit } from "unist-util-visit"
import { Root, Element, ElementContent } from "hast" import { Root, Element, ElementContent } from "hast"
import { GlobalConfiguration } from "../cfg" import { GlobalConfiguration } from "../cfg"
import { i18n } from "../i18n" import { i18n } from "../i18n"
// @ts-ignore
import mermaidScript from "./scripts/mermaid.inline"
import mermaidStyle from "./styles/mermaid.inline.scss"
import { QuartzPluginData } from "../plugins/vfile"
interface RenderComponents { interface RenderComponents {
head: QuartzComponent head: QuartzComponent
@ -24,6 +27,7 @@ interface RenderComponents {
const headerRegex = new RegExp(/h[1-6]/) const headerRegex = new RegExp(/h[1-6]/)
export function pageResources( export function pageResources(
baseDir: FullSlug | RelativeURL, baseDir: FullSlug | RelativeURL,
fileData: QuartzPluginData,
staticResources: StaticResources, staticResources: StaticResources,
): StaticResources { ): StaticResources {
const contentIndexPath = joinSegments(baseDir, "static/contentIndex.json") const contentIndexPath = joinSegments(baseDir, "static/contentIndex.json")
@ -50,9 +54,19 @@ export function pageResources(
}, },
...staticResources.js, ...staticResources.js,
], ],
additionalHead: staticResources.additionalHead,
} }
if (fileData.hasMermaidDiagram) {
resources.js.push({
script: mermaidScript,
loadTime: "afterDOMReady",
moduleType: "module",
contentType: "inline",
})
resources.css.push({ content: mermaidStyle, inline: true })
}
// NOTE: we have to put this last to make sure spa.inline.ts is the last item.
resources.js.push({ resources.js.push({
src: joinSegments(baseDir, "postscript.js"), src: joinSegments(baseDir, "postscript.js"),
loadTime: "afterDOMReady", loadTime: "afterDOMReady",
@ -63,12 +77,17 @@ export function pageResources(
return resources return resources
} }
function renderTranscludes( export function renderPage(
root: Root,
cfg: GlobalConfiguration, cfg: GlobalConfiguration,
slug: FullSlug, slug: FullSlug,
componentData: QuartzComponentProps, componentData: QuartzComponentProps,
) { components: RenderComponents,
pageResources: StaticResources,
): string {
// make a deep copy of the tree so we don't remove the transclusion references
// for the file cached in contentMap in build.ts
const root = clone(componentData.tree) as Root
// process transcludes in componentData // process transcludes in componentData
visit(root, "element", (node, _index, _parent) => { visit(root, "element", (node, _index, _parent) => {
if (node.tagName === "blockquote") { if (node.tagName === "blockquote") {
@ -184,19 +203,6 @@ function renderTranscludes(
} }
} }
}) })
}
export function renderPage(
cfg: GlobalConfiguration,
slug: FullSlug,
componentData: QuartzComponentProps,
components: RenderComponents,
pageResources: StaticResources,
): string {
// make a deep copy of the tree so we don't remove the transclusion references
// for the file cached in contentMap in build.ts
const root = clone(componentData.tree) as Root
renderTranscludes(root, cfg, slug, componentData)
// set componentData.tree to the edited html that has transclusions rendered // set componentData.tree to the edited html that has transclusions rendered
componentData.tree = root componentData.tree = root

View File

@ -28,15 +28,17 @@ function setupCallout() {
) as HTMLCollectionOf<HTMLElement> ) as HTMLCollectionOf<HTMLElement>
for (const div of collapsible) { for (const div of collapsible) {
const title = div.firstElementChild const title = div.firstElementChild
if (!title) continue
title.addEventListener("click", toggleCallout) if (title) {
window.addCleanup(() => title.removeEventListener("click", toggleCallout)) title.addEventListener("click", toggleCallout)
window.addCleanup(() => title.removeEventListener("click", toggleCallout))
const collapsed = div.classList.contains("is-collapsed") const collapsed = div.classList.contains("is-collapsed")
const height = collapsed ? title.scrollHeight : div.scrollHeight const height = collapsed ? title.scrollHeight : div.scrollHeight
div.style.maxHeight = height + "px" div.style.maxHeight = height + "px"
}
} }
} }
document.addEventListener("nav", setupCallout) document.addEventListener("nav", setupCallout)
window.addEventListener("resize", setupCallout)

View File

@ -10,7 +10,7 @@ const emitThemeChangeEvent = (theme: "light" | "dark") => {
} }
document.addEventListener("nav", () => { document.addEventListener("nav", () => {
const switchTheme = () => { const switchTheme = (e: Event) => {
const newTheme = const newTheme =
document.documentElement.getAttribute("saved-theme") === "dark" ? "light" : "dark" document.documentElement.getAttribute("saved-theme") === "dark" ? "light" : "dark"
document.documentElement.setAttribute("saved-theme", newTheme) document.documentElement.setAttribute("saved-theme", newTheme)
@ -25,11 +25,12 @@ document.addEventListener("nav", () => {
emitThemeChangeEvent(newTheme) emitThemeChangeEvent(newTheme)
} }
for (const darkmodeButton of document.getElementsByClassName("darkmode")) { // Darkmode toggle
darkmodeButton.addEventListener("click", switchTheme) const themeButton = document.querySelector("#darkmode") as HTMLButtonElement
window.addCleanup(() => darkmodeButton.removeEventListener("click", switchTheme)) if (themeButton) {
themeButton.addEventListener("click", switchTheme)
window.addCleanup(() => themeButton.removeEventListener("click", switchTheme))
} }
// Listen for changes in prefers-color-scheme // Listen for changes in prefers-color-scheme
const colorSchemeMediaQuery = window.matchMedia("(prefers-color-scheme: dark)") const colorSchemeMediaQuery = window.matchMedia("(prefers-color-scheme: dark)")
colorSchemeMediaQuery.addEventListener("change", themeChange) colorSchemeMediaQuery.addEventListener("change", themeChange)

View File

@ -1,33 +1,30 @@
import { FileTrieNode } from "../../util/fileTrie" import { FolderState } from "../ExplorerNode"
import { FullSlug, resolveRelative, simplifySlug } from "../../util/path"
import { ContentDetails } from "../../plugins/emitters/contentIndex"
type MaybeHTMLElement = HTMLElement | undefined type MaybeHTMLElement = HTMLElement | undefined
let currentExplorerState: FolderState[]
const observer = new IntersectionObserver((entries) => {
// If last element is observed, remove gradient of "overflow" class so element is visible
const explorerUl = document.getElementById("explorer-ul")
if (!explorerUl) return
for (const entry of entries) {
if (entry.isIntersecting) {
explorerUl.classList.add("no-background")
} else {
explorerUl.classList.remove("no-background")
}
}
})
interface ParsedOptions {
folderClickBehavior: "collapse" | "link"
folderDefaultState: "collapsed" | "open"
useSavedState: boolean
sortFn: (a: FileTrieNode, b: FileTrieNode) => number
filterFn: (node: FileTrieNode) => boolean
mapFn: (node: FileTrieNode) => void
order: "sort" | "filter" | "map"[]
}
type FolderState = {
path: string
collapsed: boolean
}
let currentExplorerState: Array<FolderState>
function toggleExplorer(this: HTMLElement) { function toggleExplorer(this: HTMLElement) {
const nearestExplorer = this.closest(".explorer") as HTMLElement this.classList.toggle("collapsed")
if (!nearestExplorer) return this.setAttribute(
nearestExplorer.classList.toggle("collapsed")
nearestExplorer.setAttribute(
"aria-expanded", "aria-expanded",
nearestExplorer.getAttribute("aria-expanded") === "true" ? "false" : "true", this.getAttribute("aria-expanded") === "true" ? "false" : "true",
) )
const content = this.nextElementSibling as MaybeHTMLElement
if (!content) return
content.classList.toggle("collapsed")
} }
function toggleFolder(evt: MouseEvent) { function toggleFolder(evt: MouseEvent) {
@ -35,247 +32,104 @@ function toggleFolder(evt: MouseEvent) {
const target = evt.target as MaybeHTMLElement const target = evt.target as MaybeHTMLElement
if (!target) return if (!target) return
// Check if target was svg icon or button
const isSvg = target.nodeName === "svg" const isSvg = target.nodeName === "svg"
const childFolderContainer = (
// corresponding <ul> element relative to clicked button/folder
const folderContainer = (
isSvg isSvg
? // svg -> div.folder-container ? target.parentElement?.nextSibling
target.parentElement : target.parentElement?.parentElement?.nextElementSibling
: // button.folder-button -> div -> div.folder-container
target.parentElement?.parentElement
) as MaybeHTMLElement ) as MaybeHTMLElement
if (!folderContainer) return const currentFolderParent = (
const childFolderContainer = folderContainer.nextElementSibling as MaybeHTMLElement isSvg ? target.nextElementSibling : target.parentElement
if (!childFolderContainer) return ) as MaybeHTMLElement
if (!(childFolderContainer && currentFolderParent)) return
childFolderContainer.classList.toggle("open") childFolderContainer.classList.toggle("open")
const isCollapsed = childFolderContainer.classList.contains("open")
// Collapse folder container setFolderState(childFolderContainer, !isCollapsed)
const isCollapsed = !childFolderContainer.classList.contains("open") const fullFolderPath = currentFolderParent.dataset.folderpath as string
setFolderState(childFolderContainer, isCollapsed) toggleCollapsedByPath(currentExplorerState, fullFolderPath)
const currentFolderState = currentExplorerState.find(
(item) => item.path === folderContainer.dataset.folderpath,
)
if (currentFolderState) {
currentFolderState.collapsed = isCollapsed
} else {
currentExplorerState.push({
path: folderContainer.dataset.folderpath as FullSlug,
collapsed: isCollapsed,
})
}
const stringifiedFileTree = JSON.stringify(currentExplorerState) const stringifiedFileTree = JSON.stringify(currentExplorerState)
localStorage.setItem("fileTree", stringifiedFileTree) localStorage.setItem("fileTree", stringifiedFileTree)
} }
function createFileNode(currentSlug: FullSlug, node: FileTrieNode): HTMLLIElement { function setupExplorer() {
const template = document.getElementById("template-file") as HTMLTemplateElement const explorer = document.getElementById("explorer")
const clone = template.content.cloneNode(true) as DocumentFragment
const li = clone.querySelector("li") as HTMLLIElement
const a = li.querySelector("a") as HTMLAnchorElement
a.href = resolveRelative(currentSlug, node.slug)
a.dataset.for = node.slug
a.textContent = node.displayName
if (currentSlug === node.slug) {
a.classList.add("active")
}
return li
}
function createFolderNode(
currentSlug: FullSlug,
node: FileTrieNode,
opts: ParsedOptions,
): HTMLLIElement {
const template = document.getElementById("template-folder") as HTMLTemplateElement
const clone = template.content.cloneNode(true) as DocumentFragment
const li = clone.querySelector("li") as HTMLLIElement
const folderContainer = li.querySelector(".folder-container") as HTMLElement
const titleContainer = folderContainer.querySelector("div") as HTMLElement
const folderOuter = li.querySelector(".folder-outer") as HTMLElement
const ul = folderOuter.querySelector("ul") as HTMLUListElement
const folderPath = node.slug
folderContainer.dataset.folderpath = folderPath
if (opts.folderClickBehavior === "link") {
// Replace button with link for link behavior
const button = titleContainer.querySelector(".folder-button") as HTMLElement
const a = document.createElement("a")
a.href = resolveRelative(currentSlug, folderPath)
a.dataset.for = folderPath
a.className = "folder-title"
a.textContent = node.displayName
button.replaceWith(a)
} else {
const span = titleContainer.querySelector(".folder-title") as HTMLElement
span.textContent = node.displayName
}
// if the saved state is collapsed or the default state is collapsed
const isCollapsed =
currentExplorerState.find((item) => item.path === folderPath)?.collapsed ??
opts.folderDefaultState === "collapsed"
// if this folder is a prefix of the current path we
// want to open it anyways
const simpleFolderPath = simplifySlug(folderPath)
const folderIsPrefixOfCurrentSlug =
simpleFolderPath === currentSlug.slice(0, simpleFolderPath.length)
if (!isCollapsed || folderIsPrefixOfCurrentSlug) {
folderOuter.classList.add("open")
}
for (const child of node.children) {
const childNode = child.isFolder
? createFolderNode(currentSlug, child, opts)
: createFileNode(currentSlug, child)
ul.appendChild(childNode)
}
return li
}
async function setupExplorer(currentSlug: FullSlug) {
const allExplorers = document.querySelectorAll("div.explorer") as NodeListOf<HTMLElement>
for (const explorer of allExplorers) {
const dataFns = JSON.parse(explorer.dataset.dataFns || "{}")
const opts: ParsedOptions = {
folderClickBehavior: (explorer.dataset.behavior || "collapse") as "collapse" | "link",
folderDefaultState: (explorer.dataset.collapsed || "collapsed") as "collapsed" | "open",
useSavedState: explorer.dataset.savestate === "true",
order: dataFns.order || ["filter", "map", "sort"],
sortFn: new Function("return " + (dataFns.sortFn || "undefined"))(),
filterFn: new Function("return " + (dataFns.filterFn || "undefined"))(),
mapFn: new Function("return " + (dataFns.mapFn || "undefined"))(),
}
// Get folder state from local storage
const storageTree = localStorage.getItem("fileTree")
const serializedExplorerState = storageTree && opts.useSavedState ? JSON.parse(storageTree) : []
const oldIndex = new Map<string, boolean>(
serializedExplorerState.map((entry: FolderState) => [entry.path, entry.collapsed]),
)
const data = await fetchData
const entries = [...Object.entries(data)] as [FullSlug, ContentDetails][]
const trie = FileTrieNode.fromEntries(entries)
// Apply functions in order
for (const fn of opts.order) {
switch (fn) {
case "filter":
if (opts.filterFn) trie.filter(opts.filterFn)
break
case "map":
if (opts.mapFn) trie.map(opts.mapFn)
break
case "sort":
if (opts.sortFn) trie.sort(opts.sortFn)
break
}
}
// Get folder paths for state management
const folderPaths = trie.getFolderPaths()
currentExplorerState = folderPaths.map((path) => {
const previousState = oldIndex.get(path)
return {
path,
collapsed:
previousState === undefined ? opts.folderDefaultState === "collapsed" : previousState,
}
})
const explorerUl = explorer.querySelector(".explorer-ul")
if (!explorerUl) continue
// Create and insert new content
const fragment = document.createDocumentFragment()
for (const child of trie.children) {
const node = child.isFolder
? createFolderNode(currentSlug, child, opts)
: createFileNode(currentSlug, child)
fragment.appendChild(node)
}
explorerUl.insertBefore(fragment, explorerUl.firstChild)
// restore explorer scrollTop position if it exists
const scrollTop = sessionStorage.getItem("explorerScrollTop")
if (scrollTop) {
explorerUl.scrollTop = parseInt(scrollTop)
} else {
// try to scroll to the active element if it exists
const activeElement = explorerUl.querySelector(".active")
if (activeElement) {
activeElement.scrollIntoView({ behavior: "smooth" })
}
}
// Set up event handlers
const explorerButtons = explorer.getElementsByClassName(
"explorer-toggle",
) as HTMLCollectionOf<HTMLElement>
for (const button of explorerButtons) {
button.addEventListener("click", toggleExplorer)
window.addCleanup(() => button.removeEventListener("click", toggleExplorer))
}
// Set up folder click handlers
if (opts.folderClickBehavior === "collapse") {
const folderButtons = explorer.getElementsByClassName(
"folder-button",
) as HTMLCollectionOf<HTMLElement>
for (const button of folderButtons) {
button.addEventListener("click", toggleFolder)
window.addCleanup(() => button.removeEventListener("click", toggleFolder))
}
}
const folderIcons = explorer.getElementsByClassName(
"folder-icon",
) as HTMLCollectionOf<HTMLElement>
for (const icon of folderIcons) {
icon.addEventListener("click", toggleFolder)
window.addCleanup(() => icon.removeEventListener("click", toggleFolder))
}
}
}
document.addEventListener("prenav", async () => {
// save explorer scrollTop position
const explorer = document.querySelector(".explorer-ul")
if (!explorer) return if (!explorer) return
sessionStorage.setItem("explorerScrollTop", explorer.scrollTop.toString())
})
document.addEventListener("nav", async (e: CustomEventMap["nav"]) => { if (explorer.dataset.behavior === "collapse") {
const currentSlug = e.detail.url for (const item of document.getElementsByClassName(
await setupExplorer(currentSlug) "folder-button",
) as HTMLCollectionOf<HTMLElement>) {
// if mobile hamburger is visible, collapse by default item.addEventListener("click", toggleFolder)
for (const explorer of document.getElementsByClassName("explorer")) { window.addCleanup(() => item.removeEventListener("click", toggleFolder))
const mobileExplorer = explorer.querySelector(".mobile-explorer")
if (!mobileExplorer) return
if (mobileExplorer.checkVisibility()) {
explorer.classList.add("collapsed")
explorer.setAttribute("aria-expanded", "false")
} }
}
mobileExplorer.classList.remove("hide-until-loaded") explorer.addEventListener("click", toggleExplorer)
window.addCleanup(() => explorer.removeEventListener("click", toggleExplorer))
// Set up click handlers for each folder (click handler on folder "icon")
for (const item of document.getElementsByClassName(
"folder-icon",
) as HTMLCollectionOf<HTMLElement>) {
item.addEventListener("click", toggleFolder)
window.addCleanup(() => item.removeEventListener("click", toggleFolder))
}
// Get folder state from local storage
const storageTree = localStorage.getItem("fileTree")
const useSavedFolderState = explorer?.dataset.savestate === "true"
const oldExplorerState: FolderState[] =
storageTree && useSavedFolderState ? JSON.parse(storageTree) : []
const oldIndex = new Map(oldExplorerState.map((entry) => [entry.path, entry.collapsed]))
const newExplorerState: FolderState[] = explorer.dataset.tree
? JSON.parse(explorer.dataset.tree)
: []
currentExplorerState = []
for (const { path, collapsed } of newExplorerState) {
currentExplorerState.push({ path, collapsed: oldIndex.get(path) ?? collapsed })
}
currentExplorerState.map((folderState) => {
const folderLi = document.querySelector(
`[data-folderpath='${folderState.path}']`,
) as MaybeHTMLElement
const folderUl = folderLi?.parentElement?.nextElementSibling as MaybeHTMLElement
if (folderUl) {
setFolderState(folderUl, folderState.collapsed)
}
})
}
window.addEventListener("resize", setupExplorer)
document.addEventListener("nav", () => {
setupExplorer()
observer.disconnect()
// select pseudo element at end of list
const lastItem = document.getElementById("explorer-end")
if (lastItem) {
observer.observe(lastItem)
} }
}) })
/**
* 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) { function setFolderState(folderElement: HTMLElement, collapsed: boolean) {
return collapsed ? folderElement.classList.remove("open") : folderElement.classList.add("open") return collapsed ? folderElement.classList.remove("open") : 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
}
}

View File

@ -8,7 +8,6 @@ import {
forceCenter, forceCenter,
forceLink, forceLink,
forceCollide, forceCollide,
forceRadial,
zoomIdentity, zoomIdentity,
select, select,
drag, drag,
@ -68,9 +67,11 @@ type TweenNode = {
stop: () => void stop: () => void
} }
async function renderGraph(graph: HTMLElement, fullSlug: FullSlug) { async function renderGraph(container: string, fullSlug: FullSlug) {
const slug = simplifySlug(fullSlug) const slug = simplifySlug(fullSlug)
const visited = getVisited() const visited = getVisited()
const graph = document.getElementById(container)
if (!graph) return
removeAllChildren(graph) removeAllChildren(graph)
let { let {
@ -86,7 +87,6 @@ async function renderGraph(graph: HTMLElement, fullSlug: FullSlug) {
removeTags, removeTags,
showTags, showTags,
focusOnHover, focusOnHover,
enableRadial,
} = JSON.parse(graph.dataset["cfg"]!) as D3Config } = JSON.parse(graph.dataset["cfg"]!) as D3Config
const data: Map<SimpleSlug, ContentDetails> = new Map( const data: Map<SimpleSlug, ContentDetails> = new Map(
@ -161,9 +161,6 @@ async function renderGraph(graph: HTMLElement, fullSlug: FullSlug) {
})), })),
} }
const width = graph.offsetWidth
const height = Math.max(graph.offsetHeight, 250)
// we virtualize the simulation and use pixi to actually render it // we virtualize the simulation and use pixi to actually render it
const simulation: Simulation<NodeData, LinkData> = forceSimulation<NodeData>(graphData.nodes) const simulation: Simulation<NodeData, LinkData> = forceSimulation<NodeData>(graphData.nodes)
.force("charge", forceManyBody().strength(-100 * repelForce)) .force("charge", forceManyBody().strength(-100 * repelForce))
@ -171,8 +168,8 @@ async function renderGraph(graph: HTMLElement, fullSlug: FullSlug) {
.force("link", forceLink(graphData.links).distance(linkDistance)) .force("link", forceLink(graphData.links).distance(linkDistance))
.force("collide", forceCollide<NodeData>((n) => nodeRadius(n)).iterations(3)) .force("collide", forceCollide<NodeData>((n) => nodeRadius(n)).iterations(3))
const radius = (Math.min(width, height) / 2) * 0.8 const width = graph.offsetWidth
if (enableRadial) simulation.force("radial", forceRadial(radius).strength(0.2)) const height = Math.max(graph.offsetHeight, 250)
// precompute style prop strings as pixi doesn't support css variables // precompute style prop strings as pixi doesn't support css variables
const cssVars = [ const cssVars = [
@ -366,9 +363,9 @@ async function renderGraph(graph: HTMLElement, fullSlug: FullSlug) {
const stage = app.stage const stage = app.stage
stage.interactive = false stage.interactive = false
const labelsContainer = new Container<Text>({ zIndex: 3, isRenderGroup: true }) const labelsContainer = new Container<Text>({ zIndex: 3 })
const nodesContainer = new Container<Graphics>({ zIndex: 2, isRenderGroup: true }) const nodesContainer = new Container<Graphics>({ zIndex: 2 })
const linkContainer = new Container<Graphics>({ zIndex: 1, isRenderGroup: true }) const linkContainer = new Container<Graphics>({ zIndex: 1 })
stage.addChild(nodesContainer, labelsContainer, linkContainer) stage.addChild(nodesContainer, labelsContainer, linkContainer)
for (const n of graphData.nodes) { for (const n of graphData.nodes) {
@ -400,6 +397,7 @@ async function renderGraph(graph: HTMLElement, fullSlug: FullSlug) {
}) })
.circle(0, 0, nodeRadius(n)) .circle(0, 0, nodeRadius(n))
.fill({ color: isTagNode ? computedStyleMap["--light"] : color(n) }) .fill({ color: isTagNode ? computedStyleMap["--light"] : color(n) })
.stroke({ width: isTagNode ? 2 : 0, color: color(n) })
.on("pointerover", (e) => { .on("pointerover", (e) => {
updateHoverInfo(e.target.label) updateHoverInfo(e.target.label)
oldLabelOpacity = label.alpha oldLabelOpacity = label.alpha
@ -415,10 +413,6 @@ async function renderGraph(graph: HTMLElement, fullSlug: FullSlug) {
} }
}) })
if (isTagNode) {
gfx.stroke({ width: 2, color: computedStyleMap["--tertiary"] })
}
nodesContainer.addChild(gfx) nodesContainer.addChild(gfx)
labelsContainer.addChild(label) labelsContainer.addChild(label)
@ -523,9 +517,7 @@ async function renderGraph(graph: HTMLElement, fullSlug: FullSlug) {
) )
} }
let stopAnimation = false
function animate(time: number) { function animate(time: number) {
if (stopAnimation) return
for (const n of nodeRenderData) { for (const n of nodeRenderData) {
const { x, y } = n.simulationData const { x, y } = n.simulationData
if (!x || !y) continue if (!x || !y) continue
@ -549,101 +541,61 @@ async function renderGraph(graph: HTMLElement, fullSlug: FullSlug) {
requestAnimationFrame(animate) requestAnimationFrame(animate)
} }
requestAnimationFrame(animate) const graphAnimationFrameHandle = requestAnimationFrame(animate)
return () => { window.addCleanup(() => cancelAnimationFrame(graphAnimationFrameHandle))
stopAnimation = true
app.destroy()
}
}
let localGraphCleanups: (() => void)[] = []
let globalGraphCleanups: (() => void)[] = []
function cleanupLocalGraphs() {
for (const cleanup of localGraphCleanups) {
cleanup()
}
localGraphCleanups = []
}
function cleanupGlobalGraphs() {
for (const cleanup of globalGraphCleanups) {
cleanup()
}
globalGraphCleanups = []
} }
document.addEventListener("nav", async (e: CustomEventMap["nav"]) => { document.addEventListener("nav", async (e: CustomEventMap["nav"]) => {
const slug = e.detail.url const slug = e.detail.url
addToVisited(simplifySlug(slug)) addToVisited(simplifySlug(slug))
await renderGraph("graph-container", slug)
async function renderLocalGraph() { // Function to re-render the graph when the theme changes
cleanupLocalGraphs()
const localGraphContainers = document.getElementsByClassName("graph-container")
for (const container of localGraphContainers) {
localGraphCleanups.push(await renderGraph(container as HTMLElement, slug))
}
}
await renderLocalGraph()
const handleThemeChange = () => { const handleThemeChange = () => {
void renderLocalGraph() renderGraph("graph-container", slug)
} }
// event listener for theme change
document.addEventListener("themechange", handleThemeChange) document.addEventListener("themechange", handleThemeChange)
// cleanup for the event listener
window.addCleanup(() => { window.addCleanup(() => {
document.removeEventListener("themechange", handleThemeChange) document.removeEventListener("themechange", handleThemeChange)
}) })
const containers = [...document.getElementsByClassName("global-graph-outer")] as HTMLElement[] const container = document.getElementById("global-graph-outer")
async function renderGlobalGraph() { const sidebar = container?.closest(".sidebar") as HTMLElement
const slug = getFullSlug(window)
for (const container of containers) {
container.classList.add("active")
const sidebar = container.closest(".sidebar") as HTMLElement
if (sidebar) {
sidebar.style.zIndex = "1"
}
const graphContainer = container.querySelector(".global-graph-container") as HTMLElement function renderGlobalGraph() {
registerEscapeHandler(container, hideGlobalGraph) const slug = getFullSlug(window)
if (graphContainer) { container?.classList.add("active")
globalGraphCleanups.push(await renderGraph(graphContainer, slug)) if (sidebar) {
} sidebar.style.zIndex = "1"
} }
renderGraph("global-graph-container", slug)
registerEscapeHandler(container, hideGlobalGraph)
} }
function hideGlobalGraph() { function hideGlobalGraph() {
cleanupGlobalGraphs() container?.classList.remove("active")
for (const container of containers) { if (sidebar) {
container.classList.remove("active") sidebar.style.zIndex = ""
const sidebar = container.closest(".sidebar") as HTMLElement
if (sidebar) {
sidebar.style.zIndex = ""
}
} }
} }
async function shortcutHandler(e: HTMLElementEventMap["keydown"]) { async function shortcutHandler(e: HTMLElementEventMap["keydown"]) {
if (e.key === "g" && (e.ctrlKey || e.metaKey) && !e.shiftKey) { if (e.key === "g" && (e.ctrlKey || e.metaKey) && !e.shiftKey) {
e.preventDefault() e.preventDefault()
const anyGlobalGraphOpen = containers.some((container) => const globalGraphOpen = container?.classList.contains("active")
container.classList.contains("active"), globalGraphOpen ? hideGlobalGraph() : renderGlobalGraph()
)
anyGlobalGraphOpen ? hideGlobalGraph() : renderGlobalGraph()
} }
} }
const containerIcons = document.getElementsByClassName("global-graph-icon") const containerIcon = document.getElementById("global-graph-icon")
Array.from(containerIcons).forEach((icon) => { containerIcon?.addEventListener("click", renderGlobalGraph)
icon.addEventListener("click", renderGlobalGraph) window.addCleanup(() => containerIcon?.removeEventListener("click", renderGlobalGraph))
window.addCleanup(() => icon.removeEventListener("click", renderGlobalGraph))
})
document.addEventListener("keydown", shortcutHandler) document.addEventListener("keydown", shortcutHandler)
window.addCleanup(() => { window.addCleanup(() => document.removeEventListener("keydown", shortcutHandler))
document.removeEventListener("keydown", shortcutHandler)
cleanupLocalGraphs()
cleanupGlobalGraphs()
})
}) })

View File

@ -1,4 +1,4 @@
import { registerEscapeHandler, removeAllChildren } from "./util" import { removeAllChildren } from "./util"
interface Position { interface Position {
x: number x: number
@ -12,8 +12,7 @@ class DiagramPanZoom {
private scale = 1 private scale = 1
private readonly MIN_SCALE = 0.5 private readonly MIN_SCALE = 0.5
private readonly MAX_SCALE = 3 private readonly MAX_SCALE = 3
private readonly ZOOM_SENSITIVITY = 0.001
cleanups: (() => void)[] = []
constructor( constructor(
private container: HTMLElement, private container: HTMLElement,
@ -21,33 +20,19 @@ class DiagramPanZoom {
) { ) {
this.setupEventListeners() this.setupEventListeners()
this.setupNavigationControls() this.setupNavigationControls()
this.resetTransform()
} }
private setupEventListeners() { private setupEventListeners() {
// Mouse drag events // Mouse drag events
const mouseDownHandler = this.onMouseDown.bind(this) this.container.addEventListener("mousedown", this.onMouseDown.bind(this))
const mouseMoveHandler = this.onMouseMove.bind(this) document.addEventListener("mousemove", this.onMouseMove.bind(this))
const mouseUpHandler = this.onMouseUp.bind(this) document.addEventListener("mouseup", this.onMouseUp.bind(this))
const resizeHandler = this.resetTransform.bind(this)
this.container.addEventListener("mousedown", mouseDownHandler) // Wheel zoom events
document.addEventListener("mousemove", mouseMoveHandler) this.container.addEventListener("wheel", this.onWheel.bind(this), { passive: false })
document.addEventListener("mouseup", mouseUpHandler)
window.addEventListener("resize", resizeHandler)
this.cleanups.push( // Reset on window resize
() => this.container.removeEventListener("mousedown", mouseDownHandler), window.addEventListener("resize", this.resetTransform.bind(this))
() => document.removeEventListener("mousemove", mouseMoveHandler),
() => document.removeEventListener("mouseup", mouseUpHandler),
() => window.removeEventListener("resize", resizeHandler),
)
}
cleanup() {
for (const cleanup of this.cleanups) {
cleanup()
}
} }
private setupNavigationControls() { private setupNavigationControls() {
@ -99,6 +84,26 @@ class DiagramPanZoom {
this.container.style.cursor = "grab" this.container.style.cursor = "grab"
} }
private onWheel(e: WheelEvent) {
e.preventDefault()
const delta = -e.deltaY * this.ZOOM_SENSITIVITY
const newScale = Math.min(Math.max(this.scale + delta, this.MIN_SCALE), this.MAX_SCALE)
// Calculate mouse position relative to content
const rect = this.content.getBoundingClientRect()
const mouseX = e.clientX - rect.left
const mouseY = e.clientY - rect.top
// Adjust pan to zoom around mouse position
const scaleDiff = newScale - this.scale
this.currentPan.x -= mouseX * scaleDiff
this.currentPan.y -= mouseY * scaleDiff
this.scale = newScale
this.updateTransform()
}
private zoom(delta: number) { private zoom(delta: number) {
const newScale = Math.min(Math.max(this.scale + delta, this.MIN_SCALE), this.MAX_SCALE) const newScale = Math.min(Math.max(this.scale + delta, this.MIN_SCALE), this.MAX_SCALE)
@ -121,11 +126,7 @@ class DiagramPanZoom {
private resetTransform() { private resetTransform() {
this.scale = 1 this.scale = 1
const svg = this.content.querySelector("svg")! this.currentPan = { x: 0, y: 0 }
this.currentPan = {
x: svg.getBoundingClientRect().width / 2,
y: svg.getBoundingClientRect().height / 2,
}
this.updateTransform() this.updateTransform()
} }
} }
@ -148,59 +149,38 @@ document.addEventListener("nav", async () => {
const nodes = center.querySelectorAll("code.mermaid") as NodeListOf<HTMLElement> const nodes = center.querySelectorAll("code.mermaid") as NodeListOf<HTMLElement>
if (nodes.length === 0) return if (nodes.length === 0) return
const computedStyleMap = cssVars.reduce(
(acc, key) => {
acc[key] = getComputedStyle(document.documentElement).getPropertyValue(key)
return acc
},
{} as Record<(typeof cssVars)[number], string>,
)
mermaidImport ||= await import( mermaidImport ||= await import(
// @ts-ignore //@ts-ignore
"https://cdnjs.cloudflare.com/ajax/libs/mermaid/11.4.0/mermaid.esm.min.mjs" "https://cdnjs.cloudflare.com/ajax/libs/mermaid/11.4.0/mermaid.esm.min.mjs"
) )
const mermaid = mermaidImport.default const mermaid = mermaidImport.default
const textMapping: WeakMap<HTMLElement, string> = new WeakMap() const darkMode = document.documentElement.getAttribute("saved-theme") === "dark"
for (const node of nodes) { mermaid.initialize({
textMapping.set(node, node.innerText) startOnLoad: false,
} securityLevel: "loose",
theme: darkMode ? "dark" : "base",
async function renderMermaid() { themeVariables: {
// de-init any other diagrams fontFamily: computedStyleMap["--codeFont"],
for (const node of nodes) { primaryColor: computedStyleMap["--light"],
node.removeAttribute("data-processed") primaryTextColor: computedStyleMap["--darkgray"],
const oldText = textMapping.get(node) primaryBorderColor: computedStyleMap["--tertiary"],
if (oldText) { lineColor: computedStyleMap["--darkgray"],
node.innerHTML = oldText secondaryColor: computedStyleMap["--secondary"],
} tertiaryColor: computedStyleMap["--tertiary"],
} clusterBkg: computedStyleMap["--light"],
edgeLabelBackground: computedStyleMap["--highlight"],
const computedStyleMap = cssVars.reduce( },
(acc, key) => { })
acc[key] = window.getComputedStyle(document.documentElement).getPropertyValue(key) await mermaid.run({ nodes })
return acc
},
{} as Record<(typeof cssVars)[number], string>,
)
const darkMode = document.documentElement.getAttribute("saved-theme") === "dark"
mermaid.initialize({
startOnLoad: false,
securityLevel: "loose",
theme: darkMode ? "dark" : "base",
themeVariables: {
fontFamily: computedStyleMap["--codeFont"],
primaryColor: computedStyleMap["--light"],
primaryTextColor: computedStyleMap["--darkgray"],
primaryBorderColor: computedStyleMap["--tertiary"],
lineColor: computedStyleMap["--darkgray"],
secondaryColor: computedStyleMap["--secondary"],
tertiaryColor: computedStyleMap["--tertiary"],
clusterBkg: computedStyleMap["--light"],
edgeLabelBackground: computedStyleMap["--highlight"],
},
})
await mermaid.run({ nodes })
}
await renderMermaid()
document.addEventListener("themechange", renderMermaid)
window.addCleanup(() => document.removeEventListener("themechange", renderMermaid))
for (let i = 0; i < nodes.length; i++) { for (let i = 0; i < nodes.length; i++) {
const codeBlock = nodes[i] as HTMLElement const codeBlock = nodes[i] as HTMLElement
@ -223,6 +203,7 @@ document.addEventListener("nav", async () => {
if (!popupContainer) return if (!popupContainer) return
let panZoom: DiagramPanZoom | null = null let panZoom: DiagramPanZoom | null = null
function showMermaid() { function showMermaid() {
const container = popupContainer.querySelector("#mermaid-space") as HTMLElement const container = popupContainer.querySelector("#mermaid-space") as HTMLElement
const content = popupContainer.querySelector(".mermaid-content") as HTMLElement const content = popupContainer.querySelector(".mermaid-content") as HTMLElement
@ -243,16 +224,25 @@ document.addEventListener("nav", async () => {
function hideMermaid() { function hideMermaid() {
popupContainer.classList.remove("active") popupContainer.classList.remove("active")
panZoom?.cleanup()
panZoom = null panZoom = null
} }
function handleEscape(e: any) {
if (e.key === "Escape") {
hideMermaid()
}
}
const closeBtn = popupContainer.querySelector(".close-button") as HTMLButtonElement
closeBtn.addEventListener("click", hideMermaid)
expandBtn.addEventListener("click", showMermaid) expandBtn.addEventListener("click", showMermaid)
registerEscapeHandler(popupContainer, hideMermaid) document.addEventListener("keydown", handleEscape)
window.addCleanup(() => { window.addCleanup(() => {
panZoom?.cleanup() closeBtn.removeEventListener("click", hideMermaid)
expandBtn.removeEventListener("click", showMermaid) expandBtn.removeEventListener("click", showMermaid)
document.removeEventListener("keydown", handleEscape)
}) })
} }
}) })

View File

@ -82,8 +82,6 @@ async function mouseEnterHandler(
const contents = await response.text() const contents = await response.text()
const html = p.parseFromString(contents, "text/html") const html = p.parseFromString(contents, "text/html")
normalizeRelativeURLs(html, targetUrl) normalizeRelativeURLs(html, targetUrl)
// strip all IDs from elements to prevent duplicates
html.querySelectorAll("[id]").forEach((el) => el.removeAttribute("id"))
const elts = [...html.getElementsByClassName("popover-hint")] const elts = [...html.getElementsByClassName("popover-hint")]
if (elts.length === 0) return if (elts.length === 0) return

View File

@ -143,75 +143,83 @@ function highlightHTML(searchTerm: string, el: HTMLElement) {
return html.body return html.body
} }
async function setupSearch(searchElement: Element, currentSlug: FullSlug, data: ContentIndex) { document.addEventListener("nav", async (e: CustomEventMap["nav"]) => {
const container = searchElement.querySelector(".search-container") as HTMLElement const currentSlug = e.detail.url
if (!container) return const data = await fetchData
const container = document.getElementById("search-container")
const sidebar = container.closest(".sidebar") as HTMLElement const sidebar = container?.closest(".sidebar") as HTMLElement
if (!sidebar) return const searchButton = document.getElementById("search-button")
const searchBar = document.getElementById("search-bar") as HTMLInputElement | null
const searchButton = searchElement.querySelector(".search-button") as HTMLButtonElement const searchLayout = document.getElementById("search-layout")
if (!searchButton) return
const searchBar = searchElement.querySelector(".search-bar") as HTMLInputElement
if (!searchBar) return
const searchLayout = searchElement.querySelector(".search-layout") as HTMLElement
if (!searchLayout) return
const idDataMap = Object.keys(data) as FullSlug[] const idDataMap = Object.keys(data) as FullSlug[]
const appendLayout = (el: HTMLElement) => { const appendLayout = (el: HTMLElement) => {
searchLayout.appendChild(el) if (searchLayout?.querySelector(`#${el.id}`) === null) {
searchLayout?.appendChild(el)
}
} }
const enablePreview = searchLayout.dataset.preview === "true" const enablePreview = searchLayout?.dataset?.preview === "true"
let preview: HTMLDivElement | undefined = undefined let preview: HTMLDivElement | undefined = undefined
let previewInner: HTMLDivElement | undefined = undefined let previewInner: HTMLDivElement | undefined = undefined
const results = document.createElement("div") const results = document.createElement("div")
results.className = "results-container" results.id = "results-container"
appendLayout(results) appendLayout(results)
if (enablePreview) { if (enablePreview) {
preview = document.createElement("div") preview = document.createElement("div")
preview.className = "preview-container" preview.id = "preview-container"
appendLayout(preview) appendLayout(preview)
} }
function hideSearch() { function hideSearch() {
container.classList.remove("active") container?.classList.remove("active")
searchBar.value = "" // clear the input when we dismiss the search if (searchBar) {
sidebar.style.zIndex = "" searchBar.value = "" // clear the input when we dismiss the search
removeAllChildren(results) }
if (sidebar) {
sidebar.style.zIndex = ""
}
if (results) {
removeAllChildren(results)
}
if (preview) { if (preview) {
removeAllChildren(preview) removeAllChildren(preview)
} }
searchLayout.classList.remove("display-results") if (searchLayout) {
searchLayout.classList.remove("display-results")
}
searchType = "basic" // reset search type after closing searchType = "basic" // reset search type after closing
searchButton.focus()
searchButton?.focus()
} }
function showSearch(searchTypeNew: SearchType) { function showSearch(searchTypeNew: SearchType) {
searchType = searchTypeNew searchType = searchTypeNew
sidebar.style.zIndex = "1" if (sidebar) {
container.classList.add("active") sidebar.style.zIndex = "1"
searchBar.focus() }
container?.classList.add("active")
searchBar?.focus()
} }
let currentHover: HTMLInputElement | null = null let currentHover: HTMLInputElement | null = null
async function shortcutHandler(e: HTMLElementEventMap["keydown"]) { async function shortcutHandler(e: HTMLElementEventMap["keydown"]) {
if (e.key === "k" && (e.ctrlKey || e.metaKey) && !e.shiftKey) { if (e.key === "k" && (e.ctrlKey || e.metaKey) && !e.shiftKey) {
e.preventDefault() e.preventDefault()
const searchBarOpen = container.classList.contains("active") const searchBarOpen = container?.classList.contains("active")
searchBarOpen ? hideSearch() : showSearch("basic") searchBarOpen ? hideSearch() : showSearch("basic")
return return
} else if (e.shiftKey && (e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "k") { } else if (e.shiftKey && (e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "k") {
// Hotkey to open tag search // Hotkey to open tag search
e.preventDefault() e.preventDefault()
const searchBarOpen = container.classList.contains("active") const searchBarOpen = container?.classList.contains("active")
searchBarOpen ? hideSearch() : showSearch("tags") searchBarOpen ? hideSearch() : showSearch("tags")
// add "#" prefix for tag search // add "#" prefix for tag search
searchBar.value = "#" if (searchBar) searchBar.value = "#"
return return
} }
@ -220,23 +228,23 @@ async function setupSearch(searchElement: Element, currentSlug: FullSlug, data:
} }
// If search is active, then we will render the first result and display accordingly // If search is active, then we will render the first result and display accordingly
if (!container.classList.contains("active")) return if (!container?.classList.contains("active")) return
if (e.key === "Enter") { if (e.key === "Enter") {
// If result has focus, navigate to that one, otherwise pick first result // If result has focus, navigate to that one, otherwise pick first result
if (results.contains(document.activeElement)) { if (results?.contains(document.activeElement)) {
const active = document.activeElement as HTMLInputElement const active = document.activeElement as HTMLInputElement
if (active.classList.contains("no-match")) return if (active.classList.contains("no-match")) return
await displayPreview(active) await displayPreview(active)
active.click() active.click()
} else { } else {
const anchor = document.getElementsByClassName("result-card")[0] as HTMLInputElement | null const anchor = document.getElementsByClassName("result-card")[0] as HTMLInputElement | null
if (!anchor || anchor.classList.contains("no-match")) return if (!anchor || anchor?.classList.contains("no-match")) return
await displayPreview(anchor) await displayPreview(anchor)
anchor.click() anchor.click()
} }
} else if (e.key === "ArrowUp" || (e.shiftKey && e.key === "Tab")) { } else if (e.key === "ArrowUp" || (e.shiftKey && e.key === "Tab")) {
e.preventDefault() e.preventDefault()
if (results.contains(document.activeElement)) { if (results?.contains(document.activeElement)) {
// If an element in results-container already has focus, focus previous one // If an element in results-container already has focus, focus previous one
const currentResult = currentHover const currentResult = currentHover
? currentHover ? currentHover
@ -329,6 +337,8 @@ async function setupSearch(searchElement: Element, currentSlug: FullSlug, data:
} }
async function displayResults(finalResults: Item[]) { async function displayResults(finalResults: Item[]) {
if (!results) return
removeAllChildren(results) removeAllChildren(results)
if (finalResults.length === 0) { if (finalResults.length === 0) {
results.innerHTML = `<a class="result-card no-match"> results.innerHTML = `<a class="result-card no-match">
@ -384,7 +394,7 @@ async function setupSearch(searchElement: Element, currentSlug: FullSlug, data:
preview.replaceChildren(previewInner) preview.replaceChildren(previewInner)
// scroll to longest // scroll to longest
const highlights = [...preview.getElementsByClassName("highlight")].sort( const highlights = [...preview.querySelectorAll(".highlight")].sort(
(a, b) => b.innerHTML.length - a.innerHTML.length, (a, b) => b.innerHTML.length - a.innerHTML.length,
) )
highlights[0]?.scrollIntoView({ block: "start" }) highlights[0]?.scrollIntoView({ block: "start" })
@ -450,23 +460,21 @@ async function setupSearch(searchElement: Element, currentSlug: FullSlug, data:
document.addEventListener("keydown", shortcutHandler) document.addEventListener("keydown", shortcutHandler)
window.addCleanup(() => document.removeEventListener("keydown", shortcutHandler)) window.addCleanup(() => document.removeEventListener("keydown", shortcutHandler))
searchButton.addEventListener("click", () => showSearch("basic")) searchButton?.addEventListener("click", () => showSearch("basic"))
window.addCleanup(() => searchButton.removeEventListener("click", () => showSearch("basic"))) window.addCleanup(() => searchButton?.removeEventListener("click", () => showSearch("basic")))
searchBar.addEventListener("input", onType) searchBar?.addEventListener("input", onType)
window.addCleanup(() => searchBar.removeEventListener("input", onType)) window.addCleanup(() => searchBar?.removeEventListener("input", onType))
registerEscapeHandler(container, hideSearch) registerEscapeHandler(container, hideSearch)
await fillDocument(data) await fillDocument(data)
} })
/** /**
* Fills flexsearch document with data * Fills flexsearch document with data
* @param index index to fill * @param index index to fill
* @param data data to fill index with * @param data data to fill index with
*/ */
let indexPopulated = false async function fillDocument(data: { [key: FullSlug]: ContentDetails }) {
async function fillDocument(data: ContentIndex) {
if (indexPopulated) return
let id = 0 let id = 0
const promises: Array<Promise<unknown>> = [] const promises: Array<Promise<unknown>> = []
for (const [slug, fileData] of Object.entries<ContentDetails>(data)) { for (const [slug, fileData] of Object.entries<ContentDetails>(data)) {
@ -481,15 +489,5 @@ async function fillDocument(data: ContentIndex) {
) )
} }
await Promise.all(promises) return await Promise.all(promises)
indexPopulated = true
} }
document.addEventListener("nav", async (e: CustomEventMap["nav"]) => {
const currentSlug = e.detail.url
const data = await fetchData
const searchElement = document.getElementsByClassName("search")
for (const element of searchElement) {
await setupSearch(element, currentSlug, data)
}
})

View File

@ -56,10 +56,8 @@ function startLoading() {
}, 100) }, 100)
} }
let isNavigating = false
let p: DOMParser let p: DOMParser
async function _navigate(url: URL, isBack: boolean = false) { async function navigate(url: URL, isBack: boolean = false) {
isNavigating = true
startLoading() startLoading()
p = p || new DOMParser() p = p || new DOMParser()
const contents = await fetchCanonical(url) const contents = await fetchCanonical(url)
@ -77,10 +75,6 @@ async function _navigate(url: URL, isBack: boolean = false) {
if (!contents) return if (!contents) return
// notify about to nav
const event: CustomEventMap["prenav"] = new CustomEvent("prenav", { detail: {} })
document.dispatchEvent(event)
// cleanup old // cleanup old
cleanupFns.forEach((fn) => fn()) cleanupFns.forEach((fn) => fn())
cleanupFns.clear() cleanupFns.clear()
@ -114,7 +108,7 @@ async function _navigate(url: URL, isBack: boolean = false) {
} }
} }
// now, patch head, re-executing scripts // now, patch head
const elementsToRemove = document.head.querySelectorAll(":not([spa-preserve])") const elementsToRemove = document.head.querySelectorAll(":not([spa-preserve])")
elementsToRemove.forEach((el) => el.remove()) elementsToRemove.forEach((el) => el.remove())
const elementsToAdd = html.head.querySelectorAll(":not([spa-preserve])") const elementsToAdd = html.head.querySelectorAll(":not([spa-preserve])")
@ -130,19 +124,6 @@ async function _navigate(url: URL, isBack: boolean = false) {
delete announcer.dataset.persist delete announcer.dataset.persist
} }
async function navigate(url: URL, isBack: boolean = false) {
if (isNavigating) return
isNavigating = true
try {
await _navigate(url, isBack)
} catch (e) {
console.error(e)
window.location.assign(url)
} finally {
isNavigating = false
}
}
window.spaNavigate = navigate window.spaNavigate = navigate
function createRouter() { function createRouter() {
@ -160,13 +141,21 @@ function createRouter() {
return return
} }
navigate(url, false) try {
navigate(url, false)
} catch (e) {
window.location.assign(url)
}
}) })
window.addEventListener("popstate", (event) => { window.addEventListener("popstate", (event) => {
const { url } = getOpts(event) ?? {} const { url } = getOpts(event) ?? {}
if (window.location.hash && window.location.pathname === url?.pathname) return if (window.location.hash && window.location.pathname === url?.pathname) return
navigate(new URL(window.location.toString()), true) try {
navigate(new URL(window.location.toString()), true)
} catch (e) {
window.location.reload()
}
return return
}) })
} }

View File

@ -1,3 +1,4 @@
const bufferPx = 150
const observer = new IntersectionObserver((entries) => { const observer = new IntersectionObserver((entries) => {
for (const entry of entries) { for (const entry of entries) {
const slug = entry.target.id const slug = entry.target.id
@ -25,15 +26,17 @@ function toggleToc(this: HTMLElement) {
} }
function setupToc() { function setupToc() {
for (const toc of document.getElementsByClassName("toc")) { const toc = document.getElementById("toc")
const button = toc.querySelector(".toc-header") if (toc) {
const content = toc.querySelector(".toc-content") const collapsed = toc.classList.contains("collapsed")
if (!button || !content) return const content = toc.nextElementSibling as HTMLElement | undefined
button.addEventListener("click", toggleToc) if (!content) return
window.addCleanup(() => button.removeEventListener("click", toggleToc)) toc.addEventListener("click", toggleToc)
window.addCleanup(() => toc.removeEventListener("click", toggleToc))
} }
} }
window.addEventListener("resize", setupToc)
document.addEventListener("nav", () => { document.addEventListener("nav", () => {
setupToc() setupToc()

View File

@ -37,7 +37,6 @@ export async function fetchCanonical(url: URL): Promise<Response> {
if (!res.headers.get("content-type")?.startsWith("text/html")) { if (!res.headers.get("content-type")?.startsWith("text/html")) {
return res return res
} }
// reading the body can only be done once, so we need to clone the response // reading the body can only be done once, so we need to clone the response
// to allow the caller to read it if it's was not a redirect // to allow the caller to read it if it's was not a redirect
const text = await res.clone().text() const text = await res.clone().text()

View File

@ -2,6 +2,18 @@
.backlinks { .backlinks {
flex-direction: column; flex-direction: column;
/*&:after {
pointer-events: none;
content: "";
width: 100%;
height: 50px;
position: absolute;
left: 0;
bottom: 0;
opacity: 1;
transition: opacity 0.3s ease;
background: linear-gradient(transparent 0px, var(--light));
}*/
& > h3 { & > h3 {
font-size: 1rem; font-size: 1rem;
@ -19,4 +31,14 @@
} }
} }
} }
& > .overflow {
&:after {
display: none;
}
height: auto;
@media all and not ($desktop) {
height: 250px;
}
}
} }

View File

@ -8,7 +8,6 @@
height: 20px; height: 20px;
margin: 0 10px; margin: 0 10px;
text-align: inherit; text-align: inherit;
flex-shrink: 0;
& svg { & svg {
position: absolute; position: absolute;
@ -29,19 +28,19 @@
} }
:root[saved-theme="dark"] .darkmode { :root[saved-theme="dark"] .darkmode {
& > .dayIcon { & > #dayIcon {
display: none; display: none;
} }
& > .nightIcon { & > #nightIcon {
display: inline; display: inline;
} }
} }
:root .darkmode { :root .darkmode {
& > .dayIcon { & > #dayIcon {
display: inline; display: inline;
} }
& > .nightIcon { & > #nightIcon {
display: none; display: none;
} }
} }

View File

@ -1,97 +1,29 @@
@use "../../styles/variables.scss" as *; @use "../../styles/variables.scss" as *;
@media all and ($mobile) {
.page > #quartz-body {
// Shift page position when toggling Explorer on mobile.
& > :not(.sidebar.left:has(.explorer)) {
transition: transform 300ms ease-in-out;
}
&.lock-scroll > :not(.sidebar.left:has(.explorer)) {
transform: translateX(100dvw);
transition: transform 300ms ease-in-out;
}
// Sticky top bar (stays in place when scrolling down on mobile).
.sidebar.left:has(.explorer) {
box-sizing: border-box;
position: sticky;
background-color: var(--light);
padding: 1rem 0 1rem 0;
margin: 0;
}
.hide-until-loaded ~ .explorer-content {
display: none;
}
}
}
.explorer { .explorer {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
overflow-y: hidden; overflow-y: hidden;
min-height: 1.2rem;
flex: 0 1 auto;
&.collapsed {
flex: 0 1 1.2rem;
& .fold {
transform: rotateZ(-90deg);
}
}
& .fold {
margin-left: 0.5rem;
transition: transform 0.3s ease;
opacity: 0.8;
}
@media all and ($mobile) {
order: -1;
height: initial;
overflow: hidden;
flex-shrink: 0;
align-self: flex-start;
margin-top: auto;
margin-bottom: auto;
}
button.mobile-explorer {
display: none;
}
button.desktop-explorer {
display: flex;
}
@media all and ($mobile) {
button.mobile-explorer {
display: flex;
}
button.desktop-explorer {
display: none;
}
}
&.desktop-only { &.desktop-only {
@media all and not ($mobile) { @media all and not ($mobile) {
display: flex; display: flex;
} }
} }
/*&:after {
svg { pointer-events: none;
pointer-events: all; content: "";
transition: transform 0.35s ease; width: 100%;
height: 50px;
& > polyline { position: absolute;
pointer-events: none; left: 0;
} bottom: 0;
} opacity: 1;
transition: opacity 0.3s ease;
background: linear-gradient(transparent 0px, var(--light));
}*/
} }
button.mobile-explorer, button#explorer {
button.desktop-explorer {
background-color: transparent; background-color: transparent;
border: none; border: none;
text-align: left; text-align: left;
@ -106,46 +38,75 @@ button.desktop-explorer {
display: inline-block; display: inline-block;
margin: 0; margin: 0;
} }
& .fold {
margin-left: 0.5rem;
transition: transform 0.3s ease;
opacity: 0.8;
}
&.collapsed .fold {
transform: rotateZ(-90deg);
}
} }
.explorer-content { .folder-outer {
display: grid;
grid-template-rows: 0fr;
transition: grid-template-rows 0.3s ease-in-out;
}
.folder-outer.open {
grid-template-rows: 1fr;
}
.folder-outer > ul {
overflow: hidden;
}
#explorer-content {
list-style: none; list-style: none;
overflow: hidden; overflow: hidden;
overflow-y: auto; overflow-y: auto;
max-height: 100%;
transition:
max-height 0.35s ease,
visibility 0s linear 0s;
margin-top: 0.5rem; margin-top: 0.5rem;
visibility: visible;
&.collapsed {
max-height: 0;
transition:
max-height 0.35s ease,
visibility 0s linear 0.35s;
visibility: hidden;
}
& ul { & ul {
list-style: none; list-style: none;
margin: 0; margin: 0.08rem 0;
padding: 0; padding: 0;
transition:
max-height 0.35s ease,
transform 0.35s ease,
opacity 0.2s ease;
& li > a { & li > a {
color: var(--dark); color: var(--dark);
opacity: 0.75; opacity: 0.75;
pointer-events: all; pointer-events: all;
&.active {
opacity: 1;
color: var(--tertiary);
}
} }
} }
> #explorer-ul {
.folder-outer { max-height: none;
display: grid;
grid-template-rows: 0fr;
transition: grid-template-rows 0.3s ease-in-out;
} }
}
.folder-outer.open { svg {
grid-template-rows: 1fr; pointer-events: all;
}
.folder-outer > ul { & > polyline {
overflow: hidden; pointer-events: none;
margin-left: 6px;
padding-left: 0.8rem;
border-left: 1px solid var(--lightgray);
} }
} }
@ -208,75 +169,13 @@ li:has(> .folder-outer:not(.open)) > .folder-container > svg {
color: var(--tertiary); color: var(--tertiary);
} }
.explorer { .no-background::after {
@media all and ($mobile) { background: none !important;
&.collapsed {
flex: 0 0 34px;
& > .explorer-content {
transform: translateX(-100vw);
visibility: hidden;
}
}
&:not(.collapsed) {
flex: 0 0 34px;
& > .explorer-content {
transform: translateX(0);
visibility: visible;
}
}
.explorer-content {
box-sizing: border-box;
z-index: 100;
position: absolute;
top: 0;
left: 0;
margin-top: 0;
background-color: var(--light);
max-width: 100vw;
width: 100%;
transform: translateX(-100vw);
transition:
transform 200ms ease,
visibility 200ms ease;
overflow: hidden;
padding: 4rem 0 2rem 0;
height: 100dvh;
max-height: 100dvh;
visibility: hidden;
}
.mobile-explorer {
margin: 0;
padding: 5px;
z-index: 101;
.lucide-menu {
stroke: var(--darkgray);
}
}
}
} }
.no-scroll { #explorer-end {
opacity: 0; // needs height so IntersectionObserver gets triggered
overflow: hidden; height: 4px;
} // remove default margin from li
margin: 0;
html:has(.no-scroll) {
overflow: hidden;
}
@media all and not ($mobile) {
.no-scroll {
opacity: 1 !important;
overflow: auto !important;
}
html:has(.no-scroll) {
overflow: auto !important;
}
} }

View File

@ -15,7 +15,7 @@
position: relative; position: relative;
overflow: hidden; overflow: hidden;
& > .global-graph-icon { & > #global-graph-icon {
cursor: pointer; cursor: pointer;
background: none; background: none;
border: none; border: none;
@ -38,7 +38,7 @@
} }
} }
& > .global-graph-outer { & > #global-graph-outer {
position: fixed; position: fixed;
z-index: 9999; z-index: 9999;
left: 0; left: 0;
@ -53,7 +53,7 @@
display: inline-block; display: inline-block;
} }
& > .global-graph-container { & > #global-graph-container {
border: 1px solid var(--lightgray); border: 1px solid var(--lightgray);
background-color: var(--light); background-color: var(--light);
border-radius: 5px; border-radius: 5px;

View File

@ -1,4 +1,4 @@
details.toc { details#toc {
& summary { & summary {
cursor: pointer; cursor: pointer;

View File

@ -53,16 +53,46 @@ pre {
} }
& > #mermaid-space { & > #mermaid-space {
border: 1px solid var(--lightgray); display: grid;
background-color: var(--light); width: 90%;
border-radius: 5px; height: 90vh;
position: fixed; margin: 5vh auto;
top: 50%; background: var(--light);
left: 50%; box-shadow:
transform: translate(-50%, -50%); 0 14px 50px rgba(27, 33, 48, 0.12),
height: 80vh; 0 10px 30px rgba(27, 33, 48, 0.16);
width: 80vw;
overflow: hidden; overflow: hidden;
position: relative;
& > .mermaid-header {
display: flex;
justify-content: flex-end;
padding: 1rem;
border-bottom: 1px solid var(--lightgray);
background: var(--light);
z-index: 2;
max-height: fit-content;
& > .close-button {
display: flex;
align-items: center;
justify-content: center;
width: 32px;
height: 32px;
padding: 0;
background: transparent;
border: none;
border-radius: 4px;
color: var(--darkgray);
cursor: pointer;
transition: all 0.2s ease;
&:hover {
background: var(--lightgray);
color: var(--dark);
}
}
}
& > .mermaid-content { & > .mermaid-content {
padding: 2rem; padding: 2rem;

View File

@ -42,7 +42,7 @@
} }
} }
& > .search-container { & > #search-container {
position: fixed; position: fixed;
contain: layout; contain: layout;
z-index: 999; z-index: 999;
@ -58,7 +58,7 @@
display: inline-block; display: inline-block;
} }
& > .search-space { & > #search-space {
width: 65%; width: 65%;
margin-top: 12vh; margin-top: 12vh;
margin-left: auto; margin-left: auto;
@ -91,7 +91,7 @@
} }
} }
& > .search-layout { & > #search-layout {
display: none; display: none;
flex-direction: row; flex-direction: row;
border: 1px solid var(--lightgray); border: 1px solid var(--lightgray);
@ -102,7 +102,7 @@
display: flex; display: flex;
} }
&[data-preview] > .results-container { &[data-preview] > #results-container {
flex: 0 0 min(30%, 450px); flex: 0 0 min(30%, 450px);
} }
@ -150,7 +150,7 @@
scroll-margin-top: 2rem; scroll-margin-top: 2rem;
} }
& > .preview-container { & > #preview-container {
flex-grow: 1; flex-grow: 1;
display: block; display: block;
overflow: hidden; overflow: hidden;
@ -171,7 +171,7 @@
} }
} }
& > .results-container { & > #results-container {
overflow-y: auto; overflow-y: auto;
& .result-card { & .result-card {

View File

@ -4,21 +4,18 @@
display: flex; display: flex;
flex-direction: column; flex-direction: column;
overflow-y: hidden; &.desktop-only {
min-height: 4rem; max-height: 40%;
flex: 0 1 auto;
&:has(button.toc-header.collapsed) {
flex: 0 1 1.2rem;
} }
} }
@media all and not ($mobile) { @media all and not ($mobile) {
.toc-header { .toc {
display: flex; display: flex;
} }
} }
button.toc-header { button#toc {
background-color: transparent; background-color: transparent;
border: none; border: none;
text-align: left; text-align: left;
@ -45,9 +42,28 @@ button.toc-header {
} }
} }
.toc-content { #toc-content {
list-style: none; list-style: none;
overflow: hidden;
overflow-y: auto;
max-height: 100%;
transition:
max-height 0.35s ease,
visibility 0s linear 0s;
position: relative; position: relative;
visibility: visible;
&.collapsed {
max-height: 0;
transition:
max-height 0.35s ease,
visibility 0s linear 0.35s;
visibility: hidden;
}
&.collapsed > .overflow::after {
opacity: 0;
}
& ul { & ul {
list-style: none; list-style: none;
@ -64,6 +80,10 @@ button.toc-header {
} }
} }
} }
> ul.overflow {
max-height: none;
width: 100%;
}
@for $i from 0 through 6 { @for $i from 0 through 6 {
& .depth-#{$i} { & .depth-#{$i} {

View File

@ -1,5 +1,5 @@
import { ComponentType, JSX } from "preact" import { ComponentType, JSX } from "preact"
import { StaticResources, StringResource } from "../util/resources" import { StaticResources } from "../util/resources"
import { QuartzPluginData } from "../plugins/vfile" import { QuartzPluginData } from "../plugins/vfile"
import { GlobalConfiguration } from "../cfg" import { GlobalConfiguration } from "../cfg"
import { Node } from "hast" import { Node } from "hast"
@ -19,9 +19,9 @@ export type QuartzComponentProps = {
} }
export type QuartzComponent = ComponentType<QuartzComponentProps> & { export type QuartzComponent = ComponentType<QuartzComponentProps> & {
css?: StringResource css?: string
beforeDOMLoaded?: StringResource beforeDOMLoaded?: string
afterDOMLoaded?: StringResource afterDOMLoaded?: string
} }
export type QuartzComponentConstructor<Options extends object | undefined = undefined> = ( export type QuartzComponentConstructor<Options extends object | undefined = undefined> = (

118
quartz/depgraph.test.ts Normal file
View File

@ -0,0 +1,118 @@
import test, { describe } from "node:test"
import DepGraph from "./depgraph"
import assert from "node:assert"
describe("DepGraph", () => {
test("getLeafNodes", () => {
const graph = new DepGraph<string>()
graph.addEdge("A", "B")
graph.addEdge("B", "C")
graph.addEdge("D", "C")
assert.deepStrictEqual(graph.getLeafNodes("A"), new Set(["C"]))
assert.deepStrictEqual(graph.getLeafNodes("B"), new Set(["C"]))
assert.deepStrictEqual(graph.getLeafNodes("C"), new Set(["C"]))
assert.deepStrictEqual(graph.getLeafNodes("D"), new Set(["C"]))
})
describe("getLeafNodeAncestors", () => {
test("gets correct ancestors in a graph without cycles", () => {
const graph = new DepGraph<string>()
graph.addEdge("A", "B")
graph.addEdge("B", "C")
graph.addEdge("D", "B")
assert.deepStrictEqual(graph.getLeafNodeAncestors("A"), new Set(["A", "B", "D"]))
assert.deepStrictEqual(graph.getLeafNodeAncestors("B"), new Set(["A", "B", "D"]))
assert.deepStrictEqual(graph.getLeafNodeAncestors("C"), new Set(["A", "B", "D"]))
assert.deepStrictEqual(graph.getLeafNodeAncestors("D"), new Set(["A", "B", "D"]))
})
test("gets correct ancestors in a graph with cycles", () => {
const graph = new DepGraph<string>()
graph.addEdge("A", "B")
graph.addEdge("B", "C")
graph.addEdge("C", "A")
graph.addEdge("C", "D")
assert.deepStrictEqual(graph.getLeafNodeAncestors("A"), new Set(["A", "B", "C"]))
assert.deepStrictEqual(graph.getLeafNodeAncestors("B"), new Set(["A", "B", "C"]))
assert.deepStrictEqual(graph.getLeafNodeAncestors("C"), new Set(["A", "B", "C"]))
assert.deepStrictEqual(graph.getLeafNodeAncestors("D"), new Set(["A", "B", "C"]))
})
})
describe("mergeGraph", () => {
test("merges two graphs", () => {
const graph = new DepGraph<string>()
graph.addEdge("A.md", "A.html")
const other = new DepGraph<string>()
other.addEdge("B.md", "B.html")
graph.mergeGraph(other)
const expected = {
nodes: ["A.md", "A.html", "B.md", "B.html"],
edges: [
["A.md", "A.html"],
["B.md", "B.html"],
],
}
assert.deepStrictEqual(graph.export(), expected)
})
})
describe("updateIncomingEdgesForNode", () => {
test("merges when node exists", () => {
// A.md -> B.md -> B.html
const graph = new DepGraph<string>()
graph.addEdge("A.md", "B.md")
graph.addEdge("B.md", "B.html")
// B.md is edited so it removes the A.md transclusion
// and adds C.md transclusion
// C.md -> B.md
const other = new DepGraph<string>()
other.addEdge("C.md", "B.md")
other.addEdge("B.md", "B.html")
// A.md -> B.md removed, C.md -> B.md added
// C.md -> B.md -> B.html
graph.updateIncomingEdgesForNode(other, "B.md")
const expected = {
nodes: ["A.md", "B.md", "B.html", "C.md"],
edges: [
["B.md", "B.html"],
["C.md", "B.md"],
],
}
assert.deepStrictEqual(graph.export(), expected)
})
test("adds node if it does not exist", () => {
// A.md -> B.md
const graph = new DepGraph<string>()
graph.addEdge("A.md", "B.md")
// Add a new file C.md that transcludes B.md
// B.md -> C.md
const other = new DepGraph<string>()
other.addEdge("B.md", "C.md")
// B.md -> C.md added
// A.md -> B.md -> C.md
graph.updateIncomingEdgesForNode(other, "C.md")
const expected = {
nodes: ["A.md", "B.md", "C.md"],
edges: [
["A.md", "B.md"],
["B.md", "C.md"],
],
}
assert.deepStrictEqual(graph.export(), expected)
})
})
})

228
quartz/depgraph.ts Normal file
View File

@ -0,0 +1,228 @@
export default class DepGraph<T> {
// node: incoming and outgoing edges
_graph = new Map<T, { incoming: Set<T>; outgoing: Set<T> }>()
constructor() {
this._graph = new Map()
}
export(): Object {
return {
nodes: this.nodes,
edges: this.edges,
}
}
toString(): string {
return JSON.stringify(this.export(), null, 2)
}
// BASIC GRAPH OPERATIONS
get nodes(): T[] {
return Array.from(this._graph.keys())
}
get edges(): [T, T][] {
let edges: [T, T][] = []
this.forEachEdge((edge) => edges.push(edge))
return edges
}
hasNode(node: T): boolean {
return this._graph.has(node)
}
addNode(node: T): void {
if (!this._graph.has(node)) {
this._graph.set(node, { incoming: new Set(), outgoing: new Set() })
}
}
// Remove node and all edges connected to it
removeNode(node: T): void {
if (this._graph.has(node)) {
// first remove all edges so other nodes don't have references to this node
for (const target of this._graph.get(node)!.outgoing) {
this.removeEdge(node, target)
}
for (const source of this._graph.get(node)!.incoming) {
this.removeEdge(source, node)
}
this._graph.delete(node)
}
}
forEachNode(callback: (node: T) => void): void {
for (const node of this._graph.keys()) {
callback(node)
}
}
hasEdge(from: T, to: T): boolean {
return Boolean(this._graph.get(from)?.outgoing.has(to))
}
addEdge(from: T, to: T): void {
this.addNode(from)
this.addNode(to)
this._graph.get(from)!.outgoing.add(to)
this._graph.get(to)!.incoming.add(from)
}
removeEdge(from: T, to: T): void {
if (this._graph.has(from) && this._graph.has(to)) {
this._graph.get(from)!.outgoing.delete(to)
this._graph.get(to)!.incoming.delete(from)
}
}
// returns -1 if node does not exist
outDegree(node: T): number {
return this.hasNode(node) ? this._graph.get(node)!.outgoing.size : -1
}
// returns -1 if node does not exist
inDegree(node: T): number {
return this.hasNode(node) ? this._graph.get(node)!.incoming.size : -1
}
forEachOutNeighbor(node: T, callback: (neighbor: T) => void): void {
this._graph.get(node)?.outgoing.forEach(callback)
}
forEachInNeighbor(node: T, callback: (neighbor: T) => void): void {
this._graph.get(node)?.incoming.forEach(callback)
}
forEachEdge(callback: (edge: [T, T]) => void): void {
for (const [source, { outgoing }] of this._graph.entries()) {
for (const target of outgoing) {
callback([source, target])
}
}
}
// DEPENDENCY ALGORITHMS
// Add all nodes and edges from other graph to this graph
mergeGraph(other: DepGraph<T>): void {
other.forEachEdge(([source, target]) => {
this.addNode(source)
this.addNode(target)
this.addEdge(source, target)
})
}
// For the node provided:
// If node does not exist, add it
// If an incoming edge was added in other, it is added in this graph
// If an incoming edge was deleted in other, it is deleted in this graph
updateIncomingEdgesForNode(other: DepGraph<T>, node: T): void {
this.addNode(node)
// Add edge if it is present in other
other.forEachInNeighbor(node, (neighbor) => {
this.addEdge(neighbor, node)
})
// For node provided, remove incoming edge if it is absent in other
this.forEachEdge(([source, target]) => {
if (target === node && !other.hasEdge(source, target)) {
this.removeEdge(source, target)
}
})
}
// Remove all nodes that do not have any incoming or outgoing edges
// A node may be orphaned if the only node pointing to it was removed
removeOrphanNodes(): Set<T> {
let orphanNodes = new Set<T>()
this.forEachNode((node) => {
if (this.inDegree(node) === 0 && this.outDegree(node) === 0) {
orphanNodes.add(node)
}
})
orphanNodes.forEach((node) => {
this.removeNode(node)
})
return orphanNodes
}
// Get all leaf nodes (i.e. destination paths) reachable from the node provided
// Eg. if the graph is A -> B -> C
// D ---^
// and the node is B, this function returns [C]
getLeafNodes(node: T): Set<T> {
let stack: T[] = [node]
let visited = new Set<T>()
let leafNodes = new Set<T>()
// DFS
while (stack.length > 0) {
let node = stack.pop()!
// If the node is already visited, skip it
if (visited.has(node)) {
continue
}
visited.add(node)
// Check if the node is a leaf node (i.e. destination path)
if (this.outDegree(node) === 0) {
leafNodes.add(node)
}
// Add all unvisited neighbors to the stack
this.forEachOutNeighbor(node, (neighbor) => {
if (!visited.has(neighbor)) {
stack.push(neighbor)
}
})
}
return leafNodes
}
// Get all ancestors of the leaf nodes reachable from the node provided
// Eg. if the graph is A -> B -> C
// D ---^
// and the node is B, this function returns [A, B, D]
getLeafNodeAncestors(node: T): Set<T> {
const leafNodes = this.getLeafNodes(node)
let visited = new Set<T>()
let upstreamNodes = new Set<T>()
// Backwards DFS for each leaf node
leafNodes.forEach((leafNode) => {
let stack: T[] = [leafNode]
while (stack.length > 0) {
let node = stack.pop()!
if (visited.has(node)) {
continue
}
visited.add(node)
// Add node if it's not a leaf node (i.e. destination path)
// Assumes destination file cannot depend on another destination file
if (this.outDegree(node) !== 0) {
upstreamNodes.add(node)
}
// Add all unvisited parents to the stack
this.forEachInNeighbor(node, (parentNode) => {
if (!visited.has(parentNode)) {
stack.push(parentNode)
}
})
}
})
return upstreamNodes
}
}

View File

@ -22,10 +22,6 @@ import fa from "./locales/fa-IR"
import pl from "./locales/pl-PL" import pl from "./locales/pl-PL"
import cs from "./locales/cs-CZ" import cs from "./locales/cs-CZ"
import tr from "./locales/tr-TR" import tr from "./locales/tr-TR"
import th from "./locales/th-TH"
import lt from "./locales/lt-LT"
import fi from "./locales/fi-FI"
import no from "./locales/nb-NO"
export const TRANSLATIONS = { export const TRANSLATIONS = {
"en-US": enUs, "en-US": enUs,
@ -72,10 +68,6 @@ export const TRANSLATIONS = {
"pl-PL": pl, "pl-PL": pl,
"cs-CZ": cs, "cs-CZ": cs,
"tr-TR": tr, "tr-TR": tr,
"th-TH": th,
"lt-LT": lt,
"fi-FI": fi,
"nb-NO": no,
} as const } as const
export const defaultTranslation = "en-US" export const defaultTranslation = "en-US"

View File

@ -1,84 +0,0 @@
import { Translation } from "./definition"
export default {
propertyDefaults: {
title: "Nimetön",
description: "Ei kuvausta saatavilla",
},
components: {
callout: {
note: "Merkintä",
abstract: "Tiivistelmä",
info: "Info",
todo: "Tehtävälista",
tip: "Vinkki",
success: "Onnistuminen",
question: "Kysymys",
warning: "Varoitus",
failure: "Epäonnistuminen",
danger: "Vaara",
bug: "Virhe",
example: "Esimerkki",
quote: "Lainaus",
},
backlinks: {
title: "Takalinkit",
noBacklinksFound: "Takalinkkejä ei löytynyt",
},
themeToggle: {
lightMode: "Vaalea tila",
darkMode: "Tumma tila",
},
explorer: {
title: "Selain",
},
footer: {
createdWith: "Luotu käyttäen",
},
graph: {
title: "Verkkonäkymä",
},
recentNotes: {
title: "Viimeisimmät muistiinpanot",
seeRemainingMore: ({ remaining }) => `Näytä ${remaining} lisää →`,
},
transcludes: {
transcludeOf: ({ targetSlug }) => `Upote kohteesta ${targetSlug}`,
linkToOriginal: "Linkki alkuperäiseen",
},
search: {
title: "Haku",
searchBarPlaceholder: "Hae jotain",
},
tableOfContents: {
title: "Sisällysluettelo",
},
contentMeta: {
readingTime: ({ minutes }) => `${minutes} min lukuaika`,
},
},
pages: {
rss: {
recentNotes: "Viimeisimmät muistiinpanot",
lastFewNotes: ({ count }) => `Viimeiset ${count} muistiinpanoa`,
},
error: {
title: "Ei löytynyt",
notFound: "Tämä sivu on joko yksityinen tai sitä ei ole olemassa.",
home: "Palaa etusivulle",
},
folderContent: {
folder: "Kansio",
itemsUnderFolder: ({ count }) =>
count === 1 ? "1 kohde tässä kansiossa." : `${count} kohdetta tässä kansiossa.`,
},
tagContent: {
tag: "Tunniste",
tagIndex: "Tunnisteluettelo",
itemsUnderTag: ({ count }) =>
count === 1 ? "1 kohde tällä tunnisteella." : `${count} kohdetta tällä tunnisteella.`,
showingFirst: ({ count }) => `Näytetään ensimmäiset ${count} tunnistetta.`,
totalTags: ({ count }) => `Löytyi yhteensä ${count} tunnistetta.`,
},
},
} as const satisfies Translation

View File

@ -1,104 +0,0 @@
import { Translation } from "./definition"
export default {
propertyDefaults: {
title: "Be Pavadinimo",
description: "Aprašymas Nepateiktas",
},
components: {
callout: {
note: "Pastaba",
abstract: "Santrauka",
info: "Informacija",
todo: "Darbų sąrašas",
tip: "Patarimas",
success: "Sėkmingas",
question: "Klausimas",
warning: "Įspėjimas",
failure: "Nesėkmingas",
danger: "Pavojus",
bug: "Klaida",
example: "Pavyzdys",
quote: "Citata",
},
backlinks: {
title: "Atgalinės Nuorodos",
noBacklinksFound: "Atgalinių Nuorodų Nerasta",
},
themeToggle: {
lightMode: "Šviesus Režimas",
darkMode: "Tamsus Režimas",
},
explorer: {
title: "Naršyklė",
},
footer: {
createdWith: "Sukurta Su",
},
graph: {
title: "Grafiko Vaizdas",
},
recentNotes: {
title: "Naujausi Užrašai",
seeRemainingMore: ({ remaining }) => `Peržiūrėti dar ${remaining}`,
},
transcludes: {
transcludeOf: ({ targetSlug }) => `Įterpimas iš ${targetSlug}`,
linkToOriginal: "Nuoroda į originalą",
},
search: {
title: "Paieška",
searchBarPlaceholder: "Ieškoti",
},
tableOfContents: {
title: "Turinys",
},
contentMeta: {
readingTime: ({ minutes }) => `${minutes} min skaitymo`,
},
},
pages: {
rss: {
recentNotes: "Naujausi užrašai",
lastFewNotes: ({ count }) =>
count === 1
? "Paskutinis 1 užrašas"
: count < 10
? `Paskutiniai ${count} užrašai`
: `Paskutiniai ${count} užrašų`,
},
error: {
title: "Nerasta",
notFound:
"Arba šis puslapis yra pasiekiamas tik tam tikriems vartotojams, arba tokio puslapio nėra.",
home: "Grįžti į pagrindinį puslapį",
},
folderContent: {
folder: "Aplankas",
itemsUnderFolder: ({ count }) =>
count === 1
? "1 elementas šiame aplanke."
: count < 10
? `${count} elementai šiame aplanke.`
: `${count} elementų šiame aplanke.`,
},
tagContent: {
tag: "Žyma",
tagIndex: "Žymų indeksas",
itemsUnderTag: ({ count }) =>
count === 1
? "1 elementas su šia žyma."
: count < 10
? `${count} elementai su šia žyma.`
: `${count} elementų su šia žyma.`,
showingFirst: ({ count }) =>
count < 10 ? `Rodomos pirmosios ${count} žymos.` : `Rodomos pirmosios ${count} žymų.`,
totalTags: ({ count }) =>
count === 1
? "Rasta iš viso 1 žyma."
: count < 10
? `Rasta iš viso ${count} žymos.`
: `Rasta iš viso ${count} žymų.`,
},
},
} as const satisfies Translation

View File

@ -1,84 +0,0 @@
import { Translation } from "./definition"
export default {
propertyDefaults: {
title: "Uten navn",
description: "Ingen beskrivelse angitt",
},
components: {
callout: {
note: "Notis",
abstract: "Abstrakt",
info: "Info",
todo: "Husk på",
tip: "Tips",
success: "Suksess",
question: "Spørsmål",
warning: "Advarsel",
failure: "Feil",
danger: "Farlig",
bug: "Bug",
example: "Eksempel",
quote: "Sitat",
},
backlinks: {
title: "Tilbakekoblinger",
noBacklinksFound: "Ingen tilbakekoblinger funnet",
},
themeToggle: {
lightMode: "Lys modus",
darkMode: "Mørk modus",
},
explorer: {
title: "Utforsker",
},
footer: {
createdWith: "Laget med",
},
graph: {
title: "Graf-visning",
},
recentNotes: {
title: "Nylige notater",
seeRemainingMore: ({ remaining }) => `Se ${remaining} til →`,
},
transcludes: {
transcludeOf: ({ targetSlug }) => `Transkludering of ${targetSlug}`,
linkToOriginal: "Lenke til original",
},
search: {
title: "Søk",
searchBarPlaceholder: "Søk etter noe",
},
tableOfContents: {
title: "Oversikt",
},
contentMeta: {
readingTime: ({ minutes }) => `${minutes} min lesning`,
},
},
pages: {
rss: {
recentNotes: "Nylige notat",
lastFewNotes: ({ count }) => `Siste ${count} notat`,
},
error: {
title: "Ikke funnet",
notFound: "Enten er denne siden privat eller så finnes den ikke.",
home: "Returner til hovedsiden",
},
folderContent: {
folder: "Mappe",
itemsUnderFolder: ({ count }) =>
count === 1 ? "1 gjenstand i denne mappen." : `${count} gjenstander i denne mappen.`,
},
tagContent: {
tag: "Tagg",
tagIndex: "Tagg Indeks",
itemsUnderTag: ({ count }) =>
count === 1 ? "1 gjenstand med denne taggen." : `${count} gjenstander med denne taggen.`,
showingFirst: ({ count }) => `Viser første ${count} tagger.`,
totalTags: ({ count }) => `Fant totalt ${count} tagger.`,
},
},
} as const satisfies Translation

View File

@ -1,82 +0,0 @@
import { Translation } from "./definition"
export default {
propertyDefaults: {
title: "ไม่มีชื่อ",
description: "ไม่ได้ระบุคำอธิบายย่อ",
},
components: {
callout: {
note: "หมายเหตุ",
abstract: "บทคัดย่อ",
info: "ข้อมูล",
todo: "ต้องทำเพิ่มเติม",
tip: "คำแนะนำ",
success: "เรียบร้อย",
question: "คำถาม",
warning: "คำเตือน",
failure: "ข้อผิดพลาด",
danger: "อันตราย",
bug: "บั๊ก",
example: "ตัวอย่าง",
quote: "คำพูกยกมา",
},
backlinks: {
title: "หน้าที่กล่าวถึง",
noBacklinksFound: "ไม่มีหน้าที่โยงมาหน้านี้",
},
themeToggle: {
lightMode: "โหมดสว่าง",
darkMode: "โหมดมืด",
},
explorer: {
title: "รายการหน้า",
},
footer: {
createdWith: "สร้างด้วย",
},
graph: {
title: "มุมมองกราฟ",
},
recentNotes: {
title: "บันทึกล่าสุด",
seeRemainingMore: ({ remaining }) => `ดูเพิ่มอีก ${remaining} รายการ →`,
},
transcludes: {
transcludeOf: ({ targetSlug }) => `รวมข้ามเนื้อหาจาก ${targetSlug}`,
linkToOriginal: "ดูหน้าต้นทาง",
},
search: {
title: "ค้นหา",
searchBarPlaceholder: "ค้นหาบางอย่าง",
},
tableOfContents: {
title: "สารบัญ",
},
contentMeta: {
readingTime: ({ minutes }) => `อ่านราว ${minutes} นาที`,
},
},
pages: {
rss: {
recentNotes: "บันทึกล่าสุด",
lastFewNotes: ({ count }) => `${count} บันทึกล่าสุด`,
},
error: {
title: "ไม่มีหน้านี้",
notFound: "หน้านี้อาจตั้งค่าเป็นส่วนตัวหรือยังไม่ถูกสร้าง",
home: "กลับหน้าหลัก",
},
folderContent: {
folder: "โฟลเดอร์",
itemsUnderFolder: ({ count }) => `มี ${count} รายการในโฟลเดอร์นี้`,
},
tagContent: {
tag: "แท็ก",
tagIndex: "แท็กทั้งหมด",
itemsUnderTag: ({ count }) => `มี ${count} รายการในแท็กนี้`,
showingFirst: ({ count }) => `แสดง ${count} แท็กแรก`,
totalTags: ({ count }) => `มีทั้งหมด ${count} แท็ก`,
},
},
} as const satisfies Translation

View File

@ -3,12 +3,13 @@ import { QuartzComponentProps } from "../../components/types"
import BodyConstructor from "../../components/Body" import BodyConstructor from "../../components/Body"
import { pageResources, renderPage } from "../../components/renderPage" import { pageResources, renderPage } from "../../components/renderPage"
import { FullPageLayout } from "../../cfg" import { FullPageLayout } from "../../cfg"
import { FullSlug } from "../../util/path" import { FilePath, FullSlug } from "../../util/path"
import { sharedPageComponents } from "../../../quartz.layout" import { sharedPageComponents } from "../../../quartz.layout"
import { NotFound } from "../../components" import { NotFound } from "../../components"
import { defaultProcessedContent } from "../vfile" import { defaultProcessedContent } from "../vfile"
import { write } from "./helpers" import { write } from "./helpers"
import { i18n } from "../../i18n" import { i18n } from "../../i18n"
import DepGraph from "../../depgraph"
export const NotFoundPage: QuartzEmitterPlugin = () => { export const NotFoundPage: QuartzEmitterPlugin = () => {
const opts: FullPageLayout = { const opts: FullPageLayout = {
@ -27,7 +28,10 @@ export const NotFoundPage: QuartzEmitterPlugin = () => {
getQuartzComponents() { getQuartzComponents() {
return [Head, Body, pageBody, Footer] return [Head, Body, pageBody, Footer]
}, },
async *emit(ctx, _content, resources) { async getDependencyGraph(_ctx, _content, _resources) {
return new DepGraph<FilePath>()
},
async emit(ctx, _content, resources): Promise<FilePath[]> {
const cfg = ctx.cfg.configuration const cfg = ctx.cfg.configuration
const slug = "404" as FullSlug const slug = "404" as FullSlug
@ -40,7 +44,7 @@ export const NotFoundPage: QuartzEmitterPlugin = () => {
description: notFound, description: notFound,
frontmatter: { title: notFound, tags: [] }, frontmatter: { title: notFound, tags: [] },
}) })
const externalResources = pageResources(path, resources) const externalResources = pageResources(path, vfile.data, resources)
const componentData: QuartzComponentProps = { const componentData: QuartzComponentProps = {
ctx, ctx,
fileData: vfile.data, fileData: vfile.data,
@ -51,13 +55,14 @@ export const NotFoundPage: QuartzEmitterPlugin = () => {
allFiles: [], allFiles: [],
} }
yield write({ return [
ctx, await write({
content: renderPage(cfg, slug, componentData, opts, externalResources), ctx,
slug, content: renderPage(cfg, slug, componentData, opts, externalResources),
ext: ".html", slug,
}) ext: ".html",
}),
]
}, },
async *partialEmit() {},
} }
} }

View File

@ -1,48 +1,81 @@
import { resolveRelative, simplifySlug } from "../../util/path" import { FilePath, FullSlug, joinSegments, resolveRelative, simplifySlug } from "../../util/path"
import { QuartzEmitterPlugin } from "../types" import { QuartzEmitterPlugin } from "../types"
import path from "path"
import { write } from "./helpers" import { write } from "./helpers"
import { BuildCtx } from "../../util/ctx" import DepGraph from "../../depgraph"
import { VFile } from "vfile"
async function* processFile(ctx: BuildCtx, file: VFile) {
const ogSlug = simplifySlug(file.data.slug!)
for (const slug of file.data.aliases ?? []) {
const redirUrl = resolveRelative(slug, file.data.slug!)
yield write({
ctx,
content: `
<!DOCTYPE html>
<html lang="en-us">
<head>
<title>${ogSlug}</title>
<link rel="canonical" href="${redirUrl}">
<meta name="robots" content="noindex">
<meta charset="utf-8">
<meta http-equiv="refresh" content="0; url=${redirUrl}">
</head>
</html>
`,
slug,
ext: ".html",
})
}
}
export const AliasRedirects: QuartzEmitterPlugin = () => ({ export const AliasRedirects: QuartzEmitterPlugin = () => ({
name: "AliasRedirects", name: "AliasRedirects",
async *emit(ctx, content) { getQuartzComponents() {
for (const [_tree, file] of content) { return []
yield* processFile(ctx, file)
}
}, },
async *partialEmit(ctx, _content, _resources, changeEvents) { async getDependencyGraph(ctx, content, _resources) {
for (const changeEvent of changeEvents) { const graph = new DepGraph<FilePath>()
if (!changeEvent.file) continue
if (changeEvent.type === "add" || changeEvent.type === "change") { const { argv } = ctx
// add new ones if this file still exists for (const [_tree, file] of content) {
yield* processFile(ctx, changeEvent.file) const dir = path.posix.relative(argv.directory, path.dirname(file.data.filePath!))
const aliases = file.data.frontmatter?.aliases ?? []
const slugs = aliases.map((alias) => path.posix.join(dir, alias) as FullSlug)
const permalink = file.data.frontmatter?.permalink
if (typeof permalink === "string") {
slugs.push(permalink as FullSlug)
}
for (let slug of slugs) {
// fix any slugs that have trailing slash
if (slug.endsWith("/")) {
slug = joinSegments(slug, "index") as FullSlug
}
graph.addEdge(file.data.filePath!, joinSegments(argv.output, slug + ".html") as FilePath)
} }
} }
return graph
},
async emit(ctx, content, _resources): Promise<FilePath[]> {
const { argv } = ctx
const fps: FilePath[] = []
for (const [_tree, file] of content) {
const ogSlug = simplifySlug(file.data.slug!)
const dir = path.posix.relative(argv.directory, path.dirname(file.data.filePath!))
const aliases = file.data.frontmatter?.aliases ?? []
const slugs: FullSlug[] = aliases.map((alias) => path.posix.join(dir, alias) as FullSlug)
const permalink = file.data.frontmatter?.permalink
if (typeof permalink === "string") {
slugs.push(permalink as FullSlug)
}
for (let slug of slugs) {
// fix any slugs that have trailing slash
if (slug.endsWith("/")) {
slug = joinSegments(slug, "index") as FullSlug
}
const redirUrl = resolveRelative(slug, file.data.slug!)
const fp = await write({
ctx,
content: `
<!DOCTYPE html>
<html lang="en-us">
<head>
<title>${ogSlug}</title>
<link rel="canonical" href="${redirUrl}">
<meta name="robots" content="noindex">
<meta charset="utf-8">
<meta http-equiv="refresh" content="0; url=${redirUrl}">
</head>
</html>
`,
slug,
ext: ".html",
})
fps.push(fp)
}
}
return fps
}, },
}) })

View File

@ -3,6 +3,7 @@ import { QuartzEmitterPlugin } from "../types"
import path from "path" import path from "path"
import fs from "fs" import fs from "fs"
import { glob } from "../../util/glob" import { glob } from "../../util/glob"
import DepGraph from "../../depgraph"
import { Argv } from "../../util/ctx" import { Argv } from "../../util/ctx"
import { QuartzConfig } from "../../cfg" import { QuartzConfig } from "../../cfg"
@ -11,42 +12,47 @@ const filesToCopy = async (argv: Argv, cfg: QuartzConfig) => {
return await glob("**", argv.directory, ["**/*.md", ...cfg.configuration.ignorePatterns]) return await glob("**", argv.directory, ["**/*.md", ...cfg.configuration.ignorePatterns])
} }
const copyFile = async (argv: Argv, fp: FilePath) => {
const src = joinSegments(argv.directory, fp) as FilePath
const name = slugifyFilePath(fp)
const dest = joinSegments(argv.output, name) as FilePath
// ensure dir exists
const dir = path.dirname(dest) as FilePath
await fs.promises.mkdir(dir, { recursive: true })
await fs.promises.copyFile(src, dest)
return dest
}
export const Assets: QuartzEmitterPlugin = () => { export const Assets: QuartzEmitterPlugin = () => {
return { return {
name: "Assets", name: "Assets",
async *emit({ argv, cfg }) { getQuartzComponents() {
const fps = await filesToCopy(argv, cfg) return []
for (const fp of fps) {
yield copyFile(argv, fp)
}
}, },
async *partialEmit(ctx, _content, _resources, changeEvents) { async getDependencyGraph(ctx, _content, _resources) {
for (const changeEvent of changeEvents) { const { argv, cfg } = ctx
const ext = path.extname(changeEvent.path) const graph = new DepGraph<FilePath>()
if (ext === ".md") continue
if (changeEvent.type === "add" || changeEvent.type === "change") { const fps = await filesToCopy(argv, cfg)
yield copyFile(ctx.argv, changeEvent.path)
} else if (changeEvent.type === "delete") { for (const fp of fps) {
const name = slugifyFilePath(changeEvent.path) const ext = path.extname(fp)
const dest = joinSegments(ctx.argv.output, name) as FilePath const src = joinSegments(argv.directory, fp) as FilePath
await fs.promises.unlink(dest) const name = (slugifyFilePath(fp as FilePath, true) + ext) as FilePath
}
const dest = joinSegments(argv.output, name) as FilePath
graph.addEdge(src, dest)
} }
return graph
},
async emit({ argv, cfg }, _content, _resources): Promise<FilePath[]> {
const assetsPath = argv.output
const fps = await filesToCopy(argv, cfg)
const res: FilePath[] = []
for (const fp of fps) {
const ext = path.extname(fp)
const src = joinSegments(argv.directory, fp) as FilePath
const name = (slugifyFilePath(fp as FilePath, true) + ext) as FilePath
const dest = joinSegments(assetsPath, name) as FilePath
const dir = path.dirname(dest) as FilePath
await fs.promises.mkdir(dir, { recursive: true }) // ensure dir exists
await fs.promises.copyFile(src, dest)
res.push(dest)
}
return res
}, },
} }
} }

View File

@ -2,6 +2,7 @@ import { FilePath, joinSegments } from "../../util/path"
import { QuartzEmitterPlugin } from "../types" import { QuartzEmitterPlugin } from "../types"
import fs from "fs" import fs from "fs"
import chalk from "chalk" import chalk from "chalk"
import DepGraph from "../../depgraph"
export function extractDomainFromBaseUrl(baseUrl: string) { export function extractDomainFromBaseUrl(baseUrl: string) {
const url = new URL(`https://${baseUrl}`) const url = new URL(`https://${baseUrl}`)
@ -10,7 +11,13 @@ export function extractDomainFromBaseUrl(baseUrl: string) {
export const CNAME: QuartzEmitterPlugin = () => ({ export const CNAME: QuartzEmitterPlugin = () => ({
name: "CNAME", name: "CNAME",
async emit({ argv, cfg }) { getQuartzComponents() {
return []
},
async getDependencyGraph(_ctx, _content, _resources) {
return new DepGraph<FilePath>()
},
async emit({ argv, cfg }, _content, _resources): Promise<FilePath[]> {
if (!cfg.configuration.baseUrl) { if (!cfg.configuration.baseUrl) {
console.warn(chalk.yellow("CNAME emitter requires `baseUrl` to be set in your configuration")) console.warn(chalk.yellow("CNAME emitter requires `baseUrl` to be set in your configuration"))
return [] return []
@ -20,8 +27,7 @@ export const CNAME: QuartzEmitterPlugin = () => ({
if (!content) { if (!content) {
return [] return []
} }
await fs.promises.writeFile(path, content) fs.writeFileSync(path, content)
return [path] as FilePath[] return [path] as FilePath[]
}, },
async *partialEmit() {},
}) })

View File

@ -1,4 +1,4 @@
import { FullSlug, joinSegments } from "../../util/path" import { FilePath, FullSlug, joinSegments } from "../../util/path"
import { QuartzEmitterPlugin } from "../types" import { QuartzEmitterPlugin } from "../types"
// @ts-ignore // @ts-ignore
@ -9,15 +9,11 @@ import styles from "../../styles/custom.scss"
import popoverStyle from "../../components/styles/popover.scss" import popoverStyle from "../../components/styles/popover.scss"
import { BuildCtx } from "../../util/ctx" import { BuildCtx } from "../../util/ctx"
import { QuartzComponent } from "../../components/types" import { QuartzComponent } from "../../components/types"
import { import { googleFontHref, joinStyles } from "../../util/theme"
googleFontHref,
googleFontSubsetHref,
joinStyles,
processGoogleFonts,
} from "../../util/theme"
import { Features, transform } from "lightningcss" import { Features, transform } from "lightningcss"
import { transform as transpile } from "esbuild" import { transform as transpile } from "esbuild"
import { write } from "./helpers" import { write } from "./helpers"
import DepGraph from "../../depgraph"
type ComponentResources = { type ComponentResources = {
css: string[] css: string[]
@ -28,7 +24,7 @@ type ComponentResources = {
function getComponentResources(ctx: BuildCtx): ComponentResources { function getComponentResources(ctx: BuildCtx): ComponentResources {
const allComponents: Set<QuartzComponent> = new Set() const allComponents: Set<QuartzComponent> = new Set()
for (const emitter of ctx.cfg.plugins.emitters) { for (const emitter of ctx.cfg.plugins.emitters) {
const components = emitter.getQuartzComponents?.(ctx) ?? [] const components = emitter.getQuartzComponents(ctx)
for (const component of components) { for (const component of components) {
allComponents.add(component) allComponents.add(component)
} }
@ -40,21 +36,17 @@ function getComponentResources(ctx: BuildCtx): ComponentResources {
afterDOMLoaded: new Set<string>(), afterDOMLoaded: new Set<string>(),
} }
function normalizeResource(resource: string | string[] | undefined): string[] {
if (!resource) return []
if (Array.isArray(resource)) return resource
return [resource]
}
for (const component of allComponents) { for (const component of allComponents) {
const { css, beforeDOMLoaded, afterDOMLoaded } = component const { css, beforeDOMLoaded, afterDOMLoaded } = component
const normalizedCss = normalizeResource(css) if (css) {
const normalizedBeforeDOMLoaded = normalizeResource(beforeDOMLoaded) componentResources.css.add(css)
const normalizedAfterDOMLoaded = normalizeResource(afterDOMLoaded) }
if (beforeDOMLoaded) {
normalizedCss.forEach((c) => componentResources.css.add(c)) componentResources.beforeDOMLoaded.add(beforeDOMLoaded)
normalizedBeforeDOMLoaded.forEach((b) => componentResources.beforeDOMLoaded.add(b)) }
normalizedAfterDOMLoaded.forEach((a) => componentResources.afterDOMLoaded.add(a)) if (afterDOMLoaded) {
componentResources.afterDOMLoaded.add(afterDOMLoaded)
}
} }
return { return {
@ -90,7 +82,7 @@ function addGlobalPageResources(ctx: BuildCtx, componentResources: ComponentReso
componentResources.afterDOMLoaded.push(` componentResources.afterDOMLoaded.push(`
const gtagScript = document.createElement("script") const gtagScript = document.createElement("script")
gtagScript.src = "https://www.googletagmanager.com/gtag/js?id=${tagId}" gtagScript.src = "https://www.googletagmanager.com/gtag/js?id=${tagId}"
gtagScript.defer = true gtagScript.async = true
document.head.appendChild(gtagScript) document.head.appendChild(gtagScript)
window.dataLayer = window.dataLayer || []; window.dataLayer = window.dataLayer || [];
@ -124,66 +116,47 @@ function addGlobalPageResources(ctx: BuildCtx, componentResources: ComponentReso
const umamiScript = document.createElement("script") const umamiScript = document.createElement("script")
umamiScript.src = "${cfg.analytics.host ?? "https://analytics.umami.is"}/script.js" umamiScript.src = "${cfg.analytics.host ?? "https://analytics.umami.is"}/script.js"
umamiScript.setAttribute("data-website-id", "${cfg.analytics.websiteId}") umamiScript.setAttribute("data-website-id", "${cfg.analytics.websiteId}")
umamiScript.setAttribute("data-auto-track", "false") umamiScript.async = true
umamiScript.defer = true
document.head.appendChild(umamiScript)
document.addEventListener("nav", () => { document.head.appendChild(umamiScript)
umami.track();
})
`) `)
} else if (cfg.analytics?.provider === "goatcounter") { } else if (cfg.analytics?.provider === "goatcounter") {
componentResources.afterDOMLoaded.push(` componentResources.afterDOMLoaded.push(`
const goatcounterScript = document.createElement("script") const goatcounterScript = document.createElement("script")
goatcounterScript.src = "${cfg.analytics.scriptSrc ?? "https://gc.zgo.at/count.js"}" goatcounterScript.src = "${cfg.analytics.scriptSrc ?? "https://gc.zgo.at/count.js"}"
goatcounterScript.defer = true goatcounterScript.async = true
goatcounterScript.setAttribute("data-goatcounter", goatcounterScript.setAttribute("data-goatcounter",
"https://${cfg.analytics.websiteId}.${cfg.analytics.host ?? "goatcounter.com"}/count") "https://${cfg.analytics.websiteId}.${cfg.analytics.host ?? "goatcounter.com"}/count")
document.head.appendChild(goatcounterScript) document.head.appendChild(goatcounterScript)
window.goatcounter = { no_onload: true }
document.addEventListener("nav", () => {
goatcounter.count({ path: location.pathname })
})
`) `)
} else if (cfg.analytics?.provider === "posthog") { } else if (cfg.analytics?.provider === "posthog") {
componentResources.afterDOMLoaded.push(` componentResources.afterDOMLoaded.push(`
const posthogScript = document.createElement("script") const posthogScript = document.createElement("script")
posthogScript.innerHTML= \`!function(t,e){var o,n,p,r;e.__SV||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split(".");2==o.length&&(t=t[o[0]],e=o[1]),t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}(p=t.createElement("script")).type="text/javascript",p.async=!0,p.src=s.api_host+"/static/array.js",(r=t.getElementsByTagName("script")[0]).parentNode.insertBefore(p,r);var u=e;for(void 0!==a?u=e[a]=[]:a="posthog",u.people=u.people||[],u.toString=function(t){var e="posthog";return"posthog"!==a&&(e+="."+a),t||(e+=" (stub)"),e},u.people.toString=function(){return u.toString(1)+".people (stub)"},o="capture identify alias people.set people.set_once set_config register register_once unregister opt_out_capturing has_opted_out_capturing opt_in_capturing reset isFeatureEnabled onFeatureFlags getFeatureFlag getFeatureFlagPayload reloadFeatureFlags group updateEarlyAccessFeatureEnrollment getEarlyAccessFeatures getActiveMatchingSurveys getSurveys onSessionId".split(" "),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]); posthogScript.innerHTML= \`!function(t,e){var o,n,p,r;e.__SV||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split(".");2==o.length&&(t=t[o[0]],e=o[1]),t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}(p=t.createElement("script")).type="text/javascript",p.async=!0,p.src=s.api_host+"/static/array.js",(r=t.getElementsByTagName("script")[0]).parentNode.insertBefore(p,r);var u=e;for(void 0!==a?u=e[a]=[]:a="posthog",u.people=u.people||[],u.toString=function(t){var e="posthog";return"posthog"!==a&&(e+="."+a),t||(e+=" (stub)"),e},u.people.toString=function(){return u.toString(1)+".people (stub)"},o="capture identify alias people.set people.set_once set_config register register_once unregister opt_out_capturing has_opted_out_capturing opt_in_capturing reset isFeatureEnabled onFeatureFlags getFeatureFlag getFeatureFlagPayload reloadFeatureFlags group updateEarlyAccessFeatureEnrollment getEarlyAccessFeatures getActiveMatchingSurveys getSurveys onSessionId".split(" "),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]);
posthog.init('${cfg.analytics.apiKey}', { posthog.init('${cfg.analytics.apiKey}',{api_host:'${cfg.analytics.host ?? "https://app.posthog.com"}'})\`
api_host: '${cfg.analytics.host ?? "https://app.posthog.com"}',
capture_pageview: false,
})\`
document.head.appendChild(posthogScript) document.head.appendChild(posthogScript)
document.addEventListener("nav", () => {
posthog.capture('$pageview', { path: location.pathname })
})
`) `)
} else if (cfg.analytics?.provider === "tinylytics") { } else if (cfg.analytics?.provider === "tinylytics") {
const siteId = cfg.analytics.siteId const siteId = cfg.analytics.siteId
componentResources.afterDOMLoaded.push(` componentResources.afterDOMLoaded.push(`
const tinylyticsScript = document.createElement("script") const tinylyticsScript = document.createElement("script")
tinylyticsScript.src = "https://tinylytics.app/embed/${siteId}.js?spa" tinylyticsScript.src = "https://tinylytics.app/embed/${siteId}.js"
tinylyticsScript.defer = true tinylyticsScript.defer = true
document.head.appendChild(tinylyticsScript) document.head.appendChild(tinylyticsScript)
document.addEventListener("nav", () => {
window.tinylytics.triggerUpdate()
})
`) `)
} else if (cfg.analytics?.provider === "cabin") { } else if (cfg.analytics?.provider === "cabin") {
componentResources.afterDOMLoaded.push(` componentResources.afterDOMLoaded.push(`
const cabinScript = document.createElement("script") const cabinScript = document.createElement("script")
cabinScript.src = "${cfg.analytics.host ?? "https://scripts.withcabin.com"}/hello.js" cabinScript.src = "${cfg.analytics.host ?? "https://scripts.withcabin.com"}/hello.js"
cabinScript.defer = true cabinScript.defer = true
cabinScript.async = true
document.head.appendChild(cabinScript) document.head.appendChild(cabinScript)
`) `)
} else if (cfg.analytics?.provider === "clarity") { } else if (cfg.analytics?.provider === "clarity") {
componentResources.afterDOMLoaded.push(` componentResources.afterDOMLoaded.push(`
const clarityScript = document.createElement("script") const clarityScript = document.createElement("script")
clarityScript.innerHTML= \`(function(c,l,a,r,i,t,y){c[a]=c[a]||function(){(c[a].q=c[a].q||[]).push(arguments)}; clarityScript.innerHTML= \`(function(c,l,a,r,i,t,y){c[a]=c[a]||function(){(c[a].q=c[a].q||[]).push(arguments)};
t=l.createElement(r);t.defer=1;t.src="https://www.clarity.ms/tag/"+i; t=l.createElement(r);t.async=1;t.src="https://www.clarity.ms/tag/"+i;
y=l.getElementsByTagName(r)[0];y.parentNode.insertBefore(t,y); y=l.getElementsByTagName(r)[0];y.parentNode.insertBefore(t,y);
})(window, document, "clarity", "script", "${cfg.analytics.projectId}");\` })(window, document, "clarity", "script", "${cfg.analytics.projectId}");\`
document.head.appendChild(clarityScript) document.head.appendChild(clarityScript)
@ -207,7 +180,14 @@ function addGlobalPageResources(ctx: BuildCtx, componentResources: ComponentReso
export const ComponentResources: QuartzEmitterPlugin = () => { export const ComponentResources: QuartzEmitterPlugin = () => {
return { return {
name: "ComponentResources", name: "ComponentResources",
async *emit(ctx, _content, _resources) { getQuartzComponents() {
return []
},
async getDependencyGraph(_ctx, _content, _resources) {
return new DepGraph<FilePath>()
},
async emit(ctx, _content, _resources): Promise<FilePath[]> {
const promises: Promise<FilePath>[] = []
const cfg = ctx.cfg.configuration const cfg = ctx.cfg.configuration
// component specific scripts and styles // component specific scripts and styles
const componentResources = getComponentResources(ctx) const componentResources = getComponentResources(ctx)
@ -216,42 +196,42 @@ export const ComponentResources: QuartzEmitterPlugin = () => {
// let the user do it themselves in css // let the user do it themselves in css
} else if (cfg.theme.fontOrigin === "googleFonts" && !cfg.theme.cdnCaching) { } else if (cfg.theme.fontOrigin === "googleFonts" && !cfg.theme.cdnCaching) {
// when cdnCaching is true, we link to google fonts in Head.tsx // when cdnCaching is true, we link to google fonts in Head.tsx
const theme = ctx.cfg.configuration.theme let match
const response = await fetch(googleFontHref(theme))
googleFontsStyleSheet = await response.text()
if (theme.typography.title) { const fontSourceRegex = /url\((https:\/\/fonts.gstatic.com\/s\/[^)]+\.(woff2|ttf))\)/g
const title = ctx.cfg.configuration.pageTitle
const response = await fetch(googleFontSubsetHref(theme, title))
googleFontsStyleSheet += `\n${await response.text()}`
}
if (!cfg.baseUrl) { googleFontsStyleSheet = await (
throw new Error( await fetch(googleFontHref(ctx.cfg.configuration.theme))
"baseUrl must be defined when using Google Fonts without cfg.theme.cdnCaching", ).text()
while ((match = fontSourceRegex.exec(googleFontsStyleSheet)) !== null) {
// match[0] is the `url(path)`, match[1] is the `path`
const url = match[1]
// the static name of this file.
const [filename, ext] = url.split("/").pop()!.split(".")
googleFontsStyleSheet = googleFontsStyleSheet.replace(
url,
`https://${cfg.baseUrl}/static/fonts/${filename}.ttf`,
) )
}
const { processedStylesheet, fontFiles } = await processGoogleFonts( promises.push(
googleFontsStyleSheet, fetch(url)
cfg.baseUrl, .then((res) => {
) if (!res.ok) {
googleFontsStyleSheet = processedStylesheet throw new Error(`Failed to fetch font`)
}
// Download and save font files return res.arrayBuffer()
for (const fontFile of fontFiles) { })
const res = await fetch(fontFile.url) .then((buf) =>
if (!res.ok) { write({
throw new Error(`Failed to fetch font ${fontFile.filename}`) ctx,
} slug: joinSegments("static", "fonts", filename) as FullSlug,
ext: `.${ext}`,
const buf = await res.arrayBuffer() content: Buffer.from(buf),
yield write({ }),
ctx, ),
slug: joinSegments("static", "fonts", fontFile.filename) as FullSlug, )
ext: `.${fontFile.extension}`,
content: Buffer.from(buf),
})
} }
} }
@ -266,45 +246,45 @@ export const ComponentResources: QuartzEmitterPlugin = () => {
...componentResources.css, ...componentResources.css,
styles, styles,
) )
const [prescript, postscript] = await Promise.all([ const [prescript, postscript] = await Promise.all([
joinScripts(componentResources.beforeDOMLoaded), joinScripts(componentResources.beforeDOMLoaded),
joinScripts(componentResources.afterDOMLoaded), joinScripts(componentResources.afterDOMLoaded),
]) ])
yield write({ promises.push(
ctx, write({
slug: "index" as FullSlug, ctx,
ext: ".css", slug: "index" as FullSlug,
content: transform({ ext: ".css",
filename: "index.css", content: transform({
code: Buffer.from(stylesheet), filename: "index.css",
minify: true, code: Buffer.from(stylesheet),
targets: { minify: true,
safari: (15 << 16) | (6 << 8), // 15.6 targets: {
ios_saf: (15 << 16) | (6 << 8), // 15.6 safari: (15 << 16) | (6 << 8), // 15.6
edge: 115 << 16, ios_saf: (15 << 16) | (6 << 8), // 15.6
firefox: 102 << 16, edge: 115 << 16,
chrome: 109 << 16, firefox: 102 << 16,
}, chrome: 109 << 16,
include: Features.MediaQueries, },
}).code.toString(), include: Features.MediaQueries,
}) }).code.toString(),
}),
write({
ctx,
slug: "prescript" as FullSlug,
ext: ".js",
content: prescript,
}),
write({
ctx,
slug: "postscript" as FullSlug,
ext: ".js",
content: postscript,
}),
)
yield write({ return await Promise.all(promises)
ctx,
slug: "prescript" as FullSlug,
ext: ".js",
content: prescript,
})
yield write({
ctx,
slug: "postscript" as FullSlug,
ext: ".js",
content: postscript,
})
}, },
async *partialEmit() {},
} }
} }

View File

@ -7,11 +7,10 @@ import { QuartzEmitterPlugin } from "../types"
import { toHtml } from "hast-util-to-html" import { toHtml } from "hast-util-to-html"
import { write } from "./helpers" import { write } from "./helpers"
import { i18n } from "../../i18n" import { i18n } from "../../i18n"
import DepGraph from "../../depgraph"
export type ContentIndexMap = Map<FullSlug, ContentDetails> export type ContentIndex = Map<FullSlug, ContentDetails>
export type ContentDetails = { export type ContentDetails = {
slug: FullSlug
filePath: FilePath
title: string title: string
links: SimpleSlug[] links: SimpleSlug[]
tags: string[] tags: string[]
@ -26,7 +25,6 @@ interface Options {
enableRSS: boolean enableRSS: boolean
rssLimit?: number rssLimit?: number
rssFullHtml: boolean rssFullHtml: boolean
rssSlug: string
includeEmptyFiles: boolean includeEmptyFiles: boolean
} }
@ -35,11 +33,10 @@ const defaultOptions: Options = {
enableRSS: true, enableRSS: true,
rssLimit: 10, rssLimit: 10,
rssFullHtml: false, rssFullHtml: false,
rssSlug: "index",
includeEmptyFiles: true, includeEmptyFiles: true,
} }
function generateSiteMap(cfg: GlobalConfiguration, idx: ContentIndexMap): 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://${joinSegments(base, encodeURI(slug))}</loc> <loc>https://${joinSegments(base, encodeURI(slug))}</loc>
@ -51,7 +48,7 @@ function generateSiteMap(cfg: GlobalConfiguration, idx: ContentIndexMap): string
return `<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">${urls}</urlset>` return `<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">${urls}</urlset>`
} }
function generateRSSFeed(cfg: GlobalConfiguration, idx: ContentIndexMap, limit?: number): string { function generateRSSFeed(cfg: GlobalConfiguration, idx: ContentIndex, limit?: number): string {
const base = cfg.baseUrl ?? "" const base = cfg.baseUrl ?? ""
const createURLEntry = (slug: SimpleSlug, content: ContentDetails): string => `<item> const createURLEntry = (slug: SimpleSlug, content: ContentDetails): string => `<item>
@ -96,16 +93,35 @@ export const ContentIndex: QuartzEmitterPlugin<Partial<Options>> = (opts) => {
opts = { ...defaultOptions, ...opts } opts = { ...defaultOptions, ...opts }
return { return {
name: "ContentIndex", name: "ContentIndex",
async *emit(ctx, content) { async getDependencyGraph(ctx, content, _resources) {
const graph = new DepGraph<FilePath>()
for (const [_tree, file] of content) {
const sourcePath = file.data.filePath!
graph.addEdge(
sourcePath,
joinSegments(ctx.argv.output, "static/contentIndex.json") as FilePath,
)
if (opts?.enableSiteMap) {
graph.addEdge(sourcePath, joinSegments(ctx.argv.output, "sitemap.xml") as FilePath)
}
if (opts?.enableRSS) {
graph.addEdge(sourcePath, joinSegments(ctx.argv.output, "index.xml") as FilePath)
}
}
return graph
},
async emit(ctx, content, _resources) {
const cfg = ctx.cfg.configuration const cfg = ctx.cfg.configuration
const linkIndex: ContentIndexMap = new Map() const emitted: FilePath[] = []
const linkIndex: ContentIndex = new Map()
for (const [tree, file] of content) { for (const [tree, file] of content) {
const slug = file.data.slug! const slug = file.data.slug!
const date = getDate(ctx.cfg.configuration, file.data) ?? new Date() const date = getDate(ctx.cfg.configuration, file.data) ?? new Date()
if (opts?.includeEmptyFiles || (file.data.text && file.data.text !== "")) { if (opts?.includeEmptyFiles || (file.data.text && file.data.text !== "")) {
linkIndex.set(slug, { linkIndex.set(slug, {
slug,
filePath: file.data.relativePath!,
title: file.data.frontmatter?.title!, title: file.data.frontmatter?.title!,
links: file.data.links ?? [], links: file.data.links ?? [],
tags: file.data.frontmatter?.tags ?? [], tags: file.data.frontmatter?.tags ?? [],
@ -120,21 +136,25 @@ export const ContentIndex: QuartzEmitterPlugin<Partial<Options>> = (opts) => {
} }
if (opts?.enableSiteMap) { if (opts?.enableSiteMap) {
yield write({ emitted.push(
ctx, await write({
content: generateSiteMap(cfg, linkIndex), ctx,
slug: "sitemap" as FullSlug, content: generateSiteMap(cfg, linkIndex),
ext: ".xml", slug: "sitemap" as FullSlug,
}) ext: ".xml",
}),
)
} }
if (opts?.enableRSS) { if (opts?.enableRSS) {
yield write({ emitted.push(
ctx, await write({
content: generateRSSFeed(cfg, linkIndex, opts.rssLimit), ctx,
slug: (opts?.rssSlug ?? "index") as FullSlug, content: generateRSSFeed(cfg, linkIndex, opts.rssLimit),
ext: ".xml", slug: "index" as FullSlug,
}) ext: ".xml",
}),
)
} }
const fp = joinSegments("static", "contentIndex") as FullSlug const fp = joinSegments("static", "contentIndex") as FullSlug
@ -149,26 +169,17 @@ export const ContentIndex: QuartzEmitterPlugin<Partial<Options>> = (opts) => {
}), }),
) )
yield write({ emitted.push(
ctx, await write({
content: JSON.stringify(simplifiedIndex), ctx,
slug: fp, content: JSON.stringify(simplifiedIndex),
ext: ".json", slug: fp,
}) ext: ".json",
}, }),
externalResources: (ctx) => { )
if (opts?.enableRSS) {
return { return emitted
additionalHead: [
<link
rel="alternate"
type="application/rss+xml"
title="RSS Feed"
href={`https://${ctx.cfg.configuration.baseUrl}/index.xml`}
/>,
],
}
}
}, },
getQuartzComponents: () => [],
} }
} }

View File

@ -1,48 +1,54 @@
import path from "path" import path from "path"
import { visit } from "unist-util-visit"
import { Root } from "hast"
import { VFile } from "vfile"
import { QuartzEmitterPlugin } from "../types" import { QuartzEmitterPlugin } from "../types"
import { QuartzComponentProps } from "../../components/types" import { QuartzComponentProps } from "../../components/types"
import HeaderConstructor from "../../components/Header" import HeaderConstructor from "../../components/Header"
import BodyConstructor from "../../components/Body" import BodyConstructor from "../../components/Body"
import { pageResources, renderPage } from "../../components/renderPage" import { pageResources, renderPage } from "../../components/renderPage"
import { FullPageLayout } from "../../cfg" import { FullPageLayout } from "../../cfg"
import { pathToRoot } from "../../util/path" import { Argv } from "../../util/ctx"
import { FilePath, isRelativeURL, joinSegments, pathToRoot } from "../../util/path"
import { defaultContentPageLayout, sharedPageComponents } from "../../../quartz.layout" import { defaultContentPageLayout, sharedPageComponents } from "../../../quartz.layout"
import { Content } from "../../components" import { Content } from "../../components"
import chalk from "chalk" import chalk from "chalk"
import { write } from "./helpers" import { write } from "./helpers"
import { BuildCtx } from "../../util/ctx" import DepGraph from "../../depgraph"
import { Node } from "unist"
import { StaticResources } from "../../util/resources"
import { QuartzPluginData } from "../vfile"
async function processContent( // get all the dependencies for the markdown file
ctx: BuildCtx, // eg. images, scripts, stylesheets, transclusions
tree: Node, const parseDependencies = (argv: Argv, hast: Root, file: VFile): string[] => {
fileData: QuartzPluginData, const dependencies: string[] = []
allFiles: QuartzPluginData[],
opts: FullPageLayout,
resources: StaticResources,
) {
const slug = fileData.slug!
const cfg = ctx.cfg.configuration
const externalResources = pageResources(pathToRoot(slug), resources)
const componentData: QuartzComponentProps = {
ctx,
fileData,
externalResources,
cfg,
children: [],
tree,
allFiles,
}
const content = renderPage(cfg, slug, componentData, opts, externalResources) visit(hast, "element", (elem): void => {
return write({ let ref: string | null = null
ctx,
content, if (
slug, ["script", "img", "audio", "video", "source", "iframe"].includes(elem.tagName) &&
ext: ".html", elem?.properties?.src
) {
ref = elem.properties.src.toString()
} else if (["a", "link"].includes(elem.tagName) && elem?.properties?.href) {
// transclusions will create a tags with relative hrefs
ref = elem.properties.href.toString()
}
// if it is a relative url, its a local file and we need to add
// it to the dependency graph. otherwise, ignore
if (ref === null || !isRelativeURL(ref)) {
return
}
let fp = path.join(file.data.filePath!, path.relative(argv.directory, ref)).replace(/\\/g, "/")
// markdown files have the .md extension stripped in hrefs, add it back here
if (!fp.split("/").pop()?.includes(".")) {
fp += ".md"
}
dependencies.push(fp)
}) })
return dependencies
} }
export const ContentPage: QuartzEmitterPlugin<Partial<FullPageLayout>> = (userOpts) => { export const ContentPage: QuartzEmitterPlugin<Partial<FullPageLayout>> = (userOpts) => {
@ -73,48 +79,64 @@ export const ContentPage: QuartzEmitterPlugin<Partial<FullPageLayout>> = (userOp
Footer, Footer,
] ]
}, },
async *emit(ctx, content, resources) { async getDependencyGraph(ctx, content, _resources) {
const allFiles = content.map((c) => c[1].data) const graph = new DepGraph<FilePath>()
let containsIndex = false
for (const [tree, file] of content) {
const sourcePath = file.data.filePath!
const slug = file.data.slug!
graph.addEdge(sourcePath, joinSegments(ctx.argv.output, slug + ".html") as FilePath)
parseDependencies(ctx.argv, tree as Root, file).forEach((dep) => {
graph.addEdge(dep as FilePath, sourcePath)
})
}
return graph
},
async emit(ctx, content, resources): Promise<FilePath[]> {
const cfg = ctx.cfg.configuration
const fps: FilePath[] = []
const allFiles = content.map((c) => c[1].data)
let containsIndex = false
for (const [tree, file] of content) { for (const [tree, file] of content) {
const slug = file.data.slug! const slug = file.data.slug!
if (slug === "index") { if (slug === "index") {
containsIndex = true containsIndex = true
} }
// only process home page, non-tag pages, and non-index pages const externalResources = pageResources(pathToRoot(slug), file.data, resources)
if (slug.endsWith("/index") || slug.startsWith("tags/")) continue const componentData: QuartzComponentProps = {
yield processContent(ctx, tree, file.data, allFiles, opts, resources) ctx,
fileData: file.data,
externalResources,
cfg,
children: [],
tree,
allFiles,
}
const content = renderPage(cfg, slug, componentData, opts, externalResources)
const fp = await write({
ctx,
content,
slug,
ext: ".html",
})
fps.push(fp)
} }
if (!containsIndex) { if (!containsIndex && !ctx.argv.fastRebuild) {
console.log( console.log(
chalk.yellow( chalk.yellow(
`\nWarning: you seem to be missing an \`index.md\` home page file at the root of your \`${ctx.argv.directory}\` folder (\`${path.join(ctx.argv.directory, "index.md")} does not exist\`). This may cause errors when deploying.`, `\nWarning: you seem to be missing an \`index.md\` home page file at the root of your \`${ctx.argv.directory}\` folder. This may cause errors when deploying.`,
), ),
) )
} }
},
async *partialEmit(ctx, content, resources, changeEvents) {
const allFiles = content.map((c) => c[1].data)
// find all slugs that changed or were added return fps
const changedSlugs = new Set<string>()
for (const changeEvent of changeEvents) {
if (!changeEvent.file) continue
if (changeEvent.type === "add" || changeEvent.type === "change") {
changedSlugs.add(changeEvent.file.data.slug!)
}
}
for (const [tree, file] of content) {
const slug = file.data.slug!
if (!changedSlugs.has(slug)) continue
if (slug.endsWith("/index") || slug.startsWith("tags/")) continue
yield processContent(ctx, tree, file.data, allFiles, opts, resources)
}
}, },
} }
} }

View File

@ -7,6 +7,7 @@ import { ProcessedContent, QuartzPluginData, defaultProcessedContent } from "../
import { FullPageLayout } from "../../cfg" import { FullPageLayout } from "../../cfg"
import path from "path" import path from "path"
import { import {
FilePath,
FullSlug, FullSlug,
SimpleSlug, SimpleSlug,
stripSlashes, stripSlashes,
@ -17,89 +18,13 @@ import {
import { defaultListPageLayout, sharedPageComponents } from "../../../quartz.layout" import { defaultListPageLayout, sharedPageComponents } from "../../../quartz.layout"
import { FolderContent } from "../../components" import { FolderContent } from "../../components"
import { write } from "./helpers" import { write } from "./helpers"
import { i18n, TRANSLATIONS } from "../../i18n" import { i18n } from "../../i18n"
import { BuildCtx } from "../../util/ctx" import DepGraph from "../../depgraph"
import { StaticResources } from "../../util/resources"
interface FolderPageOptions extends FullPageLayout { interface FolderPageOptions extends FullPageLayout {
sort?: (f1: QuartzPluginData, f2: QuartzPluginData) => number sort?: (f1: QuartzPluginData, f2: QuartzPluginData) => number
} }
async function* processFolderInfo(
ctx: BuildCtx,
folderInfo: Record<SimpleSlug, ProcessedContent>,
allFiles: QuartzPluginData[],
opts: FullPageLayout,
resources: StaticResources,
) {
for (const [folder, folderContent] of Object.entries(folderInfo) as [
SimpleSlug,
ProcessedContent,
][]) {
const slug = joinSegments(folder, "index") as FullSlug
const [tree, file] = folderContent
const cfg = ctx.cfg.configuration
const externalResources = pageResources(pathToRoot(slug), resources)
const componentData: QuartzComponentProps = {
ctx,
fileData: file.data,
externalResources,
cfg,
children: [],
tree,
allFiles,
}
const content = renderPage(cfg, slug, componentData, opts, externalResources)
yield write({
ctx,
content,
slug,
ext: ".html",
})
}
}
function computeFolderInfo(
folders: Set<SimpleSlug>,
content: ProcessedContent[],
locale: keyof typeof TRANSLATIONS,
): Record<SimpleSlug, ProcessedContent> {
// Create default folder descriptions
const folderInfo: Record<SimpleSlug, ProcessedContent> = Object.fromEntries(
[...folders].map((folder) => [
folder,
defaultProcessedContent({
slug: joinSegments(folder, "index") as FullSlug,
frontmatter: {
title: `${i18n(locale).pages.folderContent.folder}: ${folder}`,
tags: [],
},
}),
]),
)
// Update with actual content if available
for (const [tree, file] of content) {
const slug = stripSlashes(simplifySlug(file.data.slug!)) as SimpleSlug
if (folders.has(slug)) {
folderInfo[slug] = [tree, file]
}
}
return folderInfo
}
function _getFolders(slug: FullSlug): SimpleSlug[] {
var folderName = path.dirname(slug ?? "") as SimpleSlug
const parentFolderNames = [folderName]
while (folderName !== ".") {
folderName = path.dirname(folderName ?? "") as SimpleSlug
parentFolderNames.push(folderName)
}
return parentFolderNames
}
export const FolderPage: QuartzEmitterPlugin<Partial<FolderPageOptions>> = (userOpts) => { export const FolderPage: QuartzEmitterPlugin<Partial<FolderPageOptions>> = (userOpts) => {
const opts: FullPageLayout = { const opts: FullPageLayout = {
...sharedPageComponents, ...sharedPageComponents,
@ -128,7 +53,24 @@ export const FolderPage: QuartzEmitterPlugin<Partial<FolderPageOptions>> = (user
Footer, Footer,
] ]
}, },
async *emit(ctx, content, resources) { async getDependencyGraph(_ctx, content, _resources) {
// Example graph:
// nested/file.md --> nested/index.html
// nested/file2.md ------^
const graph = new DepGraph<FilePath>()
content.map(([_tree, vfile]) => {
const slug = vfile.data.slug
const folderName = path.dirname(slug ?? "") as SimpleSlug
if (slug && folderName !== "." && folderName !== "tags") {
graph.addEdge(vfile.data.filePath!, joinSegments(folderName, "index.html") as FilePath)
}
})
return graph
},
async emit(ctx, content, resources): Promise<FilePath[]> {
const fps: FilePath[] = []
const allFiles = content.map((c) => c[1].data) const allFiles = content.map((c) => c[1].data)
const cfg = ctx.cfg.configuration const cfg = ctx.cfg.configuration
@ -142,29 +84,62 @@ export const FolderPage: QuartzEmitterPlugin<Partial<FolderPageOptions>> = (user
}), }),
) )
const folderInfo = computeFolderInfo(folders, content, cfg.locale) const folderDescriptions: Record<string, ProcessedContent> = Object.fromEntries(
yield* processFolderInfo(ctx, folderInfo, allFiles, opts, resources) [...folders].map((folder) => [
}, folder,
async *partialEmit(ctx, content, resources, changeEvents) { defaultProcessedContent({
const allFiles = content.map((c) => c[1].data) slug: joinSegments(folder, "index") as FullSlug,
const cfg = ctx.cfg.configuration frontmatter: {
title: `${i18n(cfg.locale).pages.folderContent.folder}: ${folder}`,
tags: [],
},
}),
]),
)
// Find all folders that need to be updated based on changed files for (const [tree, file] of content) {
const affectedFolders: Set<SimpleSlug> = new Set() const slug = stripSlashes(simplifySlug(file.data.slug!)) as SimpleSlug
for (const changeEvent of changeEvents) { if (folders.has(slug)) {
if (!changeEvent.file) continue folderDescriptions[slug] = [tree, file]
const slug = changeEvent.file.data.slug! }
const folders = _getFolders(slug).filter(
(folderName) => folderName !== "." && folderName !== "tags",
)
folders.forEach((folder) => affectedFolders.add(folder))
} }
// If there are affected folders, rebuild their pages for (const folder of folders) {
if (affectedFolders.size > 0) { const slug = joinSegments(folder, "index") as FullSlug
const folderInfo = computeFolderInfo(affectedFolders, content, cfg.locale) const [tree, file] = folderDescriptions[folder]
yield* processFolderInfo(ctx, folderInfo, allFiles, opts, resources) const externalResources = pageResources(pathToRoot(slug), file.data, resources)
const componentData: QuartzComponentProps = {
ctx,
fileData: file.data,
externalResources,
cfg,
children: [],
tree,
allFiles,
}
const content = renderPage(cfg, slug, componentData, opts, externalResources)
const fp = await write({
ctx,
content,
slug,
ext: ".html",
})
fps.push(fp)
} }
return fps
}, },
} }
} }
function _getFolders(slug: FullSlug): SimpleSlug[] {
var folderName = path.dirname(slug ?? "") as SimpleSlug
const parentFolderNames = [folderName]
while (folderName !== ".") {
folderName = path.dirname(folderName ?? "") as SimpleSlug
parentFolderNames.push(folderName)
}
return parentFolderNames
}

View File

@ -2,13 +2,12 @@ import path from "path"
import fs from "fs" import fs from "fs"
import { BuildCtx } from "../../util/ctx" import { BuildCtx } from "../../util/ctx"
import { FilePath, FullSlug, joinSegments } from "../../util/path" import { FilePath, FullSlug, joinSegments } from "../../util/path"
import { Readable } from "stream"
type WriteOptions = { type WriteOptions = {
ctx: BuildCtx ctx: BuildCtx
slug: FullSlug slug: FullSlug
ext: `.${string}` | "" ext: `.${string}` | ""
content: string | Buffer | Readable content: string | Buffer
} }
export const write = async ({ ctx, slug, ext, content }: WriteOptions): Promise<FilePath> => { export const write = async ({ ctx, slug, ext, content }: WriteOptions): Promise<FilePath> => {

View File

@ -1,11 +1,10 @@
export { ContentPage } from "./contentPage" export { ContentPage } from "./contentPage"
export { TagPage } from "./tagPage" export { TagPage } from "./tagPage"
export { FolderPage } from "./folderPage" export { FolderPage } from "./folderPage"
export { ContentIndex as ContentIndex } from "./contentIndex" export { ContentIndex } from "./contentIndex"
export { AliasRedirects } from "./aliases" export { AliasRedirects } from "./aliases"
export { Assets } from "./assets" export { Assets } from "./assets"
export { Static } from "./static" export { Static } from "./static"
export { ComponentResources } from "./componentResources" export { ComponentResources } from "./componentResources"
export { NotFoundPage } from "./404" export { NotFoundPage } from "./404"
export { CNAME } from "./cname" export { CNAME } from "./cname"
export { CustomOgImages } from "./ogImage"

View File

@ -1,175 +0,0 @@
import { QuartzEmitterPlugin } from "../types"
import { i18n } from "../../i18n"
import { unescapeHTML } from "../../util/escape"
import { FullSlug, getFileExtension, joinSegments, QUARTZ } from "../../util/path"
import { ImageOptions, SocialImageOptions, defaultImage, getSatoriFonts } from "../../util/og"
import sharp from "sharp"
import satori, { SatoriOptions } from "satori"
import { loadEmoji, getIconCode } from "../../util/emoji"
import { Readable } from "stream"
import { write } from "./helpers"
import { BuildCtx } from "../../util/ctx"
import { QuartzPluginData } from "../vfile"
import fs from "node:fs/promises"
import chalk from "chalk"
const defaultOptions: SocialImageOptions = {
colorScheme: "lightMode",
width: 1200,
height: 630,
imageStructure: defaultImage,
excludeRoot: false,
}
/**
* Generates social image (OG/twitter standard) and saves it as `.webp` inside the public folder
* @param opts options for generating image
*/
async function generateSocialImage(
{ cfg, description, fonts, title, fileData }: ImageOptions,
userOpts: SocialImageOptions,
): Promise<Readable> {
const { width, height } = userOpts
const iconPath = joinSegments(QUARTZ, "static", "icon.png")
let iconBase64: string | undefined = undefined
try {
const iconData = await fs.readFile(iconPath)
iconBase64 = `data:image/png;base64,${iconData.toString("base64")}`
} catch (err) {
console.warn(chalk.yellow(`Warning: Could not find icon at ${iconPath}`))
}
const imageComponent = userOpts.imageStructure({
cfg,
userOpts,
title,
description,
fonts,
fileData,
iconBase64,
})
const svg = await satori(imageComponent, {
width,
height,
fonts,
loadAdditionalAsset: async (languageCode: string, segment: string) => {
if (languageCode === "emoji") {
return `data:image/svg+xml;base64,${btoa(await loadEmoji(getIconCode(segment)))}`
}
return languageCode
},
})
return sharp(Buffer.from(svg)).webp({ quality: 40 })
}
async function processOgImage(
ctx: BuildCtx,
fileData: QuartzPluginData,
fonts: SatoriOptions["fonts"],
fullOptions: SocialImageOptions,
) {
const cfg = ctx.cfg.configuration
const slug = fileData.slug!
const titleSuffix = cfg.pageTitleSuffix ?? ""
const title =
(fileData.frontmatter?.title ?? i18n(cfg.locale).propertyDefaults.title) + titleSuffix
const description =
fileData.frontmatter?.socialDescription ??
fileData.frontmatter?.description ??
unescapeHTML(fileData.description?.trim() ?? i18n(cfg.locale).propertyDefaults.description)
const stream = await generateSocialImage(
{
title,
description,
fonts,
cfg,
fileData,
},
fullOptions,
)
return write({
ctx,
content: stream,
slug: `${slug}-og-image` as FullSlug,
ext: ".webp",
})
}
export const CustomOgImagesEmitterName = "CustomOgImages"
export const CustomOgImages: QuartzEmitterPlugin<Partial<SocialImageOptions>> = (userOpts) => {
const fullOptions = { ...defaultOptions, ...userOpts }
return {
name: CustomOgImagesEmitterName,
getQuartzComponents() {
return []
},
async *emit(ctx, content, _resources) {
const cfg = ctx.cfg.configuration
const headerFont = cfg.theme.typography.header
const bodyFont = cfg.theme.typography.body
const fonts = await getSatoriFonts(headerFont, bodyFont)
for (const [_tree, vfile] of content) {
if (vfile.data.frontmatter?.socialImage !== undefined) continue
yield processOgImage(ctx, vfile.data, fonts, fullOptions)
}
},
async *partialEmit(ctx, _content, _resources, changeEvents) {
const cfg = ctx.cfg.configuration
const headerFont = cfg.theme.typography.header
const bodyFont = cfg.theme.typography.body
const fonts = await getSatoriFonts(headerFont, bodyFont)
// find all slugs that changed or were added
for (const changeEvent of changeEvents) {
if (!changeEvent.file) continue
if (changeEvent.file.data.frontmatter?.socialImage !== undefined) continue
if (changeEvent.type === "add" || changeEvent.type === "change") {
yield processOgImage(ctx, changeEvent.file.data, fonts, fullOptions)
}
}
},
externalResources: (ctx) => {
if (!ctx.cfg.configuration.baseUrl) {
return {}
}
const baseUrl = ctx.cfg.configuration.baseUrl
return {
additionalHead: [
(pageData) => {
const isRealFile = pageData.filePath !== undefined
const userDefinedOgImagePath = pageData.frontmatter?.socialImage
const generatedOgImagePath = isRealFile
? `https://${baseUrl}/${pageData.slug!}-og-image.webp`
: undefined
const defaultOgImagePath = `https://${baseUrl}/static/og-image.png`
const ogImagePath = userDefinedOgImagePath ?? generatedOgImagePath ?? defaultOgImagePath
const ogImageMimeType = `image/${getFileExtension(ogImagePath) ?? "png"}`
return (
<>
{!userDefinedOgImagePath && (
<>
<meta property="og:image:width" content={fullOptions.width.toString()} />
<meta property="og:image:height" content={fullOptions.height.toString()} />
</>
)}
<meta property="og:image" content={ogImagePath} />
<meta property="og:image:url" content={ogImagePath} />
<meta name="twitter:image" content={ogImagePath} />
<meta property="og:image:type" content={ogImageMimeType} />
</>
)
},
],
}
},
}
}

View File

@ -2,22 +2,34 @@ import { FilePath, QUARTZ, joinSegments } from "../../util/path"
import { QuartzEmitterPlugin } from "../types" import { QuartzEmitterPlugin } from "../types"
import fs from "fs" import fs from "fs"
import { glob } from "../../util/glob" import { glob } from "../../util/glob"
import { dirname } from "path" import DepGraph from "../../depgraph"
export const Static: QuartzEmitterPlugin = () => ({ export const Static: QuartzEmitterPlugin = () => ({
name: "Static", name: "Static",
async *emit({ argv, cfg }) { getQuartzComponents() {
return []
},
async getDependencyGraph({ argv, cfg }, _content, _resources) {
const graph = new DepGraph<FilePath>()
const staticPath = joinSegments(QUARTZ, "static") const staticPath = joinSegments(QUARTZ, "static")
const fps = await glob("**", staticPath, cfg.configuration.ignorePatterns) const fps = await glob("**", staticPath, cfg.configuration.ignorePatterns)
const outputStaticPath = joinSegments(argv.output, "static")
await fs.promises.mkdir(outputStaticPath, { recursive: true })
for (const fp of fps) { for (const fp of fps) {
const src = joinSegments(staticPath, fp) as FilePath graph.addEdge(
const dest = joinSegments(outputStaticPath, fp) as FilePath joinSegments("static", fp) as FilePath,
await fs.promises.mkdir(dirname(dest), { recursive: true }) joinSegments(argv.output, "static", fp) as FilePath,
await fs.promises.copyFile(src, dest) )
yield dest
} }
return graph
},
async emit({ argv, cfg }, _content, _resources): Promise<FilePath[]> {
const staticPath = joinSegments(QUARTZ, "static")
const fps = await glob("**", staticPath, cfg.configuration.ignorePatterns)
await fs.promises.cp(staticPath, joinSegments(argv.output, "static"), {
recursive: true,
dereference: true,
})
return fps.map((fp) => joinSegments(argv.output, "static", fp)) as FilePath[]
}, },
async *partialEmit() {},
}) })

View File

@ -5,94 +5,23 @@ import BodyConstructor from "../../components/Body"
import { pageResources, renderPage } from "../../components/renderPage" import { pageResources, renderPage } from "../../components/renderPage"
import { ProcessedContent, QuartzPluginData, defaultProcessedContent } from "../vfile" import { ProcessedContent, QuartzPluginData, defaultProcessedContent } from "../vfile"
import { FullPageLayout } from "../../cfg" import { FullPageLayout } from "../../cfg"
import { FullSlug, getAllSegmentPrefixes, joinSegments, pathToRoot } from "../../util/path" import {
FilePath,
FullSlug,
getAllSegmentPrefixes,
joinSegments,
pathToRoot,
} from "../../util/path"
import { defaultListPageLayout, sharedPageComponents } from "../../../quartz.layout" import { defaultListPageLayout, sharedPageComponents } from "../../../quartz.layout"
import { TagContent } from "../../components" import { TagContent } from "../../components"
import { write } from "./helpers" import { write } from "./helpers"
import { i18n, TRANSLATIONS } from "../../i18n" import { i18n } from "../../i18n"
import { BuildCtx } from "../../util/ctx" import DepGraph from "../../depgraph"
import { StaticResources } from "../../util/resources"
interface TagPageOptions extends FullPageLayout { interface TagPageOptions extends FullPageLayout {
sort?: (f1: QuartzPluginData, f2: QuartzPluginData) => number sort?: (f1: QuartzPluginData, f2: QuartzPluginData) => number
} }
function computeTagInfo(
allFiles: QuartzPluginData[],
content: ProcessedContent[],
locale: keyof typeof TRANSLATIONS,
): [Set<string>, Record<string, ProcessedContent>] {
const tags: Set<string> = new Set(
allFiles.flatMap((data) => data.frontmatter?.tags ?? []).flatMap(getAllSegmentPrefixes),
)
// add base tag
tags.add("index")
const tagDescriptions: Record<string, ProcessedContent> = Object.fromEntries(
[...tags].map((tag) => {
const title =
tag === "index"
? i18n(locale).pages.tagContent.tagIndex
: `${i18n(locale).pages.tagContent.tag}: ${tag}`
return [
tag,
defaultProcessedContent({
slug: joinSegments("tags", tag) as FullSlug,
frontmatter: { title, tags: [] },
}),
]
}),
)
// Update with actual content if available
for (const [tree, file] of content) {
const slug = file.data.slug!
if (slug.startsWith("tags/")) {
const tag = slug.slice("tags/".length)
if (tags.has(tag)) {
tagDescriptions[tag] = [tree, file]
if (file.data.frontmatter?.title === tag) {
file.data.frontmatter.title = `${i18n(locale).pages.tagContent.tag}: ${tag}`
}
}
}
}
return [tags, tagDescriptions]
}
async function processTagPage(
ctx: BuildCtx,
tag: string,
tagContent: ProcessedContent,
allFiles: QuartzPluginData[],
opts: FullPageLayout,
resources: StaticResources,
) {
const slug = joinSegments("tags", tag) as FullSlug
const [tree, file] = tagContent
const cfg = ctx.cfg.configuration
const externalResources = pageResources(pathToRoot(slug), resources)
const componentData: QuartzComponentProps = {
ctx,
fileData: file.data,
externalResources,
cfg,
children: [],
tree,
allFiles,
}
const content = renderPage(cfg, slug, componentData, opts, externalResources)
return write({
ctx,
content,
slug: file.data.slug!,
ext: ".html",
})
}
export const TagPage: QuartzEmitterPlugin<Partial<TagPageOptions>> = (userOpts) => { export const TagPage: QuartzEmitterPlugin<Partial<TagPageOptions>> = (userOpts) => {
const opts: FullPageLayout = { const opts: FullPageLayout = {
...sharedPageComponents, ...sharedPageComponents,
@ -121,50 +50,93 @@ export const TagPage: QuartzEmitterPlugin<Partial<TagPageOptions>> = (userOpts)
Footer, Footer,
] ]
}, },
async *emit(ctx, content, resources) { async getDependencyGraph(ctx, content, _resources) {
const allFiles = content.map((c) => c[1].data) const graph = new DepGraph<FilePath>()
const cfg = ctx.cfg.configuration
const [tags, tagDescriptions] = computeTagInfo(allFiles, content, cfg.locale)
for (const tag of tags) { for (const [_tree, file] of content) {
yield processTagPage(ctx, tag, tagDescriptions[tag], allFiles, opts, resources) const sourcePath = file.data.filePath!
} const tags = (file.data.frontmatter?.tags ?? []).flatMap(getAllSegmentPrefixes)
}, // if the file has at least one tag, it is used in the tag index page
async *partialEmit(ctx, content, resources, changeEvents) { if (tags.length > 0) {
const allFiles = content.map((c) => c[1].data) tags.push("index")
const cfg = ctx.cfg.configuration
// Find all tags that need to be updated based on changed files
const affectedTags: Set<string> = new Set()
for (const changeEvent of changeEvents) {
if (!changeEvent.file) continue
const slug = changeEvent.file.data.slug!
// If it's a tag page itself that changed
if (slug.startsWith("tags/")) {
const tag = slug.slice("tags/".length)
affectedTags.add(tag)
} }
// If a file with tags changed, we need to update those tag pages for (const tag of tags) {
const fileTags = changeEvent.file.data.frontmatter?.tags ?? [] graph.addEdge(
fileTags.flatMap(getAllSegmentPrefixes).forEach((tag) => affectedTags.add(tag)) sourcePath,
joinSegments(ctx.argv.output, "tags", tag + ".html") as FilePath,
// Always update the index tag page if any file changes )
affectedTags.add("index") }
} }
// If there are affected tags, rebuild their pages return graph
if (affectedTags.size > 0) { },
// We still need to compute all tags because tag pages show all tags async emit(ctx, content, resources): Promise<FilePath[]> {
const [_tags, tagDescriptions] = computeTagInfo(allFiles, content, cfg.locale) const fps: FilePath[] = []
const allFiles = content.map((c) => c[1].data)
const cfg = ctx.cfg.configuration
for (const tag of affectedTags) { const tags: Set<string> = new Set(
if (tagDescriptions[tag]) { allFiles.flatMap((data) => data.frontmatter?.tags ?? []).flatMap(getAllSegmentPrefixes),
yield processTagPage(ctx, tag, tagDescriptions[tag], allFiles, opts, resources) )
// add base tag
tags.add("index")
const tagDescriptions: Record<string, ProcessedContent> = Object.fromEntries(
[...tags].map((tag) => {
const title =
tag === "index"
? i18n(cfg.locale).pages.tagContent.tagIndex
: `${i18n(cfg.locale).pages.tagContent.tag}: ${tag}`
return [
tag,
defaultProcessedContent({
slug: joinSegments("tags", tag) as FullSlug,
frontmatter: { title, tags: [] },
}),
]
}),
)
for (const [tree, file] of content) {
const slug = file.data.slug!
if (slug.startsWith("tags/")) {
const tag = slug.slice("tags/".length)
if (tags.has(tag)) {
tagDescriptions[tag] = [tree, file]
if (file.data.frontmatter?.title === tag) {
file.data.frontmatter.title = `${i18n(cfg.locale).pages.tagContent.tag}: ${tag}`
}
} }
} }
} }
for (const tag of tags) {
const slug = joinSegments("tags", tag) as FullSlug
const [tree, file] = tagDescriptions[tag]
const externalResources = pageResources(pathToRoot(slug), file.data, resources)
const componentData: QuartzComponentProps = {
ctx,
fileData: file.data,
externalResources,
cfg,
children: [],
tree,
allFiles,
}
const content = renderPage(cfg, slug, componentData, opts, externalResources)
const fp = await write({
ctx,
content,
slug: file.data.slug!,
ext: ".html",
})
fps.push(fp)
}
return fps
}, },
} }
} }

View File

@ -6,10 +6,9 @@ export function getStaticResourcesFromPlugins(ctx: BuildCtx) {
const staticResources: StaticResources = { const staticResources: StaticResources = {
css: [], css: [],
js: [], js: [],
additionalHead: [],
} }
for (const transformer of [...ctx.cfg.plugins.transformers, ...ctx.cfg.plugins.emitters]) { for (const transformer of ctx.cfg.plugins.transformers) {
const res = transformer.externalResources ? transformer.externalResources(ctx) : {} const res = transformer.externalResources ? transformer.externalResources(ctx) : {}
if (res?.js) { if (res?.js) {
staticResources.js.push(...res.js) staticResources.js.push(...res.js)
@ -17,9 +16,6 @@ export function getStaticResourcesFromPlugins(ctx: BuildCtx) {
if (res?.css) { if (res?.css) {
staticResources.css.push(...res.css) staticResources.css.push(...res.css)
} }
if (res?.additionalHead) {
staticResources.additionalHead.push(...res.additionalHead)
}
} }
// if serving locally, listen for rebuilds and reload the page // if serving locally, listen for rebuilds and reload the page

View File

@ -5,13 +5,11 @@ import { escapeHTML } from "../../util/escape"
export interface Options { export interface Options {
descriptionLength: number descriptionLength: number
maxDescriptionLength: number
replaceExternalLinks: boolean replaceExternalLinks: boolean
} }
const defaultOptions: Options = { const defaultOptions: Options = {
descriptionLength: 150, descriptionLength: 150,
maxDescriptionLength: 300,
replaceExternalLinks: true, replaceExternalLinks: true,
} }
@ -39,41 +37,35 @@ export const Description: QuartzTransformerPlugin<Partial<Options>> = (userOpts)
text = text.replace(urlRegex, "$<domain>" + "$<path>") text = text.replace(urlRegex, "$<domain>" + "$<path>")
} }
if (frontMatterDescription) { const desc = frontMatterDescription ?? text
file.data.description = frontMatterDescription
file.data.text = text
return
}
// otherwise, use the text content
const desc = text
const sentences = desc.replace(/\s+/g, " ").split(/\.\s/) const sentences = desc.replace(/\s+/g, " ").split(/\.\s/)
let finalDesc = "" const finalDesc: string[] = []
const len = opts.descriptionLength
let sentenceIdx = 0 let sentenceIdx = 0
let currentDescriptionLength = 0
// Add full sentences until we exceed the guideline length if (sentences[0] !== undefined && sentences[0].length >= len) {
while (sentenceIdx < sentences.length) { const firstSentence = sentences[0].split(" ")
const sentence = sentences[sentenceIdx] while (currentDescriptionLength < len) {
if (!sentence) break const sentence = firstSentence[sentenceIdx]
if (!sentence) break
const currentSentence = sentence.endsWith(".") ? sentence : sentence + "." finalDesc.push(sentence)
const nextLength = finalDesc.length + currentSentence.length + (finalDesc ? 1 : 0) currentDescriptionLength += sentence.length
sentenceIdx++
// Add the sentence if we're under the guideline length }
// or if this is the first sentence (always include at least one) finalDesc.push("...")
if (nextLength <= opts.descriptionLength || sentenceIdx === 0) { } else {
finalDesc += (finalDesc ? " " : "") + currentSentence while (currentDescriptionLength < len) {
const sentence = sentences[sentenceIdx]
if (!sentence) break
const currentSentence = sentence.endsWith(".") ? sentence : sentence + "."
finalDesc.push(currentSentence)
currentDescriptionLength += currentSentence.length
sentenceIdx++ sentenceIdx++
} else {
break
} }
} }
// truncate to max length if necessary file.data.description = finalDesc.join(" ")
file.data.description =
finalDesc.length > opts.maxDescriptionLength
? finalDesc.slice(0, opts.maxDescriptionLength) + "..."
: finalDesc
file.data.text = text file.data.text = text
} }
}, },

View File

@ -3,7 +3,7 @@ import remarkFrontmatter from "remark-frontmatter"
import { QuartzTransformerPlugin } from "../types" import { QuartzTransformerPlugin } from "../types"
import yaml from "js-yaml" import yaml from "js-yaml"
import toml from "toml" import toml from "toml"
import { FilePath, FullSlug, getFileExtension, slugifyFilePath, slugTag } from "../../util/path" import { slugTag } from "../../util/path"
import { QuartzPluginData } from "../vfile" import { QuartzPluginData } from "../vfile"
import { i18n } from "../../i18n" import { i18n } from "../../i18n"
@ -40,30 +40,16 @@ function coerceToArray(input: string | string[]): string[] | undefined {
.map((tag: string | number) => tag.toString()) .map((tag: string | number) => tag.toString())
} }
function getAliasSlugs(aliases: string[]): FullSlug[] {
const res: FullSlug[] = []
for (const alias of aliases) {
const isMd = getFileExtension(alias) === "md"
const mockFp = isMd ? alias : alias + ".md"
const slug = slugifyFilePath(mockFp as FilePath)
res.push(slug)
}
return res
}
export const FrontMatter: QuartzTransformerPlugin<Partial<Options>> = (userOpts) => { export const FrontMatter: QuartzTransformerPlugin<Partial<Options>> = (userOpts) => {
const opts = { ...defaultOptions, ...userOpts } const opts = { ...defaultOptions, ...userOpts }
return { return {
name: "FrontMatter", name: "FrontMatter",
markdownPlugins(ctx) { markdownPlugins({ cfg }) {
const { cfg, allSlugs } = ctx
return [ return [
[remarkFrontmatter, ["yaml", "toml"]], [remarkFrontmatter, ["yaml", "toml"]],
() => { () => {
return (_, file) => { return (_, file) => {
const fileData = Buffer.from(file.value as Uint8Array) const { data } = matter(Buffer.from(file.value), {
const { data } = matter(fileData, {
...opts, ...opts,
engines: { engines: {
yaml: (s) => yaml.load(s, { schema: yaml.JSON_SCHEMA }) as object, yaml: (s) => yaml.load(s, { schema: yaml.JSON_SCHEMA }) as object,
@ -81,20 +67,7 @@ export const FrontMatter: QuartzTransformerPlugin<Partial<Options>> = (userOpts)
if (tags) data.tags = [...new Set(tags.map((tag: string) => slugTag(tag)))] if (tags) data.tags = [...new Set(tags.map((tag: string) => slugTag(tag)))]
const aliases = coerceToArray(coalesceAliases(data, ["aliases", "alias"])) const aliases = coerceToArray(coalesceAliases(data, ["aliases", "alias"]))
if (aliases) { if (aliases) data.aliases = aliases
data.aliases = aliases // frontmatter
file.data.aliases = getAliasSlugs(aliases)
allSlugs.push(...file.data.aliases)
}
if (data.permalink != null && data.permalink.toString() !== "") {
data.permalink = data.permalink.toString() as FullSlug
const aliases = file.data.aliases ?? []
aliases.push(data.permalink)
file.data.aliases = aliases
allSlugs.push(data.permalink)
}
const cssclasses = coerceToArray(coalesceAliases(data, ["cssclasses", "cssclass"])) const cssclasses = coerceToArray(coalesceAliases(data, ["cssclasses", "cssclass"]))
if (cssclasses) data.cssclasses = cssclasses if (cssclasses) data.cssclasses = cssclasses
@ -125,7 +98,6 @@ export const FrontMatter: QuartzTransformerPlugin<Partial<Options>> = (userOpts)
declare module "vfile" { declare module "vfile" {
interface DataMap { interface DataMap {
aliases: FullSlug[]
frontmatter: { [key: string]: unknown } & { frontmatter: { [key: string]: unknown } & {
title: string title: string
} & Partial<{ } & Partial<{
@ -135,7 +107,6 @@ declare module "vfile" {
created: string created: string
published: string published: string
description: string description: string
socialDescription: string
publish: boolean | string publish: boolean | string
draft: boolean | string draft: boolean | string
lang: string lang: string

View File

@ -1,8 +1,8 @@
import fs from "fs" import fs from "fs"
import path from "path"
import { Repository } from "@napi-rs/simple-git" import { Repository } from "@napi-rs/simple-git"
import { QuartzTransformerPlugin } from "../types" import { QuartzTransformerPlugin } from "../types"
import chalk from "chalk" import chalk from "chalk"
import path from "path"
export interface Options { export interface Options {
priority: ("frontmatter" | "git" | "filesystem")[] priority: ("frontmatter" | "git" | "filesystem")[]
@ -31,29 +31,17 @@ export const CreatedModifiedDate: QuartzTransformerPlugin<Partial<Options>> = (u
const opts = { ...defaultOptions, ...userOpts } const opts = { ...defaultOptions, ...userOpts }
return { return {
name: "CreatedModifiedDate", name: "CreatedModifiedDate",
markdownPlugins(ctx) { markdownPlugins() {
return [ return [
() => { () => {
let repo: Repository | undefined = undefined let repo: Repository | undefined = undefined
let repositoryWorkdir: string
if (opts.priority.includes("git")) {
try {
repo = Repository.discover(ctx.argv.directory)
repositoryWorkdir = repo.workdir() ?? ctx.argv.directory
} catch (e) {
console.log(
chalk.yellow(`\nWarning: couldn't find git repository for ${ctx.argv.directory}`),
)
}
}
return async (_tree, file) => { return async (_tree, file) => {
let created: MaybeDate = undefined let created: MaybeDate = undefined
let modified: MaybeDate = undefined let modified: MaybeDate = undefined
let published: MaybeDate = undefined let published: MaybeDate = undefined
const fp = file.data.relativePath! const fp = file.data.filePath!
const fullFp = file.data.filePath! const fullFp = path.isAbsolute(fp) ? fp : path.posix.join(file.cwd, fp)
for (const source of opts.priority) { for (const source of opts.priority) {
if (source === "filesystem") { if (source === "filesystem") {
const st = await fs.promises.stat(fullFp) const st = await fs.promises.stat(fullFp)
@ -63,14 +51,21 @@ export const CreatedModifiedDate: QuartzTransformerPlugin<Partial<Options>> = (u
created ||= file.data.frontmatter.created as MaybeDate created ||= file.data.frontmatter.created as MaybeDate
modified ||= file.data.frontmatter.modified as MaybeDate modified ||= file.data.frontmatter.modified as MaybeDate
published ||= file.data.frontmatter.published as MaybeDate published ||= file.data.frontmatter.published as MaybeDate
} else if (source === "git" && repo) { } else if (source === "git") {
if (!repo) {
// Get a reference to the main git repo.
// It's either the same as the workdir,
// or 1+ level higher in case of a submodule/subtree setup
repo = Repository.discover(file.cwd)
}
try { try {
const relativePath = path.relative(repositoryWorkdir, fullFp) modified ||= await repo.getFileLatestModifiedDateAsync(file.data.filePath!)
modified ||= await repo.getFileLatestModifiedDateAsync(relativePath)
} catch { } catch {
console.log( console.log(
chalk.yellow( chalk.yellow(
`\nWarning: ${file.data.filePath!} isn't yet tracked by git, dates will be inaccurate`, `\nWarning: ${file.data
.filePath!} isn't yet tracked by git, last modification date is not available for this file`,
), ),
) )
} }

View File

@ -59,6 +59,8 @@ export const Latex: QuartzTransformerPlugin<Partial<Options>> = (opts) => {
}, },
], ],
} }
default:
return { css: [], js: [] }
} }
}, },
} }

View File

@ -1,13 +1,5 @@
import { QuartzTransformerPlugin } from "../types" import { QuartzTransformerPlugin } from "../types"
import { import { Root, Html, BlockContent, DefinitionContent, Paragraph, Code } from "mdast"
Root,
Html,
BlockContent,
PhrasingContent,
DefinitionContent,
Paragraph,
Code,
} from "mdast"
import { Element, Literal, Root as HtmlRoot } from "hast" import { Element, Literal, Root as HtmlRoot } from "hast"
import { ReplaceFunction, findAndReplace as mdastFindReplace } from "mdast-util-find-and-replace" import { ReplaceFunction, findAndReplace as mdastFindReplace } from "mdast-util-find-and-replace"
import rehypeRaw from "rehype-raw" import rehypeRaw from "rehype-raw"
@ -16,15 +8,13 @@ import path from "path"
import { splitAnchor } from "../../util/path" import { splitAnchor } from "../../util/path"
import { JSResource, CSSResource } from "../../util/resources" import { JSResource, CSSResource } from "../../util/resources"
// @ts-ignore // @ts-ignore
import calloutScript from "../../components/scripts/callout.inline" import calloutScript from "../../components/scripts/callout.inline.ts"
// @ts-ignore // @ts-ignore
import checkboxScript from "../../components/scripts/checkbox.inline" import checkboxScript from "../../components/scripts/checkbox.inline.ts"
// @ts-ignore
import mermaidScript from "../../components/scripts/mermaid.inline"
import mermaidStyle from "../../components/styles/mermaid.inline.scss"
import { FilePath, pathToRoot, slugTag, slugifyFilePath } from "../../util/path" import { FilePath, pathToRoot, slugTag, slugifyFilePath } from "../../util/path"
import { toHast } from "mdast-util-to-hast" import { toHast } from "mdast-util-to-hast"
import { toHtml } from "hast-util-to-html" import { toHtml } from "hast-util-to-html"
import { PhrasingContent } from "mdast-util-find-and-replace/lib"
import { capitalize } from "../../util/lang" import { capitalize } from "../../util/lang"
import { PluggableList } from "unified" import { PluggableList } from "unified"
@ -159,12 +149,20 @@ export const ObsidianFlavoredMarkdown: QuartzTransformerPlugin<Partial<Options>>
textTransform(_ctx, src) { textTransform(_ctx, src) {
// do comments at text level // do comments at text level
if (opts.comments) { if (opts.comments) {
src = src.replace(commentRegex, "") if (src instanceof Buffer) {
src = src.toString()
}
src = (src as string).replace(commentRegex, "")
} }
// pre-transform blockquotes // pre-transform blockquotes
if (opts.callouts) { if (opts.callouts) {
src = src.replace(calloutLineRegex, (value) => { if (src instanceof Buffer) {
src = src.toString()
}
src = (src as string).replace(calloutLineRegex, (value) => {
// force newline after title of callout // force newline after title of callout
return value + "\n> " return value + "\n> "
}) })
@ -172,8 +170,12 @@ export const ObsidianFlavoredMarkdown: QuartzTransformerPlugin<Partial<Options>>
// pre-transform wikilinks (fix anchors to things that may contain illegal syntax e.g. codeblocks, latex) // pre-transform wikilinks (fix anchors to things that may contain illegal syntax e.g. codeblocks, latex)
if (opts.wikilinks) { if (opts.wikilinks) {
if (src instanceof Buffer) {
src = src.toString()
}
// replace all wikilinks inside a table first // replace all wikilinks inside a table first
src = src.replace(tableRegex, (value) => { src = (src as string).replace(tableRegex, (value) => {
// escape all aliases and headers in wikilinks inside a table // escape all aliases and headers in wikilinks inside a table
return value.replace(tableWikilinkRegex, (_value, raw) => { return value.replace(tableWikilinkRegex, (_value, raw) => {
// const [raw]: (string | undefined)[] = capture // const [raw]: (string | undefined)[] = capture
@ -187,7 +189,7 @@ export const ObsidianFlavoredMarkdown: QuartzTransformerPlugin<Partial<Options>>
}) })
// replace all other wikilinks // replace all other wikilinks
src = src.replace(wikilinkRegex, (value, ...capture) => { src = (src as string).replace(wikilinkRegex, (value, ...capture) => {
const [rawFp, rawHeader, rawAlias]: (string | undefined)[] = capture const [rawFp, rawHeader, rawAlias]: (string | undefined)[] = capture
const [fp, anchor] = splitAnchor(`${rawFp ?? ""}${rawHeader ?? ""}`) const [fp, anchor] = splitAnchor(`${rawFp ?? ""}${rawHeader ?? ""}`)
@ -675,6 +677,7 @@ export const ObsidianFlavoredMarkdown: QuartzTransformerPlugin<Partial<Options>>
properties: { properties: {
className: ["expand-button"], className: ["expand-button"],
"aria-label": "Expand mermaid diagram", "aria-label": "Expand mermaid diagram",
"aria-hidden": "true",
"data-view-component": true, "data-view-component": true,
}, },
children: [ children: [
@ -705,13 +708,70 @@ export const ObsidianFlavoredMarkdown: QuartzTransformerPlugin<Partial<Options>>
{ {
type: "element", type: "element",
tagName: "div", tagName: "div",
properties: { id: "mermaid-container", role: "dialog" }, properties: { id: "mermaid-container" },
children: [ children: [
{ {
type: "element", type: "element",
tagName: "div", tagName: "div",
properties: { id: "mermaid-space" }, properties: { id: "mermaid-space" },
children: [ children: [
{
type: "element",
tagName: "div",
properties: { className: ["mermaid-header"] },
children: [
{
type: "element",
tagName: "button",
properties: {
className: ["close-button"],
"aria-label": "close button",
},
children: [
{
type: "element",
tagName: "svg",
properties: {
"aria-hidden": "true",
xmlns: "http://www.w3.org/2000/svg",
width: 24,
height: 24,
viewBox: "0 0 24 24",
fill: "none",
stroke: "currentColor",
"stroke-width": "2",
"stroke-linecap": "round",
"stroke-linejoin": "round",
},
children: [
{
type: "element",
tagName: "line",
properties: {
x1: 18,
y1: 6,
x2: 6,
y2: 18,
},
children: [],
},
{
type: "element",
tagName: "line",
properties: {
x1: 6,
y1: 6,
x2: 18,
y2: 18,
},
children: [],
},
],
},
],
},
],
},
{ {
type: "element", type: "element",
tagName: "div", tagName: "div",
@ -751,20 +811,6 @@ export const ObsidianFlavoredMarkdown: QuartzTransformerPlugin<Partial<Options>>
}) })
} }
if (opts.mermaid) {
js.push({
script: mermaidScript,
loadTime: "afterDOMReady",
contentType: "inline",
moduleType: "module",
})
css.push({
content: mermaidStyle,
inline: true,
})
}
return { js, css } return { js, css }
}, },
} }

View File

@ -54,7 +54,7 @@ export const OxHugoFlavouredMarkdown: QuartzTransformerPlugin<Partial<Options>>
textTransform(_ctx, src) { textTransform(_ctx, src) {
if (opts.wikilinks) { if (opts.wikilinks) {
src = src.toString() src = src.toString()
src = src.replaceAll(relrefRegex, (_value, ...capture) => { src = src.replaceAll(relrefRegex, (value, ...capture) => {
const [text, link] = capture const [text, link] = capture
return `[${text}](${link})` return `[${text}](${link})`
}) })
@ -62,7 +62,7 @@ export const OxHugoFlavouredMarkdown: QuartzTransformerPlugin<Partial<Options>>
if (opts.removePredefinedAnchor) { if (opts.removePredefinedAnchor) {
src = src.toString() src = src.toString()
src = src.replaceAll(predefinedHeadingIdRegex, (_value, ...capture) => { src = src.replaceAll(predefinedHeadingIdRegex, (value, ...capture) => {
const [headingText] = capture const [headingText] = capture
return headingText return headingText
}) })
@ -70,7 +70,7 @@ export const OxHugoFlavouredMarkdown: QuartzTransformerPlugin<Partial<Options>>
if (opts.removeHugoShortcode) { if (opts.removeHugoShortcode) {
src = src.toString() src = src.toString()
src = src.replaceAll(hugoShortcodeRegex, (_value, ...capture) => { src = src.replaceAll(hugoShortcodeRegex, (value, ...capture) => {
const [scContent] = capture const [scContent] = capture
return scContent return scContent
}) })
@ -78,7 +78,7 @@ export const OxHugoFlavouredMarkdown: QuartzTransformerPlugin<Partial<Options>>
if (opts.replaceFigureWithMdImg) { if (opts.replaceFigureWithMdImg) {
src = src.toString() src = src.toString()
src = src.replaceAll(figureTagRegex, (_value, ...capture) => { src = src.replaceAll(figureTagRegex, (value, ...capture) => {
const [src] = capture const [src] = capture
return `![](${src})` return `![](${src})`
}) })
@ -86,11 +86,11 @@ export const OxHugoFlavouredMarkdown: QuartzTransformerPlugin<Partial<Options>>
if (opts.replaceOrgLatex) { if (opts.replaceOrgLatex) {
src = src.toString() src = src.toString()
src = src.replaceAll(inlineLatexRegex, (_value, ...capture) => { src = src.replaceAll(inlineLatexRegex, (value, ...capture) => {
const [eqn] = capture const [eqn] = capture
return `$${eqn}$` return `$${eqn}$`
}) })
src = src.replaceAll(blockLatexRegex, (_value, ...capture) => { src = src.replaceAll(blockLatexRegex, (value, ...capture) => {
const [eqn] = capture const [eqn] = capture
return `$$${eqn}$$` return `$$${eqn}$$`
}) })

View File

@ -1,8 +1,10 @@
import { QuartzTransformerPlugin } from "../types" import { QuartzTransformerPlugin } from "../types"
import { PluggableList } from "unified" import { PluggableList } from "unified"
import { visit } from "unist-util-visit" import { SKIP, visit } from "unist-util-visit"
import { ReplaceFunction, findAndReplace as mdastFindReplace } from "mdast-util-find-and-replace" import { ReplaceFunction, findAndReplace as mdastFindReplace } from "mdast-util-find-and-replace"
import { Root, Html, Paragraph, Text, Link, Parent } from "mdast" import { Root, Html, Paragraph, Text, Link, Parent } from "mdast"
import { Node } from "unist"
import { VFile } from "vfile"
import { BuildVisitor } from "unist-util-visit" import { BuildVisitor } from "unist-util-visit"
export interface Options { export interface Options {
@ -32,10 +34,21 @@ const defaultOptions: Options = {
const orRegex = new RegExp(/{{or:(.*?)}}/, "g") const orRegex = new RegExp(/{{or:(.*?)}}/, "g")
const TODORegex = new RegExp(/{{.*?\bTODO\b.*?}}/, "g") const TODORegex = new RegExp(/{{.*?\bTODO\b.*?}}/, "g")
const DONERegex = new RegExp(/{{.*?\bDONE\b.*?}}/, "g") const DONERegex = new RegExp(/{{.*?\bDONE\b.*?}}/, "g")
const videoRegex = new RegExp(/{{.*?\[\[video\]\].*?\:(.*?)}}/, "g")
const youtubeRegex = new RegExp(
/{{.*?\[\[video\]\].*?(https?:\/\/(?:www\.)?youtu(?:be\.com\/watch\?v=|\.be\/)([\w\-\_]*)(&(amp;)?[\w\?=]*)?)}}/,
"g",
)
// const multimediaRegex = new RegExp(/{{.*?\b(video|audio)\b.*?\:(.*?)}}/, "g")
const audioRegex = new RegExp(/{{.*?\[\[audio\]\].*?\:(.*?)}}/, "g")
const pdfRegex = new RegExp(/{{.*?\[\[pdf\]\].*?\:(.*?)}}/, "g")
const blockquoteRegex = new RegExp(/(\[\[>\]\])\s*(.*)/, "g") const blockquoteRegex = new RegExp(/(\[\[>\]\])\s*(.*)/, "g")
const roamHighlightRegex = new RegExp(/\^\^(.+)\^\^/, "g") const roamHighlightRegex = new RegExp(/\^\^(.+)\^\^/, "g")
const roamItalicRegex = new RegExp(/__(.+)__/, "g") const roamItalicRegex = new RegExp(/__(.+)__/, "g")
const tableRegex = new RegExp(/- {{.*?\btable\b.*?}}/, "g") /* TODO */
const attributeRegex = new RegExp(/\b\w+(?:\s+\w+)*::/, "g") /* TODO */
function isSpecialEmbed(node: Paragraph): boolean { function isSpecialEmbed(node: Paragraph): boolean {
if (node.children.length !== 2) return false if (node.children.length !== 2) return false
@ -122,7 +135,7 @@ export const RoamFlavoredMarkdown: QuartzTransformerPlugin<Partial<Options> | un
const plugins: PluggableList = [] const plugins: PluggableList = []
plugins.push(() => { plugins.push(() => {
return (tree: Root) => { return (tree: Root, file: VFile) => {
const replacements: [RegExp, ReplaceFunction][] = [] const replacements: [RegExp, ReplaceFunction][] = []
// Handle special embeds (audio, video, PDF) // Handle special embeds (audio, video, PDF)

Some files were not shown because too many files have changed in this diff Show More