mirror of
https://github.com/jackyzha0/quartz.git
synced 2025-12-13 08:09:01 +01:00
Compare commits
1 Commits
b00198b888
...
jackyzha0/
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ecf5eb6932 |
2
.github/workflows/ci.yaml
vendored
2
.github/workflows/ci.yaml
vendored
@@ -45,7 +45,7 @@ jobs:
|
||||
run: npm test
|
||||
|
||||
- name: Ensure Quartz builds, check bundle info
|
||||
run: npx quartz build --bundleInfo -d docs
|
||||
run: npx quartz build --bundleInfo
|
||||
|
||||
publish-tag:
|
||||
if: ${{ github.repository == 'jackyzha0/quartz' && github.ref == 'refs/heads/v4' }}
|
||||
|
||||
2
.github/workflows/docker-build-push.yaml
vendored
2
.github/workflows/docker-build-push.yaml
vendored
@@ -37,7 +37,7 @@ jobs:
|
||||
network=host
|
||||
- name: Install cosign
|
||||
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
|
||||
uses: docker/login-action@v3
|
||||
if: github.event_name != 'pull_request'
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
FROM node:22-slim AS builder
|
||||
FROM node:20-slim AS builder
|
||||
WORKDIR /usr/src/app
|
||||
COPY package.json .
|
||||
COPY package-lock.json* .
|
||||
RUN npm ci
|
||||
|
||||
FROM node:22-slim
|
||||
FROM node:20-slim
|
||||
WORKDIR /usr/src/app
|
||||
COPY --from=builder /usr/src/app/ /usr/src/app/
|
||||
COPY . .
|
||||
|
||||
@@ -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.
|
||||
This will get called on page navigation.
|
||||
|
||||
|
||||
@@ -37,7 +37,7 @@ Transformers **map** over content, taking a Markdown file and outputting modifie
|
||||
```ts
|
||||
export type QuartzTransformerPluginInstance = {
|
||||
name: string
|
||||
textTransform?: (ctx: BuildCtx, src: string) => string
|
||||
textTransform?: (ctx: BuildCtx, src: string | Buffer) => string | Buffer
|
||||
markdownPlugins?: (ctx: BuildCtx) => PluggableList
|
||||
htmlPlugins?: (ctx: BuildCtx) => PluggableList
|
||||
externalResources?: (ctx: BuildCtx) => Partial<StaticResources>
|
||||
@@ -99,6 +99,8 @@ export const Latex: QuartzTransformerPlugin<Options> = (opts?: Options) => {
|
||||
},
|
||||
],
|
||||
}
|
||||
} else {
|
||||
return {}
|
||||
}
|
||||
},
|
||||
}
|
||||
@@ -272,7 +274,7 @@ export const ContentPage: QuartzEmitterPlugin = () => {
|
||||
const allFiles = content.map((c) => c[1].data)
|
||||
for (const [tree, file] of content) {
|
||||
const slug = canonicalizeServer(file.data.slug!)
|
||||
const externalResources = pageResources(slug, file.data, resources)
|
||||
const externalResources = pageResources(slug, resources)
|
||||
const componentData: QuartzComponentProps = {
|
||||
fileData: file.data,
|
||||
externalResources,
|
||||
|
||||
@@ -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.
|
||||
- `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
|
||||
|
||||
When your Quartz is at a point you're happy with, you can save your changes to GitHub.
|
||||
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
|
||||
```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 .)
|
||||
```
|
||||
|
||||
@@ -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.
|
||||
|
||||
> [!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
|
||||
|
||||
This functionality is provided by the [[ContentIndex]] plugin. See the plugin page for customization options.
|
||||
|
||||
@@ -9,7 +9,6 @@ A backlink for a note is a link from another note to that note. Links in the bac
|
||||
## Customization
|
||||
|
||||
- Removing backlinks: delete all usages of `Component.Backlinks()` from `quartz.layout.ts`.
|
||||
- Hide when empty: hide `Backlinks` if given page doesn't contain any backlinks (default to `true`). To disable this, use `Component.Backlinks({ hideWhenEmpty: false })`.
|
||||
- Component: `quartz/components/Backlinks.tsx`
|
||||
- Style: `quartz/components/styles/backlinks.scss`
|
||||
- Script: `quartz/components/scripts/search.inline.ts`
|
||||
|
||||
@@ -36,7 +36,6 @@ Component.Graph({
|
||||
opacityScale: 1, // how quickly do we fade out the labels when zooming out?
|
||||
removeTags: [], // what tags to remove from the graph
|
||||
showTags: true, // whether to show tags in the graph
|
||||
enableRadial: false, // whether to constrain the graph, similar to Obsidian
|
||||
},
|
||||
globalGraph: {
|
||||
drag: true,
|
||||
@@ -50,7 +49,6 @@ Component.Graph({
|
||||
opacityScale: 1,
|
||||
removeTags: [], // what tags to remove from the graph
|
||||
showTags: true, // whether to show tags in the graph
|
||||
enableRadial: true, // whether to constrain the graph, similar to Obsidian
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
@@ -247,28 +247,6 @@ server {
|
||||
}
|
||||
```
|
||||
|
||||
### Using Apache
|
||||
|
||||
Here's an example of how to do this with Apache:
|
||||
|
||||
```apache title=".htaccess"
|
||||
RewriteEngine On
|
||||
|
||||
ErrorDocument 404 /404.html
|
||||
|
||||
# Rewrite rule for .html extension removal (with directory check)
|
||||
RewriteCond %{REQUEST_FILENAME} !-f
|
||||
RewriteCond %{REQUEST_FILENAME} !-d
|
||||
RewriteCond %{DOCUMENT_ROOT}/%{REQUEST_URI}.html -f
|
||||
RewriteRule ^(.*)$ $1.html [L]
|
||||
|
||||
# Handle directory requests explicitly
|
||||
RewriteCond %{REQUEST_FILENAME} -d
|
||||
RewriteRule ^(.*)/$ $1/index.html [L]
|
||||
```
|
||||
|
||||
Don't forget to activate brotli / gzip compression.
|
||||
|
||||
### Using Caddy
|
||||
|
||||
Here's and example of how to do this with Caddy:
|
||||
|
||||
@@ -31,13 +31,13 @@ If you prefer instructions in a video format you can try following Nicole van de
|
||||
|
||||
## 🔧 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 for both configuration and content
|
||||
- Simple JSX layouts and [[creating components|page components]]
|
||||
- [[SPA Routing|Ridiculously fast page loads]] and tiny bundle sizes
|
||||
- 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
|
||||
|
||||
|
||||
@@ -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).
|
||||
@@ -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.
|
||||
- `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.
|
||||
- `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.
|
||||
|
||||
## API
|
||||
|
||||
@@ -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"]`.
|
||||
|
||||
When loading the frontmatter, the value of [[Frontmatter#List]] is used.
|
||||
|
||||
> [!warning]
|
||||
> If you rely on `git` for dates, make sure `defaultDateType` is set to `modified` in `quartz.config.ts`.
|
||||
>
|
||||
|
||||
@@ -17,54 +17,6 @@ This plugin accepts the following configuration options:
|
||||
> [!warning]
|
||||
> 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
|
||||
|
||||
- Category: Transformer
|
||||
|
||||
@@ -31,4 +31,4 @@ This plugin accepts the following configuration options:
|
||||
|
||||
- Category: Transformer
|
||||
- Function name: `Plugin.ObsidianFlavoredMarkdown()`.
|
||||
- Source: [`quartz/plugins/transformers/ofm.ts`](https://github.com/jackyzha0/quartz/blob/v4/quartz/plugins/transformers/ofm.ts)
|
||||
- Source: [`quartz/plugins/transformers/toc.ts`](https://github.com/jackyzha0/quartz/blob/v4/quartz/plugins/transformers/toc.ts).
|
||||
|
||||
@@ -30,5 +30,5 @@ Want to see what Quartz can do? Here are some cool community gardens:
|
||||
- [🥷🏻🌳🍃 Computer Science & Thinkering Garden](https://notes.yxy.ninja)
|
||||
- [Eledah's Crystalline](https://blog.eledah.ir/)
|
||||
- [🌓 Projects & Privacy - FOSS, tech, law](https://be-far.com)
|
||||
- [Zen Browser Docs](https://docs.zen-browser.app)
|
||||
- [🪴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
2
index.d.ts
vendored
@@ -5,10 +5,8 @@ declare module "*.scss" {
|
||||
|
||||
// dom custom event
|
||||
interface CustomEventMap {
|
||||
prenav: CustomEvent<{}>
|
||||
nav: CustomEvent<{ url: FullSlug }>
|
||||
themechange: CustomEvent<{ theme: "light" | "dark" }>
|
||||
}
|
||||
|
||||
type ContentIndex = Record<FullSlug, ContentDetails>
|
||||
declare const fetchData: Promise<ContentIndex>
|
||||
|
||||
2404
package-lock.json
generated
2404
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
53
package.json
53
package.json
@@ -16,12 +16,12 @@
|
||||
"docs": "npx quartz build --serve -d docs",
|
||||
"check": "tsc --noEmit && npx prettier . --check",
|
||||
"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"
|
||||
},
|
||||
"engines": {
|
||||
"npm": ">=9.3.1",
|
||||
"node": ">=20"
|
||||
"node": "20 || >=22"
|
||||
},
|
||||
"keywords": [
|
||||
"site generator",
|
||||
@@ -35,58 +35,59 @@
|
||||
"quartz": "./quartz/bootstrap-cli.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"@clack/prompts": "^0.10.0",
|
||||
"@floating-ui/dom": "^1.6.13",
|
||||
"@myriaddreamin/rehype-typst": "^0.5.4",
|
||||
"@clack/prompts": "^0.7.0",
|
||||
"@floating-ui/dom": "^1.6.12",
|
||||
"@myriaddreamin/rehype-typst": "^0.5.0-rc7",
|
||||
"@napi-rs/simple-git": "0.1.19",
|
||||
"@tweenjs/tween.js": "^25.0.0",
|
||||
"async-mutex": "^0.5.0",
|
||||
"chalk": "^5.4.1",
|
||||
"chokidar": "^4.0.3",
|
||||
"chalk": "^5.3.0",
|
||||
"chokidar": "^4.0.1",
|
||||
"cli-spinner": "^0.2.10",
|
||||
"d3": "^7.9.0",
|
||||
"esbuild-sass-plugin": "^3.3.1",
|
||||
"flexsearch": "0.7.43",
|
||||
"github-slugger": "^2.0.0",
|
||||
"globby": "^14.1.0",
|
||||
"globby": "^14.0.2",
|
||||
"gray-matter": "^4.0.3",
|
||||
"hast-util-to-html": "^9.0.5",
|
||||
"hast-util-to-jsx-runtime": "^2.3.6",
|
||||
"hast-util-to-html": "^9.0.3",
|
||||
"hast-util-to-jsx-runtime": "^2.3.2",
|
||||
"hast-util-to-string": "^3.0.1",
|
||||
"is-absolute-url": "^4.0.1",
|
||||
"js-yaml": "^4.1.0",
|
||||
"lightningcss": "^1.29.2",
|
||||
"mdast-util-find-and-replace": "^3.0.2",
|
||||
"lightningcss": "^1.28.1",
|
||||
"mdast-util-find-and-replace": "^3.0.1",
|
||||
"mdast-util-to-hast": "^13.2.0",
|
||||
"mdast-util-to-string": "^4.0.0",
|
||||
"mermaid": "^11.4.0",
|
||||
"micromorph": "^0.4.5",
|
||||
"pixi.js": "^8.8.1",
|
||||
"preact": "^10.26.4",
|
||||
"preact-render-to-string": "^6.5.13",
|
||||
"pixi.js": "^8.5.2",
|
||||
"preact": "^10.24.3",
|
||||
"preact-render-to-string": "^6.5.11",
|
||||
"pretty-bytes": "^6.1.1",
|
||||
"pretty-time": "^1.1.0",
|
||||
"reading-time": "^1.5.0",
|
||||
"rehype-autolink-headings": "^7.1.0",
|
||||
"rehype-citation": "^2.2.2",
|
||||
"rehype-katex": "^7.0.1",
|
||||
"rehype-mathjax": "^7.1.0",
|
||||
"rehype-mathjax": "^6.0.0",
|
||||
"rehype-pretty-code": "^0.14.0",
|
||||
"rehype-raw": "^7.0.0",
|
||||
"rehype-slug": "^6.0.0",
|
||||
"remark": "^15.0.1",
|
||||
"remark-breaks": "^4.0.0",
|
||||
"remark-frontmatter": "^5.0.0",
|
||||
"remark-gfm": "^4.0.1",
|
||||
"remark-gfm": "^4.0.0",
|
||||
"remark-math": "^6.0.0",
|
||||
"remark-parse": "^11.0.0",
|
||||
"remark-rehype": "^11.1.1",
|
||||
"remark-smartypants": "^3.0.2",
|
||||
"rfdc": "^1.4.1",
|
||||
"rimraf": "^6.0.1",
|
||||
"satori": "^0.12.1",
|
||||
"satori": "^0.10.14",
|
||||
"serve-handler": "^6.1.6",
|
||||
"sharp": "^0.33.5",
|
||||
"shiki": "^1.26.2",
|
||||
"shiki": "^1.22.2",
|
||||
"source-map-support": "^0.5.21",
|
||||
"to-vfile": "^8.0.0",
|
||||
"toml": "^3.0.0",
|
||||
@@ -94,7 +95,7 @@
|
||||
"unist-util-visit": "^5.0.0",
|
||||
"vfile": "^6.0.3",
|
||||
"workerpool": "^9.2.0",
|
||||
"ws": "^8.18.1",
|
||||
"ws": "^8.18.0",
|
||||
"yargs": "^17.7.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -102,14 +103,14 @@
|
||||
"@types/d3": "^7.4.3",
|
||||
"@types/hast": "^3.0.4",
|
||||
"@types/js-yaml": "^4.0.9",
|
||||
"@types/node": "^22.13.10",
|
||||
"@types/node": "^22.9.0",
|
||||
"@types/pretty-time": "^1.1.5",
|
||||
"@types/source-map-support": "^0.5.10",
|
||||
"@types/ws": "^8.18.0",
|
||||
"@types/ws": "^8.5.13",
|
||||
"@types/yargs": "^17.0.33",
|
||||
"esbuild": "^0.25.1",
|
||||
"prettier": "^3.5.3",
|
||||
"tsx": "^4.19.3",
|
||||
"typescript": "^5.8.2"
|
||||
"esbuild": "^0.24.0",
|
||||
"prettier": "^3.3.3",
|
||||
"tsx": "^4.19.2",
|
||||
"typescript": "^5.6.3"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,13 +2,13 @@ import { QuartzConfig } from "./quartz/cfg"
|
||||
import * as Plugin from "./quartz/plugins"
|
||||
|
||||
/**
|
||||
* Quartz 4 Configuration
|
||||
* Quartz 4.0 Configuration
|
||||
*
|
||||
* See https://quartz.jzhao.xyz/configuration for more information.
|
||||
*/
|
||||
const config: QuartzConfig = {
|
||||
configuration: {
|
||||
pageTitle: "Quartz 4",
|
||||
pageTitle: "🪴 Quartz 4.0",
|
||||
pageTitleSuffix: "",
|
||||
enableSPA: true,
|
||||
enablePopovers: true,
|
||||
@@ -19,7 +19,7 @@ const config: QuartzConfig = {
|
||||
baseUrl: "quartz.jzhao.xyz",
|
||||
ignorePatterns: ["private", "templates", ".obsidian"],
|
||||
defaultDateType: "created",
|
||||
generateSocialImages: true,
|
||||
generateSocialImages: false,
|
||||
theme: {
|
||||
fontOrigin: "googleFonts",
|
||||
cdnCaching: true,
|
||||
|
||||
@@ -27,7 +27,7 @@ export const defaultContentPageLayout: PageLayout = {
|
||||
Component.MobileOnly(Component.Spacer()),
|
||||
Component.Search(),
|
||||
Component.Darkmode(),
|
||||
Component.Explorer(),
|
||||
Component.DesktopOnly(Component.Explorer()),
|
||||
],
|
||||
right: [
|
||||
Component.Graph(),
|
||||
@@ -44,7 +44,7 @@ export const defaultListPageLayout: PageLayout = {
|
||||
Component.MobileOnly(Component.Spacer()),
|
||||
Component.Search(),
|
||||
Component.Darkmode(),
|
||||
Component.Explorer(),
|
||||
Component.DesktopOnly(Component.Explorer()),
|
||||
],
|
||||
right: [],
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
#!/usr/bin/env -S node --no-deprecation
|
||||
#!/usr/bin/env node
|
||||
import yargs from "yargs"
|
||||
import { hideBin } from "yargs/helpers"
|
||||
import {
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
#!/usr/bin/env node
|
||||
import workerpool from "workerpool"
|
||||
const cacheFile = "./.quartz-cache/transpiled-worker.mjs"
|
||||
const { parseMarkdown, processHtml } = await import(cacheFile)
|
||||
const { parseFiles } = await import(cacheFile)
|
||||
workerpool.worker({
|
||||
parseMarkdown,
|
||||
processHtml,
|
||||
parseFiles,
|
||||
})
|
||||
|
||||
@@ -19,7 +19,6 @@ import { options } from "./util/sourcemap"
|
||||
import { Mutex } from "async-mutex"
|
||||
import DepGraph from "./depgraph"
|
||||
import { getStaticResourcesFromPlugins } from "./plugins"
|
||||
import { randomIdNonSecure } from "./util/random"
|
||||
|
||||
type Dependencies = Record<string, DepGraph<FilePath> | null>
|
||||
|
||||
@@ -39,9 +38,13 @@ type BuildData = {
|
||||
|
||||
type FileEvent = "add" | "change" | "delete"
|
||||
|
||||
function newBuildId() {
|
||||
return Math.random().toString(36).substring(2, 8)
|
||||
}
|
||||
|
||||
async function buildQuartz(argv: Argv, mut: Mutex, clientRefresh: () => void) {
|
||||
const ctx: BuildCtx = {
|
||||
buildId: randomIdNonSecure(),
|
||||
buildId: newBuildId(),
|
||||
argv,
|
||||
cfg,
|
||||
allSlugs: [],
|
||||
@@ -136,9 +139,9 @@ async function startServing(
|
||||
|
||||
const buildFromEntry = argv.fastRebuild ? partialRebuildFromEntrypoint : rebuildFromEntrypoint
|
||||
watcher
|
||||
.on("add", (fp) => buildFromEntry(fp as string, "add", clientRefresh, buildData))
|
||||
.on("change", (fp) => buildFromEntry(fp as string, "change", clientRefresh, buildData))
|
||||
.on("unlink", (fp) => buildFromEntry(fp as string, "delete", clientRefresh, buildData))
|
||||
.on("add", (fp) => buildFromEntry(fp, "add", clientRefresh, buildData))
|
||||
.on("change", (fp) => buildFromEntry(fp, "change", clientRefresh, buildData))
|
||||
.on("unlink", (fp) => buildFromEntry(fp, "delete", clientRefresh, buildData))
|
||||
|
||||
return async () => {
|
||||
await watcher.close()
|
||||
@@ -159,7 +162,7 @@ async function partialRebuildFromEntrypoint(
|
||||
return
|
||||
}
|
||||
|
||||
const buildId = randomIdNonSecure()
|
||||
const buildId = newBuildId()
|
||||
ctx.buildId = buildId
|
||||
buildData.lastBuildMs = new Date().getTime()
|
||||
const release = await mut.acquire()
|
||||
@@ -356,7 +359,7 @@ async function rebuildFromEntrypoint(
|
||||
toRemove.add(filePath)
|
||||
}
|
||||
|
||||
const buildId = randomIdNonSecure()
|
||||
const buildId = newBuildId()
|
||||
ctx.buildId = buildId
|
||||
buildData.lastBuildMs = new Date().getTime()
|
||||
const release = await mut.acquire()
|
||||
|
||||
@@ -33,15 +33,6 @@ import {
|
||||
cwd,
|
||||
} 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`
|
||||
* @param {*} argv arguments for `create`
|
||||
@@ -49,7 +40,7 @@ function resolveContentPath(contentPath) {
|
||||
export async function handleCreate(argv) {
|
||||
console.log()
|
||||
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 linkResolutionStrategy = argv.links?.toLowerCase()
|
||||
const sourceDirectory = argv.source
|
||||
@@ -459,7 +450,7 @@ export async function handleBuild(argv) {
|
||||
* @param {*} argv arguments for `update`
|
||||
*/
|
||||
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("Backing up your content")
|
||||
execSync(
|
||||
@@ -511,7 +502,7 @@ export async function handleUpdate(argv) {
|
||||
* @param {*} argv arguments for `restore`
|
||||
*/
|
||||
export async function handleRestore(argv) {
|
||||
const contentFolder = resolveContentPath(argv.directory)
|
||||
const contentFolder = path.join(cwd, argv.directory)
|
||||
await popContentFolder(contentFolder)
|
||||
}
|
||||
|
||||
@@ -520,7 +511,7 @@ export async function handleRestore(argv) {
|
||||
* @param {*} argv arguments for `sync`
|
||||
*/
|
||||
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("Backing up your content")
|
||||
|
||||
|
||||
@@ -3,53 +3,34 @@ import style from "./styles/backlinks.scss"
|
||||
import { resolveRelative, simplifySlug } from "../util/path"
|
||||
import { i18n } from "../i18n"
|
||||
import { classNames } from "../util/lang"
|
||||
import OverflowListFactory from "./OverflowList"
|
||||
|
||||
interface BacklinksOptions {
|
||||
hideWhenEmpty: boolean
|
||||
const Backlinks: QuartzComponent = ({
|
||||
fileData,
|
||||
allFiles,
|
||||
displayClass,
|
||||
cfg,
|
||||
}: QuartzComponentProps) => {
|
||||
const slug = simplifySlug(fileData.slug!)
|
||||
const backlinkFiles = allFiles.filter((file) => file.links?.includes(slug))
|
||||
return (
|
||||
<div class={classNames(displayClass, "backlinks")}>
|
||||
<h3>{i18n(cfg.locale).components.backlinks.title}</h3>
|
||||
<ul class="overflow">
|
||||
{backlinkFiles.length > 0 ? (
|
||||
backlinkFiles.map((f) => (
|
||||
<li>
|
||||
<a href={resolveRelative(fileData.slug!, f.slug!)} class="internal">
|
||||
{f.frontmatter?.title}
|
||||
</a>
|
||||
</li>
|
||||
))
|
||||
) : (
|
||||
<li>{i18n(cfg.locale).components.backlinks.noBacklinksFound}</li>
|
||||
)}
|
||||
</ul>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const defaultOptions: BacklinksOptions = {
|
||||
hideWhenEmpty: true,
|
||||
}
|
||||
|
||||
export default ((opts?: Partial<BacklinksOptions>) => {
|
||||
const options: BacklinksOptions = { ...defaultOptions, ...opts }
|
||||
const { OverflowList, overflowListAfterDOMLoaded } = OverflowListFactory()
|
||||
|
||||
const Backlinks: QuartzComponent = ({
|
||||
fileData,
|
||||
allFiles,
|
||||
displayClass,
|
||||
cfg,
|
||||
}: QuartzComponentProps) => {
|
||||
const slug = simplifySlug(fileData.slug!)
|
||||
const backlinkFiles = allFiles.filter((file) => file.links?.includes(slug))
|
||||
if (options.hideWhenEmpty && backlinkFiles.length == 0) {
|
||||
return null
|
||||
}
|
||||
return (
|
||||
<div class={classNames(displayClass, "backlinks")}>
|
||||
<h3>{i18n(cfg.locale).components.backlinks.title}</h3>
|
||||
<OverflowList>
|
||||
{backlinkFiles.length > 0 ? (
|
||||
backlinkFiles.map((f) => (
|
||||
<li>
|
||||
<a href={resolveRelative(fileData.slug!, f.slug!)} class="internal">
|
||||
{f.frontmatter?.title}
|
||||
</a>
|
||||
</li>
|
||||
))
|
||||
) : (
|
||||
<li>{i18n(cfg.locale).components.backlinks.noBacklinksFound}</li>
|
||||
)}
|
||||
</OverflowList>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
Backlinks.css = style
|
||||
Backlinks.afterDOMLoaded = overflowListAfterDOMLoaded
|
||||
|
||||
return Backlinks
|
||||
}) satisfies QuartzComponentConstructor
|
||||
Backlinks.css = style
|
||||
export default (() => Backlinks) satisfies QuartzComponentConstructor
|
||||
|
||||
@@ -28,8 +28,7 @@ export default ((opts: Options) => {
|
||||
const Comments: QuartzComponent = ({ displayClass, fileData, cfg }: QuartzComponentProps) => {
|
||||
// check if comments should be displayed according to frontmatter
|
||||
const disableComment: boolean =
|
||||
typeof fileData.frontmatter?.comments !== "undefined" &&
|
||||
(!fileData.frontmatter?.comments || fileData.frontmatter?.comments === "false")
|
||||
!fileData.frontmatter?.comments || fileData.frontmatter?.comments === "false"
|
||||
if (disableComment) {
|
||||
return <></>
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Date, getDate } from "./Date"
|
||||
import { formatDate, getDate } from "./Date"
|
||||
import { QuartzComponentConstructor, QuartzComponentProps } from "./types"
|
||||
import readingTime from "reading-time"
|
||||
import { classNames } from "../util/lang"
|
||||
@@ -30,7 +30,7 @@ export default ((opts?: Partial<ContentMetaOptions>) => {
|
||||
const segments: (string | JSX.Element)[] = []
|
||||
|
||||
if (fileData.dates) {
|
||||
segments.push(<Date date={getDate(cfg, fileData)!} locale={cfg.locale} />)
|
||||
segments.push(formatDate(getDate(cfg, fileData)!, cfg.locale))
|
||||
}
|
||||
|
||||
// Display reading time if enabled
|
||||
@@ -39,12 +39,14 @@ export default ((opts?: Partial<ContentMetaOptions>) => {
|
||||
const displayedTime = i18n(cfg.locale).components.contentMeta.readingTime({
|
||||
minutes: Math.ceil(minutes),
|
||||
})
|
||||
segments.push(<span>{displayedTime}</span>)
|
||||
segments.push(displayedTime)
|
||||
}
|
||||
|
||||
const segmentsElements = segments.map((segment) => <span>{segment}</span>)
|
||||
|
||||
return (
|
||||
<p show-comma={options.showComma} class={classNames(displayClass, "content-meta")}>
|
||||
{segments}
|
||||
{segmentsElements}
|
||||
</p>
|
||||
)
|
||||
} else {
|
||||
|
||||
@@ -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 styles from "./styles/darkmode.scss"
|
||||
import { QuartzComponent, QuartzComponentConstructor, QuartzComponentProps } from "./types"
|
||||
@@ -7,12 +9,12 @@ import { classNames } from "../util/lang"
|
||||
|
||||
const Darkmode: QuartzComponent = ({ displayClass, cfg }: QuartzComponentProps) => {
|
||||
return (
|
||||
<button class={classNames(displayClass, "darkmode")}>
|
||||
<button class={classNames(displayClass, "darkmode")} id="darkmode">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
xmlnsXlink="http://www.w3.org/1999/xlink"
|
||||
version="1.1"
|
||||
class="dayIcon"
|
||||
id="dayIcon"
|
||||
x="0px"
|
||||
y="0px"
|
||||
viewBox="0 0 35 35"
|
||||
@@ -27,7 +29,7 @@ const Darkmode: QuartzComponent = ({ displayClass, cfg }: QuartzComponentProps)
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
xmlnsXlink="http://www.w3.org/1999/xlink"
|
||||
version="1.1"
|
||||
class="nightIcon"
|
||||
id="nightIcon"
|
||||
x="0px"
|
||||
y="0px"
|
||||
viewBox="0 0 100 100"
|
||||
|
||||
@@ -27,5 +27,5 @@ export function formatDate(d: Date, locale: ValidLocale = "en-US"): string {
|
||||
}
|
||||
|
||||
export function Date({ date, locale }: Props) {
|
||||
return <time datetime={date.toISOString()}>{formatDate(date, locale)}</time>
|
||||
return <>{formatDate(date, locale)}</>
|
||||
}
|
||||
|
||||
@@ -1,37 +1,24 @@
|
||||
import { QuartzComponent, QuartzComponentConstructor, QuartzComponentProps } from "./types"
|
||||
import style from "./styles/explorer.scss"
|
||||
import explorerStyle from "./styles/explorer.scss"
|
||||
|
||||
// @ts-ignore
|
||||
import script from "./scripts/explorer.inline"
|
||||
import { ExplorerNode, FileNode, Options } from "./ExplorerNode"
|
||||
import { QuartzPluginData } from "../plugins/vfile"
|
||||
import { classNames } from "../util/lang"
|
||||
import { i18n } from "../i18n"
|
||||
import { FileTrieNode } from "../util/fileTrie"
|
||||
import OverflowListFactory from "./OverflowList"
|
||||
import { concatenateResources } from "../util/resources"
|
||||
|
||||
type OrderEntries = "sort" | "filter" | "map"
|
||||
|
||||
export interface Options {
|
||||
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 = {
|
||||
// Options interface defined in `ExplorerNode` to avoid circular dependency
|
||||
const defaultOptions = {
|
||||
folderClickBehavior: "collapse",
|
||||
folderDefaultState: "collapsed",
|
||||
folderClickBehavior: "link",
|
||||
useSavedState: true,
|
||||
mapFn: (node) => {
|
||||
return node
|
||||
},
|
||||
sortFn: (a, b) => {
|
||||
// Sort order: folders first, then files. Sort folders and files alphabeticall
|
||||
if ((!a.isFolder && !b.isFolder) || (a.isFolder && b.isFolder)) {
|
||||
// Sort order: folders first, then files. Sort folders and files alphabetically
|
||||
if ((!a.file && !b.file) || (a.file && b.file)) {
|
||||
// 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
|
||||
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
|
||||
} else {
|
||||
return -1
|
||||
}
|
||||
},
|
||||
filterFn: (node) => node.slugSegment !== "tags",
|
||||
filterFn: (node) => node.name !== "tags",
|
||||
order: ["filter", "map", "sort"],
|
||||
}
|
||||
|
||||
export type FolderState = {
|
||||
path: string
|
||||
collapsed: boolean
|
||||
}
|
||||
} satisfies Options
|
||||
|
||||
export default ((userOpts?: Partial<Options>) => {
|
||||
// Parse config
|
||||
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 (
|
||||
<div
|
||||
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(),
|
||||
})}
|
||||
>
|
||||
<div class={classNames(displayClass, "explorer")}>
|
||||
<button
|
||||
type="button"
|
||||
class="explorer-toggle mobile-explorer hide-until-loaded"
|
||||
data-mobile={true}
|
||||
id="explorer"
|
||||
data-behavior={opts.folderClickBehavior}
|
||||
data-collapsed={opts.folderDefaultState}
|
||||
data-savestate={opts.useSavedState}
|
||||
data-tree={jsonTree}
|
||||
aria-controls="explorer-content"
|
||||
>
|
||||
<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}
|
||||
aria-expanded={opts.folderDefaultState === "open"}
|
||||
>
|
||||
<h2>{opts.title ?? i18n(cfg.locale).components.explorer.title}</h2>
|
||||
<svg
|
||||
@@ -116,47 +112,17 @@ export default ((userOpts?: Partial<Options>) => {
|
||||
<polyline points="6 9 12 15 18 9"></polyline>
|
||||
</svg>
|
||||
</button>
|
||||
<div class="explorer-content" aria-expanded={false}>
|
||||
<OverflowList class="explorer-ul" />
|
||||
<div id="explorer-content">
|
||||
<ul class="overflow" id="explorer-ul">
|
||||
<ExplorerNode node={fileTree} opts={opts} fileData={fileData} />
|
||||
<li id="explorer-end" />
|
||||
</ul>
|
||||
</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>
|
||||
)
|
||||
}
|
||||
|
||||
Explorer.css = style
|
||||
Explorer.afterDOMLoaded = concatenateResources(script, overflowListAfterDOMLoaded)
|
||||
Explorer.css = explorerStyle
|
||||
Explorer.afterDOMLoaded = script
|
||||
return Explorer
|
||||
}) satisfies QuartzComponentConstructor
|
||||
|
||||
242
quartz/components/ExplorerNode.tsx
Normal file
242
quartz/components/ExplorerNode.tsx
Normal 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>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -18,7 +18,6 @@ export interface D3Config {
|
||||
removeTags: string[]
|
||||
showTags: boolean
|
||||
focusOnHover?: boolean
|
||||
enableRadial?: boolean
|
||||
}
|
||||
|
||||
interface GraphOptions {
|
||||
@@ -40,7 +39,6 @@ const defaultOptions: GraphOptions = {
|
||||
showTags: true,
|
||||
removeTags: [],
|
||||
focusOnHover: false,
|
||||
enableRadial: false,
|
||||
},
|
||||
globalGraph: {
|
||||
drag: true,
|
||||
@@ -48,18 +46,17 @@ const defaultOptions: GraphOptions = {
|
||||
depth: -1,
|
||||
scale: 0.9,
|
||||
repelForce: 0.5,
|
||||
centerForce: 0.2,
|
||||
centerForce: 0.3,
|
||||
linkDistance: 30,
|
||||
fontSize: 0.6,
|
||||
opacityScale: 1,
|
||||
showTags: true,
|
||||
removeTags: [],
|
||||
focusOnHover: true,
|
||||
enableRadial: true,
|
||||
},
|
||||
}
|
||||
|
||||
export default ((opts?: Partial<GraphOptions>) => {
|
||||
export default ((opts?: GraphOptions) => {
|
||||
const Graph: QuartzComponent = ({ displayClass, cfg }: QuartzComponentProps) => {
|
||||
const localGraph = { ...defaultOptions.localGraph, ...opts?.localGraph }
|
||||
const globalGraph = { ...defaultOptions.globalGraph, ...opts?.globalGraph }
|
||||
@@ -67,8 +64,8 @@ export default ((opts?: Partial<GraphOptions>) => {
|
||||
<div class={classNames(displayClass, "graph")}>
|
||||
<h3>{i18n(cfg.locale).components.graph.title}</h3>
|
||||
<div class="graph-outer">
|
||||
<div class="graph-container" data-cfg={JSON.stringify(localGraph)}></div>
|
||||
<button class="global-graph-icon" aria-label="Global Graph">
|
||||
<div id="graph-container" data-cfg={JSON.stringify(localGraph)}></div>
|
||||
<button id="global-graph-icon" aria-label="Global Graph">
|
||||
<svg
|
||||
version="1.1"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
@@ -95,8 +92,8 @@ export default ((opts?: Partial<GraphOptions>) => {
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
<div class="global-graph-outer">
|
||||
<div class="global-graph-container" data-cfg={JSON.stringify(globalGraph)}></div>
|
||||
<div id="global-graph-outer">
|
||||
<div id="global-graph-container" data-cfg={JSON.stringify(globalGraph)}></div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
import { i18n } from "../i18n"
|
||||
import { FullSlug, joinSegments, pathToRoot } from "../util/path"
|
||||
import { CSSResourceToStyleElement, JSResourceToScriptElement } from "../util/resources"
|
||||
import { getFontSpecificationName, googleFontHref } from "../util/theme"
|
||||
import { googleFontHref } from "../util/theme"
|
||||
import { QuartzComponent, QuartzComponentConstructor, QuartzComponentProps } from "./types"
|
||||
import satori, { SatoriOptions } from "satori"
|
||||
import { loadEmoji, getIconCode } from "../util/emoji"
|
||||
import fs from "fs"
|
||||
import sharp from "sharp"
|
||||
import { ImageOptions, SocialImageOptions, getSatoriFont, defaultImage } from "../util/og"
|
||||
@@ -25,18 +24,7 @@ async function generateSocialImage(
|
||||
// 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,
|
||||
loadAdditionalAsset: async (languageCode: string, segment: string) => {
|
||||
if (languageCode === "emoji") {
|
||||
return `data:image/svg+xml;base64,${btoa(await loadEmoji(getIconCode(segment)))}`
|
||||
}
|
||||
|
||||
return languageCode
|
||||
},
|
||||
})
|
||||
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()
|
||||
@@ -77,9 +65,7 @@ export default (() => {
|
||||
|
||||
// Memoize google fonts
|
||||
if (!fontsPromise && cfg.generateSocialImages) {
|
||||
const headerFont = getFontSpecificationName(cfg.theme.typography.header)
|
||||
const bodyFont = getFontSpecificationName(cfg.theme.typography.body)
|
||||
fontsPromise = getSatoriFont(headerFont, bodyFont)
|
||||
fontsPromise = getSatoriFont(cfg.theme.typography.header, cfg.theme.typography.body)
|
||||
}
|
||||
|
||||
const slug = fileData.filePath
|
||||
@@ -112,7 +98,7 @@ export default (() => {
|
||||
|
||||
if (fileName) {
|
||||
// Generate social image (happens async)
|
||||
void generateSocialImage(
|
||||
generateSocialImage(
|
||||
{
|
||||
title,
|
||||
description,
|
||||
@@ -129,7 +115,7 @@ export default (() => {
|
||||
}
|
||||
}
|
||||
|
||||
const { css, js, additionalHead } = externalResources
|
||||
const { css, js } = externalResources
|
||||
|
||||
const url = new URL(`https://${cfg.baseUrl ?? "example.com"}`)
|
||||
const path = url.pathname as FullSlug
|
||||
@@ -179,7 +165,6 @@ export default (() => {
|
||||
<link rel="stylesheet" href={googleFontHref(cfg.theme)} />
|
||||
</>
|
||||
)}
|
||||
<link rel="preconnect" href="https://cdnjs.cloudflare.com" crossOrigin="anonymous" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
{/* OG/Twitter meta tags */}
|
||||
<meta name="og:site_name" content={cfg.pageTitle}></meta>
|
||||
@@ -196,6 +181,8 @@ export default (() => {
|
||||
<>
|
||||
<meta property="og:image:width" content={fullOptions.width.toString()} />
|
||||
<meta property="og:image:height" content={fullOptions.height.toString()} />
|
||||
<meta property="og:width" content={fullOptions.width.toString()} />
|
||||
<meta property="og:height" content={fullOptions.height.toString()} />
|
||||
</>
|
||||
)}
|
||||
<meta property="og:image:url" content={ogImagePath} />
|
||||
@@ -215,13 +202,6 @@ export default (() => {
|
||||
{js
|
||||
.filter((resource) => resource.loadTime === "beforeDOMReady")
|
||||
.map((res) => JSResourceToScriptElement(res, true))}
|
||||
{additionalHead.map((resource) => {
|
||||
if (typeof resource === "function") {
|
||||
return resource(fileData)
|
||||
} else {
|
||||
return resource
|
||||
}
|
||||
})}
|
||||
</head>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -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())
|
||||
})
|
||||
`,
|
||||
}
|
||||
}
|
||||
@@ -46,9 +46,13 @@ export const PageList: QuartzComponent = ({ cfg, fileData, allFiles, limit, sort
|
||||
return (
|
||||
<li class="section-li">
|
||||
<div class="section">
|
||||
<p class="meta">
|
||||
{page.dates && <Date date={getDate(cfg, page)!} locale={cfg.locale} />}
|
||||
</p>
|
||||
<div>
|
||||
{page.dates && (
|
||||
<p class="meta">
|
||||
<Date date={getDate(cfg, page)!} locale={cfg.locale} />
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<div class="desc">
|
||||
<h3>
|
||||
<a href={resolveRelative(fileData.slug!, page.slug!)} class="internal">
|
||||
|
||||
@@ -19,7 +19,7 @@ export default ((userOpts?: Partial<SearchOptions>) => {
|
||||
const searchPlaceholder = i18n(cfg.locale).components.search.searchBarPlaceholder
|
||||
return (
|
||||
<div class={classNames(displayClass, "search")}>
|
||||
<button class="search-button">
|
||||
<button class="search-button" id="search-button">
|
||||
<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">
|
||||
<title>Search</title>
|
||||
@@ -29,17 +29,17 @@ export default ((userOpts?: Partial<SearchOptions>) => {
|
||||
</g>
|
||||
</svg>
|
||||
</button>
|
||||
<div class="search-container">
|
||||
<div class="search-space">
|
||||
<div id="search-container">
|
||||
<div id="search-space">
|
||||
<input
|
||||
autocomplete="off"
|
||||
class="search-bar"
|
||||
id="search-bar"
|
||||
name="search"
|
||||
type="text"
|
||||
aria-label={searchPlaceholder}
|
||||
placeholder={searchPlaceholder}
|
||||
/>
|
||||
<div class="search-layout" data-preview={opts.enablePreview}></div>
|
||||
<div id="search-layout" data-preview={opts.enablePreview}></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -6,8 +6,6 @@ import { classNames } from "../util/lang"
|
||||
// @ts-ignore
|
||||
import script from "./scripts/toc.inline"
|
||||
import { i18n } from "../i18n"
|
||||
import OverflowListFactory from "./OverflowList"
|
||||
import { concatenateResources } from "../util/resources"
|
||||
|
||||
interface Options {
|
||||
layout: "modern" | "legacy"
|
||||
@@ -17,70 +15,42 @@ const defaultOptions: Options = {
|
||||
layout: "modern",
|
||||
}
|
||||
|
||||
export default ((opts?: Partial<Options>) => {
|
||||
const layout = opts?.layout ?? defaultOptions.layout
|
||||
const { OverflowList, overflowListAfterDOMLoaded } = OverflowListFactory()
|
||||
const TableOfContents: QuartzComponent = ({
|
||||
fileData,
|
||||
displayClass,
|
||||
cfg,
|
||||
}: 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>
|
||||
)
|
||||
const TableOfContents: QuartzComponent = ({
|
||||
fileData,
|
||||
displayClass,
|
||||
cfg,
|
||||
}: QuartzComponentProps) => {
|
||||
if (!fileData.toc) {
|
||||
return null
|
||||
}
|
||||
|
||||
TableOfContents.css = modernStyle
|
||||
TableOfContents.afterDOMLoaded = concatenateResources(script, overflowListAfterDOMLoaded)
|
||||
|
||||
const LegacyTableOfContents: QuartzComponent = ({ fileData, cfg }: QuartzComponentProps) => {
|
||||
if (!fileData.toc) {
|
||||
return null
|
||||
}
|
||||
return (
|
||||
<details class="toc" open={!fileData.collapseToc}>
|
||||
<summary>
|
||||
<h3>{i18n(cfg.locale).components.tableOfContents.title}</h3>
|
||||
</summary>
|
||||
<ul>
|
||||
return (
|
||||
<div class={classNames(displayClass, "toc")}>
|
||||
<button
|
||||
type="button"
|
||||
id="toc"
|
||||
class={fileData.collapseToc ? "collapsed" : ""}
|
||||
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 id="toc-content" class={fileData.collapseToc ? "collapsed" : ""}>
|
||||
<ul class="overflow">
|
||||
{fileData.toc.map((tocEntry) => (
|
||||
<li key={tocEntry.slug} class={`depth-${tocEntry.depth}`}>
|
||||
<a href={`#${tocEntry.slug}`} data-for={tocEntry.slug}>
|
||||
@@ -89,10 +59,37 @@ export default ((opts?: Partial<Options>) => {
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</details>
|
||||
)
|
||||
}
|
||||
LegacyTableOfContents.css = legacyStyle
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
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
|
||||
}) satisfies QuartzComponentConstructor
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
import { ComponentChildren } from "preact"
|
||||
import { htmlToJsx } from "../../util/jsx"
|
||||
import { QuartzComponent, QuartzComponentConstructor, QuartzComponentProps } from "../types"
|
||||
|
||||
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 classString = ["popover-hint", ...classes].join(" ")
|
||||
return <article class={classString}>{content}</article>
|
||||
|
||||
@@ -8,8 +8,6 @@ import { Root } from "hast"
|
||||
import { htmlToJsx } from "../../util/jsx"
|
||||
import { i18n } from "../../i18n"
|
||||
import { QuartzPluginData } from "../../plugins/vfile"
|
||||
import { ComponentChildren } from "preact"
|
||||
import { concatenateResources } from "../../util/resources"
|
||||
|
||||
interface FolderContentOptions {
|
||||
/**
|
||||
@@ -73,22 +71,21 @@ export default ((opts?: Partial<FolderContentOptions>) => {
|
||||
})
|
||||
|
||||
const cssClasses: string[] = fileData.frontmatter?.cssclasses ?? []
|
||||
const classes = cssClasses.join(" ")
|
||||
const classes = ["popover-hint", ...cssClasses].join(" ")
|
||||
const listProps = {
|
||||
...props,
|
||||
sort: options.sort,
|
||||
allFiles: allPagesInFolder,
|
||||
}
|
||||
|
||||
const content = (
|
||||
const content =
|
||||
(tree as Root).children.length === 0
|
||||
? fileData.description
|
||||
: htmlToJsx(fileData.filePath!, tree)
|
||||
) as ComponentChildren
|
||||
|
||||
return (
|
||||
<div class="popover-hint">
|
||||
<article class={classes}>{content}</article>
|
||||
<div class={classes}>
|
||||
<article>{content}</article>
|
||||
<div class="page-listing">
|
||||
{options.showFolderCount && (
|
||||
<p>
|
||||
@@ -105,6 +102,6 @@ export default ((opts?: Partial<FolderContentOptions>) => {
|
||||
)
|
||||
}
|
||||
|
||||
FolderContent.css = concatenateResources(style, PageList.css)
|
||||
FolderContent.css = style + PageList.css
|
||||
return FolderContent
|
||||
}) satisfies QuartzComponentConstructor
|
||||
|
||||
@@ -6,8 +6,6 @@ import { QuartzPluginData } from "../../plugins/vfile"
|
||||
import { Root } from "hast"
|
||||
import { htmlToJsx } from "../../util/jsx"
|
||||
import { i18n } from "../../i18n"
|
||||
import { ComponentChildren } from "preact"
|
||||
import { concatenateResources } from "../../util/resources"
|
||||
|
||||
interface TagContentOptions {
|
||||
sort?: SortFn
|
||||
@@ -35,13 +33,12 @@ export default ((opts?: Partial<TagContentOptions>) => {
|
||||
(file.frontmatter?.tags ?? []).flatMap(getAllSegmentPrefixes).includes(tag),
|
||||
)
|
||||
|
||||
const content = (
|
||||
const content =
|
||||
(tree as Root).children.length === 0
|
||||
? fileData.description
|
||||
: htmlToJsx(fileData.filePath!, tree)
|
||||
) as ComponentChildren
|
||||
const cssClasses: string[] = fileData.frontmatter?.cssclasses ?? []
|
||||
const classes = cssClasses.join(" ")
|
||||
const classes = ["popover-hint", ...cssClasses].join(" ")
|
||||
if (tag === "/") {
|
||||
const tags = [
|
||||
...new Set(
|
||||
@@ -53,8 +50,8 @@ export default ((opts?: Partial<TagContentOptions>) => {
|
||||
tagItemMap.set(tag, allPagesWithTag(tag))
|
||||
}
|
||||
return (
|
||||
<div class="popover-hint">
|
||||
<article class={classes}>
|
||||
<div class={classes}>
|
||||
<article>
|
||||
<p>{content}</p>
|
||||
</article>
|
||||
<p>{i18n(cfg.locale).pages.tagContent.totalTags({ count: tags.length })}</p>
|
||||
@@ -96,7 +93,7 @@ export default ((opts?: Partial<TagContentOptions>) => {
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
<PageList limit={options.numPages} {...listProps} sort={options?.sort} />
|
||||
<PageList limit={options.numPages} {...listProps} sort={opts?.sort} />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
@@ -113,11 +110,11 @@ export default ((opts?: Partial<TagContentOptions>) => {
|
||||
|
||||
return (
|
||||
<div class={classes}>
|
||||
<article class="popover-hint">{content}</article>
|
||||
<article>{content}</article>
|
||||
<div class="page-listing">
|
||||
<p>{i18n(cfg.locale).pages.tagContent.itemsUnderTag({ count: pages.length })}</p>
|
||||
<div>
|
||||
<PageList {...listProps} sort={options?.sort} />
|
||||
<PageList {...listProps} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -125,6 +122,6 @@ export default ((opts?: Partial<TagContentOptions>) => {
|
||||
}
|
||||
}
|
||||
|
||||
TagContent.css = concatenateResources(style, PageList.css)
|
||||
TagContent.css = style + PageList.css
|
||||
return TagContent
|
||||
}) satisfies QuartzComponentConstructor
|
||||
|
||||
@@ -3,13 +3,11 @@ import { QuartzComponent, QuartzComponentProps } from "./types"
|
||||
import HeaderConstructor from "./Header"
|
||||
import BodyConstructor from "./Body"
|
||||
import { JSResourceToScriptElement, StaticResources } from "../util/resources"
|
||||
import { FullSlug, RelativeURL, joinSegments, normalizeHastElement } from "../util/path"
|
||||
import { clone } from "../util/clone"
|
||||
import { clone, FullSlug, RelativeURL, joinSegments, normalizeHastElement } from "../util/path"
|
||||
import { visit } from "unist-util-visit"
|
||||
import { Root, Element, ElementContent } from "hast"
|
||||
import { GlobalConfiguration } from "../cfg"
|
||||
import { i18n } from "../i18n"
|
||||
import { QuartzPluginData } from "../plugins/vfile"
|
||||
|
||||
interface RenderComponents {
|
||||
head: QuartzComponent
|
||||
@@ -25,13 +23,12 @@ interface RenderComponents {
|
||||
const headerRegex = new RegExp(/h[1-6]/)
|
||||
export function pageResources(
|
||||
baseDir: FullSlug | RelativeURL,
|
||||
fileData: QuartzPluginData,
|
||||
staticResources: StaticResources,
|
||||
): StaticResources {
|
||||
const contentIndexPath = joinSegments(baseDir, "static/contentIndex.json")
|
||||
const contentIndexScript = `const fetchData = fetch("${contentIndexPath}").then(data => data.json())`
|
||||
|
||||
const resources: StaticResources = {
|
||||
return {
|
||||
css: [
|
||||
{
|
||||
content: joinSegments(baseDir, "index.css"),
|
||||
@@ -51,18 +48,14 @@ export function pageResources(
|
||||
script: contentIndexScript,
|
||||
},
|
||||
...staticResources.js,
|
||||
{
|
||||
src: joinSegments(baseDir, "postscript.js"),
|
||||
loadTime: "afterDOMReady",
|
||||
moduleType: "module",
|
||||
contentType: "external",
|
||||
},
|
||||
],
|
||||
additionalHead: staticResources.additionalHead,
|
||||
}
|
||||
|
||||
resources.js.push({
|
||||
src: joinSegments(baseDir, "postscript.js"),
|
||||
loadTime: "afterDOMReady",
|
||||
moduleType: "module",
|
||||
contentType: "external",
|
||||
})
|
||||
|
||||
return resources
|
||||
}
|
||||
|
||||
export function renderPage(
|
||||
|
||||
@@ -28,15 +28,17 @@ function setupCallout() {
|
||||
) as HTMLCollectionOf<HTMLElement>
|
||||
for (const div of collapsible) {
|
||||
const title = div.firstElementChild
|
||||
if (!title) continue
|
||||
|
||||
title.addEventListener("click", toggleCallout)
|
||||
window.addCleanup(() => title.removeEventListener("click", toggleCallout))
|
||||
if (title) {
|
||||
title.addEventListener("click", toggleCallout)
|
||||
window.addCleanup(() => title.removeEventListener("click", toggleCallout))
|
||||
|
||||
const collapsed = div.classList.contains("is-collapsed")
|
||||
const height = collapsed ? title.scrollHeight : div.scrollHeight
|
||||
div.style.maxHeight = height + "px"
|
||||
const collapsed = div.classList.contains("is-collapsed")
|
||||
const height = collapsed ? title.scrollHeight : div.scrollHeight
|
||||
div.style.maxHeight = height + "px"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener("nav", setupCallout)
|
||||
window.addEventListener("resize", setupCallout)
|
||||
|
||||
@@ -25,10 +25,10 @@ document.addEventListener("nav", () => {
|
||||
emitThemeChangeEvent(newTheme)
|
||||
}
|
||||
|
||||
for (const darkmodeButton of document.getElementsByClassName("darkmode")) {
|
||||
darkmodeButton.addEventListener("click", switchTheme)
|
||||
window.addCleanup(() => darkmodeButton.removeEventListener("click", switchTheme))
|
||||
}
|
||||
// Darkmode toggle
|
||||
const themeButton = document.querySelector("#darkmode") as HTMLButtonElement
|
||||
themeButton.addEventListener("click", switchTheme)
|
||||
window.addCleanup(() => themeButton.removeEventListener("click", switchTheme))
|
||||
|
||||
// Listen for changes in prefers-color-scheme
|
||||
const colorSchemeMediaQuery = window.matchMedia("(prefers-color-scheme: dark)")
|
||||
|
||||
@@ -1,33 +1,30 @@
|
||||
import { FileTrieNode } from "../../util/fileTrie"
|
||||
import { FullSlug, resolveRelative, simplifySlug } from "../../util/path"
|
||||
import { ContentDetails } from "../../plugins/emitters/contentIndex"
|
||||
import { FolderState } from "../ExplorerNode"
|
||||
|
||||
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) {
|
||||
const nearestExplorer = this.closest(".explorer") as HTMLElement
|
||||
if (!nearestExplorer) return
|
||||
nearestExplorer.classList.toggle("collapsed")
|
||||
nearestExplorer.setAttribute(
|
||||
this.classList.toggle("collapsed")
|
||||
this.setAttribute(
|
||||
"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) {
|
||||
@@ -35,241 +32,104 @@ function toggleFolder(evt: MouseEvent) {
|
||||
const target = evt.target as MaybeHTMLElement
|
||||
if (!target) return
|
||||
|
||||
// Check if target was svg icon or button
|
||||
const isSvg = target.nodeName === "svg"
|
||||
|
||||
// corresponding <ul> element relative to clicked button/folder
|
||||
const folderContainer = (
|
||||
const childFolderContainer = (
|
||||
isSvg
|
||||
? // svg -> div.folder-container
|
||||
target.parentElement
|
||||
: // button.folder-button -> div -> div.folder-container
|
||||
target.parentElement?.parentElement
|
||||
? target.parentElement?.nextSibling
|
||||
: target.parentElement?.parentElement?.nextElementSibling
|
||||
) as MaybeHTMLElement
|
||||
if (!folderContainer) return
|
||||
const childFolderContainer = folderContainer.nextElementSibling as MaybeHTMLElement
|
||||
if (!childFolderContainer) return
|
||||
const currentFolderParent = (
|
||||
isSvg ? target.nextElementSibling : target.parentElement
|
||||
) as MaybeHTMLElement
|
||||
if (!(childFolderContainer && currentFolderParent)) return
|
||||
|
||||
childFolderContainer.classList.toggle("open")
|
||||
|
||||
// Collapse folder container
|
||||
const isCollapsed = !childFolderContainer.classList.contains("open")
|
||||
setFolderState(childFolderContainer, isCollapsed)
|
||||
|
||||
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 isCollapsed = childFolderContainer.classList.contains("open")
|
||||
setFolderState(childFolderContainer, !isCollapsed)
|
||||
const fullFolderPath = currentFolderParent.dataset.folderpath as string
|
||||
toggleCollapsedByPath(currentExplorerState, fullFolderPath)
|
||||
const stringifiedFileTree = JSON.stringify(currentExplorerState)
|
||||
localStorage.setItem("fileTree", stringifiedFileTree)
|
||||
}
|
||||
|
||||
function createFileNode(currentSlug: FullSlug, node: FileTrieNode): HTMLLIElement {
|
||||
const template = document.getElementById("template-file") as HTMLTemplateElement
|
||||
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.data
|
||||
? createFileNode(currentSlug, child)
|
||||
: createFolderNode(currentSlug, child, opts)
|
||||
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(
|
||||
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) => ({
|
||||
path,
|
||||
collapsed: oldIndex.get(path) === true,
|
||||
}))
|
||||
|
||||
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")
|
||||
function setupExplorer() {
|
||||
const explorer = document.getElementById("explorer")
|
||||
if (!explorer) return
|
||||
sessionStorage.setItem("explorerScrollTop", explorer.scrollTop.toString())
|
||||
})
|
||||
|
||||
document.addEventListener("nav", async (e: CustomEventMap["nav"]) => {
|
||||
const currentSlug = e.detail.url
|
||||
await setupExplorer(currentSlug)
|
||||
|
||||
// if mobile hamburger is visible, collapse by default
|
||||
for (const explorer of document.getElementsByClassName("mobile-explorer")) {
|
||||
if (explorer.checkVisibility()) {
|
||||
explorer.classList.add("collapsed")
|
||||
explorer.setAttribute("aria-expanded", "false")
|
||||
if (explorer.dataset.behavior === "collapse") {
|
||||
for (const item of document.getElementsByClassName(
|
||||
"folder-button",
|
||||
) as HTMLCollectionOf<HTMLElement>) {
|
||||
item.addEventListener("click", toggleFolder)
|
||||
window.addCleanup(() => item.removeEventListener("click", toggleFolder))
|
||||
}
|
||||
}
|
||||
|
||||
const hiddenUntilDoneLoading = document.querySelector("#mobile-explorer")
|
||||
hiddenUntilDoneLoading?.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) {
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,7 +8,6 @@ import {
|
||||
forceCenter,
|
||||
forceLink,
|
||||
forceCollide,
|
||||
forceRadial,
|
||||
zoomIdentity,
|
||||
select,
|
||||
drag,
|
||||
@@ -68,9 +67,11 @@ type TweenNode = {
|
||||
stop: () => void
|
||||
}
|
||||
|
||||
async function renderGraph(graph: HTMLElement, fullSlug: FullSlug) {
|
||||
async function renderGraph(container: string, fullSlug: FullSlug) {
|
||||
const slug = simplifySlug(fullSlug)
|
||||
const visited = getVisited()
|
||||
const graph = document.getElementById(container)
|
||||
if (!graph) return
|
||||
removeAllChildren(graph)
|
||||
|
||||
let {
|
||||
@@ -86,7 +87,6 @@ async function renderGraph(graph: HTMLElement, fullSlug: FullSlug) {
|
||||
removeTags,
|
||||
showTags,
|
||||
focusOnHover,
|
||||
enableRadial,
|
||||
} = JSON.parse(graph.dataset["cfg"]!) as D3Config
|
||||
|
||||
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
|
||||
const simulation: Simulation<NodeData, LinkData> = forceSimulation<NodeData>(graphData.nodes)
|
||||
.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("collide", forceCollide<NodeData>((n) => nodeRadius(n)).iterations(3))
|
||||
|
||||
const radius = (Math.min(width, height) / 2) * 0.8
|
||||
if (enableRadial) simulation.force("radial", forceRadial(radius).strength(0.2))
|
||||
const width = graph.offsetWidth
|
||||
const height = Math.max(graph.offsetHeight, 250)
|
||||
|
||||
// precompute style prop strings as pixi doesn't support css variables
|
||||
const cssVars = [
|
||||
@@ -366,9 +363,9 @@ async function renderGraph(graph: HTMLElement, fullSlug: FullSlug) {
|
||||
const stage = app.stage
|
||||
stage.interactive = false
|
||||
|
||||
const labelsContainer = new Container<Text>({ zIndex: 3, isRenderGroup: true })
|
||||
const nodesContainer = new Container<Graphics>({ zIndex: 2, isRenderGroup: true })
|
||||
const linkContainer = new Container<Graphics>({ zIndex: 1, isRenderGroup: true })
|
||||
const labelsContainer = new Container<Text>({ zIndex: 3 })
|
||||
const nodesContainer = new Container<Graphics>({ zIndex: 2 })
|
||||
const linkContainer = new Container<Graphics>({ zIndex: 1 })
|
||||
stage.addChild(nodesContainer, labelsContainer, linkContainer)
|
||||
|
||||
for (const n of graphData.nodes) {
|
||||
@@ -520,9 +517,7 @@ async function renderGraph(graph: HTMLElement, fullSlug: FullSlug) {
|
||||
)
|
||||
}
|
||||
|
||||
let stopAnimation = false
|
||||
function animate(time: number) {
|
||||
if (stopAnimation) return
|
||||
for (const n of nodeRenderData) {
|
||||
const { x, y } = n.simulationData
|
||||
if (!x || !y) continue
|
||||
@@ -546,101 +541,61 @@ async function renderGraph(graph: HTMLElement, fullSlug: FullSlug) {
|
||||
requestAnimationFrame(animate)
|
||||
}
|
||||
|
||||
requestAnimationFrame(animate)
|
||||
return () => {
|
||||
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 = []
|
||||
const graphAnimationFrameHandle = requestAnimationFrame(animate)
|
||||
window.addCleanup(() => cancelAnimationFrame(graphAnimationFrameHandle))
|
||||
}
|
||||
|
||||
document.addEventListener("nav", async (e: CustomEventMap["nav"]) => {
|
||||
const slug = e.detail.url
|
||||
addToVisited(simplifySlug(slug))
|
||||
await renderGraph("graph-container", slug)
|
||||
|
||||
async function renderLocalGraph() {
|
||||
cleanupLocalGraphs()
|
||||
const localGraphContainers = document.getElementsByClassName("graph-container")
|
||||
for (const container of localGraphContainers) {
|
||||
localGraphCleanups.push(await renderGraph(container as HTMLElement, slug))
|
||||
}
|
||||
}
|
||||
|
||||
await renderLocalGraph()
|
||||
// Function to re-render the graph when the theme changes
|
||||
const handleThemeChange = () => {
|
||||
void renderLocalGraph()
|
||||
renderGraph("graph-container", slug)
|
||||
}
|
||||
|
||||
// event listener for theme change
|
||||
document.addEventListener("themechange", handleThemeChange)
|
||||
|
||||
// cleanup for the event listener
|
||||
window.addCleanup(() => {
|
||||
document.removeEventListener("themechange", handleThemeChange)
|
||||
})
|
||||
|
||||
const containers = [...document.getElementsByClassName("global-graph-outer")] as HTMLElement[]
|
||||
async function renderGlobalGraph() {
|
||||
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 container = document.getElementById("global-graph-outer")
|
||||
const sidebar = container?.closest(".sidebar") as HTMLElement
|
||||
|
||||
const graphContainer = container.querySelector(".global-graph-container") as HTMLElement
|
||||
registerEscapeHandler(container, hideGlobalGraph)
|
||||
if (graphContainer) {
|
||||
globalGraphCleanups.push(await renderGraph(graphContainer, slug))
|
||||
}
|
||||
function renderGlobalGraph() {
|
||||
const slug = getFullSlug(window)
|
||||
container?.classList.add("active")
|
||||
if (sidebar) {
|
||||
sidebar.style.zIndex = "1"
|
||||
}
|
||||
|
||||
renderGraph("global-graph-container", slug)
|
||||
registerEscapeHandler(container, hideGlobalGraph)
|
||||
}
|
||||
|
||||
function hideGlobalGraph() {
|
||||
cleanupGlobalGraphs()
|
||||
for (const container of containers) {
|
||||
container.classList.remove("active")
|
||||
const sidebar = container.closest(".sidebar") as HTMLElement
|
||||
if (sidebar) {
|
||||
sidebar.style.zIndex = ""
|
||||
}
|
||||
container?.classList.remove("active")
|
||||
if (sidebar) {
|
||||
sidebar.style.zIndex = ""
|
||||
}
|
||||
}
|
||||
|
||||
async function shortcutHandler(e: HTMLElementEventMap["keydown"]) {
|
||||
if (e.key === "g" && (e.ctrlKey || e.metaKey) && !e.shiftKey) {
|
||||
e.preventDefault()
|
||||
const anyGlobalGraphOpen = containers.some((container) =>
|
||||
container.classList.contains("active"),
|
||||
)
|
||||
anyGlobalGraphOpen ? hideGlobalGraph() : renderGlobalGraph()
|
||||
const globalGraphOpen = container?.classList.contains("active")
|
||||
globalGraphOpen ? hideGlobalGraph() : renderGlobalGraph()
|
||||
}
|
||||
}
|
||||
|
||||
const containerIcons = document.getElementsByClassName("global-graph-icon")
|
||||
Array.from(containerIcons).forEach((icon) => {
|
||||
icon.addEventListener("click", renderGlobalGraph)
|
||||
window.addCleanup(() => icon.removeEventListener("click", renderGlobalGraph))
|
||||
})
|
||||
const containerIcon = document.getElementById("global-graph-icon")
|
||||
containerIcon?.addEventListener("click", renderGlobalGraph)
|
||||
window.addCleanup(() => containerIcon?.removeEventListener("click", renderGlobalGraph))
|
||||
|
||||
document.addEventListener("keydown", shortcutHandler)
|
||||
window.addCleanup(() => {
|
||||
document.removeEventListener("keydown", shortcutHandler)
|
||||
cleanupLocalGraphs()
|
||||
cleanupGlobalGraphs()
|
||||
})
|
||||
window.addCleanup(() => document.removeEventListener("keydown", shortcutHandler))
|
||||
})
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { registerEscapeHandler, removeAllChildren } from "./util"
|
||||
import { removeAllChildren } from "./util"
|
||||
import mermaid from "mermaid"
|
||||
|
||||
interface Position {
|
||||
x: number
|
||||
@@ -143,7 +144,6 @@ const cssVars = [
|
||||
"--codeFont",
|
||||
] as const
|
||||
|
||||
let mermaidImport = undefined
|
||||
document.addEventListener("nav", async () => {
|
||||
const center = document.querySelector(".center") as HTMLElement
|
||||
const nodes = center.querySelectorAll("code.mermaid") as NodeListOf<HTMLElement>
|
||||
@@ -157,12 +157,6 @@ document.addEventListener("nav", async () => {
|
||||
{} as Record<(typeof cssVars)[number], string>,
|
||||
)
|
||||
|
||||
mermaidImport ||= await import(
|
||||
// @ts-ignore
|
||||
"https://cdnjs.cloudflare.com/ajax/libs/mermaid/11.4.0/mermaid.esm.min.mjs"
|
||||
)
|
||||
const mermaid = mermaidImport.default
|
||||
|
||||
const darkMode = document.documentElement.getAttribute("saved-theme") === "dark"
|
||||
mermaid.initialize({
|
||||
startOnLoad: false,
|
||||
@@ -237,12 +231,12 @@ document.addEventListener("nav", async () => {
|
||||
|
||||
closeBtn.addEventListener("click", hideMermaid)
|
||||
expandBtn.addEventListener("click", showMermaid)
|
||||
registerEscapeHandler(popupContainer, hideMermaid)
|
||||
document.addEventListener("keydown", handleEscape)
|
||||
|
||||
window.addCleanup(() => {
|
||||
closeBtn.removeEventListener("click", hideMermaid)
|
||||
expandBtn.removeEventListener("click", showMermaid)
|
||||
document.removeEventListener("keydown", handleEscape)
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { computePosition, flip, inline, shift } from "@floating-ui/dom"
|
||||
import { normalizeRelativeURLs } from "../../util/path"
|
||||
import { fetchCanonical } from "./util"
|
||||
|
||||
const p = new DOMParser()
|
||||
async function mouseEnterHandler(
|
||||
@@ -38,7 +37,7 @@ async function mouseEnterHandler(
|
||||
targetUrl.hash = ""
|
||||
targetUrl.search = ""
|
||||
|
||||
const response = await fetchCanonical(targetUrl).catch((err) => {
|
||||
const response = await fetch(`${targetUrl}`).catch((err) => {
|
||||
console.error(err)
|
||||
})
|
||||
|
||||
@@ -82,8 +81,6 @@ async function mouseEnterHandler(
|
||||
const contents = await response.text()
|
||||
const html = p.parseFromString(contents, "text/html")
|
||||
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")]
|
||||
if (elts.length === 0) return
|
||||
|
||||
|
||||
@@ -143,75 +143,83 @@ function highlightHTML(searchTerm: string, el: HTMLElement) {
|
||||
return html.body
|
||||
}
|
||||
|
||||
async function setupSearch(searchElement: Element, currentSlug: FullSlug, data: ContentIndex) {
|
||||
const container = searchElement.querySelector(".search-container") as HTMLElement
|
||||
if (!container) return
|
||||
|
||||
const sidebar = container.closest(".sidebar") as HTMLElement
|
||||
if (!sidebar) return
|
||||
|
||||
const searchButton = searchElement.querySelector(".search-button") as HTMLButtonElement
|
||||
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
|
||||
|
||||
document.addEventListener("nav", async (e: CustomEventMap["nav"]) => {
|
||||
const currentSlug = e.detail.url
|
||||
const data = await fetchData
|
||||
const container = document.getElementById("search-container")
|
||||
const sidebar = container?.closest(".sidebar") as HTMLElement
|
||||
const searchButton = document.getElementById("search-button")
|
||||
const searchBar = document.getElementById("search-bar") as HTMLInputElement | null
|
||||
const searchLayout = document.getElementById("search-layout")
|
||||
const idDataMap = Object.keys(data) as FullSlug[]
|
||||
|
||||
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 previewInner: HTMLDivElement | undefined = undefined
|
||||
const results = document.createElement("div")
|
||||
results.className = "results-container"
|
||||
results.id = "results-container"
|
||||
appendLayout(results)
|
||||
|
||||
if (enablePreview) {
|
||||
preview = document.createElement("div")
|
||||
preview.className = "preview-container"
|
||||
preview.id = "preview-container"
|
||||
appendLayout(preview)
|
||||
}
|
||||
|
||||
function hideSearch() {
|
||||
container.classList.remove("active")
|
||||
searchBar.value = "" // clear the input when we dismiss the search
|
||||
sidebar.style.zIndex = ""
|
||||
removeAllChildren(results)
|
||||
container?.classList.remove("active")
|
||||
if (searchBar) {
|
||||
searchBar.value = "" // clear the input when we dismiss the search
|
||||
}
|
||||
if (sidebar) {
|
||||
sidebar.style.zIndex = ""
|
||||
}
|
||||
if (results) {
|
||||
removeAllChildren(results)
|
||||
}
|
||||
if (preview) {
|
||||
removeAllChildren(preview)
|
||||
}
|
||||
searchLayout.classList.remove("display-results")
|
||||
if (searchLayout) {
|
||||
searchLayout.classList.remove("display-results")
|
||||
}
|
||||
|
||||
searchType = "basic" // reset search type after closing
|
||||
searchButton.focus()
|
||||
|
||||
searchButton?.focus()
|
||||
}
|
||||
|
||||
function showSearch(searchTypeNew: SearchType) {
|
||||
searchType = searchTypeNew
|
||||
sidebar.style.zIndex = "1"
|
||||
container.classList.add("active")
|
||||
searchBar.focus()
|
||||
if (sidebar) {
|
||||
sidebar.style.zIndex = "1"
|
||||
}
|
||||
container?.classList.add("active")
|
||||
searchBar?.focus()
|
||||
}
|
||||
|
||||
let currentHover: HTMLInputElement | null = null
|
||||
|
||||
async function shortcutHandler(e: HTMLElementEventMap["keydown"]) {
|
||||
if (e.key === "k" && (e.ctrlKey || e.metaKey) && !e.shiftKey) {
|
||||
e.preventDefault()
|
||||
const searchBarOpen = container.classList.contains("active")
|
||||
const searchBarOpen = container?.classList.contains("active")
|
||||
searchBarOpen ? hideSearch() : showSearch("basic")
|
||||
return
|
||||
} else if (e.shiftKey && (e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "k") {
|
||||
// Hotkey to open tag search
|
||||
e.preventDefault()
|
||||
const searchBarOpen = container.classList.contains("active")
|
||||
const searchBarOpen = container?.classList.contains("active")
|
||||
searchBarOpen ? hideSearch() : showSearch("tags")
|
||||
|
||||
// add "#" prefix for tag search
|
||||
searchBar.value = "#"
|
||||
if (searchBar) searchBar.value = "#"
|
||||
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 (!container.classList.contains("active")) return
|
||||
if (!container?.classList.contains("active")) return
|
||||
if (e.key === "Enter") {
|
||||
// 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
|
||||
if (active.classList.contains("no-match")) return
|
||||
await displayPreview(active)
|
||||
active.click()
|
||||
} else {
|
||||
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)
|
||||
anchor.click()
|
||||
}
|
||||
} else if (e.key === "ArrowUp" || (e.shiftKey && e.key === "Tab")) {
|
||||
e.preventDefault()
|
||||
if (results.contains(document.activeElement)) {
|
||||
if (results?.contains(document.activeElement)) {
|
||||
// If an element in results-container already has focus, focus previous one
|
||||
const currentResult = currentHover
|
||||
? currentHover
|
||||
@@ -329,6 +337,8 @@ async function setupSearch(searchElement: Element, currentSlug: FullSlug, data:
|
||||
}
|
||||
|
||||
async function displayResults(finalResults: Item[]) {
|
||||
if (!results) return
|
||||
|
||||
removeAllChildren(results)
|
||||
if (finalResults.length === 0) {
|
||||
results.innerHTML = `<a class="result-card no-match">
|
||||
@@ -384,7 +394,7 @@ async function setupSearch(searchElement: Element, currentSlug: FullSlug, data:
|
||||
preview.replaceChildren(previewInner)
|
||||
|
||||
// scroll to longest
|
||||
const highlights = [...preview.getElementsByClassName("highlight")].sort(
|
||||
const highlights = [...preview.querySelectorAll(".highlight")].sort(
|
||||
(a, b) => b.innerHTML.length - a.innerHTML.length,
|
||||
)
|
||||
highlights[0]?.scrollIntoView({ block: "start" })
|
||||
@@ -450,23 +460,21 @@ async function setupSearch(searchElement: Element, currentSlug: FullSlug, data:
|
||||
|
||||
document.addEventListener("keydown", shortcutHandler)
|
||||
window.addCleanup(() => document.removeEventListener("keydown", shortcutHandler))
|
||||
searchButton.addEventListener("click", () => showSearch("basic"))
|
||||
window.addCleanup(() => searchButton.removeEventListener("click", () => showSearch("basic")))
|
||||
searchBar.addEventListener("input", onType)
|
||||
window.addCleanup(() => searchBar.removeEventListener("input", onType))
|
||||
searchButton?.addEventListener("click", () => showSearch("basic"))
|
||||
window.addCleanup(() => searchButton?.removeEventListener("click", () => showSearch("basic")))
|
||||
searchBar?.addEventListener("input", onType)
|
||||
window.addCleanup(() => searchBar?.removeEventListener("input", onType))
|
||||
|
||||
registerEscapeHandler(container, hideSearch)
|
||||
await fillDocument(data)
|
||||
}
|
||||
})
|
||||
|
||||
/**
|
||||
* Fills flexsearch document with data
|
||||
* @param index index to fill
|
||||
* @param data data to fill index with
|
||||
*/
|
||||
let indexPopulated = false
|
||||
async function fillDocument(data: ContentIndex) {
|
||||
if (indexPopulated) return
|
||||
async function fillDocument(data: { [key: FullSlug]: ContentDetails }) {
|
||||
let id = 0
|
||||
const promises: Array<Promise<unknown>> = []
|
||||
for (const [slug, fileData] of Object.entries<ContentDetails>(data)) {
|
||||
@@ -481,15 +489,5 @@ async function fillDocument(data: ContentIndex) {
|
||||
)
|
||||
}
|
||||
|
||||
await Promise.all(promises)
|
||||
indexPopulated = true
|
||||
return await Promise.all(promises)
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
})
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import micromorph from "micromorph"
|
||||
import { FullSlug, RelativeURL, getFullSlug, normalizeRelativeURLs } from "../../util/path"
|
||||
import { fetchCanonical } from "./util"
|
||||
|
||||
// adapted from `micromorph`
|
||||
// https://github.com/natemoo-re/micromorph
|
||||
@@ -43,26 +42,10 @@ function notifyNav(url: FullSlug) {
|
||||
const cleanupFns: Set<(...args: any[]) => void> = new Set()
|
||||
window.addCleanup = (fn) => cleanupFns.add(fn)
|
||||
|
||||
function startLoading() {
|
||||
const loadingBar = document.createElement("div")
|
||||
loadingBar.className = "navigation-progress"
|
||||
loadingBar.style.width = "0"
|
||||
if (!document.body.contains(loadingBar)) {
|
||||
document.body.appendChild(loadingBar)
|
||||
}
|
||||
|
||||
setTimeout(() => {
|
||||
loadingBar.style.width = "80%"
|
||||
}, 100)
|
||||
}
|
||||
|
||||
let isNavigating = false
|
||||
let p: DOMParser
|
||||
async function _navigate(url: URL, isBack: boolean = false) {
|
||||
isNavigating = true
|
||||
startLoading()
|
||||
async function navigate(url: URL, isBack: boolean = false) {
|
||||
p = p || new DOMParser()
|
||||
const contents = await fetchCanonical(url)
|
||||
const contents = await fetch(`${url}`)
|
||||
.then((res) => {
|
||||
const contentType = res.headers.get("content-type")
|
||||
if (contentType?.startsWith("text/html")) {
|
||||
@@ -77,10 +60,6 @@ async function _navigate(url: URL, isBack: boolean = false) {
|
||||
|
||||
if (!contents) return
|
||||
|
||||
// notify about to nav
|
||||
const event: CustomEventMap["prenav"] = new CustomEvent("prenav", { detail: {} })
|
||||
document.dispatchEvent(event)
|
||||
|
||||
// cleanup old
|
||||
cleanupFns.forEach((fn) => fn())
|
||||
cleanupFns.clear()
|
||||
@@ -114,7 +93,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])")
|
||||
elementsToRemove.forEach((el) => el.remove())
|
||||
const elementsToAdd = html.head.querySelectorAll(":not([spa-preserve])")
|
||||
@@ -125,24 +104,10 @@ async function _navigate(url: URL, isBack: boolean = false) {
|
||||
if (!isBack) {
|
||||
history.pushState({}, "", url)
|
||||
}
|
||||
|
||||
notifyNav(getFullSlug(window))
|
||||
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
|
||||
|
||||
function createRouter() {
|
||||
@@ -160,13 +125,21 @@ function createRouter() {
|
||||
return
|
||||
}
|
||||
|
||||
navigate(url, false)
|
||||
try {
|
||||
navigate(url, false)
|
||||
} catch (e) {
|
||||
window.location.assign(url)
|
||||
}
|
||||
})
|
||||
|
||||
window.addEventListener("popstate", (event) => {
|
||||
const { url } = getOpts(event) ?? {}
|
||||
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
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
const bufferPx = 150
|
||||
const observer = new IntersectionObserver((entries) => {
|
||||
for (const entry of entries) {
|
||||
const slug = entry.target.id
|
||||
@@ -25,15 +26,17 @@ function toggleToc(this: HTMLElement) {
|
||||
}
|
||||
|
||||
function setupToc() {
|
||||
for (const toc of document.getElementsByClassName("toc")) {
|
||||
const button = toc.querySelector(".toc-header")
|
||||
const content = toc.querySelector(".toc-content")
|
||||
if (!button || !content) return
|
||||
button.addEventListener("click", toggleToc)
|
||||
window.addCleanup(() => button.removeEventListener("click", toggleToc))
|
||||
const toc = document.getElementById("toc")
|
||||
if (toc) {
|
||||
const collapsed = toc.classList.contains("collapsed")
|
||||
const content = toc.nextElementSibling as HTMLElement | undefined
|
||||
if (!content) return
|
||||
toc.addEventListener("click", toggleToc)
|
||||
window.addCleanup(() => toc.removeEventListener("click", toggleToc))
|
||||
}
|
||||
}
|
||||
|
||||
window.addEventListener("resize", setupToc)
|
||||
document.addEventListener("nav", () => {
|
||||
setupToc()
|
||||
|
||||
|
||||
@@ -24,23 +24,3 @@ export function removeAllChildren(node: HTMLElement) {
|
||||
node.removeChild(node.firstChild)
|
||||
}
|
||||
}
|
||||
|
||||
// AliasRedirect emits HTML redirects which also have the link[rel="canonical"]
|
||||
// containing the URL it's redirecting to.
|
||||
// Extracting it here with regex is _probably_ faster than parsing the entire HTML
|
||||
// with a DOMParser effectively twice (here and later in the SPA code), even if
|
||||
// way less robust - we only care about our own generated redirects after all.
|
||||
const canonicalRegex = /<link rel="canonical" href="([^"]*)">/
|
||||
|
||||
export async function fetchCanonical(url: URL): Promise<Response> {
|
||||
const res = await fetch(`${url}`)
|
||||
if (!res.headers.get("content-type")?.startsWith("text/html")) {
|
||||
return res
|
||||
}
|
||||
|
||||
// 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
|
||||
const text = await res.clone().text()
|
||||
const [_, redirect] = text.match(canonicalRegex) ?? []
|
||||
return redirect ? fetch(`${new URL(redirect, url)}`) : res
|
||||
}
|
||||
|
||||
@@ -2,6 +2,18 @@
|
||||
|
||||
.backlinks {
|
||||
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 {
|
||||
font-size: 1rem;
|
||||
@@ -19,4 +31,14 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
& > .overflow {
|
||||
&:after {
|
||||
display: none;
|
||||
}
|
||||
height: auto;
|
||||
@media all and not ($desktop) {
|
||||
height: 250px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
color: var(--gray);
|
||||
|
||||
&[show-comma="true"] {
|
||||
> *:not(:last-child) {
|
||||
> span:not(:last-child) {
|
||||
margin-right: 8px;
|
||||
|
||||
&::after {
|
||||
|
||||
@@ -8,7 +8,6 @@
|
||||
height: 20px;
|
||||
margin: 0 10px;
|
||||
text-align: inherit;
|
||||
flex-shrink: 0;
|
||||
|
||||
& svg {
|
||||
position: absolute;
|
||||
@@ -29,19 +28,19 @@
|
||||
}
|
||||
|
||||
:root[saved-theme="dark"] .darkmode {
|
||||
& > .dayIcon {
|
||||
& > #dayIcon {
|
||||
display: none;
|
||||
}
|
||||
& > .nightIcon {
|
||||
& > #nightIcon {
|
||||
display: inline;
|
||||
}
|
||||
}
|
||||
|
||||
:root .darkmode {
|
||||
& > .dayIcon {
|
||||
& > #dayIcon {
|
||||
display: inline;
|
||||
}
|
||||
& > .nightIcon {
|
||||
& > #nightIcon {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,95 +1,29 @@
|
||||
@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 {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
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;
|
||||
}
|
||||
|
||||
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 {
|
||||
@media all and not ($mobile) {
|
||||
display: flex;
|
||||
}
|
||||
}
|
||||
|
||||
svg {
|
||||
pointer-events: all;
|
||||
transition: transform 0.35s ease;
|
||||
|
||||
& > polyline {
|
||||
pointer-events: none;
|
||||
}
|
||||
}
|
||||
/*&: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));
|
||||
}*/
|
||||
}
|
||||
|
||||
button.mobile-explorer,
|
||||
button.desktop-explorer {
|
||||
button#explorer {
|
||||
background-color: transparent;
|
||||
border: none;
|
||||
text-align: left;
|
||||
@@ -104,46 +38,75 @@ button.desktop-explorer {
|
||||
display: inline-block;
|
||||
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;
|
||||
overflow: hidden;
|
||||
overflow-y: auto;
|
||||
max-height: 100%;
|
||||
transition:
|
||||
max-height 0.35s ease,
|
||||
visibility 0s linear 0s;
|
||||
margin-top: 0.5rem;
|
||||
visibility: visible;
|
||||
|
||||
&.collapsed {
|
||||
max-height: 0;
|
||||
transition:
|
||||
max-height 0.35s ease,
|
||||
visibility 0s linear 0.35s;
|
||||
visibility: hidden;
|
||||
}
|
||||
|
||||
& ul {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
margin: 0.08rem 0;
|
||||
padding: 0;
|
||||
|
||||
transition:
|
||||
max-height 0.35s ease,
|
||||
transform 0.35s ease,
|
||||
opacity 0.2s ease;
|
||||
& li > a {
|
||||
color: var(--dark);
|
||||
opacity: 0.75;
|
||||
pointer-events: all;
|
||||
|
||||
&.active {
|
||||
opacity: 1;
|
||||
color: var(--tertiary);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.folder-outer {
|
||||
display: grid;
|
||||
grid-template-rows: 0fr;
|
||||
transition: grid-template-rows 0.3s ease-in-out;
|
||||
> #explorer-ul {
|
||||
max-height: none;
|
||||
}
|
||||
}
|
||||
|
||||
.folder-outer.open {
|
||||
grid-template-rows: 1fr;
|
||||
}
|
||||
svg {
|
||||
pointer-events: all;
|
||||
|
||||
.folder-outer > ul {
|
||||
overflow: hidden;
|
||||
margin-left: 6px;
|
||||
padding-left: 0.8rem;
|
||||
border-left: 1px solid var(--lightgray);
|
||||
& > polyline {
|
||||
pointer-events: none;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -206,75 +169,13 @@ li:has(> .folder-outer:not(.open)) > .folder-container > svg {
|
||||
color: var(--tertiary);
|
||||
}
|
||||
|
||||
.explorer {
|
||||
@media all and ($mobile) {
|
||||
&.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-background::after {
|
||||
background: none !important;
|
||||
}
|
||||
|
||||
.no-scroll {
|
||||
opacity: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
#explorer-end {
|
||||
// needs height so IntersectionObserver gets triggered
|
||||
height: 4px;
|
||||
// remove default margin from li
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
|
||||
& > .global-graph-icon {
|
||||
& > #global-graph-icon {
|
||||
cursor: pointer;
|
||||
background: none;
|
||||
border: none;
|
||||
@@ -38,7 +38,7 @@
|
||||
}
|
||||
}
|
||||
|
||||
& > .global-graph-outer {
|
||||
& > #global-graph-outer {
|
||||
position: fixed;
|
||||
z-index: 9999;
|
||||
left: 0;
|
||||
@@ -53,7 +53,7 @@
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
& > .global-graph-container {
|
||||
& > #global-graph-container {
|
||||
border: 1px solid var(--lightgray);
|
||||
background-color: var(--light);
|
||||
border-radius: 5px;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
details.toc {
|
||||
details#toc {
|
||||
& summary {
|
||||
cursor: pointer;
|
||||
|
||||
|
||||
@@ -42,7 +42,7 @@
|
||||
}
|
||||
}
|
||||
|
||||
& > .search-container {
|
||||
& > #search-container {
|
||||
position: fixed;
|
||||
contain: layout;
|
||||
z-index: 999;
|
||||
@@ -58,7 +58,7 @@
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
& > .search-space {
|
||||
& > #search-space {
|
||||
width: 65%;
|
||||
margin-top: 12vh;
|
||||
margin-left: auto;
|
||||
@@ -91,7 +91,7 @@
|
||||
}
|
||||
}
|
||||
|
||||
& > .search-layout {
|
||||
& > #search-layout {
|
||||
display: none;
|
||||
flex-direction: row;
|
||||
border: 1px solid var(--lightgray);
|
||||
@@ -102,11 +102,11 @@
|
||||
display: flex;
|
||||
}
|
||||
|
||||
&[data-preview] > .results-container {
|
||||
&[data-preview] > #results-container {
|
||||
flex: 0 0 min(30%, 450px);
|
||||
}
|
||||
|
||||
@media all and not ($mobile) {
|
||||
@media all and not ($tablet) {
|
||||
&[data-preview] {
|
||||
& .result-card > p.preview {
|
||||
display: none;
|
||||
@@ -132,7 +132,7 @@
|
||||
border-radius: 5px;
|
||||
}
|
||||
|
||||
@media all and ($mobile) {
|
||||
@media all and ($tablet) {
|
||||
& > #preview-container {
|
||||
display: none !important;
|
||||
}
|
||||
@@ -150,8 +150,7 @@
|
||||
scroll-margin-top: 2rem;
|
||||
}
|
||||
|
||||
& > .preview-container {
|
||||
flex-grow: 1;
|
||||
& > #preview-container {
|
||||
display: block;
|
||||
overflow: hidden;
|
||||
font-family: inherit;
|
||||
@@ -171,7 +170,7 @@
|
||||
}
|
||||
}
|
||||
|
||||
& > .results-container {
|
||||
& > #results-container {
|
||||
overflow-y: auto;
|
||||
|
||||
& .result-card {
|
||||
|
||||
@@ -4,21 +4,18 @@
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
overflow-y: hidden;
|
||||
min-height: 4rem;
|
||||
flex: 0 1 auto;
|
||||
&:has(button.toc-header.collapsed) {
|
||||
flex: 0 1 1.2rem;
|
||||
&.desktop-only {
|
||||
max-height: 40%;
|
||||
}
|
||||
}
|
||||
|
||||
@media all and not ($mobile) {
|
||||
.toc-header {
|
||||
.toc {
|
||||
display: flex;
|
||||
}
|
||||
}
|
||||
|
||||
button.toc-header {
|
||||
button#toc {
|
||||
background-color: transparent;
|
||||
border: none;
|
||||
text-align: left;
|
||||
@@ -45,9 +42,28 @@ button.toc-header {
|
||||
}
|
||||
}
|
||||
|
||||
.toc-content {
|
||||
#toc-content {
|
||||
list-style: none;
|
||||
overflow: hidden;
|
||||
overflow-y: auto;
|
||||
max-height: 100%;
|
||||
transition:
|
||||
max-height 0.35s ease,
|
||||
visibility 0s linear 0s;
|
||||
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 {
|
||||
list-style: none;
|
||||
@@ -64,6 +80,10 @@ button.toc-header {
|
||||
}
|
||||
}
|
||||
}
|
||||
> ul.overflow {
|
||||
max-height: none;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
@for $i from 0 through 6 {
|
||||
& .depth-#{$i} {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { ComponentType, JSX } from "preact"
|
||||
import { StaticResources, StringResource } from "../util/resources"
|
||||
import { StaticResources } from "../util/resources"
|
||||
import { QuartzPluginData } from "../plugins/vfile"
|
||||
import { GlobalConfiguration } from "../cfg"
|
||||
import { Node } from "hast"
|
||||
@@ -19,9 +19,9 @@ export type QuartzComponentProps = {
|
||||
}
|
||||
|
||||
export type QuartzComponent = ComponentType<QuartzComponentProps> & {
|
||||
css?: StringResource
|
||||
beforeDOMLoaded?: StringResource
|
||||
afterDOMLoaded?: StringResource
|
||||
css?: string
|
||||
beforeDOMLoaded?: string
|
||||
afterDOMLoaded?: string
|
||||
}
|
||||
|
||||
export type QuartzComponentConstructor<Options extends object | undefined = undefined> = (
|
||||
|
||||
@@ -14,7 +14,6 @@ import uk from "./locales/uk-UA"
|
||||
import ru from "./locales/ru-RU"
|
||||
import ko from "./locales/ko-KR"
|
||||
import zh from "./locales/zh-CN"
|
||||
import zhTw from "./locales/zh-TW"
|
||||
import vi from "./locales/vi-VN"
|
||||
import pt from "./locales/pt-BR"
|
||||
import hu from "./locales/hu-HU"
|
||||
@@ -22,10 +21,6 @@ import fa from "./locales/fa-IR"
|
||||
import pl from "./locales/pl-PL"
|
||||
import cs from "./locales/cs-CZ"
|
||||
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 = {
|
||||
"en-US": enUs,
|
||||
@@ -64,7 +59,6 @@ export const TRANSLATIONS = {
|
||||
"ru-RU": ru,
|
||||
"ko-KR": ko,
|
||||
"zh-CN": zh,
|
||||
"zh-TW": zhTw,
|
||||
"vi-VN": vi,
|
||||
"pt-BR": pt,
|
||||
"hu-HU": hu,
|
||||
@@ -72,10 +66,6 @@ export const TRANSLATIONS = {
|
||||
"pl-PL": pl,
|
||||
"cs-CZ": cs,
|
||||
"tr-TR": tr,
|
||||
"th-TH": th,
|
||||
"lt-LT": lt,
|
||||
"fi-FI": fi,
|
||||
"nb-NO": no,
|
||||
} as const
|
||||
|
||||
export const defaultTranslation = "en-US"
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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: "Created with",
|
||||
},
|
||||
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
|
||||
@@ -37,6 +37,7 @@ export const NotFoundPage: QuartzEmitterPlugin = () => {
|
||||
|
||||
const url = new URL(`https://${cfg.baseUrl ?? "example.com"}`)
|
||||
const path = url.pathname as FullSlug
|
||||
const externalResources = pageResources(path, resources)
|
||||
const notFound = i18n(cfg.locale).pages.error.title
|
||||
const [tree, vfile] = defaultProcessedContent({
|
||||
slug,
|
||||
@@ -44,7 +45,6 @@ export const NotFoundPage: QuartzEmitterPlugin = () => {
|
||||
description: notFound,
|
||||
frontmatter: { title: notFound, tags: [] },
|
||||
})
|
||||
const externalResources = pageResources(path, vfile.data, resources)
|
||||
const componentData: QuartzComponentProps = {
|
||||
ctx,
|
||||
fileData: vfile.data,
|
||||
|
||||
@@ -1,17 +1,33 @@
|
||||
import { FilePath, joinSegments, resolveRelative, simplifySlug } from "../../util/path"
|
||||
import { FilePath, FullSlug, joinSegments, resolveRelative, simplifySlug } from "../../util/path"
|
||||
import { QuartzEmitterPlugin } from "../types"
|
||||
import path from "path"
|
||||
import { write } from "./helpers"
|
||||
import DepGraph from "../../depgraph"
|
||||
import { getAliasSlugs } from "../transformers/frontmatter"
|
||||
|
||||
export const AliasRedirects: QuartzEmitterPlugin = () => ({
|
||||
name: "AliasRedirects",
|
||||
getQuartzComponents() {
|
||||
return []
|
||||
},
|
||||
async getDependencyGraph(ctx, content, _resources) {
|
||||
const graph = new DepGraph<FilePath>()
|
||||
|
||||
const { argv } = ctx
|
||||
for (const [_tree, file] of content) {
|
||||
for (const slug of getAliasSlugs(file.data.frontmatter?.aliases ?? [], argv, 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)
|
||||
}
|
||||
}
|
||||
@@ -19,12 +35,25 @@ export const AliasRedirects: QuartzEmitterPlugin = () => ({
|
||||
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
|
||||
}
|
||||
|
||||
for (const slug of file.data.aliases ?? []) {
|
||||
const redirUrl = resolveRelative(slug, file.data.slug!)
|
||||
const fp = await write({
|
||||
ctx,
|
||||
|
||||
@@ -15,6 +15,9 @@ const filesToCopy = async (argv: Argv, cfg: QuartzConfig) => {
|
||||
export const Assets: QuartzEmitterPlugin = () => {
|
||||
return {
|
||||
name: "Assets",
|
||||
getQuartzComponents() {
|
||||
return []
|
||||
},
|
||||
async getDependencyGraph(ctx, _content, _resources) {
|
||||
const { argv, cfg } = ctx
|
||||
const graph = new DepGraph<FilePath>()
|
||||
|
||||
@@ -11,6 +11,9 @@ export function extractDomainFromBaseUrl(baseUrl: string) {
|
||||
|
||||
export const CNAME: QuartzEmitterPlugin = () => ({
|
||||
name: "CNAME",
|
||||
getQuartzComponents() {
|
||||
return []
|
||||
},
|
||||
async getDependencyGraph(_ctx, _content, _resources) {
|
||||
return new DepGraph<FilePath>()
|
||||
},
|
||||
|
||||
@@ -24,7 +24,7 @@ type ComponentResources = {
|
||||
function getComponentResources(ctx: BuildCtx): ComponentResources {
|
||||
const allComponents: Set<QuartzComponent> = new Set()
|
||||
for (const emitter of ctx.cfg.plugins.emitters) {
|
||||
const components = emitter.getQuartzComponents?.(ctx) ?? []
|
||||
const components = emitter.getQuartzComponents(ctx)
|
||||
for (const component of components) {
|
||||
allComponents.add(component)
|
||||
}
|
||||
@@ -36,21 +36,17 @@ function getComponentResources(ctx: BuildCtx): ComponentResources {
|
||||
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) {
|
||||
const { css, beforeDOMLoaded, afterDOMLoaded } = component
|
||||
const normalizedCss = normalizeResource(css)
|
||||
const normalizedBeforeDOMLoaded = normalizeResource(beforeDOMLoaded)
|
||||
const normalizedAfterDOMLoaded = normalizeResource(afterDOMLoaded)
|
||||
|
||||
normalizedCss.forEach((c) => componentResources.css.add(c))
|
||||
normalizedBeforeDOMLoaded.forEach((b) => componentResources.beforeDOMLoaded.add(b))
|
||||
normalizedAfterDOMLoaded.forEach((a) => componentResources.afterDOMLoaded.add(a))
|
||||
if (css) {
|
||||
componentResources.css.add(css)
|
||||
}
|
||||
if (beforeDOMLoaded) {
|
||||
componentResources.beforeDOMLoaded.add(beforeDOMLoaded)
|
||||
}
|
||||
if (afterDOMLoaded) {
|
||||
componentResources.afterDOMLoaded.add(afterDOMLoaded)
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -120,13 +116,9 @@ function addGlobalPageResources(ctx: BuildCtx, componentResources: ComponentReso
|
||||
const umamiScript = document.createElement("script")
|
||||
umamiScript.src = "${cfg.analytics.host ?? "https://analytics.umami.is"}/script.js"
|
||||
umamiScript.setAttribute("data-website-id", "${cfg.analytics.websiteId}")
|
||||
umamiScript.setAttribute("data-auto-track", "false")
|
||||
umamiScript.async = true
|
||||
document.head.appendChild(umamiScript)
|
||||
|
||||
document.addEventListener("nav", () => {
|
||||
umami.track();
|
||||
})
|
||||
document.head.appendChild(umamiScript)
|
||||
`)
|
||||
} else if (cfg.analytics?.provider === "goatcounter") {
|
||||
componentResources.afterDOMLoaded.push(`
|
||||
@@ -136,37 +128,21 @@ function addGlobalPageResources(ctx: BuildCtx, componentResources: ComponentReso
|
||||
goatcounterScript.setAttribute("data-goatcounter",
|
||||
"https://${cfg.analytics.websiteId}.${cfg.analytics.host ?? "goatcounter.com"}/count")
|
||||
document.head.appendChild(goatcounterScript)
|
||||
|
||||
window.goatcounter = { no_onload: true }
|
||||
document.addEventListener("nav", () => {
|
||||
goatcounter.count({ path: location.pathname })
|
||||
})
|
||||
`)
|
||||
} else if (cfg.analytics?.provider === "posthog") {
|
||||
componentResources.afterDOMLoaded.push(`
|
||||
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||[]);
|
||||
posthog.init('${cfg.analytics.apiKey}', {
|
||||
api_host: '${cfg.analytics.host ?? "https://app.posthog.com"}',
|
||||
capture_pageview: false,
|
||||
})\`
|
||||
posthog.init('${cfg.analytics.apiKey}',{api_host:'${cfg.analytics.host ?? "https://app.posthog.com"}'})\`
|
||||
document.head.appendChild(posthogScript)
|
||||
|
||||
document.addEventListener("nav", () => {
|
||||
posthog.capture('$pageview', { path: location.pathname })
|
||||
})
|
||||
`)
|
||||
} else if (cfg.analytics?.provider === "tinylytics") {
|
||||
const siteId = cfg.analytics.siteId
|
||||
componentResources.afterDOMLoaded.push(`
|
||||
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
|
||||
document.head.appendChild(tinylyticsScript)
|
||||
|
||||
document.addEventListener("nav", () => {
|
||||
window.tinylytics.triggerUpdate()
|
||||
})
|
||||
`)
|
||||
} else if (cfg.analytics?.provider === "cabin") {
|
||||
componentResources.afterDOMLoaded.push(`
|
||||
@@ -204,6 +180,9 @@ function addGlobalPageResources(ctx: BuildCtx, componentResources: ComponentReso
|
||||
export const ComponentResources: QuartzEmitterPlugin = () => {
|
||||
return {
|
||||
name: "ComponentResources",
|
||||
getQuartzComponents() {
|
||||
return []
|
||||
},
|
||||
async getDependencyGraph(_ctx, _content, _resources) {
|
||||
return new DepGraph<FilePath>()
|
||||
},
|
||||
|
||||
@@ -9,9 +9,8 @@ import { write } from "./helpers"
|
||||
import { i18n } from "../../i18n"
|
||||
import DepGraph from "../../depgraph"
|
||||
|
||||
export type ContentIndexMap = Map<FullSlug, ContentDetails>
|
||||
export type ContentIndex = Map<FullSlug, ContentDetails>
|
||||
export type ContentDetails = {
|
||||
slug: FullSlug
|
||||
title: string
|
||||
links: SimpleSlug[]
|
||||
tags: string[]
|
||||
@@ -26,7 +25,6 @@ interface Options {
|
||||
enableRSS: boolean
|
||||
rssLimit?: number
|
||||
rssFullHtml: boolean
|
||||
rssSlug: string
|
||||
includeEmptyFiles: boolean
|
||||
}
|
||||
|
||||
@@ -35,11 +33,10 @@ const defaultOptions: Options = {
|
||||
enableRSS: true,
|
||||
rssLimit: 10,
|
||||
rssFullHtml: false,
|
||||
rssSlug: "index",
|
||||
includeEmptyFiles: true,
|
||||
}
|
||||
|
||||
function generateSiteMap(cfg: GlobalConfiguration, idx: ContentIndexMap): string {
|
||||
function generateSiteMap(cfg: GlobalConfiguration, idx: ContentIndex): string {
|
||||
const base = cfg.baseUrl ?? ""
|
||||
const createURLEntry = (slug: SimpleSlug, content: ContentDetails): string => `<url>
|
||||
<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>`
|
||||
}
|
||||
|
||||
function generateRSSFeed(cfg: GlobalConfiguration, idx: ContentIndexMap, limit?: number): string {
|
||||
function generateRSSFeed(cfg: GlobalConfiguration, idx: ContentIndex, limit?: number): string {
|
||||
const base = cfg.baseUrl ?? ""
|
||||
|
||||
const createURLEntry = (slug: SimpleSlug, content: ContentDetails): string => `<item>
|
||||
@@ -119,13 +116,12 @@ export const ContentIndex: QuartzEmitterPlugin<Partial<Options>> = (opts) => {
|
||||
async emit(ctx, content, _resources) {
|
||||
const cfg = ctx.cfg.configuration
|
||||
const emitted: FilePath[] = []
|
||||
const linkIndex: ContentIndexMap = new Map()
|
||||
const linkIndex: ContentIndex = new Map()
|
||||
for (const [tree, file] of content) {
|
||||
const slug = file.data.slug!
|
||||
const date = getDate(ctx.cfg.configuration, file.data) ?? new Date()
|
||||
if (opts?.includeEmptyFiles || (file.data.text && file.data.text !== "")) {
|
||||
linkIndex.set(slug, {
|
||||
slug,
|
||||
title: file.data.frontmatter?.title!,
|
||||
links: file.data.links ?? [],
|
||||
tags: file.data.frontmatter?.tags ?? [],
|
||||
@@ -155,7 +151,7 @@ export const ContentIndex: QuartzEmitterPlugin<Partial<Options>> = (opts) => {
|
||||
await write({
|
||||
ctx,
|
||||
content: generateRSSFeed(cfg, linkIndex, opts.rssLimit),
|
||||
slug: (opts?.rssSlug ?? "index") as FullSlug,
|
||||
slug: "index" as FullSlug,
|
||||
ext: ".xml",
|
||||
}),
|
||||
)
|
||||
@@ -184,19 +180,6 @@ export const ContentIndex: QuartzEmitterPlugin<Partial<Options>> = (opts) => {
|
||||
|
||||
return emitted
|
||||
},
|
||||
externalResources: (ctx) => {
|
||||
if (opts?.enableRSS) {
|
||||
return {
|
||||
additionalHead: [
|
||||
<link
|
||||
rel="alternate"
|
||||
type="application/rss+xml"
|
||||
title="RSS Feed"
|
||||
href={`https://${ctx.cfg.configuration.baseUrl}/index.xml`}
|
||||
/>,
|
||||
],
|
||||
}
|
||||
}
|
||||
},
|
||||
getQuartzComponents: () => [],
|
||||
}
|
||||
}
|
||||
@@ -106,7 +106,7 @@ export const ContentPage: QuartzEmitterPlugin<Partial<FullPageLayout>> = (userOp
|
||||
containsIndex = true
|
||||
}
|
||||
|
||||
const externalResources = pageResources(pathToRoot(slug), file.data, resources)
|
||||
const externalResources = pageResources(pathToRoot(slug), resources)
|
||||
const componentData: QuartzComponentProps = {
|
||||
ctx,
|
||||
fileData: file.data,
|
||||
@@ -131,7 +131,7 @@ export const ContentPage: QuartzEmitterPlugin<Partial<FullPageLayout>> = (userOp
|
||||
if (!containsIndex && !ctx.argv.fastRebuild) {
|
||||
console.log(
|
||||
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.`,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -106,8 +106,8 @@ export const FolderPage: QuartzEmitterPlugin<Partial<FolderPageOptions>> = (user
|
||||
|
||||
for (const folder of folders) {
|
||||
const slug = joinSegments(folder, "index") as FullSlug
|
||||
const externalResources = pageResources(pathToRoot(slug), resources)
|
||||
const [tree, file] = folderDescriptions[folder]
|
||||
const externalResources = pageResources(pathToRoot(slug), file.data, resources)
|
||||
const componentData: QuartzComponentProps = {
|
||||
ctx,
|
||||
fileData: file.data,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
export { ContentPage } from "./contentPage"
|
||||
export { TagPage } from "./tagPage"
|
||||
export { FolderPage } from "./folderPage"
|
||||
export { ContentIndex as ContentIndex } from "./contentIndex"
|
||||
export { ContentIndex } from "./contentIndex"
|
||||
export { AliasRedirects } from "./aliases"
|
||||
export { Assets } from "./assets"
|
||||
export { Static } from "./static"
|
||||
|
||||
@@ -6,6 +6,9 @@ import DepGraph from "../../depgraph"
|
||||
|
||||
export const Static: QuartzEmitterPlugin = () => ({
|
||||
name: "Static",
|
||||
getQuartzComponents() {
|
||||
return []
|
||||
},
|
||||
async getDependencyGraph({ argv, cfg }, _content, _resources) {
|
||||
const graph = new DepGraph<FilePath>()
|
||||
|
||||
|
||||
@@ -105,17 +105,14 @@ export const TagPage: QuartzEmitterPlugin<Partial<TagPageOptions>> = (userOpts)
|
||||
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 externalResources = pageResources(pathToRoot(slug), resources)
|
||||
const [tree, file] = tagDescriptions[tag]
|
||||
const externalResources = pageResources(pathToRoot(slug), file.data, resources)
|
||||
const componentData: QuartzComponentProps = {
|
||||
ctx,
|
||||
fileData: file.data,
|
||||
|
||||
@@ -6,10 +6,9 @@ export function getStaticResourcesFromPlugins(ctx: BuildCtx) {
|
||||
const staticResources: StaticResources = {
|
||||
css: [],
|
||||
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) : {}
|
||||
if (res?.js) {
|
||||
staticResources.js.push(...res.js)
|
||||
@@ -17,9 +16,6 @@ export function getStaticResourcesFromPlugins(ctx: BuildCtx) {
|
||||
if (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
|
||||
|
||||
@@ -3,12 +3,9 @@ import remarkFrontmatter from "remark-frontmatter"
|
||||
import { QuartzTransformerPlugin } from "../types"
|
||||
import yaml from "js-yaml"
|
||||
import toml from "toml"
|
||||
import { FilePath, FullSlug, joinSegments, slugifyFilePath, slugTag } from "../../util/path"
|
||||
import { slugTag } from "../../util/path"
|
||||
import { QuartzPluginData } from "../vfile"
|
||||
import { i18n } from "../../i18n"
|
||||
import { Argv } from "../../util/ctx"
|
||||
import { VFile } from "vfile"
|
||||
import path from "path"
|
||||
|
||||
export interface Options {
|
||||
delimiters: string | [string, string]
|
||||
@@ -43,32 +40,16 @@ function coerceToArray(input: string | string[]): string[] | undefined {
|
||||
.map((tag: string | number) => tag.toString())
|
||||
}
|
||||
|
||||
export function getAliasSlugs(aliases: string[], argv: Argv, file: VFile): FullSlug[] {
|
||||
const dir = path.posix.relative(argv.directory, path.dirname(file.data.filePath!))
|
||||
const slugs: FullSlug[] = aliases.map(
|
||||
(alias) => path.posix.join(dir, slugifyFilePath(alias as FilePath)) as FullSlug,
|
||||
)
|
||||
const permalink = file.data.frontmatter?.permalink
|
||||
if (typeof permalink === "string") {
|
||||
slugs.push(permalink as FullSlug)
|
||||
}
|
||||
// fix any slugs that have trailing slash
|
||||
return slugs.map((slug) =>
|
||||
slug.endsWith("/") ? (joinSegments(slug, "index") as FullSlug) : slug,
|
||||
)
|
||||
}
|
||||
|
||||
export const FrontMatter: QuartzTransformerPlugin<Partial<Options>> = (userOpts) => {
|
||||
const opts = { ...defaultOptions, ...userOpts }
|
||||
return {
|
||||
name: "FrontMatter",
|
||||
markdownPlugins({ cfg, allSlugs, argv }) {
|
||||
markdownPlugins({ cfg }) {
|
||||
return [
|
||||
[remarkFrontmatter, ["yaml", "toml"]],
|
||||
() => {
|
||||
return (_, file) => {
|
||||
const fileData = Buffer.from(file.value as Uint8Array)
|
||||
const { data } = matter(fileData, {
|
||||
const { data } = matter(Buffer.from(file.value), {
|
||||
...opts,
|
||||
engines: {
|
||||
yaml: (s) => yaml.load(s, { schema: yaml.JSON_SCHEMA }) as object,
|
||||
@@ -86,28 +67,12 @@ export const FrontMatter: QuartzTransformerPlugin<Partial<Options>> = (userOpts)
|
||||
if (tags) data.tags = [...new Set(tags.map((tag: string) => slugTag(tag)))]
|
||||
|
||||
const aliases = coerceToArray(coalesceAliases(data, ["aliases", "alias"]))
|
||||
if (aliases) {
|
||||
data.aliases = aliases // frontmatter
|
||||
const slugs = (file.data.aliases = getAliasSlugs(aliases, argv, file))
|
||||
allSlugs.push(...slugs)
|
||||
}
|
||||
if (aliases) data.aliases = aliases
|
||||
const cssclasses = coerceToArray(coalesceAliases(data, ["cssclasses", "cssclass"]))
|
||||
if (cssclasses) data.cssclasses = cssclasses
|
||||
|
||||
const socialImage = coalesceAliases(data, ["socialImage", "image", "cover"])
|
||||
|
||||
const created = coalesceAliases(data, ["created", "date"])
|
||||
if (created) data.created = created
|
||||
const modified = coalesceAliases(data, [
|
||||
"modified",
|
||||
"lastmod",
|
||||
"updated",
|
||||
"last-modified",
|
||||
])
|
||||
if (modified) data.modified = modified
|
||||
const published = coalesceAliases(data, ["published", "publishDate", "date"])
|
||||
if (published) data.published = published
|
||||
|
||||
if (socialImage) data.socialImage = socialImage
|
||||
|
||||
// fill in frontmatter
|
||||
@@ -121,15 +86,11 @@ export const FrontMatter: QuartzTransformerPlugin<Partial<Options>> = (userOpts)
|
||||
|
||||
declare module "vfile" {
|
||||
interface DataMap {
|
||||
aliases: FullSlug[]
|
||||
frontmatter: { [key: string]: unknown } & {
|
||||
title: string
|
||||
} & Partial<{
|
||||
tags: string[]
|
||||
aliases: string[]
|
||||
modified: string
|
||||
created: string
|
||||
published: string
|
||||
description: string
|
||||
publish: boolean | string
|
||||
draft: boolean | string
|
||||
|
||||
@@ -48,9 +48,11 @@ export const CreatedModifiedDate: QuartzTransformerPlugin<Partial<Options>> = (u
|
||||
created ||= st.birthtimeMs
|
||||
modified ||= st.mtimeMs
|
||||
} else if (source === "frontmatter" && file.data.frontmatter) {
|
||||
created ||= file.data.frontmatter.created as MaybeDate
|
||||
modified ||= file.data.frontmatter.modified as MaybeDate
|
||||
published ||= file.data.frontmatter.published as MaybeDate
|
||||
created ||= file.data.frontmatter.date as MaybeDate
|
||||
modified ||= file.data.frontmatter.lastmod as MaybeDate
|
||||
modified ||= file.data.frontmatter.updated as MaybeDate
|
||||
modified ||= file.data.frontmatter["last-modified"] as MaybeDate
|
||||
published ||= file.data.frontmatter.publishDate as MaybeDate
|
||||
} else if (source === "git") {
|
||||
if (!repo) {
|
||||
// Get a reference to the main git repo.
|
||||
|
||||
@@ -59,6 +59,8 @@ export const Latex: QuartzTransformerPlugin<Partial<Options>> = (opts) => {
|
||||
},
|
||||
],
|
||||
}
|
||||
default:
|
||||
return { css: [], js: [] }
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
@@ -1,13 +1,5 @@
|
||||
import { QuartzTransformerPlugin } from "../types"
|
||||
import {
|
||||
Root,
|
||||
Html,
|
||||
BlockContent,
|
||||
PhrasingContent,
|
||||
DefinitionContent,
|
||||
Paragraph,
|
||||
Code,
|
||||
} from "mdast"
|
||||
import { Root, Html, BlockContent, DefinitionContent, Paragraph, Code } from "mdast"
|
||||
import { Element, Literal, Root as HtmlRoot } from "hast"
|
||||
import { ReplaceFunction, findAndReplace as mdastFindReplace } from "mdast-util-find-and-replace"
|
||||
import rehypeRaw from "rehype-raw"
|
||||
@@ -16,15 +8,16 @@ import path from "path"
|
||||
import { splitAnchor } from "../../util/path"
|
||||
import { JSResource, CSSResource } from "../../util/resources"
|
||||
// @ts-ignore
|
||||
import calloutScript from "../../components/scripts/callout.inline"
|
||||
import calloutScript from "../../components/scripts/callout.inline.ts"
|
||||
// @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 mermaidExtensionScript from "../../components/scripts/mermaid.inline.ts"
|
||||
import mermaidStyle from "../../components/styles/mermaid.inline.scss"
|
||||
import { FilePath, pathToRoot, slugTag, slugifyFilePath } from "../../util/path"
|
||||
import { toHast } from "mdast-util-to-hast"
|
||||
import { toHtml } from "hast-util-to-html"
|
||||
import { PhrasingContent } from "mdast-util-find-and-replace/lib"
|
||||
import { capitalize } from "../../util/lang"
|
||||
import { PluggableList } from "unified"
|
||||
|
||||
@@ -131,12 +124,12 @@ const commentRegex = new RegExp(/%%[\s\S]*?%%/g)
|
||||
// from https://github.com/escwxyz/remark-obsidian-callout/blob/main/src/index.ts
|
||||
const calloutRegex = new RegExp(/^\[\!([\w-]+)\|?(.+?)?\]([+-]?)/)
|
||||
const calloutLineRegex = new RegExp(/^> *\[\!\w+\|?.*?\][+-]?.*$/gm)
|
||||
// (?<=^| ) -> a lookbehind assertion, tag should start be separated by a space or be the start of the line
|
||||
// (?:^| ) -> non-capturing group, tag should start be separated by a space or be the start of the line
|
||||
// #(...) -> capturing group, tag itself must start with #
|
||||
// (?:[-_\p{L}\d\p{Z}])+ -> non-capturing group, non-empty string of (Unicode-aware) alpha-numeric characters and symbols, hyphens and/or underscores
|
||||
// (?:\/[-_\p{L}\d\p{Z}]+)*) -> non-capturing group, matches an arbitrary number of tag strings separated by "/"
|
||||
const tagRegex = new RegExp(
|
||||
/(?<=^| )#((?:[-_\p{L}\p{Emoji}\p{M}\d])+(?:\/[-_\p{L}\p{Emoji}\p{M}\d]+)*)/gu,
|
||||
/(?:^| )#((?:[-_\p{L}\p{Emoji}\p{M}\d])+(?:\/[-_\p{L}\p{Emoji}\p{M}\d]+)*)/gu,
|
||||
)
|
||||
const blockReferenceRegex = new RegExp(/\^([-_A-Za-z0-9]+)$/g)
|
||||
const ytLinkRegex = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/
|
||||
@@ -159,11 +152,19 @@ export const ObsidianFlavoredMarkdown: QuartzTransformerPlugin<Partial<Options>>
|
||||
textTransform(_ctx, src) {
|
||||
// do comments at text level
|
||||
if (opts.comments) {
|
||||
if (src instanceof Buffer) {
|
||||
src = src.toString()
|
||||
}
|
||||
|
||||
src = src.replace(commentRegex, "")
|
||||
}
|
||||
|
||||
// pre-transform blockquotes
|
||||
if (opts.callouts) {
|
||||
if (src instanceof Buffer) {
|
||||
src = src.toString()
|
||||
}
|
||||
|
||||
src = src.replace(calloutLineRegex, (value) => {
|
||||
// force newline after title of callout
|
||||
return value + "\n> "
|
||||
@@ -172,6 +173,10 @@ export const ObsidianFlavoredMarkdown: QuartzTransformerPlugin<Partial<Options>>
|
||||
|
||||
// pre-transform wikilinks (fix anchors to things that may contain illegal syntax e.g. codeblocks, latex)
|
||||
if (opts.wikilinks) {
|
||||
if (src instanceof Buffer) {
|
||||
src = src.toString()
|
||||
}
|
||||
|
||||
// replace all wikilinks inside a table first
|
||||
src = src.replace(tableRegex, (value) => {
|
||||
// escape all aliases and headers in wikilinks inside a table
|
||||
@@ -508,10 +513,9 @@ export const ObsidianFlavoredMarkdown: QuartzTransformerPlugin<Partial<Options>>
|
||||
|
||||
if (opts.mermaid) {
|
||||
plugins.push(() => {
|
||||
return (tree: Root, file) => {
|
||||
return (tree: Root, _file) => {
|
||||
visit(tree, "code", (node: Code) => {
|
||||
if (node.lang === "mermaid") {
|
||||
file.data.hasMermaidDiagram = true
|
||||
node.data = {
|
||||
hProperties: {
|
||||
className: ["mermaid"],
|
||||
@@ -811,12 +815,11 @@ export const ObsidianFlavoredMarkdown: QuartzTransformerPlugin<Partial<Options>>
|
||||
|
||||
if (opts.mermaid) {
|
||||
js.push({
|
||||
script: mermaidScript,
|
||||
script: mermaidExtensionScript,
|
||||
loadTime: "afterDOMReady",
|
||||
contentType: "inline",
|
||||
moduleType: "module",
|
||||
contentType: "inline",
|
||||
})
|
||||
|
||||
css.push({
|
||||
content: mermaidStyle,
|
||||
inline: true,
|
||||
@@ -832,6 +835,5 @@ declare module "vfile" {
|
||||
interface DataMap {
|
||||
blocks: Record<string, Element>
|
||||
htmlAst: HtmlRoot
|
||||
hasMermaidDiagram: boolean | undefined
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,16 +13,15 @@ export interface PluginTypes {
|
||||
}
|
||||
|
||||
type OptionType = object | undefined
|
||||
type ExternalResourcesFn = (ctx: BuildCtx) => Partial<StaticResources> | undefined
|
||||
export type QuartzTransformerPlugin<Options extends OptionType = undefined> = (
|
||||
opts?: Options,
|
||||
) => QuartzTransformerPluginInstance
|
||||
export type QuartzTransformerPluginInstance = {
|
||||
name: string
|
||||
textTransform?: (ctx: BuildCtx, src: string) => string
|
||||
textTransform?: (ctx: BuildCtx, src: string | Buffer) => string | Buffer
|
||||
markdownPlugins?: (ctx: BuildCtx) => PluggableList
|
||||
htmlPlugins?: (ctx: BuildCtx) => PluggableList
|
||||
externalResources?: ExternalResourcesFn
|
||||
externalResources?: (ctx: BuildCtx) => Partial<StaticResources>
|
||||
}
|
||||
|
||||
export type QuartzFilterPlugin<Options extends OptionType = undefined> = (
|
||||
@@ -39,16 +38,10 @@ export type QuartzEmitterPlugin<Options extends OptionType = undefined> = (
|
||||
export type QuartzEmitterPluginInstance = {
|
||||
name: string
|
||||
emit(ctx: BuildCtx, content: ProcessedContent[], resources: StaticResources): Promise<FilePath[]>
|
||||
/**
|
||||
* Returns the components (if any) that are used in rendering the page.
|
||||
* This helps Quartz optimize the page by only including necessary resources
|
||||
* for components that are actually used.
|
||||
*/
|
||||
getQuartzComponents?: (ctx: BuildCtx) => QuartzComponent[]
|
||||
getQuartzComponents(ctx: BuildCtx): QuartzComponent[]
|
||||
getDependencyGraph?(
|
||||
ctx: BuildCtx,
|
||||
content: ProcessedContent[],
|
||||
resources: StaticResources,
|
||||
): Promise<DepGraph<FilePath>>
|
||||
externalResources?: ExternalResourcesFn
|
||||
}
|
||||
|
||||
@@ -1,13 +1,11 @@
|
||||
import { Root as HtmlRoot } from "hast"
|
||||
import { Root as MdRoot } from "mdast"
|
||||
import { Node, Parent } from "hast"
|
||||
import { Data, VFile } from "vfile"
|
||||
|
||||
export type QuartzPluginData = Data
|
||||
export type MarkdownContent = [MdRoot, VFile]
|
||||
export type ProcessedContent = [HtmlRoot, VFile]
|
||||
export type ProcessedContent = [Node, VFile]
|
||||
|
||||
export function defaultProcessedContent(vfileData: Partial<QuartzPluginData>): ProcessedContent {
|
||||
const root: HtmlRoot = { type: "root", children: [] }
|
||||
const root: Parent = { type: "root", children: [] }
|
||||
const vfile = new VFile("")
|
||||
vfile.data = vfileData
|
||||
return [root, vfile]
|
||||
|
||||
@@ -4,20 +4,18 @@ import remarkRehype from "remark-rehype"
|
||||
import { Processor, unified } from "unified"
|
||||
import { Root as MDRoot } from "remark-parse/lib"
|
||||
import { Root as HTMLRoot } from "hast"
|
||||
import { MarkdownContent, ProcessedContent } from "../plugins/vfile"
|
||||
import { ProcessedContent } from "../plugins/vfile"
|
||||
import { PerfTimer } from "../util/perf"
|
||||
import { read } from "to-vfile"
|
||||
import { FilePath, FullSlug, QUARTZ, slugifyFilePath } from "../util/path"
|
||||
import { FilePath, QUARTZ, slugifyFilePath } from "../util/path"
|
||||
import path from "path"
|
||||
import workerpool, { Promise as WorkerPromise } from "workerpool"
|
||||
import { QuartzLogger } from "../util/log"
|
||||
import { trace } from "../util/trace"
|
||||
import { BuildCtx } from "../util/ctx"
|
||||
|
||||
export type QuartzMdProcessor = Processor<MDRoot, MDRoot, MDRoot>
|
||||
export type QuartzHtmlProcessor = Processor<undefined, MDRoot, HTMLRoot>
|
||||
|
||||
export function createMdProcessor(ctx: BuildCtx): QuartzMdProcessor {
|
||||
export type QuartzProcessor = Processor<MDRoot, MDRoot, HTMLRoot>
|
||||
export function createProcessor(ctx: BuildCtx): QuartzProcessor {
|
||||
const transformers = ctx.cfg.plugins.transformers
|
||||
|
||||
return (
|
||||
@@ -26,20 +24,14 @@ export function createMdProcessor(ctx: BuildCtx): QuartzMdProcessor {
|
||||
.use(remarkParse)
|
||||
// MD AST -> MD AST transforms
|
||||
.use(
|
||||
transformers.flatMap((plugin) => plugin.markdownPlugins?.(ctx) ?? []),
|
||||
) as unknown as QuartzMdProcessor
|
||||
// ^ sadly the typing of `use` is not smart enough to infer the correct type from our plugin list
|
||||
)
|
||||
}
|
||||
|
||||
export function createHtmlProcessor(ctx: BuildCtx): QuartzHtmlProcessor {
|
||||
const transformers = ctx.cfg.plugins.transformers
|
||||
return (
|
||||
unified()
|
||||
transformers
|
||||
.filter((p) => p.markdownPlugins)
|
||||
.flatMap((plugin) => plugin.markdownPlugins!(ctx)),
|
||||
)
|
||||
// MD AST -> HTML AST
|
||||
.use(remarkRehype, { allowDangerousHtml: true })
|
||||
// HTML AST -> HTML AST transforms
|
||||
.use(transformers.flatMap((plugin) => plugin.htmlPlugins?.(ctx) ?? []))
|
||||
.use(transformers.filter((p) => p.htmlPlugins).flatMap((plugin) => plugin.htmlPlugins!(ctx)))
|
||||
)
|
||||
}
|
||||
|
||||
@@ -83,8 +75,8 @@ async function transpileWorkerScript() {
|
||||
|
||||
export function createFileParser(ctx: BuildCtx, fps: FilePath[]) {
|
||||
const { argv, cfg } = ctx
|
||||
return async (processor: QuartzMdProcessor) => {
|
||||
const res: MarkdownContent[] = []
|
||||
return async (processor: QuartzProcessor) => {
|
||||
const res: ProcessedContent[] = []
|
||||
for (const fp of fps) {
|
||||
try {
|
||||
const perf = new PerfTimer()
|
||||
@@ -108,32 +100,10 @@ export function createFileParser(ctx: BuildCtx, fps: FilePath[]) {
|
||||
res.push([newAst, file])
|
||||
|
||||
if (argv.verbose) {
|
||||
console.log(`[markdown] ${fp} -> ${file.data.slug} (${perf.timeSince()})`)
|
||||
console.log(`[process] ${fp} -> ${file.data.slug} (${perf.timeSince()})`)
|
||||
}
|
||||
} catch (err) {
|
||||
trace(`\nFailed to process markdown \`${fp}\``, err as Error)
|
||||
}
|
||||
}
|
||||
|
||||
return res
|
||||
}
|
||||
}
|
||||
|
||||
export function createMarkdownParser(ctx: BuildCtx, mdContent: MarkdownContent[]) {
|
||||
return async (processor: QuartzHtmlProcessor) => {
|
||||
const res: ProcessedContent[] = []
|
||||
for (const [ast, file] of mdContent) {
|
||||
try {
|
||||
const perf = new PerfTimer()
|
||||
|
||||
const newAst = await processor.run(ast as MDRoot, file)
|
||||
res.push([newAst, file])
|
||||
|
||||
if (ctx.argv.verbose) {
|
||||
console.log(`[html] ${file.data.slug} (${perf.timeSince()})`)
|
||||
}
|
||||
} catch (err) {
|
||||
trace(`\nFailed to process html \`${file.data.filePath}\``, err as Error)
|
||||
trace(`\nFailed to process \`${fp}\``, err as Error)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -143,7 +113,6 @@ export function createMarkdownParser(ctx: BuildCtx, mdContent: MarkdownContent[]
|
||||
|
||||
const clamp = (num: number, min: number, max: number) =>
|
||||
Math.min(Math.max(Math.round(num), min), max)
|
||||
|
||||
export async function parseMarkdown(ctx: BuildCtx, fps: FilePath[]): Promise<ProcessedContent[]> {
|
||||
const { argv } = ctx
|
||||
const perf = new PerfTimer()
|
||||
@@ -157,8 +126,9 @@ export async function parseMarkdown(ctx: BuildCtx, fps: FilePath[]): Promise<Pro
|
||||
log.start(`Parsing input files using ${concurrency} threads`)
|
||||
if (concurrency === 1) {
|
||||
try {
|
||||
const mdRes = await createFileParser(ctx, fps)(createMdProcessor(ctx))
|
||||
res = await createMarkdownParser(ctx, mdRes)(createHtmlProcessor(ctx))
|
||||
const processor = createProcessor(ctx)
|
||||
const parse = createFileParser(ctx, fps)
|
||||
res = await parse(processor)
|
||||
} catch (error) {
|
||||
log.end()
|
||||
throw error
|
||||
@@ -170,27 +140,17 @@ export async function parseMarkdown(ctx: BuildCtx, fps: FilePath[]): Promise<Pro
|
||||
maxWorkers: concurrency,
|
||||
workerType: "thread",
|
||||
})
|
||||
const errorHandler = (err: any) => {
|
||||
console.error(`${err}`.replace(/^error:\s*/i, ""))
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const mdPromises: WorkerPromise<[MarkdownContent[], FullSlug[]]>[] = []
|
||||
for (const chunk of chunks(fps, CHUNK_SIZE)) {
|
||||
mdPromises.push(pool.exec("parseMarkdown", [ctx.buildId, argv, chunk]))
|
||||
}
|
||||
const mdResults: [MarkdownContent[], FullSlug[]][] =
|
||||
await WorkerPromise.all(mdPromises).catch(errorHandler)
|
||||
|
||||
const childPromises: WorkerPromise<ProcessedContent[]>[] = []
|
||||
for (const [_, extraSlugs] of mdResults) {
|
||||
ctx.allSlugs.push(...extraSlugs)
|
||||
for (const chunk of chunks(fps, CHUNK_SIZE)) {
|
||||
childPromises.push(pool.exec("parseFiles", [ctx.buildId, argv, chunk, ctx.allSlugs]))
|
||||
}
|
||||
for (const [mdChunk, _] of mdResults) {
|
||||
childPromises.push(pool.exec("processHtml", [ctx.buildId, argv, mdChunk, ctx.allSlugs]))
|
||||
}
|
||||
const results: ProcessedContent[][] = await WorkerPromise.all(childPromises).catch(errorHandler)
|
||||
|
||||
const results: ProcessedContent[][] = await WorkerPromise.all(childPromises).catch((err) => {
|
||||
const errString = err.toString().slice("Error:".length)
|
||||
console.error(errString)
|
||||
process.exit(1)
|
||||
})
|
||||
res = results.flat()
|
||||
await pool.terminate()
|
||||
}
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
@use "sass:map";
|
||||
|
||||
@use "./variables.scss" as *;
|
||||
@use "./syntax.scss";
|
||||
@use "./callouts.scss";
|
||||
@@ -87,7 +85,7 @@ a {
|
||||
line-height: 1.4rem;
|
||||
|
||||
&:has(> img) {
|
||||
background-color: transparent;
|
||||
background-color: none;
|
||||
border-radius: 0;
|
||||
padding: 0;
|
||||
}
|
||||
@@ -123,7 +121,7 @@ a {
|
||||
}
|
||||
|
||||
.page {
|
||||
max-width: calc(#{map.get($breakpoints, desktop)} + 300px);
|
||||
max-width: calc(#{map-get($breakpoints, desktop)} + 300px);
|
||||
margin: 0 auto;
|
||||
& article {
|
||||
& > h1 {
|
||||
@@ -153,25 +151,24 @@ a {
|
||||
|
||||
& > #quartz-body {
|
||||
display: grid;
|
||||
grid-template-columns: #{map.get($desktopGrid, templateColumns)};
|
||||
grid-template-rows: #{map.get($desktopGrid, templateRows)};
|
||||
column-gap: #{map.get($desktopGrid, columnGap)};
|
||||
row-gap: #{map.get($desktopGrid, rowGap)};
|
||||
grid-template-areas: #{map.get($desktopGrid, templateAreas)};
|
||||
|
||||
grid-template-columns: #{map-get($desktopGrid, templateColumns)};
|
||||
grid-template-rows: #{map-get($desktopGrid, templateRows)};
|
||||
column-gap: #{map-get($desktopGrid, columnGap)};
|
||||
row-gap: #{map-get($desktopGrid, rowGap)};
|
||||
grid-template-areas: #{map-get($desktopGrid, templateAreas)};
|
||||
@media all and ($tablet) {
|
||||
grid-template-columns: #{map.get($tabletGrid, templateColumns)};
|
||||
grid-template-rows: #{map.get($tabletGrid, templateRows)};
|
||||
column-gap: #{map.get($tabletGrid, columnGap)};
|
||||
row-gap: #{map.get($tabletGrid, rowGap)};
|
||||
grid-template-areas: #{map.get($tabletGrid, templateAreas)};
|
||||
grid-template-columns: #{map-get($tabletGrid, templateColumns)};
|
||||
grid-template-rows: #{map-get($tabletGrid, templateRows)};
|
||||
column-gap: #{map-get($tabletGrid, columnGap)};
|
||||
row-gap: #{map-get($tabletGrid, rowGap)};
|
||||
grid-template-areas: #{map-get($tabletGrid, templateAreas)};
|
||||
}
|
||||
@media all and ($mobile) {
|
||||
grid-template-columns: #{map.get($mobileGrid, templateColumns)};
|
||||
grid-template-rows: #{map.get($mobileGrid, templateRows)};
|
||||
column-gap: #{map.get($mobileGrid, columnGap)};
|
||||
row-gap: #{map.get($mobileGrid, rowGap)};
|
||||
grid-template-areas: #{map.get($mobileGrid, templateAreas)};
|
||||
grid-template-columns: #{map-get($mobileGrid, templateColumns)};
|
||||
grid-template-rows: #{map-get($mobileGrid, templateRows)};
|
||||
column-gap: #{map-get($mobileGrid, columnGap)};
|
||||
row-gap: #{map-get($mobileGrid, rowGap)};
|
||||
grid-template-areas: #{map-get($mobileGrid, templateAreas)};
|
||||
}
|
||||
|
||||
@media all and not ($desktop) {
|
||||
@@ -351,10 +348,6 @@ h6 {
|
||||
&[id]:hover > a {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
&:not([id]) > a[role="anchor"] {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
// typography improvements
|
||||
@@ -395,7 +388,7 @@ figure[data-rehype-pretty-code-figure] {
|
||||
font-size: 0.9rem;
|
||||
padding: 0.1rem 0.5rem;
|
||||
border: 1px solid var(--lightgray);
|
||||
width: fit-content;
|
||||
width: max-content;
|
||||
border-radius: 5px;
|
||||
margin-bottom: -0.5rem;
|
||||
color: var(--darkgray);
|
||||
@@ -519,7 +512,6 @@ img {
|
||||
max-width: 100%;
|
||||
border-radius: 5px;
|
||||
margin: 1rem 0;
|
||||
content-visibility: auto;
|
||||
}
|
||||
|
||||
p > img + em {
|
||||
@@ -542,11 +534,12 @@ video {
|
||||
}
|
||||
|
||||
.spacer {
|
||||
flex: 2 1 auto;
|
||||
flex: 1 1 auto;
|
||||
}
|
||||
|
||||
div:has(> .overflow) {
|
||||
display: flex;
|
||||
overflow-y: auto;
|
||||
max-height: 100%;
|
||||
}
|
||||
|
||||
@@ -554,21 +547,26 @@ ul.overflow,
|
||||
ol.overflow {
|
||||
max-height: 100%;
|
||||
overflow-y: auto;
|
||||
width: 100%;
|
||||
margin-bottom: 0;
|
||||
|
||||
// clearfix
|
||||
content: "";
|
||||
clear: both;
|
||||
|
||||
& > li.overflow-end {
|
||||
height: 1rem;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
&.gradient-active {
|
||||
mask-image: linear-gradient(to bottom, black calc(100% - 50px), transparent 100%);
|
||||
& > li:last-of-type {
|
||||
margin-bottom: 30px;
|
||||
}
|
||||
/*&: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));
|
||||
}*/
|
||||
}
|
||||
|
||||
.transclude {
|
||||
@@ -589,14 +587,3 @@ iframe.pdf {
|
||||
width: 100%;
|
||||
border-radius: 5px;
|
||||
}
|
||||
|
||||
.navigation-progress {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 0;
|
||||
height: 3px;
|
||||
background: var(--secondary);
|
||||
transition: width 0.2s ease;
|
||||
z-index: 9999;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
@use "sass:map";
|
||||
|
||||
/**
|
||||
* Layout breakpoints
|
||||
* $mobile: screen width below this value will use mobile styles
|
||||
@@ -12,11 +10,11 @@ $breakpoints: (
|
||||
desktop: 1200px,
|
||||
);
|
||||
|
||||
$mobile: "(max-width: #{map.get($breakpoints, mobile)})";
|
||||
$tablet: "(min-width: #{map.get($breakpoints, mobile)}) and (max-width: #{map.get($breakpoints, desktop)})";
|
||||
$desktop: "(min-width: #{map.get($breakpoints, desktop)})";
|
||||
$mobile: "(max-width: #{map-get($breakpoints, mobile)})";
|
||||
$tablet: "(min-width: #{map-get($breakpoints, mobile)}) and (max-width: #{map-get($breakpoints, desktop)})";
|
||||
$desktop: "(min-width: #{map-get($breakpoints, desktop)})";
|
||||
|
||||
$pageWidth: #{map.get($breakpoints, mobile)};
|
||||
$pageWidth: #{map-get($breakpoints, mobile)};
|
||||
$sidePanelWidth: 320px; //380px;
|
||||
$topSpacing: 6rem;
|
||||
$boldWeight: 700;
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
import rfdc from "rfdc"
|
||||
|
||||
export const clone = rfdc()
|
||||
@@ -1,38 +0,0 @@
|
||||
const U200D = String.fromCharCode(8205)
|
||||
const UFE0Fg = /\uFE0F/g
|
||||
|
||||
export function getIconCode(char: string) {
|
||||
return toCodePoint(char.indexOf(U200D) < 0 ? char.replace(UFE0Fg, "") : char)
|
||||
}
|
||||
|
||||
function toCodePoint(unicodeSurrogates: string) {
|
||||
const r = []
|
||||
let c = 0,
|
||||
p = 0,
|
||||
i = 0
|
||||
|
||||
while (i < unicodeSurrogates.length) {
|
||||
c = unicodeSurrogates.charCodeAt(i++)
|
||||
if (p) {
|
||||
r.push((65536 + ((p - 55296) << 10) + (c - 56320)).toString(16))
|
||||
p = 0
|
||||
} else if (55296 <= c && c <= 56319) {
|
||||
p = c
|
||||
} else {
|
||||
r.push(c.toString(16))
|
||||
}
|
||||
}
|
||||
return r.join("-")
|
||||
}
|
||||
|
||||
const twemoji = (code: string) =>
|
||||
`https://cdnjs.cloudflare.com/ajax/libs/twemoji/15.1.0/svg/${code.toLowerCase()}.svg`
|
||||
const emojiCache: Record<string, Promise<any>> = {}
|
||||
|
||||
export function loadEmoji(code: string) {
|
||||
const type = "twemoji"
|
||||
const key = type + ":" + code
|
||||
if (key in emojiCache) return emojiCache[key]
|
||||
|
||||
return (emojiCache[key] = fetch(twemoji(code)).then((r) => r.text()))
|
||||
}
|
||||
@@ -1,194 +0,0 @@
|
||||
import test, { describe, beforeEach } from "node:test"
|
||||
import assert from "node:assert"
|
||||
import { FileTrieNode } from "./fileTrie"
|
||||
|
||||
interface TestData {
|
||||
title: string
|
||||
slug: string
|
||||
}
|
||||
|
||||
describe("FileTrie", () => {
|
||||
let trie: FileTrieNode<TestData>
|
||||
|
||||
beforeEach(() => {
|
||||
trie = new FileTrieNode<TestData>([])
|
||||
})
|
||||
|
||||
describe("constructor", () => {
|
||||
test("should create an empty trie", () => {
|
||||
assert.deepStrictEqual(trie.children, [])
|
||||
assert.strictEqual(trie.slug, "")
|
||||
assert.strictEqual(trie.displayName, "")
|
||||
assert.strictEqual(trie.data, null)
|
||||
})
|
||||
|
||||
test("should set displayName from data title", () => {
|
||||
const data = {
|
||||
title: "Test Title",
|
||||
slug: "test",
|
||||
}
|
||||
|
||||
trie.add(data)
|
||||
assert.strictEqual(trie.children[0].displayName, "Test Title")
|
||||
})
|
||||
})
|
||||
|
||||
describe("add", () => {
|
||||
test("should add a file at root level", () => {
|
||||
const data = {
|
||||
title: "Test",
|
||||
slug: "test",
|
||||
}
|
||||
|
||||
trie.add(data)
|
||||
assert.strictEqual(trie.children.length, 1)
|
||||
assert.strictEqual(trie.children[0].slug, "test")
|
||||
assert.strictEqual(trie.children[0].data, data)
|
||||
})
|
||||
|
||||
test("should handle index files", () => {
|
||||
const data = {
|
||||
title: "Index",
|
||||
slug: "index",
|
||||
}
|
||||
|
||||
trie.add(data)
|
||||
assert.strictEqual(trie.data, data)
|
||||
assert.strictEqual(trie.children.length, 0)
|
||||
})
|
||||
|
||||
test("should add nested files", () => {
|
||||
const data1 = {
|
||||
title: "Nested",
|
||||
slug: "folder/test",
|
||||
}
|
||||
|
||||
const data2 = {
|
||||
title: "Really nested index",
|
||||
slug: "a/b/c/index",
|
||||
}
|
||||
|
||||
trie.add(data1)
|
||||
trie.add(data2)
|
||||
assert.strictEqual(trie.children.length, 2)
|
||||
assert.strictEqual(trie.children[0].slug, "folder/index")
|
||||
assert.strictEqual(trie.children[0].children.length, 1)
|
||||
assert.strictEqual(trie.children[0].children[0].slug, "folder/test")
|
||||
assert.strictEqual(trie.children[0].children[0].data, data1)
|
||||
|
||||
assert.strictEqual(trie.children[1].slug, "a/index")
|
||||
assert.strictEqual(trie.children[1].children.length, 1)
|
||||
assert.strictEqual(trie.children[1].data, null)
|
||||
|
||||
assert.strictEqual(trie.children[1].children[0].slug, "a/b/index")
|
||||
assert.strictEqual(trie.children[1].children[0].children.length, 1)
|
||||
assert.strictEqual(trie.children[1].children[0].data, null)
|
||||
|
||||
assert.strictEqual(trie.children[1].children[0].children[0].slug, "a/b/c/index")
|
||||
assert.strictEqual(trie.children[1].children[0].children[0].data, data2)
|
||||
assert.strictEqual(trie.children[1].children[0].children[0].children.length, 0)
|
||||
})
|
||||
})
|
||||
|
||||
describe("filter", () => {
|
||||
test("should filter nodes based on condition", () => {
|
||||
const data1 = { title: "Test1", slug: "test1" }
|
||||
const data2 = { title: "Test2", slug: "test2" }
|
||||
|
||||
trie.add(data1)
|
||||
trie.add(data2)
|
||||
|
||||
trie.filter((node) => node.slug !== "test1")
|
||||
assert.strictEqual(trie.children.length, 1)
|
||||
assert.strictEqual(trie.children[0].slug, "test2")
|
||||
})
|
||||
})
|
||||
|
||||
describe("map", () => {
|
||||
test("should apply function to all nodes", () => {
|
||||
const data1 = { title: "Test1", slug: "test1" }
|
||||
const data2 = { title: "Test2", slug: "test2" }
|
||||
|
||||
trie.add(data1)
|
||||
trie.add(data2)
|
||||
|
||||
trie.map((node) => {
|
||||
if (node.data) {
|
||||
node.data.title = "Modified"
|
||||
}
|
||||
})
|
||||
|
||||
assert.strictEqual(trie.children[0].displayName, "Modified")
|
||||
assert.strictEqual(trie.children[1].displayName, "Modified")
|
||||
})
|
||||
})
|
||||
|
||||
describe("entries", () => {
|
||||
test("should return all entries", () => {
|
||||
const data1 = { title: "Test1", slug: "test1" }
|
||||
const data2 = { title: "Test2", slug: "a/b/test2" }
|
||||
|
||||
trie.add(data1)
|
||||
trie.add(data2)
|
||||
|
||||
const entries = trie.entries()
|
||||
assert.deepStrictEqual(
|
||||
entries.map(([path, node]) => [path, node.data]),
|
||||
[
|
||||
["index", trie.data],
|
||||
["test1", data1],
|
||||
["a/index", null],
|
||||
["a/b/index", null],
|
||||
["a/b/test2", data2],
|
||||
],
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe("getFolderPaths", () => {
|
||||
test("should return all folder paths", () => {
|
||||
const data1 = {
|
||||
title: "Root",
|
||||
slug: "index",
|
||||
}
|
||||
const data2 = {
|
||||
title: "Test",
|
||||
slug: "folder/subfolder/test",
|
||||
}
|
||||
const data3 = {
|
||||
title: "Folder Index",
|
||||
slug: "abc/index",
|
||||
}
|
||||
|
||||
trie.add(data1)
|
||||
trie.add(data2)
|
||||
trie.add(data3)
|
||||
const paths = trie.getFolderPaths()
|
||||
|
||||
assert.deepStrictEqual(paths, [
|
||||
"index",
|
||||
"folder/index",
|
||||
"folder/subfolder/index",
|
||||
"abc/index",
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe("sort", () => {
|
||||
test("should sort nodes according to sort function", () => {
|
||||
const data1 = { title: "A", slug: "a" }
|
||||
const data2 = { title: "B", slug: "b" }
|
||||
const data3 = { title: "C", slug: "c" }
|
||||
|
||||
trie.add(data3)
|
||||
trie.add(data1)
|
||||
trie.add(data2)
|
||||
|
||||
trie.sort((a, b) => a.slug.localeCompare(b.slug))
|
||||
assert.deepStrictEqual(
|
||||
trie.children.map((n) => n.slug),
|
||||
["a", "b", "c"],
|
||||
)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,127 +0,0 @@
|
||||
import { ContentDetails } from "../plugins/emitters/contentIndex"
|
||||
import { FullSlug, joinSegments } from "./path"
|
||||
|
||||
interface FileTrieData {
|
||||
slug: string
|
||||
title: string
|
||||
}
|
||||
|
||||
export class FileTrieNode<T extends FileTrieData = ContentDetails> {
|
||||
isFolder: boolean
|
||||
children: Array<FileTrieNode<T>>
|
||||
|
||||
private slugSegments: string[]
|
||||
data: T | null
|
||||
|
||||
constructor(segments: string[], data?: T) {
|
||||
this.children = []
|
||||
this.slugSegments = segments
|
||||
this.data = data ?? null
|
||||
this.isFolder = false
|
||||
}
|
||||
|
||||
get displayName(): string {
|
||||
return this.data?.title ?? this.slugSegment ?? ""
|
||||
}
|
||||
|
||||
get slug(): FullSlug {
|
||||
const path = joinSegments(...this.slugSegments) as FullSlug
|
||||
if (this.isFolder) {
|
||||
return joinSegments(path, "index") as FullSlug
|
||||
}
|
||||
|
||||
return path
|
||||
}
|
||||
|
||||
get slugSegment(): string {
|
||||
return this.slugSegments[this.slugSegments.length - 1]
|
||||
}
|
||||
|
||||
private makeChild(path: string[], file?: T) {
|
||||
const fullPath = [...this.slugSegments, path[0]]
|
||||
const child = new FileTrieNode<T>(fullPath, file)
|
||||
this.children.push(child)
|
||||
return child
|
||||
}
|
||||
|
||||
private insert(path: string[], file: T) {
|
||||
if (path.length === 0) {
|
||||
throw new Error("path is empty")
|
||||
}
|
||||
|
||||
// if we are inserting, we are a folder
|
||||
this.isFolder = true
|
||||
const segment = path[0]
|
||||
if (path.length === 1) {
|
||||
// base case, we are at the end of the path
|
||||
if (segment === "index") {
|
||||
this.data ??= file
|
||||
} else {
|
||||
this.makeChild(path, file)
|
||||
}
|
||||
} else if (path.length > 1) {
|
||||
// recursive case, we are not at the end of the path
|
||||
const child =
|
||||
this.children.find((c) => c.slugSegment === segment) ?? this.makeChild(path, undefined)
|
||||
child.insert(path.slice(1), file)
|
||||
}
|
||||
}
|
||||
|
||||
// Add new file to trie
|
||||
add(file: T) {
|
||||
this.insert(file.slug.split("/"), file)
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter trie nodes. Behaves similar to `Array.prototype.filter()`, but modifies tree in place
|
||||
*/
|
||||
filter(filterFn: (node: FileTrieNode<T>) => boolean) {
|
||||
this.children = this.children.filter(filterFn)
|
||||
this.children.forEach((child) => child.filter(filterFn))
|
||||
}
|
||||
|
||||
/**
|
||||
* Map over trie nodes. Behaves similar to `Array.prototype.map()`, but modifies tree in place
|
||||
*/
|
||||
map(mapFn: (node: FileTrieNode<T>) => void) {
|
||||
mapFn(this)
|
||||
this.children.forEach((child) => child.map(mapFn))
|
||||
}
|
||||
|
||||
/**
|
||||
* Sort trie nodes according to sort/compare function
|
||||
*/
|
||||
sort(sortFn: (a: FileTrieNode<T>, b: FileTrieNode<T>) => number) {
|
||||
this.children = this.children.sort(sortFn)
|
||||
this.children.forEach((e) => e.sort(sortFn))
|
||||
}
|
||||
|
||||
static fromEntries<T extends FileTrieData>(entries: [FullSlug, T][]) {
|
||||
const trie = new FileTrieNode<T>([])
|
||||
entries.forEach(([, entry]) => trie.add(entry))
|
||||
return trie
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all entries in the trie
|
||||
* in the a flat array including the full path and the node
|
||||
*/
|
||||
entries(): [FullSlug, FileTrieNode<T>][] {
|
||||
const traverse = (node: FileTrieNode<T>): [FullSlug, FileTrieNode<T>][] => {
|
||||
const result: [FullSlug, FileTrieNode<T>][] = [[node.slug, node]]
|
||||
return result.concat(...node.children.map(traverse))
|
||||
}
|
||||
|
||||
return traverse(this)
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all folder paths in the trie
|
||||
* @returns array containing folder state for trie
|
||||
*/
|
||||
getFolderPaths() {
|
||||
return this.entries()
|
||||
.filter(([_, node]) => node.isFolder)
|
||||
.map(([path, _]) => path)
|
||||
}
|
||||
}
|
||||
@@ -35,9 +35,7 @@ export async function getSatoriFont(headerFontName: string, bodyFontName: string
|
||||
async function fetchTtf(fontName: string, weight: FontWeight): Promise<ArrayBuffer> {
|
||||
try {
|
||||
// Get css file from google fonts
|
||||
const cssResponse = await fetch(
|
||||
`https://fonts.googleapis.com/css2?family=${fontName}:wght@${weight}`,
|
||||
)
|
||||
const cssResponse = await fetch(`https://fonts.googleapis.com/css?family=${fontName}:${weight}`)
|
||||
const css = await cssResponse.text()
|
||||
|
||||
// Extract .ttf url from css file
|
||||
@@ -143,10 +141,12 @@ export const defaultImage: SocialImageOptions["imageStructure"] = (
|
||||
fonts: SatoriOptions["fonts"],
|
||||
_fileData: QuartzPluginData,
|
||||
) => {
|
||||
// How many characters are allowed before switching to smaller font
|
||||
const fontBreakPoint = 22
|
||||
const useSmallerFont = title.length > fontBreakPoint
|
||||
const iconPath = `https://${cfg.baseUrl}/static/icon.png`
|
||||
|
||||
// Setup to access image
|
||||
const iconPath = `https://${cfg.baseUrl}/static/icon.png`
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
@@ -158,66 +158,43 @@ export const defaultImage: SocialImageOptions["imageStructure"] = (
|
||||
width: "100%",
|
||||
backgroundColor: cfg.theme.colors[colorScheme].light,
|
||||
gap: "2rem",
|
||||
padding: "1.5rem 5rem",
|
||||
paddingTop: "1.5rem",
|
||||
paddingBottom: "1.5rem",
|
||||
paddingLeft: "5rem",
|
||||
paddingRight: "5rem",
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "flex-start",
|
||||
width: "100%",
|
||||
flexDirection: "row",
|
||||
gap: "2.5rem",
|
||||
}}
|
||||
>
|
||||
<img src={iconPath} width={135} height={135} />
|
||||
<div
|
||||
<p
|
||||
style={{
|
||||
display: "flex",
|
||||
color: cfg.theme.colors[colorScheme].dark,
|
||||
fontSize: useSmallerFont ? 70 : 82,
|
||||
fontFamily: fonts[0].name,
|
||||
maxWidth: "70%",
|
||||
overflow: "hidden",
|
||||
textOverflow: "ellipsis",
|
||||
}}
|
||||
>
|
||||
<p
|
||||
style={{
|
||||
margin: 0,
|
||||
overflow: "hidden",
|
||||
textOverflow: "ellipsis",
|
||||
whiteSpace: "nowrap",
|
||||
}}
|
||||
>
|
||||
{title}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
color: cfg.theme.colors[colorScheme].dark,
|
||||
fontSize: 44,
|
||||
fontFamily: fonts[1].name,
|
||||
maxWidth: "100%",
|
||||
maxHeight: "40%",
|
||||
overflow: "hidden",
|
||||
}}
|
||||
>
|
||||
<p
|
||||
style={{
|
||||
margin: 0,
|
||||
display: "-webkit-box",
|
||||
WebkitBoxOrient: "vertical",
|
||||
WebkitLineClamp: 3,
|
||||
overflow: "hidden",
|
||||
textOverflow: "ellipsis",
|
||||
}}
|
||||
>
|
||||
{description}
|
||||
{title}
|
||||
</p>
|
||||
</div>
|
||||
<p
|
||||
style={{
|
||||
color: cfg.theme.colors[colorScheme].dark,
|
||||
fontSize: 44,
|
||||
lineClamp: 3,
|
||||
fontFamily: fonts[1].name,
|
||||
}}
|
||||
>
|
||||
{description}
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -158,29 +158,6 @@ describe("transforms", () => {
|
||||
path.isRelativeURL,
|
||||
)
|
||||
})
|
||||
|
||||
test("joinSegments", () => {
|
||||
assert.strictEqual(path.joinSegments("a", "b"), "a/b")
|
||||
assert.strictEqual(path.joinSegments("a/", "b"), "a/b")
|
||||
assert.strictEqual(path.joinSegments("a", "b/"), "a/b/")
|
||||
assert.strictEqual(path.joinSegments("a/", "b/"), "a/b/")
|
||||
|
||||
// preserve leading and trailing slashes
|
||||
assert.strictEqual(path.joinSegments("/a", "b"), "/a/b")
|
||||
assert.strictEqual(path.joinSegments("/a/", "b"), "/a/b")
|
||||
assert.strictEqual(path.joinSegments("/a", "b/"), "/a/b/")
|
||||
assert.strictEqual(path.joinSegments("/a/", "b/"), "/a/b/")
|
||||
|
||||
// lone slash
|
||||
assert.strictEqual(path.joinSegments("/a/", "b", "/"), "/a/b/")
|
||||
assert.strictEqual(path.joinSegments("a/", "b" + "/"), "a/b/")
|
||||
|
||||
// works with protocol specifiers
|
||||
assert.strictEqual(path.joinSegments("https://example.com", "a"), "https://example.com/a")
|
||||
assert.strictEqual(path.joinSegments("https://example.com/", "a"), "https://example.com/a")
|
||||
assert.strictEqual(path.joinSegments("https://example.com", "a/"), "https://example.com/a/")
|
||||
assert.strictEqual(path.joinSegments("https://example.com/", "a/"), "https://example.com/a/")
|
||||
})
|
||||
})
|
||||
|
||||
describe("link strategies", () => {
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import { slug as slugAnchor } from "github-slugger"
|
||||
import type { Element as HastElement } from "hast"
|
||||
import { clone } from "./clone"
|
||||
import rfdc from "rfdc"
|
||||
|
||||
export const clone = rfdc()
|
||||
|
||||
// this file must be isomorphic so it can't use node libs (e.g. path)
|
||||
|
||||
export const QUARTZ = "quartz"
|
||||
@@ -105,10 +108,10 @@ const _rebaseHtmlElement = (el: Element, attr: string, newBase: string | URL) =>
|
||||
el.setAttribute(attr, rebased.pathname + rebased.hash)
|
||||
}
|
||||
export function normalizeRelativeURLs(el: Element | Document, destination: string | URL) {
|
||||
el.querySelectorAll('[href=""], [href^="./"], [href^="../"]').forEach((item) =>
|
||||
el.querySelectorAll('[href^="./"], [href^="../"]').forEach((item) =>
|
||||
_rebaseHtmlElement(item, "href", destination),
|
||||
)
|
||||
el.querySelectorAll('[src=""], [src^="./"], [src^="../"]').forEach((item) =>
|
||||
el.querySelectorAll('[src^="./"], [src^="../"]').forEach((item) =>
|
||||
_rebaseHtmlElement(item, "src", destination),
|
||||
)
|
||||
}
|
||||
@@ -180,26 +183,10 @@ export function slugTag(tag: string) {
|
||||
}
|
||||
|
||||
export function joinSegments(...args: string[]): string {
|
||||
if (args.length === 0) {
|
||||
return ""
|
||||
}
|
||||
|
||||
let joined = args
|
||||
.filter((segment) => segment !== "" && segment !== "/")
|
||||
.map((segment) => stripSlashes(segment))
|
||||
return args
|
||||
.filter((segment) => segment !== "")
|
||||
.join("/")
|
||||
|
||||
// if the first segment starts with a slash, add it back
|
||||
if (args[0].startsWith("/")) {
|
||||
joined = "/" + joined
|
||||
}
|
||||
|
||||
// if the last segment is a folder, add a trailing slash
|
||||
if (args[args.length - 1].endsWith("/")) {
|
||||
joined = joined + "/"
|
||||
}
|
||||
|
||||
return joined
|
||||
.replace(/\/\/+/g, "/")
|
||||
}
|
||||
|
||||
export function getAllSegmentPrefixes(tags: string): string[] {
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
export function randomIdNonSecure() {
|
||||
return Math.random().toString(36).substring(2, 8)
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
import { randomUUID } from "crypto"
|
||||
import { JSX } from "preact/jsx-runtime"
|
||||
import { QuartzPluginData } from "../plugins/vfile"
|
||||
|
||||
export type JSResource = {
|
||||
loadTime: "beforeDOMReady" | "afterDOMReady"
|
||||
@@ -63,12 +62,4 @@ export function CSSResourceToStyleElement(resource: CSSResource, preserve?: bool
|
||||
export interface StaticResources {
|
||||
css: CSSResource[]
|
||||
js: JSResource[]
|
||||
additionalHead: (JSX.Element | ((pageData: QuartzPluginData) => JSX.Element))[]
|
||||
}
|
||||
|
||||
export type StringResource = string | string[] | undefined
|
||||
export function concatenateResources(...resources: StringResource[]): StringResource {
|
||||
return resources
|
||||
.filter((resource): resource is string | string[] => resource !== undefined)
|
||||
.flat()
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user