Compare commits
19 Commits
v4
...
bf5aa870ab
Author | SHA1 | Date | |
---|---|---|---|
bf5aa870ab | |||
726ea3b91f | |||
c6f9cd12e0 | |||
e86450abd3 | |||
6e29281f91 | |||
d63e5ae6a7 | |||
5f4e04d364 | |||
1ce534d696 | |||
760cb91ad2 | |||
242bd75378 | |||
7d8cc8d0be | |||
51da3c172d | |||
4cb6b5fa4c | |||
2be716bf75 | |||
7108c68a7b | |||
5283a7e481 | |||
c2dab1344e | |||
fbed2635e2 | |||
4595f54660 |
19
.github/dependabot.yml
vendored
@ -1,20 +1,11 @@
|
||||
# To get started with Dependabot version updates, you'll need to specify which
|
||||
# package ecosystems to update and where the package manifests are located.
|
||||
# Please see the documentation for all configuration options:
|
||||
# https://docs.github.com/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file
|
||||
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: "npm"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
groups:
|
||||
production-dependencies:
|
||||
applies-to: "version-updates"
|
||||
patterns:
|
||||
- "*"
|
||||
- package-ecosystem: "github-actions"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
groups:
|
||||
ci-dependencies:
|
||||
applies-to: "version-updates"
|
||||
patterns:
|
||||
- "*"
|
||||
|
43
.github/workflows/build-preview.yaml
vendored
@ -1,43 +0,0 @@
|
||||
name: Build Preview Deployment
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types: [opened, synchronize]
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
build-preview:
|
||||
if: ${{ github.repository == 'jackyzha0/quartz' }}
|
||||
runs-on: ubuntu-latest
|
||||
name: Build Preview
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 22
|
||||
|
||||
- name: Cache dependencies
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.npm
|
||||
key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-node-
|
||||
|
||||
- run: npm ci
|
||||
|
||||
- name: Check types and style
|
||||
run: npm run check
|
||||
|
||||
- name: Build Quartz
|
||||
run: npx quartz build -d docs -v
|
||||
|
||||
- name: Upload build artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: preview-build
|
||||
path: public
|
21
.github/workflows/ci.yaml
vendored
@ -7,7 +7,6 @@ on:
|
||||
push:
|
||||
branches:
|
||||
- v4
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
build-and-test:
|
||||
@ -19,17 +18,17 @@ jobs:
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v3
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v4
|
||||
uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version: 22
|
||||
node-version: 18
|
||||
|
||||
- name: Cache dependencies
|
||||
uses: actions/cache@v4
|
||||
uses: actions/cache@v3
|
||||
with:
|
||||
path: ~/.npm
|
||||
key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
|
||||
@ -45,25 +44,25 @@ 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' }}
|
||||
if: ${{ github.repository == 'jackyzha0/quartz' }}
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v3
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v4
|
||||
uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version: 22
|
||||
node-version: 18
|
||||
- name: Get package version
|
||||
run: node -p -e '`PACKAGE_VERSION=${require("./package.json").version}`' >> $GITHUB_ENV
|
||||
- name: Create release tag
|
||||
uses: pkgdeps/git-tag-action@v3
|
||||
uses: pkgdeps/git-tag-action@v2
|
||||
with:
|
||||
github_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
github_repo: ${{ github.repository }}
|
||||
|
37
.github/workflows/deploy-preview.yaml
vendored
@ -1,37 +0,0 @@
|
||||
name: Upload Preview Deployment
|
||||
on:
|
||||
workflow_run:
|
||||
workflows: ["Build Preview Deployment"]
|
||||
types:
|
||||
- completed
|
||||
|
||||
permissions:
|
||||
actions: read
|
||||
deployments: write
|
||||
contents: read
|
||||
pull-requests: write
|
||||
|
||||
jobs:
|
||||
deploy-preview:
|
||||
if: ${{ github.repository == 'jackyzha0/quartz' && github.event.workflow_run.conclusion == 'success' }}
|
||||
runs-on: ubuntu-latest
|
||||
name: Deploy Preview to Cloudflare Pages
|
||||
steps:
|
||||
- name: Download build artifact
|
||||
uses: actions/download-artifact@v4
|
||||
id: preview-build-artifact
|
||||
with:
|
||||
name: preview-build
|
||||
path: build
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
run-id: ${{ github.event.workflow_run.id }}
|
||||
|
||||
- name: Deploy to Cloudflare Pages
|
||||
uses: AdrianGonz97/refined-cf-pages-action@v1
|
||||
with:
|
||||
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
|
||||
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
|
||||
githubToken: ${{ secrets.GITHUB_TOKEN }}
|
||||
projectName: quartz
|
||||
deploymentName: Branch Preview
|
||||
directory: ${{ steps.preview-build-artifact.outputs.download-path }}
|
88
.github/workflows/docker-build-push.yaml
vendored
@ -1,88 +0,0 @@
|
||||
name: Docker build & push image
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [v4]
|
||||
tags: ["v*"]
|
||||
pull_request:
|
||||
branches: [v4]
|
||||
paths:
|
||||
- .github/workflows/docker-build-push.yaml
|
||||
- quartz/**
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
build:
|
||||
if: ${{ github.repository == 'jackyzha0/quartz' }} # Comment this out if you want to publish your own images on a fork!
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Set lowercase repository owner environment variable
|
||||
run: |
|
||||
echo "OWNER_LOWERCASE=${OWNER,,}" >> ${GITHUB_ENV}
|
||||
env:
|
||||
OWNER: "${{ github.repository_owner }}"
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 1
|
||||
- name: Inject slug/short variables
|
||||
uses: rlespinasse/github-slug-action@v5.1.0
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v3
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
with:
|
||||
install: true
|
||||
driver-opts: |
|
||||
image=moby/buildkit:master
|
||||
network=host
|
||||
- name: Install cosign
|
||||
if: github.event_name != 'pull_request'
|
||||
uses: sigstore/cosign-installer@v3.8.2
|
||||
- name: Login to GitHub Container Registry
|
||||
uses: docker/login-action@v3
|
||||
if: github.event_name != 'pull_request'
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Extract metadata tags and labels on PRs
|
||||
if: github.event_name == 'pull_request'
|
||||
id: meta-pr
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: ghcr.io/${{ env.OWNER_LOWERCASE }}/quartz
|
||||
tags: |
|
||||
type=raw,value=sha-${{ env.GITHUB_SHA_SHORT }}
|
||||
labels: |
|
||||
org.opencontainers.image.source="https://github.com/${{ github.repository_owner }}/quartz"
|
||||
- name: Extract metadata tags and labels for main, release or tag
|
||||
if: github.event_name != 'pull_request'
|
||||
id: meta
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
flavor: |
|
||||
latest=auto
|
||||
images: ghcr.io/${{ env.OWNER_LOWERCASE }}/quartz
|
||||
tags: |
|
||||
type=semver,pattern={{version}}
|
||||
type=semver,pattern={{major}}.{{minor}}
|
||||
type=semver,pattern={{major}}.{{minor}}.{{patch}}
|
||||
type=raw,value=latest,enable=${{ github.ref == format('refs/heads/{0}', github.event.repository.default_branch) }}
|
||||
type=raw,value=sha-${{ env.GITHUB_SHA_SHORT }}
|
||||
labels: |
|
||||
maintainer=${{ github.repository_owner }}
|
||||
org.opencontainers.image.source="https://github.com/${{ github.repository_owner }}/quartz"
|
||||
|
||||
- name: Build and push Docker image
|
||||
id: build-and-push
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
push: ${{ github.event_name != 'pull_request' }}
|
||||
build-args: |
|
||||
GIT_SHA=${{ env.GITHUB_SHA }}
|
||||
DOCKER_LABEL=sha-${{ env.GITHUB_SHA_SHORT }}
|
||||
tags: ${{ steps.meta.outputs.tags || steps.meta-pr.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels || steps.meta-pr.outputs.labels }}
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha
|
@ -1 +0,0 @@
|
||||
v22.16.0
|
16
Dockerfile
@ -1,11 +1,23 @@
|
||||
FROM node:22-slim AS builder
|
||||
FROM python:latest as convert
|
||||
WORKDIR /usr/src/app
|
||||
COPY content/ ./
|
||||
COPY custom/convert-furigana/program/convert-furigana.py ./
|
||||
COPY custom/convert-usage/program/convert-usage.py ./
|
||||
ENV PIP_ROOT_USER_ACTION=ignore
|
||||
RUN python -m pip install --upgrade pip
|
||||
RUN python -m pip install beautifulsoup4
|
||||
RUN python convert-furigana.py .
|
||||
RUN python convert-usage.py .
|
||||
|
||||
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 . .
|
||||
COPY --from=convert /usr/src/app/ /usr/src/app/content/
|
||||
CMD ["npx", "quartz", "build", "--serve"]
|
||||
|
48
content/index.md
Normal file
@ -0,0 +1,48 @@
|
||||
# Japanese Grammar (JPG)
|
||||
|
||||
Welcome to my Japanese Grammar project!
|
||||
|
||||
## Goal
|
||||
|
||||
The goal of this website is to be a synthesis of useful resources for my Japanese learning adventure. I want to have grammar points next to each other, independently of any "difficulty level", set up in a logical and consistent form. I don't want to have to open 5 pages to compare information, and I don't want a deep dive into a notion. The goal is to be a reminder of the things I learn, rather than a way to learn. I want a few examples to grasp it, but I do not want to have ten of the same kind. And nothing quite fits for me!
|
||||
|
||||
## Sources
|
||||
|
||||
Of course, since I'm _learning_ the language, I need to borrow what I write from different sources. So this website uses data from the websites listed here. I don't want any recognition of what is here! It's mostly a compilation of what people who are way better in this language have made before.
|
||||
|
||||
* [Bunpro](https://bunpro.jp/grammar_points)
|
||||
* [JLPT Sensei](https://jlptsensei.com/#jlpt-grammar-lists)
|
||||
* [Maggie Sensei](https://maggiesensei.com/)
|
||||
* [Try! Series of books](https://2024.ask-books.com/tag/try/)
|
||||
* [Hedgehog Japanese](https://hedgehog-japanese.com/category/grammar/)
|
||||
* [Wasabi](https://www.wasabi-jpn.com/category/japanese-grammar/)
|
||||
* [Japanese StackExchange](https://japanese.stackexchange.com/)
|
||||
* [Guide du Japonais](https://guidedujaponais.fr/)
|
||||
|
||||
## Other useful resources
|
||||
|
||||
In addition to those I cited, here are other resources I find useful.
|
||||
|
||||
### Kanjis
|
||||
|
||||
* [Remembering the Kanji (RTK)](https://en.wikipedia.org/wiki/Remembering_the_Kanji_and_Remembering_the_Hanzi), a kanji learning method
|
||||
* [Kanji Koohii](https://kanji.koohii.com/), a website using the RTK method and spaced repetition
|
||||
* [Remember the JLPT](https://git.marchal.dev/keb/remember-the-JLPT), a tool I made to learn kanjis by JLPT levels
|
||||
|
||||
### Reading
|
||||
|
||||
* [Sakubun](https://sakubun.xyz/)
|
||||
* [NHK News Web Easy](https://www3.nhk.or.jp/news/easy/)
|
||||
|
||||
### Grammar
|
||||
|
||||
* [jtest4you](https://japanesetest4you.com/)
|
||||
* [Japanese Conjugation Drill](https://drill.marchal.dev)
|
||||
|
||||
### Vocabulary
|
||||
|
||||
* [Jisho](https://jisho.org/), an online dictionary
|
||||
|
||||
## Any errors?
|
||||
|
||||
If you find any error, please do contact me! You can find my website in the footer of any page of this website. Thanks!
|
2
custom/build-run.sh
Normal file
@ -0,0 +1,2 @@
|
||||
docker build -t quartz-jpg .
|
||||
cd custom && docker-compose up -d --force-recreate
|
9
custom/convert-furigana/LICENSE
Normal file
@ -0,0 +1,9 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2024 keb
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
43
custom/convert-furigana/README.md
Normal file
@ -0,0 +1,43 @@
|
||||
# convert-furigana
|
||||
|
||||
## What is it?
|
||||
|
||||
There are a few extensions that add [furigana](https://en.wikipedia.org/wiki/Furigana) support to Markdown. I use [Obsidian](https://obsidian.md/), and therefore its furigana extension: [obsidian-markdown-furigana](https://github.com/steven-kraft/obsidian-markdown-furigana). It works well, but by nature is limited by being used within Obsidian.
|
||||
|
||||
For that purpose, this python script converts this specific syntax to common, all-platforms HTML ruby tags.
|
||||
|
||||
## Process
|
||||
|
||||
This specific extension syntax is as following:
|
||||
```
|
||||
{漢字|かんじ}
|
||||
{漢字|かん|じ}
|
||||
```
|
||||
|
||||
When processed by this script, the result is:
|
||||
```
|
||||
<ruby>漢字<rt>かんじ</rt></ruby>
|
||||
<ruby>漢<rt>かん</rt>字<rt>じ</rt></ruby>
|
||||
```
|
||||
|
||||
Which leads visually from, by default markdown standards:
|
||||
|
||||
> {漢字|かんじ}
|
||||
>
|
||||
> {漢字|かん|じ}
|
||||
|
||||
to common HTML ruby syntax:
|
||||
|
||||
> <ruby>漢字<rt>かんじ</rt></ruby>
|
||||
>
|
||||
> <ruby>漢<rt>かん</rt>字<rt>じ</rt></ruby>
|
||||
|
||||
## Limitations
|
||||
|
||||
This has been made for my personal use, which is only kanjis with kanas as furigana. The regexp used do not recognize other inputs. But you can modify them easily for your use if needed.
|
||||
|
||||
## Usage
|
||||
|
||||
Usage: `python3 convert-furigana.py [root folder]`
|
||||
|
||||
Note: Please be careful, this software applies modifications recursively!
|
6
custom/convert-furigana/examples/furigana1.md
Normal file
@ -0,0 +1,6 @@
|
||||
{僕|ボク}の{筆記|ひっ|き}
|
||||
|
||||
### ~によるN
|
||||
|
||||
* テレビによる{報道|ほうどう}
|
||||
* この{地震|じ|しん}による{津波|つ|なみ}の{心配|しんぱい}はありません。
|
7
custom/convert-furigana/examples/subfolder/furigana2.md
Normal file
@ -0,0 +1,7 @@
|
||||
## ふりがなテスト
|
||||
|
||||
{漢字|かんじ}
|
||||
|
||||
{漢字|かん|じ}
|
||||
|
||||
{漢字|カン|ジ}
|
71
custom/convert-furigana/program/convert-furigana.py
Normal file
@ -0,0 +1,71 @@
|
||||
import sys
|
||||
import os
|
||||
from glob import glob
|
||||
import re
|
||||
|
||||
### Patterns ###
|
||||
|
||||
# https://www.reddit.com/r/learnpython/comments/h0tsaa/regex_expression_for_japanese_extracting/
|
||||
re_brace = '{(.+?)}'
|
||||
re_kanji = '([㐀-䶵一-鿋豈-頻]+)'
|
||||
re_kana = '([ぁ-ゟ゠-ヿ]+)'
|
||||
|
||||
### Open file ###
|
||||
|
||||
def open_file(filename):
|
||||
with open(filename, 'r', encoding='utf-8-sig') as file:
|
||||
filedata = file.read()
|
||||
return filedata
|
||||
|
||||
### Replace ###
|
||||
|
||||
def write_ruby_simple(kanji, kana):
|
||||
return f"<ruby>{kanji}<rt>{kana}</rt></ruby>"
|
||||
|
||||
def write_ruby_multiple(kanji, kanas):
|
||||
result = f"<ruby>"
|
||||
for idx, kana in enumerate(kanas):
|
||||
result += f"{kanji[idx]}"
|
||||
result += f"<rt>{kana}</rt>"
|
||||
result += f"</ruby>"
|
||||
return result
|
||||
|
||||
def convert_to_ruby(content):
|
||||
kanji = re.search(re_kanji, content.group())
|
||||
kana = re.findall(re_kana, content.group())
|
||||
|
||||
if (len(kana) == 1):
|
||||
return write_ruby_simple(kanji.group(), kana[0])
|
||||
else:
|
||||
return write_ruby_multiple(kanji.group(), kana)
|
||||
|
||||
def convert_pattern(text):
|
||||
res_text = re.sub(re_brace, convert_to_ruby, text)
|
||||
return res_text
|
||||
|
||||
### Write to file ###
|
||||
|
||||
def write_file(filename, text):
|
||||
with open(filename, 'w', encoding='utf-8-sig') as file:
|
||||
file.write(text)
|
||||
|
||||
|
||||
### Execution ###
|
||||
|
||||
file_list = []
|
||||
|
||||
if len(sys.argv) > 1:
|
||||
path = sys.argv[1]
|
||||
for filename in glob(path + "/**/*.md", recursive=True):
|
||||
if (os.path.isfile(filename)):
|
||||
file_list.append(filename)
|
||||
else:
|
||||
print(f"Usage: python3 {sys.argv[0]} [root folder]")
|
||||
print(f"Note: Please be careful, this software applies modifications recursively!")
|
||||
|
||||
for filename in file_list:
|
||||
print(f"Found file {filename}, processing...", end='')
|
||||
data = open_file(filename)
|
||||
text = convert_pattern(data)
|
||||
write_file(filename, text)
|
||||
print(f" done!")
|
9
custom/convert-usage/LICENSE
Normal file
@ -0,0 +1,9 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2024 keb
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
17
custom/convert-usage/README.md
Normal file
@ -0,0 +1,17 @@
|
||||
# convert-usage
|
||||
|
||||
## Obsidian snippet
|
||||
|
||||
For my Japanese Grammar (JPG) project, I have created a style for explanation on the usage of certain grammar points. There is no simple way to make it in Markdown, so I tried to make it with the least amount of HTML possible. You can find it in `examples/sample.md`. However, for it to work, you have to import a custom [CSS snippet](https://help.obsidian.md/Extending+Obsidian/CSS+snippets) to Obsidian, which is located in `obsidian-snippet/usage.css`. But using it, you will have this kind of result:
|
||||
|
||||

|
||||
|
||||
## convert-usage.py
|
||||
|
||||
In my Quartz rendering of my markdown data, I want this kind of data to be in a callout. However, it is not possible to combine HTML and Markdown in Obsidian. For that purpose, this script encapsulates it directly in HTML. To make it both compatible in Obsidian and Quartz, and to be still easy to write, it's done with this python script. This is probably super specific and will not be of use for anybody except me!
|
||||
|
||||
## Usage
|
||||
|
||||
Usage: `python3 convert-usage.py [root folder]`
|
||||
|
||||
Note: Please be careful, this software applies modifications recursively!
|
33
custom/convert-usage/examples/sample.md
Normal file
@ -0,0 +1,33 @@
|
||||
# test file
|
||||
|
||||
## Lorem ipsum
|
||||
|
||||
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris massa eros, feugiat eu dapibus nec, fermentum vel ex. Nulla malesuada luctus pretium. Phasellus ac felis ut nisi lacinia malesuada nec vel odio. Donec tincidunt tincidunt lorem vel tempus. Nullam sed efficitur ligula, a porttitor nibh. Praesent justo dui, venenatis ac mi non, laoreet consequat libero. Aenean ut molestie mauris. Proin mattis volutpat ligula eget tincidunt. Fusce ex eros, condimentum consectetur efficitur vitae, euismod at justo.
|
||||
|
||||
**Usage**
|
||||
|
||||
<div class="usage">
|
||||
<div class="left">
|
||||
<p><span class="box">item1</span></p>
|
||||
<p><span class="box">item2</span></p>
|
||||
<p><span class="box">item3</span></p>
|
||||
<p><span class="box">item4</span></p>
|
||||
</div>
|
||||
<p class="right">+ final</p>
|
||||
</div>
|
||||
|
||||
## Phasellus tristique
|
||||
|
||||
Phasellus tristique rutrum enim. Integer vitae ex at turpis convallis posuere nec nec erat. Cras finibus erat mauris. Suspendisse id diam at sapien luctus faucibus. Pellentesque fermentum auctor libero, ut porta orci porttitor quis. In varius at sem sed ultricies. Mauris iaculis convallis erat, congue tincidunt turpis luctus vitae.
|
||||
|
||||
**Usage**
|
||||
|
||||
<div class="usage">
|
||||
<div class="left">
|
||||
<p><span class="box">アイテム1</span></p>
|
||||
<p><span class="box">アイテム2</span></p>
|
||||
<p><span class="box">アイテム3</span></p>
|
||||
<p><span class="box">アイテム4</span></p>
|
||||
</div>
|
||||
<p class="right">+ ファイナル</p>
|
||||
</div>
|
23
custom/convert-usage/examples/sample2.md
Normal file
@ -0,0 +1,23 @@
|
||||
# test file
|
||||
|
||||
## Lorem ipsum
|
||||
|
||||
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris massa eros, feugiat eu dapibus nec, fermentum vel ex. Nulla malesuada luctus pretium. Phasellus ac felis ut nisi lacinia malesuada nec vel odio. Donec tincidunt tincidunt lorem vel tempus. Nullam sed efficitur ligula, a porttitor nibh. Praesent justo dui, venenatis ac mi non, laoreet consequat libero. Aenean ut molestie mauris. Proin mattis volutpat ligula eget tincidunt. Fusce ex eros, condimentum consectetur efficitur vitae, euismod at justo.
|
||||
|
||||
**Usage**
|
||||
|
||||
<div class="usage">
|
||||
<div class="left">
|
||||
<p><span class="box">item1</span></p>
|
||||
<p><span class="box">item2</span></p>
|
||||
<p><span class="box">item3</span></p>
|
||||
<p><span class="box">item4</span></p>
|
||||
</div>
|
||||
<p class="right">+ final</p>
|
||||
</div>
|
||||
|
||||
## Callout
|
||||
|
||||
> [!info] Example
|
||||
> Callout example
|
||||
> Careful with BS4 encoding some characters
|
35
custom/convert-usage/obsidian-snippets/usage.css
Normal file
@ -0,0 +1,35 @@
|
||||
.box {
|
||||
display: inline-block;
|
||||
width: fit-content;
|
||||
margin: 0.2rem;
|
||||
padding: 0.2rem 0.3rem 0.2rem 0.3rem;
|
||||
|
||||
border: 1px solid black;
|
||||
border-radius: 0.5rem;
|
||||
}
|
||||
|
||||
.usage {
|
||||
display:flex;
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.left {
|
||||
padding-right: 1.7rem;
|
||||
|
||||
background-image: linear-gradient(black, black), linear-gradient(black, black);
|
||||
background-repeat: no-repeat;
|
||||
background-size: 8px 2px;
|
||||
background-position: top right, bottom right;
|
||||
|
||||
border-right: solid black;
|
||||
border-width: 0 2px;
|
||||
}
|
||||
|
||||
.left p {
|
||||
margin:0;
|
||||
}
|
||||
|
||||
.right {
|
||||
padding-left: 1rem;
|
||||
}
|
66
custom/convert-usage/program/convert-usage.py
Normal file
@ -0,0 +1,66 @@
|
||||
import sys
|
||||
import os
|
||||
from glob import glob
|
||||
from bs4 import BeautifulSoup
|
||||
import re
|
||||
|
||||
### Patterns ###
|
||||
|
||||
re_usage = r'(^\*\*Usage\*\*$\n\n)'
|
||||
callout_title_html = '''
|
||||
<div class="callout-title">
|
||||
<div class="callout-icon"></div>
|
||||
<div class="callout-title-inner"><p>Usage</p></div>
|
||||
</div>'''
|
||||
|
||||
### Open file ###
|
||||
|
||||
def open_file(filename):
|
||||
with open(filename, 'r', encoding='utf-8-sig') as file:
|
||||
filedata = file.read()
|
||||
return filedata
|
||||
|
||||
### Write to file ###
|
||||
|
||||
def write_file(filename, text):
|
||||
with open(filename, 'w', encoding='utf-8-sig') as file:
|
||||
file.write(text)
|
||||
|
||||
### Replace ###
|
||||
|
||||
def convert_pattern(text):
|
||||
text, success = re.subn(re_usage, '', text, flags=re.MULTILINE)
|
||||
if (success == 0):
|
||||
return text
|
||||
|
||||
soup = BeautifulSoup(text, features="html.parser")
|
||||
|
||||
for tag in soup.find_all('div', {"class": "usage"}):
|
||||
new_blockquote = soup.new_tag("blockquote", **{"class": "callout notes", "data-callout": "notes"})
|
||||
tag.wrap(new_blockquote)
|
||||
|
||||
calloutTitle = BeautifulSoup(callout_title_html, features="html.parser")
|
||||
tag.insert_before(calloutTitle)
|
||||
|
||||
return (soup.decode(False, formatter=None))
|
||||
|
||||
|
||||
### Execution ###
|
||||
|
||||
file_list = []
|
||||
|
||||
if len(sys.argv) > 1:
|
||||
path = sys.argv[1]
|
||||
for filename in glob(path + "/**/*.md", recursive=True):
|
||||
if (os.path.isfile(filename)):
|
||||
file_list.append(filename)
|
||||
else:
|
||||
print(f"Usage: python3 {sys.argv[0]} [root folder]")
|
||||
print(f"Note: Please be careful, this software applies modifications recursively!")
|
||||
|
||||
for filename in file_list:
|
||||
print(f"Found file {filename}, processing...", end='')
|
||||
data = open_file(filename)
|
||||
text = convert_pattern(data)
|
||||
write_file(filename, text)
|
||||
print(f" done!")
|
BIN
custom/convert-usage/screenshot.png
Normal file
After Width: | Height: | Size: 22 KiB |
14
custom/docker-compose.yml
Normal file
@ -0,0 +1,14 @@
|
||||
version: '3.4'
|
||||
|
||||
services:
|
||||
quartz:
|
||||
image: quartz-jpg
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
environment:
|
||||
NODE_ENV: production
|
||||
container_name: quartz-jpg-container
|
||||
restart: always
|
||||
ports:
|
||||
- 8080:8080
|
8
custom/update-repos.sh
Normal file
@ -0,0 +1,8 @@
|
||||
git fetch convert-furigana main
|
||||
git subtree pull --prefix custom/convert-furigana convert-furigana main --squash
|
||||
|
||||
git fetch convert-usage main
|
||||
git subtree pull --prefix custom/convert-usage convert-usage main --squash
|
||||
|
||||
git fetch content main
|
||||
git subtree pull --prefix content content main --squash
|
@ -129,11 +129,11 @@ export default (() => {
|
||||
return <button id="btn">Click me</button>
|
||||
}
|
||||
|
||||
YourComponent.beforeDOMLoaded = `
|
||||
YourComponent.beforeDOM = `
|
||||
console.log("hello from before the page loads!")
|
||||
`
|
||||
|
||||
YourComponent.afterDOMLoaded = `
|
||||
YourComponent.afterDOM = `
|
||||
document.getElementById('btn').onclick = () => {
|
||||
alert('button clicked!')
|
||||
}
|
||||
@ -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.
|
||||
|
||||
@ -192,7 +180,7 @@ export default (() => {
|
||||
return <button id="btn">Click me</button>
|
||||
}
|
||||
|
||||
YourComponent.afterDOMLoaded = script
|
||||
YourComponent.afterDOM = script
|
||||
return YourComponent
|
||||
}) satisfies QuartzComponentConstructor
|
||||
```
|
||||
|
@ -25,11 +25,10 @@ The following sections will go into detail for what methods can be implemented f
|
||||
- `BuildCtx` is defined in `quartz/ctx.ts`. It consists of
|
||||
- `argv`: The command line arguments passed to the Quartz [[build]] command
|
||||
- `cfg`: The full Quartz [[configuration]]
|
||||
- `allSlugs`: a list of all the valid content slugs (see [[paths]] for more information on what a slug is)
|
||||
- `allSlugs`: a list of all the valid content slugs (see [[paths]] for more information on what a `ServerSlug` is)
|
||||
- `StaticResources` is defined in `quartz/resources.tsx`. It consists of
|
||||
- `css`: a list of CSS style definitions that should be loaded. A CSS style is described with the `CSSResource` type which is also defined in `quartz/resources.tsx`. It accepts either a source URL or the inline content of the stylesheet.
|
||||
- `css`: a list of URLs for stylesheets that should be loaded
|
||||
- `js`: a list of scripts that should be loaded. A script is described with the `JSResource` type which is also defined in `quartz/resources.tsx`. It allows you to define a load time (either before or after the DOM has been loaded), whether it should be a module, and either the source URL or the inline content of the script.
|
||||
- `additionalHead`: a list of JSX elements or functions that return JSX elements to be added to the `<head>` tag of the page. Functions receive the page's data as an argument and can conditionally render elements.
|
||||
|
||||
## Transformers
|
||||
|
||||
@ -38,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>
|
||||
@ -86,10 +85,8 @@ export const Latex: QuartzTransformerPlugin<Options> = (opts?: Options) => {
|
||||
if (engine === "katex") {
|
||||
return {
|
||||
css: [
|
||||
{
|
||||
// base css
|
||||
content: "https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.16.9/katex.min.css",
|
||||
},
|
||||
"https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.16.9/katex.min.css",
|
||||
],
|
||||
js: [
|
||||
{
|
||||
@ -100,6 +97,8 @@ export const Latex: QuartzTransformerPlugin<Options> = (opts?: Options) => {
|
||||
},
|
||||
],
|
||||
}
|
||||
} else {
|
||||
return {}
|
||||
}
|
||||
},
|
||||
}
|
||||
@ -221,26 +220,12 @@ export type QuartzEmitterPlugin<Options extends OptionType = undefined> = (
|
||||
|
||||
export type QuartzEmitterPluginInstance = {
|
||||
name: string
|
||||
emit(
|
||||
ctx: BuildCtx,
|
||||
content: ProcessedContent[],
|
||||
resources: StaticResources,
|
||||
): Promise<FilePath[]> | AsyncGenerator<FilePath>
|
||||
partialEmit?(
|
||||
ctx: BuildCtx,
|
||||
content: ProcessedContent[],
|
||||
resources: StaticResources,
|
||||
changeEvents: ChangeEvent[],
|
||||
): Promise<FilePath[]> | AsyncGenerator<FilePath> | null
|
||||
emit(ctx: BuildCtx, content: ProcessedContent[], resources: StaticResources): Promise<FilePath[]>
|
||||
getQuartzComponents(ctx: BuildCtx): QuartzComponent[]
|
||||
}
|
||||
```
|
||||
|
||||
An emitter plugin must define a `name` field, an `emit` function, and a `getQuartzComponents` function. It can optionally implement a `partialEmit` function for incremental builds.
|
||||
|
||||
- `emit` is responsible for looking at all the parsed and filtered content and then appropriately creating files and returning a list of paths to files the plugin created.
|
||||
- `partialEmit` is an optional function that enables incremental builds. It receives information about which files have changed (`changeEvents`) and can selectively rebuild only the necessary files. This is useful for optimizing build times in development mode. If `partialEmit` is undefined, it will default to the `emit` function.
|
||||
- `getQuartzComponents` declares which Quartz components the emitter uses to construct its pages.
|
||||
An emitter plugin must define a `name` field, an `emit` function, and a `getQuartzComponents` function. `emit` is responsible for looking at all the parsed and filtered content and then appropriately creating files and returning a list of paths to files the plugin created.
|
||||
|
||||
Creating new files can be done via regular Node [fs module](https://nodejs.org/api/fs.html) (i.e. `fs.cp` or `fs.writeFile`) or via the `write` function in `quartz/plugins/emitters/helpers.ts` if you are creating files that contain text. `write` has the following signature:
|
||||
|
||||
@ -249,7 +234,7 @@ export type WriteOptions = (data: {
|
||||
// the build context
|
||||
ctx: BuildCtx
|
||||
// the name of the file to emit (not including the file extension)
|
||||
slug: FullSlug
|
||||
slug: ServerSlug
|
||||
// the file extension
|
||||
ext: `.${string}` | ""
|
||||
// the file content to add
|
||||
@ -275,11 +260,11 @@ export const ContentPage: QuartzEmitterPlugin = () => {
|
||||
...defaultContentPageLayout,
|
||||
pageBody: Content(),
|
||||
}
|
||||
const { head, header, beforeBody, pageBody, afterBody, left, right, footer } = layout
|
||||
const { head, header, beforeBody, pageBody, left, right, footer } = layout
|
||||
return {
|
||||
name: "ContentPage",
|
||||
getQuartzComponents() {
|
||||
return [head, ...header, ...beforeBody, pageBody, ...afterBody, ...left, ...right, footer]
|
||||
return [head, ...header, ...beforeBody, pageBody, ...left, ...right, footer]
|
||||
},
|
||||
async emit(ctx, content, resources, emit): Promise<FilePath[]> {
|
||||
const cfg = ctx.cfg.configuration
|
||||
@ -287,7 +272,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,
|
||||
|
@ -48,4 +48,4 @@ Here are the main types of slugs with a rough description of each type of path:
|
||||
- `SimpleSlug`: cannot be relative and shouldn't have `/index` as an ending or a file extension. It _can_ however have a trailing slash to indicate a folder path.
|
||||
- `RelativeURL`: must start with `.` or `..` to indicate it's a relative URL. Shouldn't have `/index` as an ending or a file extension but can contain a trailing slash.
|
||||
|
||||
To get a clearer picture of how these relate to each other, take a look at the path tests in `quartz/util/path.test.ts`.
|
||||
To get a clearer picture of how these relate to each other, take a look at the path tests in `quartz/path.test.ts`.
|
||||
|
@ -29,14 +29,11 @@ Some common frontmatter fields that are natively supported by Quartz:
|
||||
|
||||
- `title`: Title of the page. If it isn't provided, Quartz will use the name of the file as the title.
|
||||
- `description`: Description of the page used for link previews.
|
||||
- `permalink`: A custom URL for the page that will remain constant even if the path to the file changes.
|
||||
- `aliases`: Other names for this note. This is a list of strings.
|
||||
- `tags`: Tags for this note.
|
||||
- `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.
|
||||
|
@ -21,7 +21,3 @@ This will start a local web server to run your Quartz on your computer. Open a w
|
||||
> - `--serve`: run a local hot-reloading server to preview your Quartz
|
||||
> - `--port`: what port to run the local preview server on
|
||||
> - `--concurrency`: how many threads to use to parse notes
|
||||
|
||||
> [!warning] Not to be used for production
|
||||
> Serve mode is intended for local previews only.
|
||||
> For production workloads, see the page on [[hosting]].
|
||||
|
@ -21,19 +21,14 @@ const config: QuartzConfig = {
|
||||
This part of the configuration concerns anything that can affect the whole site. The following is a list breaking down all the things you can configure:
|
||||
|
||||
- `pageTitle`: title of the site. This is also used when generating the [[RSS Feed]] for your site.
|
||||
- `pageTitleSuffix`: a string added to the end of the page title. This only applies to the browser tab title, not the title shown at the top of the page.
|
||||
- `enableSPA`: whether to enable [[SPA Routing]] on your site.
|
||||
- `enablePopovers`: whether to enable [[popover previews]] on your site.
|
||||
- `analytics`: what to use for analytics on your site. Values can be
|
||||
- `null`: don't use analytics;
|
||||
- `{ provider: 'google', tagId: '<your-google-tag>' }`: use Google Analytics;
|
||||
- `{ provider: 'plausible' }` (managed) or `{ provider: 'plausible', host: 'https://<your-plausible-host>' }` (self-hosted, make sure to include the `https://` protocol prefix): use [Plausible](https://plausible.io/);
|
||||
- `{ provider: 'plausible' }` (managed) or `{ provider: 'plausible', host: '<your-plausible-host>' }` (self-hosted): use [Plausible](https://plausible.io/);
|
||||
- `{ provider: 'umami', host: '<your-umami-host>', websiteId: '<your-umami-website-id>' }`: use [Umami](https://umami.is/);
|
||||
- `{ provider: 'goatcounter', websiteId: 'my-goatcounter-id' }` (managed) or `{ provider: 'goatcounter', websiteId: 'my-goatcounter-id', host: 'my-goatcounter-domain.com', scriptSrc: 'https://my-url.to/counter.js' }` (self-hosted) use [GoatCounter](https://goatcounter.com);
|
||||
- `{ provider: 'posthog', apiKey: '<your-posthog-project-apiKey>', host: '<your-posthog-host>' }`: use [Posthog](https://posthog.com/);
|
||||
- `{ provider: 'tinylytics', siteId: '<your-site-id>' }`: use [Tinylytics](https://tinylytics.app/);
|
||||
- `{ provider: 'cabin' }` or `{ provider: 'cabin', host: 'https://cabin.example.com' }` (custom domain): use [Cabin](https://withcabin.com);
|
||||
- `{provider: 'clarity', projectId: '<your-clarity-id-code' }`: use [Microsoft clarity](https://clarity.microsoft.com/). The project id can be found on top of the overview page.
|
||||
- `{ provider: 'goatcounter', websiteId: 'my-goatcounter-id' }` (managed) or `{ provider: 'goatcounter', websiteId: 'my-goatcounter-id', host: 'my-goatcounter-domain.com', scriptSrc: 'https://my-url.to/counter.js' }` (self-hosted) use [GoatCounter](https://goatcounter.com)
|
||||
- `locale`: used for [[i18n]] and date formatting
|
||||
- `baseUrl`: this is used for sitemaps and RSS feeds that require an absolute URL to know where the canonical 'home' of your site lives. This is normally the deployed URL of your site (e.g. `quartz.jzhao.xyz` for this site). Do not include the protocol (i.e. `https://`) or any leading or trailing slashes.
|
||||
- This should also include the subpath if you are [[hosting]] on GitHub pages without a custom domain. For example, if my repository is `jackyzha0/quartz`, GitHub pages would deploy to `https://jackyzha0.github.io/quartz` and the `baseUrl` would be `jackyzha0.github.io/quartz`.
|
||||
@ -41,12 +36,11 @@ This part of the configuration concerns anything that can affect the whole site.
|
||||
- `ignorePatterns`: a list of [glob](<https://en.wikipedia.org/wiki/Glob_(programming)>) patterns that Quartz should ignore and not search through when looking for files inside the `content` folder. See [[private pages]] for more details.
|
||||
- `defaultDateType`: whether to use created, modified, or published as the default date to display on pages and page listings.
|
||||
- `theme`: configure how the site looks.
|
||||
- `cdnCaching`: if `true` (default), use Google CDN to cache the fonts. This will generally be faster. Disable (`false`) this if you want Quartz to download the fonts to be self-contained.
|
||||
- `cdnCaching`: If `true` (default), use Google CDN to cache the fonts. This will generally will be faster. Disable (`false`) this if you want Quartz to download the fonts to be self-contained.
|
||||
- `typography`: what fonts to use. Any font available on [Google Fonts](https://fonts.google.com/) works here.
|
||||
- `title`: font for the title of the site (optional, same as `header` by default)
|
||||
- `header`: font to use for headers
|
||||
- `code`: font for inline and block quotes
|
||||
- `body`: font for everything
|
||||
- `header`: Font to use for headers
|
||||
- `code`: Font for inline and block quotes.
|
||||
- `body`: Font for everything
|
||||
- `colors`: controls the theming of the site.
|
||||
- `light`: page background
|
||||
- `lightgray`: borders
|
||||
@ -56,7 +50,6 @@ This part of the configuration concerns anything that can affect the whole site.
|
||||
- `secondary`: link colour, current [[graph view|graph]] node
|
||||
- `tertiary`: hover states and visited [[graph view|graph]] nodes
|
||||
- `highlight`: internal link background, highlighted text, [[syntax highlighting|highlighted lines of code]]
|
||||
- `textHighlight`: markdown highlighted text background
|
||||
|
||||
## Plugins
|
||||
|
||||
@ -104,30 +97,8 @@ transformers: [
|
||||
]
|
||||
```
|
||||
|
||||
Some plugins are included by default in the [`quartz.config.ts`](https://github.com/jackyzha0/quartz/blob/v4/quartz.config.ts), but there are more available.
|
||||
Some plugins are included by default in the[ `quartz.config.ts`](https://github.com/jackyzha0/quartz/blob/v4/quartz.config.ts), but there are more available.
|
||||
|
||||
You can see a list of all plugins and their configuration options [[tags/plugin|here]].
|
||||
|
||||
If you'd like to make your own plugins, see the [[making plugins|making custom plugins]] guide.
|
||||
|
||||
## Fonts
|
||||
|
||||
Fonts can be specified as a `string` or a `FontSpecification`:
|
||||
|
||||
```ts
|
||||
// string
|
||||
typography: {
|
||||
header: "Schibsted Grotesk",
|
||||
...
|
||||
}
|
||||
|
||||
// FontSpecification
|
||||
typography: {
|
||||
header: {
|
||||
name: "Schibsted Grotesk",
|
||||
weights: [400, 700],
|
||||
includeItalic: true,
|
||||
},
|
||||
...
|
||||
}
|
||||
```
|
||||
|
@ -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.
|
||||
|
@ -1,28 +0,0 @@
|
||||
---
|
||||
title: "Roam Research Compatibility"
|
||||
tags:
|
||||
- feature/transformer
|
||||
---
|
||||
|
||||
[Roam Research](https://roamresearch.com) is a note-taking tool that organizes your knowledge graph in a unique and interconnected way.
|
||||
|
||||
Quartz supports transforming the special Markdown syntax from Roam Research (like `{{[[components]]}}` and other formatting) into
|
||||
regular Markdown via the [[RoamFlavoredMarkdown]] plugin.
|
||||
|
||||
```typescript title="quartz.config.ts"
|
||||
plugins: {
|
||||
transformers: [
|
||||
// ...
|
||||
Plugin.RoamFlavoredMarkdown(),
|
||||
Plugin.ObsidianFlavoredMarkdown(),
|
||||
// ...
|
||||
],
|
||||
},
|
||||
```
|
||||
|
||||
> [!warning]
|
||||
> As seen above placement of `Plugin.RoamFlavoredMarkdown()` within `quartz.config.ts` is very important. It must come before `Plugin.ObsidianFlavoredMarkdown()`.
|
||||
|
||||
## Customization
|
||||
|
||||
This functionality is provided by the [[RoamFlavoredMarkdown]] 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`
|
||||
|
@ -19,6 +19,7 @@ Component.Breadcrumbs({
|
||||
spacerSymbol: "❯", // symbol between crumbs
|
||||
rootName: "Home", // name of first/root element
|
||||
resolveFrontmatterTitle: true, // whether to resolve folder names through frontmatter titles
|
||||
hideOnRoot: true, // whether to hide breadcrumbs on root `index.md` page
|
||||
showCurrentPage: true, // whether to display the current page in the breadcrumbs
|
||||
})
|
||||
```
|
||||
|
@ -1,133 +0,0 @@
|
||||
---
|
||||
title: Comments
|
||||
tags:
|
||||
- component
|
||||
---
|
||||
|
||||
Quartz also has the ability to hook into various providers to enable readers to leave comments on your site.
|
||||
|
||||
![[giscus-example.png]]
|
||||
|
||||
As of today, only [Giscus](https://giscus.app/) is supported out of the box but PRs to support other providers are welcome!
|
||||
|
||||
## Providers
|
||||
|
||||
### Giscus
|
||||
|
||||
First, make sure that the [[setting up your GitHub repository|GitHub]] repository you are using for your Quartz meets the following requirements:
|
||||
|
||||
1. The **repository is [public](https://docs.github.com/en/github/administering-a-repository/managing-repository-settings/setting-repository-visibility#making-a-repository-public)**, otherwise visitors will not be able to view the discussion.
|
||||
2. The **[giscus](https://github.com/apps/giscus) app is installed**, otherwise visitors will not be able to comment and react.
|
||||
3. The **Discussions feature is turned on** by [enabling it for your repository](https://docs.github.com/en/github/administering-a-repository/managing-repository-settings/enabling-or-disabling-github-discussions-for-a-repository).
|
||||
|
||||
Then, use the [Giscus site](https://giscus.app/#repository) to figure out what your `repoId` and `categoryId` should be. Make sure you select `Announcements` for the Discussion category.
|
||||
|
||||
![[giscus-repo.png]]
|
||||
|
||||
![[giscus-discussion.png]]
|
||||
|
||||
After entering both your repository and selecting the discussion category, Giscus will compute some IDs that you'll need to provide back to Quartz. You won't need to manually add the script yourself as Quartz will handle that part for you but will need these values in the next step!
|
||||
|
||||
![[giscus-results.png]]
|
||||
|
||||
Finally, in `quartz.layout.ts`, edit the `afterBody` field of `sharedPageComponents` to include the following options but with the values you got from above:
|
||||
|
||||
```ts title="quartz.layout.ts"
|
||||
afterBody: [
|
||||
Component.Comments({
|
||||
provider: 'giscus',
|
||||
options: {
|
||||
// from data-repo
|
||||
repo: 'jackyzha0/quartz',
|
||||
// from data-repo-id
|
||||
repoId: 'MDEwOlJlcG9zaXRvcnkzODcyMTMyMDg',
|
||||
// from data-category
|
||||
category: 'Announcements',
|
||||
// from data-category-id
|
||||
categoryId: 'DIC_kwDOFxRnmM4B-Xg6',
|
||||
// from data-lang
|
||||
lang: 'en'
|
||||
}
|
||||
}),
|
||||
],
|
||||
```
|
||||
|
||||
### Customization
|
||||
|
||||
Quartz also exposes a few of the other Giscus options as well and you can provide them the same way `repo`, `repoId`, `category`, and `categoryId` are provided.
|
||||
|
||||
```ts
|
||||
type Options = {
|
||||
provider: "giscus"
|
||||
options: {
|
||||
repo: `${string}/${string}`
|
||||
repoId: string
|
||||
category: string
|
||||
categoryId: string
|
||||
|
||||
// Url to folder with custom themes
|
||||
// defaults to 'https://${cfg.baseUrl}/static/giscus'
|
||||
themeUrl?: string
|
||||
|
||||
// filename for light theme .css file
|
||||
// defaults to 'light'
|
||||
lightTheme?: string
|
||||
|
||||
// filename for dark theme .css file
|
||||
// defaults to 'dark'
|
||||
darkTheme?: string
|
||||
|
||||
// how to map pages -> discussions
|
||||
// defaults to 'url'
|
||||
mapping?: "url" | "title" | "og:title" | "specific" | "number" | "pathname"
|
||||
|
||||
// use strict title matching
|
||||
// defaults to true
|
||||
strict?: boolean
|
||||
|
||||
// whether to enable reactions for the main post
|
||||
// defaults to true
|
||||
reactionsEnabled?: boolean
|
||||
|
||||
// where to put the comment input box relative to the comments
|
||||
// defaults to 'bottom'
|
||||
inputPosition?: "top" | "bottom"
|
||||
|
||||
// set your preference language here
|
||||
// defaults to 'en'
|
||||
lang?: string
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### Custom CSS theme
|
||||
|
||||
Quartz supports custom theme for Giscus. To use a custom CSS theme, place the `.css` file inside the `quartz/static` folder and set the configuration values.
|
||||
|
||||
For example, if you have a light theme `light-theme.css`, a dark theme `dark-theme.css`, and your Quartz site is hosted at `https://example.com/`:
|
||||
|
||||
```ts
|
||||
afterBody: [
|
||||
Component.Comments({
|
||||
provider: 'giscus',
|
||||
options: {
|
||||
// Other options
|
||||
|
||||
themeUrl: "https://example.com/static/giscus", // corresponds to quartz/static/giscus/
|
||||
lightTheme: "light-theme", // corresponds to light-theme.css in quartz/static/giscus/
|
||||
darkTheme: "dark-theme", // corresponds to dark-theme.css quartz/static/giscus/
|
||||
}
|
||||
}),
|
||||
],
|
||||
```
|
||||
|
||||
#### Conditionally display comments
|
||||
|
||||
Quartz can conditionally display the comment box based on a field `comments` in the frontmatter. By default, all pages will display comments, to disable it for a specific page, set `comments` to `false`.
|
||||
|
||||
```
|
||||
---
|
||||
title: Comments disabled here!
|
||||
comments: false
|
||||
---
|
||||
```
|
@ -27,10 +27,12 @@ Component.Explorer({
|
||||
folderClickBehavior: "collapse", // what happens when you click a folder ("link" to navigate to folder page on click or "collapse" to collapse folder on click)
|
||||
folderDefaultState: "collapsed", // default state of folders ("collapsed" or "open")
|
||||
useSavedState: true, // whether to use local storage to save "state" (which folders are opened) of explorer
|
||||
// omitted but shown later
|
||||
sortFn: ...,
|
||||
filterFn: ...,
|
||||
mapFn: ...,
|
||||
// Sort order: folders first, then files. Sort folders and files alphabetically
|
||||
sortFn: (a, b) => {
|
||||
... // default implementation shown later
|
||||
},
|
||||
filterFn: filterFn: (node) => node.name !== "tags", // filters out 'tags' folder
|
||||
mapFn: undefined,
|
||||
// what order to apply functions in
|
||||
order: ["filter", "map", "sort"],
|
||||
})
|
||||
@ -43,30 +45,26 @@ Want to customize it even more?
|
||||
- Removing explorer: remove `Component.Explorer()` from `quartz.layout.ts`
|
||||
- (optional): After removing the explorer component, you can move the [[table of contents | Table of Contents]] component back to the `left` part of the layout
|
||||
- Changing `sort`, `filter` and `map` behavior: explained in [[#Advanced customization]]
|
||||
- Component: `quartz/components/Explorer.tsx`
|
||||
- Component:
|
||||
- Wrapper (Outer component, generates file tree, etc): `quartz/components/Explorer.tsx`
|
||||
- Explorer node (recursive, either a folder or a file): `quartz/components/ExplorerNode.tsx`
|
||||
- Style: `quartz/components/styles/explorer.scss`
|
||||
- Script: `quartz/components/scripts/explorer.inline.ts`
|
||||
|
||||
## Advanced customization
|
||||
|
||||
This component allows you to fully customize all of its behavior. You can pass a custom `sort`, `filter` and `map` function.
|
||||
All functions you can pass work with the `FileTrieNode` class, which has the following properties:
|
||||
All functions you can pass work with the `FileNode` class, which has the following properties:
|
||||
|
||||
```ts title="quartz/components/Explorer.tsx"
|
||||
class FileTrieNode {
|
||||
isFolder: boolean
|
||||
children: Array<FileTrieNode>
|
||||
data: ContentDetails | null
|
||||
}
|
||||
```
|
||||
```ts title="quartz/components/ExplorerNode.tsx" {2-5}
|
||||
export class FileNode {
|
||||
children: FileNode[] // children of current node
|
||||
name: string // last part of slug
|
||||
displayName: string // what actually should be displayed in the explorer
|
||||
file: QuartzPluginData | null // if node is a file, this is the file's metadata. See `QuartzPluginData` for more detail
|
||||
depth: number // depth of current node
|
||||
|
||||
```ts title="quartz/plugins/emitters/contentIndex.tsx"
|
||||
export type ContentDetails = {
|
||||
slug: FullSlug
|
||||
title: string
|
||||
links: SimpleSlug[]
|
||||
tags: string[]
|
||||
content: string
|
||||
... // rest of implementation
|
||||
}
|
||||
```
|
||||
|
||||
@ -76,14 +74,15 @@ Every function you can pass is optional. By default, only a `sort` function will
|
||||
// Sort order: folders first, then files. Sort folders and files alphabetically
|
||||
Component.Explorer({
|
||||
sortFn: (a, b) => {
|
||||
if ((!a.isFolder && !b.isFolder) || (a.isFolder && b.isFolder)) {
|
||||
if ((!a.file && !b.file) || (a.file && b.file)) {
|
||||
// sensitivity: "base": Only strings that differ in base letters compare as unequal. Examples: a ≠ b, a = á, a = A
|
||||
// numeric: true: Whether numeric collation should be used, such that "1" < "2" < "10"
|
||||
return a.displayName.localeCompare(b.displayName, undefined, {
|
||||
numeric: true,
|
||||
sensitivity: "base",
|
||||
})
|
||||
}
|
||||
|
||||
if (!a.isFolder && b.isFolder) {
|
||||
if (a.file && !b.file) {
|
||||
return 1
|
||||
} else {
|
||||
return -1
|
||||
@ -101,23 +100,41 @@ For more information on how to use `sort`, `filter` and `map`, you can check [Ar
|
||||
Type definitions look like this:
|
||||
|
||||
```ts
|
||||
type SortFn = (a: FileTrieNode, b: FileTrieNode) => number
|
||||
type FilterFn = (node: FileTrieNode) => boolean
|
||||
type MapFn = (node: FileTrieNode) => void
|
||||
sortFn: (a: FileNode, b: FileNode) => number
|
||||
filterFn: (node: FileNode) => boolean
|
||||
mapFn: (node: FileNode) => void
|
||||
```
|
||||
|
||||
> [!tip]
|
||||
> You can check if a `FileNode` is a folder or a file like this:
|
||||
>
|
||||
> ```ts
|
||||
> if (node.file) {
|
||||
> // node is a file
|
||||
> } else {
|
||||
> // node is a folder
|
||||
> }
|
||||
> ```
|
||||
|
||||
## Basic examples
|
||||
|
||||
These examples show the basic usage of `sort`, `map` and `filter`.
|
||||
|
||||
### Use `sort` to put files first
|
||||
|
||||
Using this example, the explorer will alphabetically sort everything.
|
||||
Using this example, the explorer will alphabetically sort everything, but put all **files** above all **folders**.
|
||||
|
||||
```ts title="quartz.layout.ts"
|
||||
Component.Explorer({
|
||||
sortFn: (a, b) => {
|
||||
if ((!a.file && !b.file) || (a.file && b.file)) {
|
||||
return a.displayName.localeCompare(b.displayName)
|
||||
}
|
||||
if (a.file && !b.file) {
|
||||
return -1
|
||||
} else {
|
||||
return 1
|
||||
}
|
||||
},
|
||||
})
|
||||
```
|
||||
@ -130,47 +147,42 @@ Using this example, the display names of all `FileNodes` (folders + files) will
|
||||
Component.Explorer({
|
||||
mapFn: (node) => {
|
||||
node.displayName = node.displayName.toUpperCase()
|
||||
return node
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
### Remove list of elements (`filter`)
|
||||
|
||||
Using this example, you can remove elements from your explorer by providing an array of folders/files to exclude.
|
||||
Note that this example filters on the title but you can also do it via slug or any other field available on `FileTrieNode`.
|
||||
Using this example, you can remove elements from your explorer by providing an array of folders/files using the `omit` set.
|
||||
|
||||
```ts title="quartz.layout.ts"
|
||||
Component.Explorer({
|
||||
filterFn: (node) => {
|
||||
// set containing names of everything you want to filter out
|
||||
const omit = new Set(["authoring content", "tags", "advanced"])
|
||||
|
||||
// can also use node.slug or by anything on node.data
|
||||
// note that node.data is only present for files that exist on disk
|
||||
// (e.g. implicit folder nodes that have no associated index.md)
|
||||
return !omit.has(node.displayName.toLowerCase())
|
||||
const omit = new Set(["authoring content", "tags", "hosting"])
|
||||
return !omit.has(node.name.toLowerCase())
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
You can customize this by changing the entries of the `omit` set. Simply add all folder or file names you want to remove.
|
||||
|
||||
### Remove files by tag
|
||||
|
||||
You can access the tags of a file by `node.data.tags`.
|
||||
You can access the frontmatter of a file by `node.file?.frontmatter?`. This allows you to filter out files based on their frontmatter, for example by their tags.
|
||||
|
||||
```ts title="quartz.layout.ts"
|
||||
Component.Explorer({
|
||||
filterFn: (node) => {
|
||||
// exclude files with the tag "explorerexclude"
|
||||
return node.data.tags?.includes("explorerexclude") !== true
|
||||
return node.file?.frontmatter?.tags?.includes("explorerexclude") !== true
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
### Show every element in explorer
|
||||
|
||||
By default, the explorer will filter out the `tags` folder.
|
||||
To override the default filter function, you can set the filter function to `undefined`.
|
||||
To override the default filter function that removes the `tags` folder from the explorer, you can set the filter function to `undefined`.
|
||||
|
||||
```ts title="quartz.layout.ts"
|
||||
Component.Explorer({
|
||||
@ -182,12 +194,10 @@ Component.Explorer({
|
||||
|
||||
> [!tip]
|
||||
> When writing more complicated functions, the `layout` file can start to look very cramped.
|
||||
> You can fix this by defining your sort functions outside of the component
|
||||
> and passing it in.
|
||||
>
|
||||
> ```ts title="quartz.layout.ts"
|
||||
> import { Options } from "./quartz/components/Explorer"
|
||||
> You can fix this by defining your functions in another file.
|
||||
>
|
||||
> ```ts title="functions.ts"
|
||||
> import { Options } from "./quartz/components/ExplorerNode"
|
||||
> export const mapFn: Options["mapFn"] = (node) => {
|
||||
> // implement your function here
|
||||
> }
|
||||
@ -197,12 +207,16 @@ Component.Explorer({
|
||||
> export const sortFn: Options["sortFn"] = (a, b) => {
|
||||
> // implement your function here
|
||||
> }
|
||||
> ```
|
||||
>
|
||||
> You can then import them like this:
|
||||
>
|
||||
> ```ts title="quartz.layout.ts"
|
||||
> import { mapFn, filterFn, sortFn } from "./functions.ts"
|
||||
> Component.Explorer({
|
||||
> // ... your other options
|
||||
> mapFn,
|
||||
> filterFn,
|
||||
> sortFn,
|
||||
> mapFn: mapFn,
|
||||
> filterFn: filterFn,
|
||||
> sortFn: sortFn,
|
||||
> })
|
||||
> ```
|
||||
|
||||
@ -213,11 +227,93 @@ To add emoji prefixes (📁 for folders, 📄 for files), you could use a map fu
|
||||
```ts title="quartz.layout.ts"
|
||||
Component.Explorer({
|
||||
mapFn: (node) => {
|
||||
if (node.isFolder) {
|
||||
node.displayName = "📁 " + node.displayName
|
||||
} else {
|
||||
// dont change name of root node
|
||||
if (node.depth > 0) {
|
||||
// set emoji for file/folder
|
||||
if (node.file) {
|
||||
node.displayName = "📄 " + node.displayName
|
||||
} else {
|
||||
node.displayName = "📁 " + node.displayName
|
||||
}
|
||||
}
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
### Putting it all together
|
||||
|
||||
In this example, we're going to customize the explorer by using functions from examples above to [[#Add emoji prefix | add emoji prefixes]], [[#remove-list-of-elements-filter| filter out some folders]] and [[#use-sort-to-put-files-first | sort with files above folders]].
|
||||
|
||||
```ts title="quartz.layout.ts"
|
||||
Component.Explorer({
|
||||
filterFn: sampleFilterFn,
|
||||
mapFn: sampleMapFn,
|
||||
sortFn: sampleSortFn,
|
||||
order: ["filter", "sort", "map"],
|
||||
})
|
||||
```
|
||||
|
||||
Notice how we customized the `order` array here. This is done because the default order applies the `sort` function last. While this normally works well, it would cause unintended behavior here, since we changed the first characters of all display names. In our example, `sort` would be applied based off the emoji prefix instead of the first _real_ character.
|
||||
|
||||
To fix this, we just changed around the order and apply the `sort` function before changing the display names in the `map` function.
|
||||
|
||||
### Use `sort` with pre-defined sort order
|
||||
|
||||
Here's another example where a map containing file/folder names (as slugs) is used to define the sort order of the explorer in quartz. All files/folders that aren't listed inside of `nameOrderMap` will appear at the top of that folders hierarchy level.
|
||||
|
||||
It's also worth mentioning, that the smaller the number set in `nameOrderMap`, the higher up the entry will be in the explorer. Incrementing every folder/file by 100, makes ordering files in their folders a lot easier. Lastly, this example still allows you to use a `mapFn` or frontmatter titles to change display names, as it uses slugs for `nameOrderMap` (which is unaffected by display name changes).
|
||||
|
||||
```ts title="quartz.layout.ts"
|
||||
Component.Explorer({
|
||||
sortFn: (a, b) => {
|
||||
const nameOrderMap: Record<string, number> = {
|
||||
"poetry-folder": 100,
|
||||
"essay-folder": 200,
|
||||
"research-paper-file": 201,
|
||||
"dinosaur-fossils-file": 300,
|
||||
"other-folder": 400,
|
||||
}
|
||||
|
||||
let orderA = 0
|
||||
let orderB = 0
|
||||
|
||||
if (a.file && a.file.slug) {
|
||||
orderA = nameOrderMap[a.file.slug] || 0
|
||||
} else if (a.name) {
|
||||
orderA = nameOrderMap[a.name] || 0
|
||||
}
|
||||
|
||||
if (b.file && b.file.slug) {
|
||||
orderB = nameOrderMap[b.file.slug] || 0
|
||||
} else if (b.name) {
|
||||
orderB = nameOrderMap[b.name] || 0
|
||||
}
|
||||
|
||||
return orderA - orderB
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
For reference, this is how the quartz explorer window would look like with that example:
|
||||
|
||||
```
|
||||
📖 Poetry Folder
|
||||
📑 Essay Folder
|
||||
⚗️ Research Paper File
|
||||
🦴 Dinosaur Fossils File
|
||||
🔮 Other Folder
|
||||
```
|
||||
|
||||
And this is how the file structure would look like:
|
||||
|
||||
```
|
||||
index.md
|
||||
poetry-folder
|
||||
index.md
|
||||
essay-folder
|
||||
index.md
|
||||
research-paper-file.md
|
||||
dinosaur-fossils-file.md
|
||||
other-folder
|
||||
index.md
|
||||
```
|
||||
|
@ -30,4 +30,4 @@ As with folder listings, you can also provide a description and title for a tag
|
||||
|
||||
## Customization
|
||||
|
||||
Quartz allows you to define a custom sort ordering for content on both page types. The folder listings are a functionality of the [[FolderPage]] plugin, the tag listings of the [[TagPage]] plugin. See the plugin pages for customization options.
|
||||
The folder listings are a functionality of the [[FolderPage]] plugin, the tag listings of the [[TagPage]] plugin. See the plugin pages for customization options.
|
||||
|
@ -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
|
||||
},
|
||||
})
|
||||
```
|
||||
|
@ -13,7 +13,9 @@ There may be some notes you want to avoid publishing as a website. Quartz suppor
|
||||
If you'd like to only publish a select number of notes, you can instead use [[ExplicitPublish]] which will filter out all notes except for any that have `publish: true` in the frontmatter.
|
||||
|
||||
> [!warning]
|
||||
> Regardless of the filter plugin used, **all non-markdown files will be emitted and available publically in the final build.** This includes files such as images, voice recordings, PDFs, etc.
|
||||
> Regardless of the filter plugin used, **all non-markdown files will be emitted and available publically in the final build.** This includes files such as images, voice recordings, PDFs, etc. One way to prevent this and still be able to embed local images is to create a folder specifically for public media and add the following two patterns to the ignorePatterns array.
|
||||
>
|
||||
> `"!(PublicMedia)**/!(*.md)", "!(*.md)"`
|
||||
|
||||
## `ignorePatterns`
|
||||
|
||||
@ -26,7 +28,7 @@ Common examples include:
|
||||
|
||||
- `some/folder`: exclude the entire of `some/folder`
|
||||
- `*.md`: exclude all files with a `.md` extension
|
||||
- `!(*.md)` exclude all files that _don't_ have a `.md` extension. Note that negations _must_ parenthesize the rest of the pattern!
|
||||
- `!*.md` exclude all files that _don't_ have a `.md` extension
|
||||
- `**/private`: exclude any files or folders named `private` at any level of nesting
|
||||
|
||||
> [!warning]
|
||||
|
@ -1,44 +0,0 @@
|
||||
---
|
||||
title: Reader Mode
|
||||
tags:
|
||||
- component
|
||||
---
|
||||
|
||||
Reader Mode is a feature that allows users to focus on the content by hiding the sidebars and other UI elements. When enabled, it provides a clean, distraction-free reading experience.
|
||||
|
||||
## Configuration
|
||||
|
||||
Reader Mode is enabled by default. To disable it, you can remove the component from your layout configuration in `quartz.layout.ts`:
|
||||
|
||||
```ts
|
||||
// Remove or comment out this line
|
||||
Component.ReaderMode(),
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
The Reader Mode toggle appears as a button with a book icon. When clicked:
|
||||
|
||||
- Sidebars are hidden
|
||||
- Hovering over the content area reveals the sidebars temporarily
|
||||
|
||||
Unlike Dark Mode, Reader Mode state is not persisted between page reloads but is maintained during SPA navigation within the site.
|
||||
|
||||
## Customization
|
||||
|
||||
You can customize the appearance of Reader Mode through CSS variables and styles. The component uses the following classes:
|
||||
|
||||
- `.readermode`: The toggle button
|
||||
- `.readerIcon`: The book icon
|
||||
- `[reader-mode="on"]`: Applied to the root element when Reader Mode is active
|
||||
|
||||
Example customization in your custom CSS:
|
||||
|
||||
```scss
|
||||
.readermode {
|
||||
// Customize the button
|
||||
svg {
|
||||
stroke: var(--custom-color);
|
||||
}
|
||||
}
|
||||
```
|
@ -9,7 +9,6 @@ Quartz can generate a list of recent notes based on some filtering and sorting c
|
||||
|
||||
- Changing the title from "Recent notes": pass in an additional parameter to `Component.RecentNotes({ title: "Recent writing" })`
|
||||
- Changing the number of recent notes: pass in an additional parameter to `Component.RecentNotes({ limit: 5 })`
|
||||
- Display the note's tags (defaults to true): `Component.RecentNotes({ showTags: false })`
|
||||
- Show a 'see more' link: pass in an additional parameter to `Component.RecentNotes({ linkToMore: "tags/components" })`. This field should be a full slug to a page that exists.
|
||||
- Customize filtering: pass in an additional parameter to `Component.RecentNotes({ filter: someFilterFunction })`. The filter function should be a function that has the signature `(f: QuartzPluginData) => boolean`.
|
||||
- Customize sorting: pass in an additional parameter to `Component.RecentNotes({ sort: someSortFunction })`. By default, Quartz will sort by date and then tie break lexographically. The sort function should be a function that has the signature `(f1: QuartzPluginData, f2: QuartzPluginData) => number`. See `byDateAndAlphabetical` in `quartz/components/PageList.tsx` for an example.
|
||||
|
@ -1,19 +0,0 @@
|
||||
---
|
||||
title: "Social Media Preview Cards"
|
||||
---
|
||||
|
||||
A lot of social media platforms can display a rich preview for your website when sharing a link (most notably, a cover image, a title and a description).
|
||||
|
||||
Quartz can also dynamically generate and use new cover images for every page to be used in link previews on social media for you.
|
||||
|
||||
## Showcase
|
||||
|
||||
After enabling the [[CustomOgImages]] emitter plugin, the social media link preview for [[authoring content | Authoring Content]] looks like this:
|
||||
|
||||
| Light | Dark |
|
||||
| ----------------------------------- | ---------------------------------- |
|
||||
| ![[social-image-preview-light.png]] | ![[social-image-preview-dark.png]] |
|
||||
|
||||
## Configuration
|
||||
|
||||
This functionality is provided by the [[CustomOgImages]] plugin. See the plugin page for customization options.
|
@ -95,16 +95,6 @@ const [age, setAge] = useState(50)
|
||||
const [name, setName] = useState("Taylor")
|
||||
```
|
||||
|
||||
### Inline Highlighting
|
||||
|
||||
Append {:lang} to the end of inline code to highlight it like a regular code block.
|
||||
|
||||
```
|
||||
This is an array `[1, 2, 3]{:js}` of numbers 1 through 3.
|
||||
```
|
||||
|
||||
This is an array `[1, 2, 3]{:js}` of numbers 1 through 3.
|
||||
|
||||
### Line numbers
|
||||
|
||||
Syntax highlighting has line numbers configured automatically. If you want to start line numbers at a specific number, use `showLineNumbers{number}`:
|
||||
|
@ -2,11 +2,22 @@
|
||||
draft: true
|
||||
---
|
||||
|
||||
## misc backlog
|
||||
## high priority backlog
|
||||
|
||||
- static dead link detection
|
||||
- block links: https://help.obsidian.md/Linking+notes+and+files/Internal+links#Link+to+a+block+in+a+note
|
||||
- note/header/block transcludes: https://help.obsidian.md/Linking+notes+and+files/Embedding+files
|
||||
- docker support
|
||||
|
||||
## misc backlog
|
||||
|
||||
- breadcrumbs component
|
||||
- cursor chat extension
|
||||
- https://giscus.app/ extension
|
||||
- sidenotes? https://github.com/capnfabs/paperesque
|
||||
- direct match in search using double quotes
|
||||
- https://help.obsidian.md/Advanced+topics/Using+Obsidian+URI
|
||||
- audio/video embed styling
|
||||
- Canvas
|
||||
- parse all images in page: use this for page lists if applicable?
|
||||
- CV mode? with print stylesheet
|
||||
|
@ -57,18 +57,18 @@ jobs:
|
||||
build:
|
||||
runs-on: ubuntu-22.04
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v3
|
||||
with:
|
||||
fetch-depth: 0 # Fetch all history for git info
|
||||
- uses: actions/setup-node@v4
|
||||
- uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version: 22
|
||||
node-version: 18.14
|
||||
- name: Install Dependencies
|
||||
run: npm ci
|
||||
- name: Build Quartz
|
||||
run: npx quartz build
|
||||
- name: Upload artifact
|
||||
uses: actions/upload-pages-artifact@v3
|
||||
uses: actions/upload-pages-artifact@v2
|
||||
with:
|
||||
path: public
|
||||
|
||||
@ -81,7 +81,7 @@ jobs:
|
||||
steps:
|
||||
- name: Deploy to GitHub Pages
|
||||
id: deployment
|
||||
uses: actions/deploy-pages@v4
|
||||
uses: actions/deploy-pages@v2
|
||||
```
|
||||
|
||||
Then:
|
||||
@ -182,33 +182,37 @@ Using `docs.example.com` is an example of a subdomain. They're a simple way of c
|
||||
|
||||
## GitLab Pages
|
||||
|
||||
In your local Quartz, create a new file `.gitlab-ci.yml`.
|
||||
In your local Quartz, create a new file `.gitlab-ci.yaml`.
|
||||
|
||||
```yaml title=".gitlab-ci.yml"
|
||||
```yaml title=".gitlab-ci.yaml"
|
||||
stages:
|
||||
- build
|
||||
- deploy
|
||||
|
||||
image: node:22
|
||||
cache: # Cache modules in between jobs
|
||||
key: $CI_COMMIT_REF_SLUG
|
||||
paths:
|
||||
- .npm/
|
||||
variables:
|
||||
NODE_VERSION: "18.14"
|
||||
|
||||
build:
|
||||
stage: build
|
||||
rules:
|
||||
- if: '$CI_COMMIT_REF_NAME == "v4"'
|
||||
before_script:
|
||||
- apt-get update -q && apt-get install -y nodejs npm
|
||||
- npm install -g n
|
||||
- n $NODE_VERSION
|
||||
- hash -r
|
||||
- npm ci --cache .npm --prefer-offline
|
||||
- npm ci
|
||||
script:
|
||||
- npx quartz build
|
||||
artifacts:
|
||||
paths:
|
||||
- public
|
||||
cache:
|
||||
paths:
|
||||
- ~/.npm/
|
||||
key: "${CI_COMMIT_REF_SLUG}-node-${CI_COMMIT_REF_NAME}"
|
||||
tags:
|
||||
- gitlab-org-docker
|
||||
- docker
|
||||
|
||||
pages:
|
||||
stage: deploy
|
||||
@ -247,28 +251,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:
|
||||
|
Before Width: | Height: | Size: 129 KiB |
Before Width: | Height: | Size: 132 KiB |
Before Width: | Height: | Size: 88 KiB |
Before Width: | Height: | Size: 572 KiB |
Before Width: | Height: | Size: 108 KiB |
Before Width: | Height: | Size: 171 KiB |
BIN
docs/images/quartz layout.png
Normal file
After Width: | Height: | Size: 55 KiB |
Before Width: | Height: | Size: 36 KiB |
Before Width: | Height: | Size: 36 KiB |
Before Width: | Height: | Size: 35 KiB |
Before Width: | Height: | Size: 139 KiB |
Before Width: | Height: | Size: 134 KiB |
@ -6,7 +6,7 @@ Quartz is a fast, batteries-included static-site generator that transforms Markd
|
||||
|
||||
## 🪴 Get Started
|
||||
|
||||
Quartz requires **at least [Node](https://nodejs.org/) v22** and `npm` v10.9.2 to function correctly. Ensure you have this installed on your machine before continuing.
|
||||
Quartz requires **at least [Node](https://nodejs.org/) v18.14** and `npm` v9.3.1 to function correctly. Ensure you have this installed on your machine before continuing.
|
||||
|
||||
Then, in your terminal of choice, enter the following commands line by line:
|
||||
|
||||
@ -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]], [[wikilinks|wikilinks, transclusions]], [[backlinks]], [[features/Latex|Latex]], [[syntax highlighting]], [[popover previews]], [[Docker Support]], [[i18n|internationalization]], [[comments]] and [many more](./features/) right out of the box
|
||||
- Hot-reload on configuration edits and incremental rebuilds for content edits
|
||||
- [[Obsidian compatibility]], [[full-text search]], [[graph view]], note transclusion, [[wikilinks]], [[backlinks]], [[features/Latex|Latex]], [[syntax highlighting]], [[popover previews]], [[Docker Support]], [[i18n|internationalization]] 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,102 +0,0 @@
|
||||
---
|
||||
title: Higher-Order Layout Components
|
||||
---
|
||||
|
||||
Quartz provides several higher-order components that help with layout composition and responsive design. These components wrap other components to add additional functionality or modify their behavior.
|
||||
|
||||
## `Flex` Component
|
||||
|
||||
The `Flex` component creates a [flexible box layout](https://developer.mozilla.org/en-US/docs/Web/CSS/flex) that can arrange child components in various ways. It's particularly useful for creating responsive layouts and organizing components in rows or columns.
|
||||
|
||||
```typescript
|
||||
type FlexConfig = {
|
||||
components: {
|
||||
Component: QuartzComponent
|
||||
grow?: boolean // whether component should grow to fill space
|
||||
shrink?: boolean // whether component should shrink if needed
|
||||
basis?: string // initial main size of the component
|
||||
order?: number // order in flex container
|
||||
align?: "start" | "end" | "center" | "stretch" // cross-axis alignment
|
||||
justify?: "start" | "end" | "center" | "between" | "around" // main-axis alignment
|
||||
}[]
|
||||
direction?: "row" | "row-reverse" | "column" | "column-reverse"
|
||||
wrap?: "nowrap" | "wrap" | "wrap-reverse"
|
||||
gap?: string
|
||||
}
|
||||
```
|
||||
|
||||
### Example Usage
|
||||
|
||||
```typescript
|
||||
Component.Flex({
|
||||
components: [
|
||||
{
|
||||
Component: Component.Search(),
|
||||
grow: true, // Search will grow to fill available space
|
||||
},
|
||||
{ Component: Component.Darkmode() }, // Darkmode keeps its natural size
|
||||
],
|
||||
direction: "row",
|
||||
gap: "1rem",
|
||||
})
|
||||
```
|
||||
|
||||
> [!note] Overriding behavior
|
||||
> Components inside `Flex` get an additional CSS class `flex-component` that add the `display: flex` property. If you want to override this behavior, you can add a `display` property to the component's CSS class in your custom CSS file.
|
||||
>
|
||||
> ```scss
|
||||
> .flex-component {
|
||||
> display: block; // or any other display type
|
||||
> }
|
||||
> ```
|
||||
|
||||
## `MobileOnly` Component
|
||||
|
||||
The `MobileOnly` component is a wrapper that makes its child component only visible on mobile devices. This is useful for creating responsive layouts where certain components should only appear on smaller screens.
|
||||
|
||||
### Example Usage
|
||||
|
||||
```typescript
|
||||
Component.MobileOnly(Component.Spacer())
|
||||
```
|
||||
|
||||
## `DesktopOnly` Component
|
||||
|
||||
The `DesktopOnly` component is the counterpart to `MobileOnly`. It makes its child component only visible on desktop devices. This helps create responsive layouts where certain components should only appear on larger screens.
|
||||
|
||||
### Example Usage
|
||||
|
||||
```typescript
|
||||
Component.DesktopOnly(Component.TableOfContents())
|
||||
```
|
||||
|
||||
## `ConditionalRender` Component
|
||||
|
||||
The `ConditionalRender` component is a wrapper that conditionally renders its child component based on a provided condition function. This is useful for creating dynamic layouts where components should only appear under certain conditions.
|
||||
|
||||
```typescript
|
||||
type ConditionalRenderConfig = {
|
||||
component: QuartzComponent
|
||||
condition: (props: QuartzComponentProps) => boolean
|
||||
}
|
||||
```
|
||||
|
||||
### Example Usage
|
||||
|
||||
```typescript
|
||||
Component.ConditionalRender({
|
||||
component: Component.Search(),
|
||||
condition: (props) => props.displayClass !== "fullpage",
|
||||
})
|
||||
```
|
||||
|
||||
The example above would only render the Search component when the page is not in fullpage mode.
|
||||
|
||||
```typescript
|
||||
Component.ConditionalRender({
|
||||
component: Component.Breadcrumbs(),
|
||||
condition: (page) => page.fileData.slug !== "index",
|
||||
})
|
||||
```
|
||||
|
||||
The example above would hide breadcrumbs on the root `index.md` page.
|
@ -12,20 +12,15 @@ export interface FullPageLayout {
|
||||
header: QuartzComponent[] // laid out horizontally
|
||||
beforeBody: QuartzComponent[] // laid out vertically
|
||||
pageBody: QuartzComponent // single component
|
||||
afterBody: QuartzComponent[] // laid out vertically
|
||||
left: QuartzComponent[] // vertical on desktop and tablet, horizontal on mobile
|
||||
right: QuartzComponent[] // vertical on desktop, horizontal on tablet and mobile
|
||||
left: QuartzComponent[] // vertical on desktop, horizontal on mobile
|
||||
right: QuartzComponent[] // vertical on desktop, horizontal on mobile
|
||||
footer: QuartzComponent // single component
|
||||
}
|
||||
```
|
||||
|
||||
These correspond to following parts of the page:
|
||||
|
||||
| Layout | Preview |
|
||||
| ------------------------------- | ----------------------------------- |
|
||||
| Desktop (width > 1200px) | ![[quartz-layout-desktop.png\|800]] |
|
||||
| Tablet (800px < width < 1200px) | ![[quartz-layout-tablet.png\|800]] |
|
||||
| Mobile (width < 800px) | ![[quartz-layout-mobile.png\|800]] |
|
||||
![[quartz layout.png|800]]
|
||||
|
||||
> [!note]
|
||||
> There are two additional layout fields that are _not_ shown in the above diagram.
|
||||
@ -35,26 +30,7 @@ These correspond to following parts of the page:
|
||||
|
||||
Quartz **components**, like plugins, can take in additional properties as configuration options. If you're familiar with React terminology, you can think of them as Higher-order Components.
|
||||
|
||||
See [a list of all the components](component.md) for all available components along with their configuration options. Additionally, Quartz provides several built-in higher-order components for layout composition - see [[layout-components]] for more details.
|
||||
|
||||
You can also checkout the guide on [[creating components]] if you're interested in further customizing the behaviour of Quartz.
|
||||
|
||||
### Layout breakpoints
|
||||
|
||||
Quartz has different layouts depending on the width the screen viewing the website.
|
||||
|
||||
The breakpoints for layouts can be configured in `variables.scss`.
|
||||
|
||||
- `mobile`: screen width below this size will use mobile layout.
|
||||
- `desktop`: screen width above this size will use desktop layout.
|
||||
- Screen width between `mobile` and `desktop` width will use the tablet layout.
|
||||
|
||||
```scss
|
||||
$breakpoints: (
|
||||
mobile: 800px,
|
||||
desktop: 1200px,
|
||||
);
|
||||
```
|
||||
See [a list of all the components](component.md) for all available components along with their configuration options. You can also checkout the guide on [[creating components]] if you're interested in further customizing the behaviour of Quartz.
|
||||
|
||||
### Style
|
||||
|
||||
|
@ -8,7 +8,7 @@ This plugin emits a `CNAME` record that points your subdomain to the default dom
|
||||
|
||||
If you want to use a custom domain name like `quartz.example.com` for the site, then this is needed.
|
||||
|
||||
See [[hosting|Hosting]] for more information.
|
||||
See [[Hosting]] for more information.
|
||||
|
||||
> [!note]
|
||||
> For information on how to add, remove or configure plugins, see the [[configuration#Plugins|Configuration]] page.
|
||||
|
@ -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
|
||||
|
@ -11,9 +11,7 @@ This plugin determines the created, modified, and published dates for a document
|
||||
|
||||
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.
|
||||
- `priority`: The data sources to consult for date information. Highest priority first. Possible values are `"frontmatter"`, `"git"`, and `"filesystem"`. Defaults to `"frontmatter", "git", "filesystem"]`.
|
||||
|
||||
> [!warning]
|
||||
> If you rely on `git` for dates, make sure `defaultDateType` is set to `modified` in `quartz.config.ts`.
|
||||
|
@ -1,360 +0,0 @@
|
||||
---
|
||||
title: Custom OG Images
|
||||
tags:
|
||||
- feature/emitter
|
||||
---
|
||||
|
||||
The Custom OG Images emitter plugin generates social media preview images for your pages. It uses [satori](https://github.com/vercel/satori) to convert HTML/CSS into images, allowing you to create beautiful and consistent social media preview cards for your content.
|
||||
|
||||
> [!note]
|
||||
> For information on how to add, remove or configure plugins, see the [[configuration#Plugins|Configuration]] page.
|
||||
|
||||
## Features
|
||||
|
||||
- Automatically generates social media preview images for each page
|
||||
- Supports both light and dark mode themes
|
||||
- Customizable through frontmatter properties
|
||||
- Fallback to default image when needed
|
||||
- Full control over image design through custom components
|
||||
|
||||
## Configuration
|
||||
|
||||
> [!info] Info
|
||||
>
|
||||
> The `baseUrl` property in your [[configuration]] must be set properly for social images to work correctly, as they require absolute paths.
|
||||
|
||||
This plugin accepts the following configuration options:
|
||||
|
||||
```typescript title="quartz.config.ts"
|
||||
import { CustomOgImages } from "./quartz/plugins/emitters/ogImage"
|
||||
|
||||
const config: QuartzConfig = {
|
||||
plugins: {
|
||||
emitters: [
|
||||
CustomOgImages({
|
||||
colorScheme: "lightMode", // what colors to use for generating image, same as theme colors from config, valid values are "darkMode" and "lightMode"
|
||||
width: 1200, // width to generate with (in pixels)
|
||||
height: 630, // height to generate with (in pixels)
|
||||
excludeRoot: false, // wether to exclude "/" index path to be excluded from auto generated images (false = use auto, true = use default og image)
|
||||
imageStructure: defaultImage, // custom image component to use
|
||||
}),
|
||||
],
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
### Configuration Options
|
||||
|
||||
| Option | Type | Default | Description |
|
||||
| ---------------- | --------- | ------------ | ----------------------------------------------------------------- |
|
||||
| `colorScheme` | string | "lightMode" | Theme to use for generating images ("darkMode" or "lightMode") |
|
||||
| `width` | number | 1200 | Width of the generated image in pixels |
|
||||
| `height` | number | 630 | Height of the generated image in pixels |
|
||||
| `excludeRoot` | boolean | false | Whether to exclude the root index page from auto-generated images |
|
||||
| `imageStructure` | component | defaultImage | Custom component to use for image generation |
|
||||
|
||||
## Frontmatter Properties
|
||||
|
||||
The following properties can be used to customize your link previews:
|
||||
|
||||
| Property | Alias | Summary |
|
||||
| ------------------- | ---------------- | ----------------------------------- |
|
||||
| `socialDescription` | `description` | Description to be used for preview. |
|
||||
| `socialImage` | `image`, `cover` | Link to preview image. |
|
||||
|
||||
The `socialImage` property should contain a link to an image either relative to `quartz/static`, or a full URL. If you have a folder for all your images in `quartz/static/my-images`, an example for `socialImage` could be `"my-images/cover.png"`. Alternatively, you can use a fully qualified URL like `"https://example.com/cover.png"`.
|
||||
|
||||
> [!info] Info
|
||||
>
|
||||
> The priority for what image will be used for the cover image looks like the following: `frontmatter property > generated image (if enabled) > default image`.
|
||||
>
|
||||
> The default image (`quartz/static/og-image.png`) will only be used as a fallback if nothing else is set. If the Custom OG Images emitter plugin is enabled, it will be treated as the new default per page, but can be overwritten by setting the `socialImage` frontmatter property for that page.
|
||||
|
||||
## Customization
|
||||
|
||||
You can fully customize how the images being generated look by passing your own component to `imageStructure`. This component takes JSX + some page metadata/config options and converts it to an image using [satori](https://github.com/vercel/satori). Vercel provides an [online playground](https://og-playground.vercel.app/) that can be used to preview how your JSX looks like as a picture. This is ideal for prototyping your custom design.
|
||||
|
||||
### Fonts
|
||||
|
||||
You will also be passed an array containing a header and a body font (where the first entry is header and the second is body). The fonts matches the ones selected in `theme.typography.header` and `theme.typography.body` from `quartz.config.ts` and will be passed in the format required by [`satori`](https://github.com/vercel/satori). To use them in CSS, use the `.name` property (e.g. `fontFamily: fonts[1].name` to use the "body" font family).
|
||||
|
||||
An example of a component using the header font could look like this:
|
||||
|
||||
```tsx title="socialImage.tsx"
|
||||
export const myImage: SocialImageOptions["imageStructure"] = (...) => {
|
||||
return <p style={{ fontFamily: fonts[0].name }}>Cool Header!</p>
|
||||
}
|
||||
```
|
||||
|
||||
> [!example]- Local fonts
|
||||
>
|
||||
> For cases where you use a local fonts under `static` folder, make sure to set the correct `@font-face` in `custom.scss`
|
||||
>
|
||||
> ```scss title="custom.scss"
|
||||
> @font-face {
|
||||
> font-family: "Newsreader";
|
||||
> font-style: normal;
|
||||
> font-weight: normal;
|
||||
> font-display: swap;
|
||||
> src: url("/static/Newsreader.woff2") format("woff2");
|
||||
> }
|
||||
> ```
|
||||
>
|
||||
> Then in `quartz/util/og.tsx`, you can load the Satori fonts like so:
|
||||
>
|
||||
> ```tsx title="quartz/util/og.tsx"
|
||||
> import { joinSegments, QUARTZ } from "../path"
|
||||
> import fs from "fs"
|
||||
> import path from "path"
|
||||
>
|
||||
> const newsreaderFontPath = joinSegments(QUARTZ, "static", "Newsreader.woff2")
|
||||
> export async function getSatoriFonts(headerFont: FontSpecification, bodyFont: FontSpecification) {
|
||||
> // ... rest of implementation remains same
|
||||
> const fonts: SatoriOptions["fonts"] = [
|
||||
> ...headerFontData.map((data, idx) => ({
|
||||
> name: headerFontName,
|
||||
> data,
|
||||
> weight: headerWeights[idx],
|
||||
> style: "normal" as const,
|
||||
> })),
|
||||
> ...bodyFontData.map((data, idx) => ({
|
||||
> name: bodyFontName,
|
||||
> data,
|
||||
> weight: bodyWeights[idx],
|
||||
> style: "normal" as const,
|
||||
> })),
|
||||
> {
|
||||
> name: "Newsreader",
|
||||
> data: await fs.promises.readFile(path.resolve(newsreaderFontPath)),
|
||||
> weight: 400,
|
||||
> style: "normal" as const,
|
||||
> },
|
||||
> ]
|
||||
>
|
||||
> return fonts
|
||||
> }
|
||||
> ```
|
||||
>
|
||||
> This font then can be used with your custom structure.
|
||||
|
||||
## Examples
|
||||
|
||||
Here are some example image components you can use as a starting point:
|
||||
|
||||
### Basic Example
|
||||
|
||||
This example will generate images that look as follows:
|
||||
|
||||
| Light | Dark |
|
||||
| ------------------------------------------ | ----------------------------------------- |
|
||||
| ![[custom-social-image-preview-light.png]] | ![[custom-social-image-preview-dark.png]] |
|
||||
|
||||
```tsx
|
||||
import { SatoriOptions } from "satori/wasm"
|
||||
import { GlobalConfiguration } from "../cfg"
|
||||
import { SocialImageOptions, UserOpts } from "./imageHelper"
|
||||
import { QuartzPluginData } from "../plugins/vfile"
|
||||
|
||||
export const customImage: SocialImageOptions["imageStructure"] = (
|
||||
cfg: GlobalConfiguration,
|
||||
userOpts: UserOpts,
|
||||
title: string,
|
||||
description: string,
|
||||
fonts: SatoriOptions["fonts"],
|
||||
fileData: QuartzPluginData,
|
||||
) => {
|
||||
// How many characters are allowed before switching to smaller font
|
||||
const fontBreakPoint = 22
|
||||
const useSmallerFont = title.length > fontBreakPoint
|
||||
|
||||
const { colorScheme } = userOpts
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
flexDirection: "row",
|
||||
justifyContent: "flex-start",
|
||||
alignItems: "center",
|
||||
height: "100%",
|
||||
width: "100%",
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
height: "100%",
|
||||
width: "100%",
|
||||
backgroundColor: cfg.theme.colors[colorScheme].light,
|
||||
flexDirection: "column",
|
||||
gap: "2.5rem",
|
||||
paddingTop: "2rem",
|
||||
paddingBottom: "2rem",
|
||||
}}
|
||||
>
|
||||
<p
|
||||
style={{
|
||||
color: cfg.theme.colors[colorScheme].dark,
|
||||
fontSize: useSmallerFont ? 70 : 82,
|
||||
marginLeft: "4rem",
|
||||
textAlign: "center",
|
||||
marginRight: "4rem",
|
||||
fontFamily: fonts[0].name,
|
||||
}}
|
||||
>
|
||||
{title}
|
||||
</p>
|
||||
<p
|
||||
style={{
|
||||
color: cfg.theme.colors[colorScheme].dark,
|
||||
fontSize: 44,
|
||||
marginLeft: "8rem",
|
||||
marginRight: "8rem",
|
||||
lineClamp: 3,
|
||||
fontFamily: fonts[1].name,
|
||||
}}
|
||||
>
|
||||
{description}
|
||||
</p>
|
||||
</div>
|
||||
<div
|
||||
style={{
|
||||
height: "100%",
|
||||
width: "2vw",
|
||||
position: "absolute",
|
||||
backgroundColor: cfg.theme.colors[colorScheme].tertiary,
|
||||
opacity: 0.85,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
### Advanced Example
|
||||
|
||||
The following example includes a customized social image with a custom background and formatted date:
|
||||
|
||||
```typescript title="custom-og.tsx"
|
||||
export const og: SocialImageOptions["Component"] = (
|
||||
cfg: GlobalConfiguration,
|
||||
fileData: QuartzPluginData,
|
||||
{ colorScheme }: Options,
|
||||
title: string,
|
||||
description: string,
|
||||
fonts: SatoriOptions["fonts"],
|
||||
) => {
|
||||
let created: string | undefined
|
||||
let reading: string | undefined
|
||||
if (fileData.dates) {
|
||||
created = formatDate(getDate(cfg, fileData)!, cfg.locale)
|
||||
}
|
||||
const { minutes, text: _timeTaken, words: _words } = readingTime(fileData.text!)
|
||||
reading = i18n(cfg.locale).components.contentMeta.readingTime({
|
||||
minutes: Math.ceil(minutes),
|
||||
})
|
||||
|
||||
const Li = [created, reading]
|
||||
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
position: "relative",
|
||||
display: "flex",
|
||||
flexDirection: "row",
|
||||
alignItems: "flex-start",
|
||||
height: "100%",
|
||||
width: "100%",
|
||||
backgroundImage: `url("https://${cfg.baseUrl}/static/og-image.jpeg")`,
|
||||
backgroundSize: "100% 100%",
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
position: "absolute",
|
||||
top: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
background: "radial-gradient(circle at center, transparent, rgba(0, 0, 0, 0.4) 70%)",
|
||||
}}
|
||||
/>
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
height: "100%",
|
||||
width: "100%",
|
||||
flexDirection: "column",
|
||||
justifyContent: "flex-start",
|
||||
alignItems: "flex-start",
|
||||
gap: "1.5rem",
|
||||
paddingTop: "4rem",
|
||||
paddingBottom: "4rem",
|
||||
marginLeft: "4rem",
|
||||
}}
|
||||
>
|
||||
<img
|
||||
src={`"https://${cfg.baseUrl}/static/icon.jpeg"`}
|
||||
style={{
|
||||
position: "relative",
|
||||
backgroundClip: "border-box",
|
||||
borderRadius: "6rem",
|
||||
}}
|
||||
width={80}
|
||||
/>
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
textAlign: "left",
|
||||
fontFamily: fonts[0].name,
|
||||
}}
|
||||
>
|
||||
<h2
|
||||
style={{
|
||||
color: cfg.theme.colors[colorScheme].light,
|
||||
fontSize: "3rem",
|
||||
fontWeight: 700,
|
||||
marginRight: "4rem",
|
||||
fontFamily: fonts[0].name,
|
||||
}}
|
||||
>
|
||||
{title}
|
||||
</h2>
|
||||
<ul
|
||||
style={{
|
||||
color: cfg.theme.colors[colorScheme].gray,
|
||||
gap: "1rem",
|
||||
fontSize: "1.5rem",
|
||||
fontFamily: fonts[1].name,
|
||||
}}
|
||||
>
|
||||
{Li.map((item, index) => {
|
||||
if (item) {
|
||||
return <li key={index}>{item}</li>
|
||||
}
|
||||
})}
|
||||
</ul>
|
||||
</div>
|
||||
<p
|
||||
style={{
|
||||
color: cfg.theme.colors[colorScheme].light,
|
||||
fontSize: "1.5rem",
|
||||
overflow: "hidden",
|
||||
marginRight: "8rem",
|
||||
textOverflow: "ellipsis",
|
||||
display: "-webkit-box",
|
||||
WebkitLineClamp: 7,
|
||||
WebkitBoxOrient: "vertical",
|
||||
lineClamp: 7,
|
||||
fontFamily: fonts[1].name,
|
||||
}}
|
||||
>
|
||||
{description}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
```
|
@ -1,19 +0,0 @@
|
||||
---
|
||||
title: Favicon
|
||||
tags:
|
||||
- plugin/emitter
|
||||
---
|
||||
|
||||
This plugin emits a `favicon.ico` into the `public` folder. It creates the favicon from `icon.png` located in the `quartz/static` folder.
|
||||
The plugin resizes `icon.png` to 48x48px to make it as small as possible.
|
||||
|
||||
> [!note]
|
||||
> For information on how to add, remove or configure plugins, see the [[configuration#Plugins|Configuration]] page.
|
||||
|
||||
This plugin has no configuration options.
|
||||
|
||||
## API
|
||||
|
||||
- Category: Emitter
|
||||
- Function name: `Plugin.Favicon()`.
|
||||
- Source: [`quartz/plugins/emitters/favicon.ts`](https://github.com/jackyzha0/quartz/blob/v4/quartz/plugins/emitters/favicon.ts).
|
@ -11,12 +11,10 @@ Example: [[advanced/|Advanced]]
|
||||
> [!note]
|
||||
> For information on how to add, remove or configure plugins, see the [[configuration#Plugins|Configuration]] page.
|
||||
|
||||
This plugin has no configuration options.
|
||||
|
||||
The pages are displayed using the `defaultListPageLayout` in `quartz.layouts.ts`. For the content, the `FolderContent` component is used. If you want to modify the layout, you must edit it directly (`quartz/components/pages/FolderContent.tsx`).
|
||||
|
||||
This plugin accepts the following configuration options:
|
||||
|
||||
- `sort`: A function of type `(f1: QuartzPluginData, f2: QuartzPluginData) => number{:ts}` used to sort entries. Defaults to sorting by date and tie-breaking on lexographical order.
|
||||
|
||||
## API
|
||||
|
||||
- Category: Emitter
|
||||
|
@ -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
|
||||
|
@ -11,12 +11,7 @@ This plugin adds LaTeX support to Quartz. See [[features/Latex|Latex]] for more
|
||||
|
||||
This plugin accepts the following configuration options:
|
||||
|
||||
- `renderEngine`: the engine to use to render LaTeX equations. Can be `"katex"` for [KaTeX](https://katex.org/), `"mathjax"` for [MathJax](https://www.mathjax.org/) [SVG rendering](https://docs.mathjax.org/en/latest/output/svg.html), or `"typst"` for [Typst](https://typst.app/) (a new way to compose LaTeX equation). Defaults to KaTeX.
|
||||
- `customMacros`: custom macros for all LaTeX blocks. It takes the form of a key-value pair where the key is a new command name and the value is the expansion of the macro. For example: `{"\\R": "\\mathbb{R}"}`
|
||||
|
||||
> [!note] Typst support
|
||||
>
|
||||
> Currently, typst doesn't support inline-math
|
||||
- `renderEngine`: the engine to use to render LaTeX equations. Can be `"katex"` for [KaTeX](https://katex.org/) or `"mathjax"` for [MathJax](https://www.mathjax.org/) [SVG rendering](https://docs.mathjax.org/en/latest/output/svg.html). Defaults to KaTeX.
|
||||
|
||||
## API
|
||||
|
||||
|
@ -23,7 +23,6 @@ This plugin accepts the following configuration options:
|
||||
- `enableYouTubeEmbed`: If `true` (default), enables the embedding of YouTube videos and playlists using external image Markdown syntax.
|
||||
- `enableVideoEmbed`: If `true` (default), enables the embedding of video files.
|
||||
- `enableCheckbox`: If `true`, adds support for interactive checkboxes in content. Defaults to `false`.
|
||||
- `disableBrokenWikilinks`: If `true`, replaces links to non-existent notes with a dimmed, disabled link. Defaults to `false`.
|
||||
|
||||
> [!warning]
|
||||
> Don't remove this plugin if you're using [[Obsidian compatibility|Obsidian]] to author the content!
|
||||
@ -32,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).
|
||||
|
@ -1,26 +0,0 @@
|
||||
---
|
||||
title: RoamFlavoredMarkdown
|
||||
tags:
|
||||
- plugin/transformer
|
||||
---
|
||||
|
||||
This plugin provides support for [Roam Research](https://roamresearch.com) compatibility. See [[Roam Research Compatibility]] for more information.
|
||||
|
||||
> [!note]
|
||||
> For information on how to add, remove or configure plugins, see the [[Configuration#Plugins|Configuration]] page.
|
||||
|
||||
This plugin accepts the following configuration options:
|
||||
|
||||
- `orComponent`: If `true` (default), converts Roam `{{ or:ONE|TWO|THREE }}` shortcodes into HTML Dropdown options.
|
||||
- `TODOComponent`: If `true` (default), converts Roam `{{[[TODO]]}}` shortcodes into HTML check boxes.
|
||||
- `DONEComponent`: If `true` (default), converts Roam `{{[[DONE]]}}` shortcodes into checked HTML check boxes.
|
||||
- `videoComponent`: If `true` (default), converts Roam `{{[[video]]:URL}}` shortcodes into embeded HTML video.
|
||||
- `audioComponent`: If `true` (default), converts Roam `{{[[audio]]:URL}}` shortcodes into embeded HTML audio.
|
||||
- `pdfComponent`: If `true` (default), converts Roam `{{[[pdf]]:URL}}` shortcodes into embeded HTML PDF viewer.
|
||||
- `blockquoteComponent`: If `true` (default), converts Roam `{{[[>]]}}` shortcodes into Quartz blockquotes.
|
||||
|
||||
## API
|
||||
|
||||
- Category: Transformer
|
||||
- Function name: `Plugin.RoamFlavoredMarkdown()`.
|
||||
- Source: [`quartz/plugins/transformers/roam.ts`](https://github.com/jackyzha0/quartz/blob/v4/quartz/plugins/transformers/roam.ts).
|
@ -9,12 +9,10 @@ This plugin emits dedicated pages for each tag used in the content. See [[folder
|
||||
> [!note]
|
||||
> For information on how to add, remove or configure plugins, see the [[configuration#Plugins|Configuration]] page.
|
||||
|
||||
This plugin has no configuration options.
|
||||
|
||||
The pages are displayed using the `defaultListPageLayout` in `quartz.layouts.ts`. For the content, the `TagContent` component is used. If you want to modify the layout, you must edit it directly (`quartz/components/pages/TagContent.tsx`).
|
||||
|
||||
This plugin accepts the following configuration options:
|
||||
|
||||
- `sort`: A function of type `(f1: QuartzPluginData, f2: QuartzPluginData) => number{:ts}` used to sort entries. Defaults to sorting by date and tie-breaking on lexographical order.
|
||||
|
||||
## API
|
||||
|
||||
- Category: Emitter
|
||||
|
@ -34,13 +34,6 @@ npx quartz sync --no-pull
|
||||
> [!warning]- `fatal: --[no-]autostash option is only valid with --rebase`
|
||||
> You may have an outdated version of `git`. Updating `git` should fix this issue.
|
||||
|
||||
> [!warning]- `fatal: The remote end hung up unexpectedly`
|
||||
> It might be due to Git's default buffer size. You can fix it by increasing the buffer with this command:
|
||||
>
|
||||
> ```bash
|
||||
> git config http.postBuffer 524288000
|
||||
> ```
|
||||
|
||||
In future updates, you can simply run `npx quartz sync` every time you want to push updates to your repository.
|
||||
|
||||
> [!hint] Flags and options
|
||||
|
@ -6,18 +6,26 @@ Want to see what Quartz can do? Here are some cool community gardens:
|
||||
|
||||
- [Quartz Documentation (this site!)](https://quartz.jzhao.xyz/)
|
||||
- [Jacky Zhao's Garden](https://jzhao.xyz/)
|
||||
- [Aaron Pham's Garden](https://aarnphm.xyz/)
|
||||
- [The Pond](https://turntrout.com/welcome)
|
||||
- [Eilleen's Everything Notebook](https://quartz.eilleeenz.com/)
|
||||
- [Morrowind Modding Wiki](https://morrowind-modding.github.io/)
|
||||
- [Stanford CME 302 Numerical Linear Algebra](https://ericdarve.github.io/NLA/)
|
||||
- [Socratica Toolbox](https://toolbox.socratica.info/)
|
||||
- [A Pattern Language - Christopher Alexander (Architecture)](https://patternlanguage.cc/)
|
||||
- [oldwinter の数字花园](https://garden.oldwinter.top/)
|
||||
- [Aaron Pham's Garden](https://aarnphm.xyz/)
|
||||
- [The Quantum Garden](https://quantumgardener.blog/)
|
||||
- [Abhijeet's Math Wiki](https://abhmul.github.io/quartz/Math-Wiki/)
|
||||
- [Matt Dunn's Second Brain](https://mattdunn.info/)
|
||||
- [Pelayo Arbues' Notes](https://pelayoarbues.github.io/)
|
||||
- [Vince Imbat's Talahardin](https://vinceimbat.com/)
|
||||
- [🧠🌳 Chad's Mind Garden](https://www.chadly.net/)
|
||||
- [Pedro MC Fernandes's Topo da Mente](https://www.pmcf.xyz/topo-da-mente/)
|
||||
- [Mau Camargo's Notkesto](https://notes.camargomau.com/)
|
||||
- [Caicai's Novels](https://imoko.cc/blog/caicai/)
|
||||
- [🌊 Collapsed Wave](https://collapsedwave.com/)
|
||||
- [Sideny's 3D Artist's Handbook](https://sidney-eliot.github.io/3d-artists-handbook/)
|
||||
- [Mike's AI Garden 🤖🪴](https://mwalton.me/)
|
||||
- [Brandon Boswell's Garden](https://brandonkboswell.com)
|
||||
- [Data Engineering Vault: A Second Brain Knowledge Network](https://vault.ssp.sh/)
|
||||
- [Scaling Synthesis - A hypertext research notebook](https://scalingsynthesis.com/)
|
||||
- [Data Dictionary 🧠](https://glossary.airbyte.com/)
|
||||
- [sspaeti.com's Second Brain](https://brain.sspaeti.com/)
|
||||
- [🪴Aster's notebook](https://notes.asterhu.com)
|
||||
- [Gatekeeper Wiki](https://www.gatekeeper.wiki)
|
||||
- [Ellie's Notes](https://ellie.wtf)
|
||||
- [Eledah's Crystalline](https://blog.eledah.ir/)
|
||||
- [🌓 Projects & Privacy - FOSS, tech, law](https://be-far.com)
|
||||
- [🥷🏻🌳🍃 Computer Science & Thinkering Garden](https://notes.yxy.ninja)
|
||||
|
||||
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)!
|
||||
|
4
globals.d.ts
vendored
@ -4,10 +4,6 @@ export declare global {
|
||||
type: K,
|
||||
listener: (this: Document, ev: CustomEventMap[K]) => void,
|
||||
): void
|
||||
removeEventListener<K extends keyof CustomEventMap>(
|
||||
type: K,
|
||||
listener: (this: Document, ev: CustomEventMap[K]) => void,
|
||||
): void
|
||||
dispatchEvent<K extends keyof CustomEventMap>(ev: CustomEventMap[K] | UIEvent): void
|
||||
}
|
||||
interface Window {
|
||||
|
3
index.d.ts
vendored
@ -5,11 +5,8 @@ declare module "*.scss" {
|
||||
|
||||
// dom custom event
|
||||
interface CustomEventMap {
|
||||
prenav: CustomEvent<{}>
|
||||
nav: CustomEvent<{ url: FullSlug }>
|
||||
themechange: CustomEvent<{ theme: "light" | "dark" }>
|
||||
readermodechange: CustomEvent<{ mode: "on" | "off" }>
|
||||
}
|
||||
|
||||
type ContentIndex = Record<FullSlug, ContentDetails>
|
||||
declare const fetchData: Promise<ContentIndex>
|
||||
|
4115
package-lock.json
generated
94
package.json
@ -2,7 +2,7 @@
|
||||
"name": "@jackyzha0/quartz",
|
||||
"description": "🌱 publish your digital garden and notes as a website",
|
||||
"private": true,
|
||||
"version": "4.5.1",
|
||||
"version": "4.2.3",
|
||||
"type": "module",
|
||||
"author": "jackyzha0 <j.zhao2k19@gmail.com>",
|
||||
"license": "MIT",
|
||||
@ -12,16 +12,15 @@
|
||||
"url": "https://github.com/jackyzha0/quartz.git"
|
||||
},
|
||||
"scripts": {
|
||||
"quartz": "./quartz/bootstrap-cli.mjs",
|
||||
"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": ">=10.9.2",
|
||||
"node": ">=22"
|
||||
"npm": ">=9.3.1",
|
||||
"node": ">=18.14"
|
||||
},
|
||||
"keywords": [
|
||||
"site generator",
|
||||
@ -35,81 +34,76 @@
|
||||
"quartz": "./quartz/bootstrap-cli.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"@clack/prompts": "^0.11.0",
|
||||
"@floating-ui/dom": "^1.7.0",
|
||||
"@myriaddreamin/rehype-typst": "^0.6.0",
|
||||
"@napi-rs/simple-git": "0.1.19",
|
||||
"@tweenjs/tween.js": "^25.0.0",
|
||||
"@webgpu/types": "^0.1.61",
|
||||
"ansi-truncate": "^1.2.0",
|
||||
"@clack/prompts": "^0.7.0",
|
||||
"@floating-ui/dom": "^1.6.3",
|
||||
"@napi-rs/simple-git": "0.1.16",
|
||||
"async-mutex": "^0.5.0",
|
||||
"chokidar": "^4.0.3",
|
||||
"chalk": "^5.3.0",
|
||||
"chokidar": "^3.6.0",
|
||||
"cli-spinner": "^0.2.10",
|
||||
"d3": "^7.9.0",
|
||||
"esbuild-sass-plugin": "^3.3.1",
|
||||
"esbuild-sass-plugin": "^2.16.1",
|
||||
"flexsearch": "0.7.43",
|
||||
"github-slugger": "^2.0.0",
|
||||
"globby": "^14.1.0",
|
||||
"globby": "^14.0.1",
|
||||
"gray-matter": "^4.0.3",
|
||||
"hast-util-to-html": "^9.0.5",
|
||||
"hast-util-to-jsx-runtime": "^2.3.6",
|
||||
"hast-util-to-string": "^3.0.1",
|
||||
"hast-util-to-html": "^9.0.0",
|
||||
"hast-util-to-jsx-runtime": "^2.3.0",
|
||||
"hast-util-to-string": "^3.0.0",
|
||||
"is-absolute-url": "^4.0.1",
|
||||
"js-yaml": "^4.1.0",
|
||||
"lightningcss": "^1.30.1",
|
||||
"mdast-util-find-and-replace": "^3.0.2",
|
||||
"mdast-util-to-hast": "^13.2.0",
|
||||
"lightningcss": "^1.24.1",
|
||||
"mdast-util-find-and-replace": "^3.0.1",
|
||||
"mdast-util-to-hast": "^13.1.0",
|
||||
"mdast-util-to-string": "^4.0.0",
|
||||
"micromorph": "^0.4.5",
|
||||
"minimatch": "^10.0.1",
|
||||
"pixi.js": "^8.9.2",
|
||||
"preact": "^10.26.7",
|
||||
"preact-render-to-string": "^6.5.13",
|
||||
"pretty-bytes": "^7.0.0",
|
||||
"preact": "^10.20.1",
|
||||
"preact-render-to-string": "^6.4.0",
|
||||
"pretty-bytes": "^6.1.1",
|
||||
"pretty-time": "^1.1.0",
|
||||
"reading-time": "^1.5.0",
|
||||
"rehype-autolink-headings": "^7.1.0",
|
||||
"rehype-citation": "^2.3.1",
|
||||
"rehype-katex": "^7.0.1",
|
||||
"rehype-mathjax": "^7.1.0",
|
||||
"rehype-pretty-code": "^0.14.1",
|
||||
"rehype-citation": "^2.0.0",
|
||||
"rehype-katex": "^7.0.0",
|
||||
"rehype-mathjax": "^6.0.0",
|
||||
"rehype-pretty-code": "^0.13.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.2",
|
||||
"remark-smartypants": "^3.0.2",
|
||||
"rfdc": "^1.4.1",
|
||||
"satori": "^0.13.1",
|
||||
"serve-handler": "^6.1.6",
|
||||
"sharp": "^0.34.2",
|
||||
"shiki": "^1.26.2",
|
||||
"remark-rehype": "^11.1.0",
|
||||
"remark-smartypants": "^2.1.0",
|
||||
"rfdc": "^1.3.1",
|
||||
"rimraf": "^5.0.5",
|
||||
"serve-handler": "^6.1.5",
|
||||
"shiki": "^1.2.3",
|
||||
"source-map-support": "^0.5.21",
|
||||
"to-vfile": "^8.0.0",
|
||||
"toml": "^3.0.0",
|
||||
"unified": "^11.0.5",
|
||||
"unified": "^11.0.4",
|
||||
"unist-util-visit": "^5.0.0",
|
||||
"vfile": "^6.0.3",
|
||||
"workerpool": "^9.2.0",
|
||||
"ws": "^8.18.2",
|
||||
"yargs": "^18.0.0"
|
||||
"vfile": "^6.0.1",
|
||||
"workerpool": "^9.1.0",
|
||||
"ws": "^8.15.1",
|
||||
"yargs": "^17.7.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/cli-spinner": "^0.2.3",
|
||||
"@types/d3": "^7.4.3",
|
||||
"@types/hast": "^3.0.4",
|
||||
"@types/js-yaml": "^4.0.9",
|
||||
"@types/node": "^22.15.23",
|
||||
"@types/node": "^20.11.29",
|
||||
"@types/pretty-time": "^1.1.5",
|
||||
"@types/source-map-support": "^0.5.10",
|
||||
"@types/ws": "^8.18.1",
|
||||
"@types/yargs": "^17.0.33",
|
||||
"esbuild": "^0.25.5",
|
||||
"prettier": "^3.5.3",
|
||||
"tsx": "^4.19.4",
|
||||
"typescript": "^5.8.3"
|
||||
"@types/ws": "^8.5.10",
|
||||
"@types/yargs": "^17.0.32",
|
||||
"esbuild": "^0.19.9",
|
||||
"prettier": "^3.2.4",
|
||||
"tsx": "^4.7.1",
|
||||
"typescript": "^5.4.3"
|
||||
}
|
||||
}
|
||||
|
@ -2,23 +2,22 @@ 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",
|
||||
pageTitleSuffix: "",
|
||||
pageTitle: "[JPG]",
|
||||
enableSPA: true,
|
||||
enablePopovers: true,
|
||||
analytics: {
|
||||
provider: "plausible",
|
||||
},
|
||||
locale: "en-US",
|
||||
baseUrl: "quartz.jzhao.xyz",
|
||||
baseUrl: "jpg.marchal.dev",
|
||||
ignorePatterns: ["private", "templates", ".obsidian"],
|
||||
defaultDateType: "modified",
|
||||
defaultDateType: "created",
|
||||
theme: {
|
||||
fontOrigin: "googleFonts",
|
||||
cdnCaching: true,
|
||||
@ -37,7 +36,6 @@ const config: QuartzConfig = {
|
||||
secondary: "#284b63",
|
||||
tertiary: "#84a59d",
|
||||
highlight: "rgba(143, 159, 169, 0.15)",
|
||||
textHighlight: "#fff23688",
|
||||
},
|
||||
darkMode: {
|
||||
light: "#161618",
|
||||
@ -48,7 +46,6 @@ const config: QuartzConfig = {
|
||||
secondary: "#7b97aa",
|
||||
tertiary: "#84a59d",
|
||||
highlight: "rgba(143, 159, 169, 0.15)",
|
||||
textHighlight: "#b3aa0288",
|
||||
},
|
||||
},
|
||||
},
|
||||
@ -57,8 +54,9 @@ const config: QuartzConfig = {
|
||||
transformers: [
|
||||
Plugin.FrontMatter(),
|
||||
Plugin.CreatedModifiedDate({
|
||||
priority: ["frontmatter", "git", "filesystem"],
|
||||
priority: ["frontmatter", "filesystem"],
|
||||
}),
|
||||
Plugin.Latex({ renderEngine: "katex" }), // mathjax or katex
|
||||
Plugin.SyntaxHighlighting({
|
||||
theme: {
|
||||
light: "github-light",
|
||||
@ -66,12 +64,11 @@ const config: QuartzConfig = {
|
||||
},
|
||||
keepBackground: false,
|
||||
}),
|
||||
Plugin.ObsidianFlavoredMarkdown({ enableInHtmlEmbed: false }),
|
||||
Plugin.ObsidianFlavoredMarkdown({ enableInHtmlEmbed: true, enableYouTubeEmbed: true }),
|
||||
Plugin.GitHubFlavoredMarkdown(),
|
||||
Plugin.TableOfContents(),
|
||||
Plugin.CrawlLinks({ markdownLinkResolution: "shortest" }),
|
||||
Plugin.Description(),
|
||||
Plugin.Latex({ renderEngine: "katex" }),
|
||||
],
|
||||
filters: [Plugin.RemoveDrafts()],
|
||||
emitters: [
|
||||
@ -86,10 +83,7 @@ const config: QuartzConfig = {
|
||||
}),
|
||||
Plugin.Assets(),
|
||||
Plugin.Static(),
|
||||
Plugin.Favicon(),
|
||||
Plugin.NotFoundPage(),
|
||||
// Comment out CustomOgImages to speed up build time
|
||||
Plugin.CustomOgImages(),
|
||||
],
|
||||
},
|
||||
}
|
||||
|
@ -5,11 +5,9 @@ import * as Component from "./quartz/components"
|
||||
export const sharedPageComponents: SharedLayout = {
|
||||
head: Component.Head(),
|
||||
header: [],
|
||||
afterBody: [],
|
||||
footer: Component.Footer({
|
||||
links: {
|
||||
GitHub: "https://github.com/jackyzha0/quartz",
|
||||
"Discord Community": "https://discord.gg/cRFFHYye7t",
|
||||
"Théo Marchal": "https://theo.marchal.dev"
|
||||
},
|
||||
}),
|
||||
}
|
||||
@ -17,33 +15,19 @@ export const sharedPageComponents: SharedLayout = {
|
||||
// components for pages that display a single page (e.g. a single note)
|
||||
export const defaultContentPageLayout: PageLayout = {
|
||||
beforeBody: [
|
||||
Component.ConditionalRender({
|
||||
component: Component.Breadcrumbs(),
|
||||
condition: (page) => page.fileData.slug !== "index",
|
||||
}),
|
||||
Component.ArticleTitle(),
|
||||
Component.ContentMeta(),
|
||||
Component.TagList(),
|
||||
Component.MobileOnly(Component.Explorer()),
|
||||
Component.Breadcrumbs()
|
||||
],
|
||||
left: [
|
||||
Component.PageTitle(),
|
||||
Component.MobileOnly(Component.Spacer()),
|
||||
Component.Flex({
|
||||
components: [
|
||||
{
|
||||
Component: Component.Search(),
|
||||
grow: true,
|
||||
},
|
||||
{ Component: Component.Darkmode() },
|
||||
{ Component: Component.ReaderMode() },
|
||||
],
|
||||
}),
|
||||
Component.Explorer(),
|
||||
Component.MobileOnly(Component.Darkmode()),
|
||||
Component.Search(),
|
||||
Component.DesktopOnly(Component.Explorer())
|
||||
],
|
||||
right: [
|
||||
Component.Graph(),
|
||||
Component.DesktopOnly(Component.Darkmode()),
|
||||
Component.DesktopOnly(Component.TableOfContents()),
|
||||
Component.Backlinks(),
|
||||
],
|
||||
}
|
||||
|
||||
@ -53,16 +37,9 @@ export const defaultListPageLayout: PageLayout = {
|
||||
left: [
|
||||
Component.PageTitle(),
|
||||
Component.MobileOnly(Component.Spacer()),
|
||||
Component.Flex({
|
||||
components: [
|
||||
{
|
||||
Component: Component.Search(),
|
||||
grow: true,
|
||||
},
|
||||
{ Component: Component.Darkmode() },
|
||||
],
|
||||
}),
|
||||
Component.Explorer(),
|
||||
Component.Search(),
|
||||
Component.Darkmode(),
|
||||
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,
|
||||
})
|
||||
|
446
quartz/build.ts
@ -2,14 +2,14 @@ import sourceMapSupport from "source-map-support"
|
||||
sourceMapSupport.install(options)
|
||||
import path from "path"
|
||||
import { PerfTimer } from "./util/perf"
|
||||
import { rm } from "fs/promises"
|
||||
import { rimraf } from "rimraf"
|
||||
import { GlobbyFilterFunction, isGitIgnored } from "globby"
|
||||
import { styleText } from "util"
|
||||
import chalk from "chalk"
|
||||
import { parseMarkdown } from "./processors/parse"
|
||||
import { filterContent } from "./processors/filter"
|
||||
import { emitContent } from "./processors/emit"
|
||||
import cfg from "../quartz.config"
|
||||
import { FilePath, joinSegments, slugifyFilePath } from "./util/path"
|
||||
import { FilePath, FullSlug, joinSegments, slugifyFilePath } from "./util/path"
|
||||
import chokidar from "chokidar"
|
||||
import { ProcessedContent } from "./plugins/vfile"
|
||||
import { Argv, BuildCtx } from "./util/ctx"
|
||||
@ -17,39 +17,32 @@ import { glob, toPosixPath } from "./util/glob"
|
||||
import { trace } from "./util/trace"
|
||||
import { options } from "./util/sourcemap"
|
||||
import { Mutex } from "async-mutex"
|
||||
import DepGraph from "./depgraph"
|
||||
import { getStaticResourcesFromPlugins } from "./plugins"
|
||||
import { randomIdNonSecure } from "./util/random"
|
||||
import { ChangeEvent } from "./plugins/types"
|
||||
import { minimatch } from "minimatch"
|
||||
|
||||
type ContentMap = Map<
|
||||
FilePath,
|
||||
| {
|
||||
type: "markdown"
|
||||
content: ProcessedContent
|
||||
}
|
||||
| {
|
||||
type: "other"
|
||||
}
|
||||
>
|
||||
type Dependencies = Record<string, DepGraph<FilePath> | null>
|
||||
|
||||
type BuildData = {
|
||||
ctx: BuildCtx
|
||||
ignored: GlobbyFilterFunction
|
||||
mut: Mutex
|
||||
contentMap: ContentMap
|
||||
changesSinceLastBuild: Record<FilePath, ChangeEvent["type"]>
|
||||
initialSlugs: FullSlug[]
|
||||
// TODO merge contentMap and trackedAssets
|
||||
contentMap: Map<FilePath, ProcessedContent>
|
||||
trackedAssets: Set<FilePath>
|
||||
toRebuild: Set<FilePath>
|
||||
toRemove: Set<FilePath>
|
||||
lastBuildMs: number
|
||||
dependencies: Dependencies
|
||||
}
|
||||
|
||||
type FileEvent = "add" | "change" | "delete"
|
||||
|
||||
async function buildQuartz(argv: Argv, mut: Mutex, clientRefresh: () => void) {
|
||||
const ctx: BuildCtx = {
|
||||
buildId: randomIdNonSecure(),
|
||||
argv,
|
||||
cfg,
|
||||
allSlugs: [],
|
||||
allFiles: [],
|
||||
incremental: false,
|
||||
}
|
||||
|
||||
const perf = new PerfTimer()
|
||||
@ -67,78 +60,69 @@ async function buildQuartz(argv: Argv, mut: Mutex, clientRefresh: () => void) {
|
||||
|
||||
const release = await mut.acquire()
|
||||
perf.addEvent("clean")
|
||||
await rm(output, { recursive: true, force: true })
|
||||
await rimraf(path.join(output, "*"), { glob: true })
|
||||
console.log(`Cleaned output directory \`${output}\` in ${perf.timeSince("clean")}`)
|
||||
|
||||
perf.addEvent("glob")
|
||||
const allFiles = await glob("**/*.*", argv.directory, cfg.configuration.ignorePatterns)
|
||||
const markdownPaths = allFiles.filter((fp) => fp.endsWith(".md")).sort()
|
||||
const fps = allFiles.filter((fp) => fp.endsWith(".md")).sort()
|
||||
console.log(
|
||||
`Found ${markdownPaths.length} input files from \`${argv.directory}\` in ${perf.timeSince("glob")}`,
|
||||
`Found ${fps.length} input files from \`${argv.directory}\` in ${perf.timeSince("glob")}`,
|
||||
)
|
||||
|
||||
const filePaths = markdownPaths.map((fp) => joinSegments(argv.directory, fp) as FilePath)
|
||||
ctx.allFiles = allFiles
|
||||
const filePaths = fps.map((fp) => joinSegments(argv.directory, fp) as FilePath)
|
||||
ctx.allSlugs = allFiles.map((fp) => slugifyFilePath(fp as FilePath))
|
||||
|
||||
const parsedFiles = await parseMarkdown(ctx, filePaths)
|
||||
const filteredContent = filterContent(ctx, parsedFiles)
|
||||
|
||||
const dependencies: Record<string, DepGraph<FilePath> | null> = {}
|
||||
|
||||
// Only build dependency graphs if we're doing a fast rebuild
|
||||
if (argv.fastRebuild) {
|
||||
const staticResources = getStaticResourcesFromPlugins(ctx)
|
||||
for (const emitter of cfg.plugins.emitters) {
|
||||
dependencies[emitter.name] =
|
||||
(await emitter.getDependencyGraph?.(ctx, filteredContent, staticResources)) ?? null
|
||||
}
|
||||
}
|
||||
|
||||
await emitContent(ctx, filteredContent)
|
||||
console.log(
|
||||
styleText("green", `Done processing ${markdownPaths.length} files in ${perf.timeSince()}`),
|
||||
)
|
||||
console.log(chalk.green(`Done processing ${fps.length} files in ${perf.timeSince()}`))
|
||||
release()
|
||||
|
||||
if (argv.watch) {
|
||||
ctx.incremental = true
|
||||
return startWatching(ctx, mut, parsedFiles, clientRefresh)
|
||||
if (argv.serve) {
|
||||
return startServing(ctx, mut, parsedFiles, clientRefresh, dependencies)
|
||||
}
|
||||
}
|
||||
|
||||
// setup watcher for rebuilds
|
||||
async function startWatching(
|
||||
async function startServing(
|
||||
ctx: BuildCtx,
|
||||
mut: Mutex,
|
||||
initialContent: ProcessedContent[],
|
||||
clientRefresh: () => void,
|
||||
dependencies: Dependencies, // emitter name: dep graph
|
||||
) {
|
||||
const { argv, allFiles } = ctx
|
||||
|
||||
const contentMap: ContentMap = new Map()
|
||||
for (const filePath of allFiles) {
|
||||
contentMap.set(filePath, {
|
||||
type: "other",
|
||||
})
|
||||
}
|
||||
const { argv } = ctx
|
||||
|
||||
// cache file parse results
|
||||
const contentMap = new Map<FilePath, ProcessedContent>()
|
||||
for (const content of initialContent) {
|
||||
const [_tree, vfile] = content
|
||||
contentMap.set(vfile.data.relativePath!, {
|
||||
type: "markdown",
|
||||
content,
|
||||
})
|
||||
contentMap.set(vfile.data.filePath!, content)
|
||||
}
|
||||
|
||||
const gitIgnoredMatcher = await isGitIgnored()
|
||||
const buildData: BuildData = {
|
||||
ctx,
|
||||
mut,
|
||||
dependencies,
|
||||
contentMap,
|
||||
ignored: (fp) => {
|
||||
const pathStr = toPosixPath(fp.toString())
|
||||
if (pathStr.startsWith(".git/")) return true
|
||||
if (gitIgnoredMatcher(pathStr)) return true
|
||||
for (const pattern of cfg.configuration.ignorePatterns) {
|
||||
if (minimatch(pathStr, pattern)) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
},
|
||||
|
||||
changesSinceLastBuild: {},
|
||||
ignored: await isGitIgnored(),
|
||||
initialSlugs: ctx.allSlugs,
|
||||
toRebuild: new Set<FilePath>(),
|
||||
toRemove: new Set<FilePath>(),
|
||||
trackedAssets: new Set<FilePath>(),
|
||||
lastBuildMs: 0,
|
||||
}
|
||||
|
||||
@ -148,146 +132,274 @@ async function startWatching(
|
||||
ignoreInitial: true,
|
||||
})
|
||||
|
||||
const changes: ChangeEvent[] = []
|
||||
const buildFromEntry = argv.fastRebuild ? partialRebuildFromEntrypoint : rebuildFromEntrypoint
|
||||
watcher
|
||||
.on("add", (fp) => {
|
||||
if (buildData.ignored(fp)) return
|
||||
changes.push({ path: fp as FilePath, type: "add" })
|
||||
void rebuild(changes, clientRefresh, buildData)
|
||||
})
|
||||
.on("change", (fp) => {
|
||||
if (buildData.ignored(fp)) return
|
||||
changes.push({ path: fp as FilePath, type: "change" })
|
||||
void rebuild(changes, clientRefresh, buildData)
|
||||
})
|
||||
.on("unlink", (fp) => {
|
||||
if (buildData.ignored(fp)) return
|
||||
changes.push({ path: fp as FilePath, type: "delete" })
|
||||
void rebuild(changes, clientRefresh, buildData)
|
||||
})
|
||||
.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()
|
||||
}
|
||||
}
|
||||
|
||||
async function rebuild(changes: ChangeEvent[], clientRefresh: () => void, buildData: BuildData) {
|
||||
const { ctx, contentMap, mut, changesSinceLastBuild } = buildData
|
||||
async function partialRebuildFromEntrypoint(
|
||||
filepath: string,
|
||||
action: FileEvent,
|
||||
clientRefresh: () => void,
|
||||
buildData: BuildData, // note: this function mutates buildData
|
||||
) {
|
||||
const { ctx, ignored, dependencies, contentMap, mut, toRemove } = buildData
|
||||
const { argv, cfg } = ctx
|
||||
|
||||
const buildId = randomIdNonSecure()
|
||||
ctx.buildId = buildId
|
||||
buildData.lastBuildMs = new Date().getTime()
|
||||
const numChangesInBuild = changes.length
|
||||
const release = await mut.acquire()
|
||||
// don't do anything for gitignored files
|
||||
if (ignored(filepath)) {
|
||||
return
|
||||
}
|
||||
|
||||
// if there's another build after us, release and let them do it
|
||||
if (ctx.buildId !== buildId) {
|
||||
const buildStart = new Date().getTime()
|
||||
buildData.lastBuildMs = buildStart
|
||||
const release = await mut.acquire()
|
||||
if (buildData.lastBuildMs > buildStart) {
|
||||
release()
|
||||
return
|
||||
}
|
||||
|
||||
const perf = new PerfTimer()
|
||||
perf.addEvent("rebuild")
|
||||
console.log(styleText("yellow", "Detected change, rebuilding..."))
|
||||
console.log(chalk.yellow("Detected change, rebuilding..."))
|
||||
|
||||
// update changesSinceLastBuild
|
||||
for (const change of changes) {
|
||||
changesSinceLastBuild[change.path] = change.type
|
||||
}
|
||||
// UPDATE DEP GRAPH
|
||||
const fp = joinSegments(argv.directory, toPosixPath(filepath)) as FilePath
|
||||
|
||||
const staticResources = getStaticResourcesFromPlugins(ctx)
|
||||
const pathsToParse: FilePath[] = []
|
||||
for (const [fp, type] of Object.entries(changesSinceLastBuild)) {
|
||||
if (type === "delete" || path.extname(fp) !== ".md") continue
|
||||
const fullPath = joinSegments(argv.directory, toPosixPath(fp)) as FilePath
|
||||
pathsToParse.push(fullPath)
|
||||
}
|
||||
let processedFiles: ProcessedContent[] = []
|
||||
|
||||
const parsed = await parseMarkdown(ctx, pathsToParse)
|
||||
for (const content of parsed) {
|
||||
contentMap.set(content[1].data.relativePath!, {
|
||||
type: "markdown",
|
||||
content,
|
||||
})
|
||||
}
|
||||
switch (action) {
|
||||
case "add":
|
||||
// add to cache when new file is added
|
||||
processedFiles = await parseMarkdown(ctx, [fp])
|
||||
processedFiles.forEach(([tree, vfile]) => contentMap.set(vfile.data.filePath!, [tree, vfile]))
|
||||
|
||||
// update state using changesSinceLastBuild
|
||||
// we do this weird play of add => compute change events => remove
|
||||
// so that partialEmitters can do appropriate cleanup based on the content of deleted files
|
||||
for (const [file, change] of Object.entries(changesSinceLastBuild)) {
|
||||
if (change === "delete") {
|
||||
// universal delete case
|
||||
contentMap.delete(file as FilePath)
|
||||
}
|
||||
|
||||
// manually track non-markdown files as processed files only
|
||||
// contains markdown files
|
||||
if (change === "add" && path.extname(file) !== ".md") {
|
||||
contentMap.set(file as FilePath, {
|
||||
type: "other",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const changeEvents: ChangeEvent[] = Object.entries(changesSinceLastBuild).map(([fp, type]) => {
|
||||
const path = fp as FilePath
|
||||
const processedContent = contentMap.get(path)
|
||||
if (processedContent?.type === "markdown") {
|
||||
const [_tree, file] = processedContent.content
|
||||
return {
|
||||
type,
|
||||
path,
|
||||
file,
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
type,
|
||||
path,
|
||||
}
|
||||
})
|
||||
|
||||
// update allFiles and then allSlugs with the consistent view of content map
|
||||
ctx.allFiles = Array.from(contentMap.keys())
|
||||
ctx.allSlugs = ctx.allFiles.map((fp) => slugifyFilePath(fp as FilePath))
|
||||
const processedFiles = Array.from(contentMap.values())
|
||||
.filter((file) => file.type === "markdown")
|
||||
.map((file) => file.content)
|
||||
|
||||
let emittedFiles = 0
|
||||
// update the dep graph by asking all emitters whether they depend on this file
|
||||
for (const emitter of cfg.plugins.emitters) {
|
||||
// Try to use partialEmit if available, otherwise assume the output is static
|
||||
const emitFn = emitter.partialEmit ?? emitter.emit
|
||||
const emitted = await emitFn(ctx, processedFiles, staticResources, changeEvents)
|
||||
if (emitted === null) {
|
||||
const emitterGraph =
|
||||
(await emitter.getDependencyGraph?.(ctx, processedFiles, staticResources)) ?? null
|
||||
|
||||
if (emitterGraph) {
|
||||
const existingGraph = dependencies[emitter.name]
|
||||
if (existingGraph !== null) {
|
||||
existingGraph.mergeGraph(emitterGraph)
|
||||
} else {
|
||||
// might be the first time we're adding a mardown file
|
||||
dependencies[emitter.name] = emitterGraph
|
||||
}
|
||||
}
|
||||
}
|
||||
break
|
||||
case "change":
|
||||
// invalidate cache when file is changed
|
||||
processedFiles = await parseMarkdown(ctx, [fp])
|
||||
processedFiles.forEach(([tree, vfile]) => contentMap.set(vfile.data.filePath!, [tree, vfile]))
|
||||
|
||||
// only content files can have added/removed dependencies because of transclusions
|
||||
if (path.extname(fp) === ".md") {
|
||||
for (const emitter of cfg.plugins.emitters) {
|
||||
// get new dependencies from all emitters for this file
|
||||
const emitterGraph =
|
||||
(await emitter.getDependencyGraph?.(ctx, processedFiles, staticResources)) ?? null
|
||||
|
||||
// only update the graph if the emitter plugin uses the changed file
|
||||
// eg. Assets plugin ignores md files, so we skip updating the graph
|
||||
if (emitterGraph?.hasNode(fp)) {
|
||||
// merge the new dependencies into the dep graph
|
||||
dependencies[emitter.name]?.updateIncomingEdgesForNode(emitterGraph, fp)
|
||||
}
|
||||
}
|
||||
}
|
||||
break
|
||||
case "delete":
|
||||
toRemove.add(fp)
|
||||
break
|
||||
}
|
||||
|
||||
if (argv.verbose) {
|
||||
console.log(`Updated dependency graphs in ${perf.timeSince()}`)
|
||||
}
|
||||
|
||||
// EMIT
|
||||
perf.addEvent("rebuild")
|
||||
let emittedFiles = 0
|
||||
|
||||
for (const emitter of cfg.plugins.emitters) {
|
||||
const depGraph = dependencies[emitter.name]
|
||||
|
||||
// emitter hasn't defined a dependency graph. call it with all processed files
|
||||
if (depGraph === null) {
|
||||
if (argv.verbose) {
|
||||
console.log(
|
||||
`Emitter ${emitter.name} doesn't define a dependency graph. Calling it with all files...`,
|
||||
)
|
||||
}
|
||||
|
||||
const files = [...contentMap.values()].filter(
|
||||
([_node, vfile]) => !toRemove.has(vfile.data.filePath!),
|
||||
)
|
||||
|
||||
const emittedFps = await emitter.emit(ctx, files, staticResources)
|
||||
|
||||
if (ctx.argv.verbose) {
|
||||
for (const file of emittedFps) {
|
||||
console.log(`[emit:${emitter.name}] ${file}`)
|
||||
}
|
||||
}
|
||||
|
||||
emittedFiles += emittedFps.length
|
||||
continue
|
||||
}
|
||||
|
||||
if (Symbol.asyncIterator in emitted) {
|
||||
// Async generator case
|
||||
for await (const file of emitted) {
|
||||
emittedFiles++
|
||||
// only call the emitter if it uses this file
|
||||
if (depGraph.hasNode(fp)) {
|
||||
// re-emit using all files that are needed for the downstream of this file
|
||||
// eg. for ContentIndex, the dep graph could be:
|
||||
// a.md --> contentIndex.json
|
||||
// b.md ------^
|
||||
//
|
||||
// if a.md changes, we need to re-emit contentIndex.json,
|
||||
// and supply [a.md, b.md] to the emitter
|
||||
const upstreams = [...depGraph.getLeafNodeAncestors(fp)] as FilePath[]
|
||||
|
||||
const upstreamContent = upstreams
|
||||
// filter out non-markdown files
|
||||
.filter((file) => contentMap.has(file))
|
||||
// if file was deleted, don't give it to the emitter
|
||||
.filter((file) => !toRemove.has(file))
|
||||
.map((file) => contentMap.get(file)!)
|
||||
|
||||
const emittedFps = await emitter.emit(ctx, upstreamContent, staticResources)
|
||||
|
||||
if (ctx.argv.verbose) {
|
||||
for (const file of emittedFps) {
|
||||
console.log(`[emit:${emitter.name}] ${file}`)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Array case
|
||||
emittedFiles += emitted.length
|
||||
if (ctx.argv.verbose) {
|
||||
for (const file of emitted) {
|
||||
console.log(`[emit:${emitter.name}] ${file}`)
|
||||
}
|
||||
}
|
||||
|
||||
emittedFiles += emittedFps.length
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`Emitted ${emittedFiles} files to \`${argv.output}\` in ${perf.timeSince("rebuild")}`)
|
||||
console.log(styleText("green", `Done rebuilding in ${perf.timeSince()}`))
|
||||
changes.splice(0, numChangesInBuild)
|
||||
clientRefresh()
|
||||
|
||||
// CLEANUP
|
||||
const destinationsToDelete = new Set<FilePath>()
|
||||
for (const file of toRemove) {
|
||||
// remove from cache
|
||||
contentMap.delete(file)
|
||||
Object.values(dependencies).forEach((depGraph) => {
|
||||
// remove the node from dependency graphs
|
||||
depGraph?.removeNode(file)
|
||||
// remove any orphan nodes. eg if a.md is deleted, a.html is orphaned and should be removed
|
||||
const orphanNodes = depGraph?.removeOrphanNodes()
|
||||
orphanNodes?.forEach((node) => {
|
||||
// only delete files that are in the output directory
|
||||
if (node.startsWith(argv.output)) {
|
||||
destinationsToDelete.add(node)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
await rimraf([...destinationsToDelete])
|
||||
|
||||
console.log(chalk.green(`Done rebuilding in ${perf.timeSince()}`))
|
||||
|
||||
toRemove.clear()
|
||||
release()
|
||||
clientRefresh()
|
||||
}
|
||||
|
||||
async function rebuildFromEntrypoint(
|
||||
fp: string,
|
||||
action: FileEvent,
|
||||
clientRefresh: () => void,
|
||||
buildData: BuildData, // note: this function mutates buildData
|
||||
) {
|
||||
const { ctx, ignored, mut, initialSlugs, contentMap, toRebuild, toRemove, trackedAssets } =
|
||||
buildData
|
||||
|
||||
const { argv } = ctx
|
||||
|
||||
// don't do anything for gitignored files
|
||||
if (ignored(fp)) {
|
||||
return
|
||||
}
|
||||
|
||||
// dont bother rebuilding for non-content files, just track and refresh
|
||||
fp = toPosixPath(fp)
|
||||
const filePath = joinSegments(argv.directory, fp) as FilePath
|
||||
if (path.extname(fp) !== ".md") {
|
||||
if (action === "add" || action === "change") {
|
||||
trackedAssets.add(filePath)
|
||||
} else if (action === "delete") {
|
||||
trackedAssets.delete(filePath)
|
||||
}
|
||||
clientRefresh()
|
||||
return
|
||||
}
|
||||
|
||||
if (action === "add" || action === "change") {
|
||||
toRebuild.add(filePath)
|
||||
} else if (action === "delete") {
|
||||
toRemove.add(filePath)
|
||||
}
|
||||
|
||||
const buildStart = new Date().getTime()
|
||||
buildData.lastBuildMs = buildStart
|
||||
const release = await mut.acquire()
|
||||
|
||||
// there's another build after us, release and let them do it
|
||||
if (buildData.lastBuildMs > buildStart) {
|
||||
release()
|
||||
return
|
||||
}
|
||||
|
||||
const perf = new PerfTimer()
|
||||
console.log(chalk.yellow("Detected change, rebuilding..."))
|
||||
try {
|
||||
const filesToRebuild = [...toRebuild].filter((fp) => !toRemove.has(fp))
|
||||
|
||||
const trackedSlugs = [...new Set([...contentMap.keys(), ...toRebuild, ...trackedAssets])]
|
||||
.filter((fp) => !toRemove.has(fp))
|
||||
.map((fp) => slugifyFilePath(path.posix.relative(argv.directory, fp) as FilePath))
|
||||
|
||||
ctx.allSlugs = [...new Set([...initialSlugs, ...trackedSlugs])]
|
||||
const parsedContent = await parseMarkdown(ctx, filesToRebuild)
|
||||
for (const content of parsedContent) {
|
||||
const [_tree, vfile] = content
|
||||
contentMap.set(vfile.data.filePath!, content)
|
||||
}
|
||||
|
||||
for (const fp of toRemove) {
|
||||
contentMap.delete(fp)
|
||||
}
|
||||
|
||||
const parsedFiles = [...contentMap.values()]
|
||||
const filteredContent = filterContent(ctx, parsedFiles)
|
||||
|
||||
// TODO: we can probably traverse the link graph to figure out what's safe to delete here
|
||||
// instead of just deleting everything
|
||||
await rimraf(path.join(argv.output, ".*"), { glob: true })
|
||||
await emitContent(ctx, filteredContent)
|
||||
console.log(chalk.green(`Done rebuilding in ${perf.timeSince()}`))
|
||||
} catch (err) {
|
||||
console.log(chalk.yellow(`Rebuild failed. Waiting on a change to fix the error...`))
|
||||
if (argv.verbose) {
|
||||
console.log(chalk.red(err))
|
||||
}
|
||||
}
|
||||
|
||||
release()
|
||||
clientRefresh()
|
||||
toRebuild.clear()
|
||||
toRemove.clear()
|
||||
}
|
||||
|
||||
export default async (argv: Argv, mut: Mutex, clientRefresh: () => void) => {
|
||||
|
@ -25,27 +25,9 @@ export type Analytics =
|
||||
host?: string
|
||||
scriptSrc?: string
|
||||
}
|
||||
| {
|
||||
provider: "posthog"
|
||||
apiKey: string
|
||||
host?: string
|
||||
}
|
||||
| {
|
||||
provider: "tinylytics"
|
||||
siteId: string
|
||||
}
|
||||
| {
|
||||
provider: "cabin"
|
||||
host?: string
|
||||
}
|
||||
| {
|
||||
provider: "clarity"
|
||||
projectId?: string
|
||||
}
|
||||
|
||||
export interface GlobalConfiguration {
|
||||
pageTitle: string
|
||||
pageTitleSuffix?: string
|
||||
/** Whether to enable single-page-app style rendering. this prevents flashes of unstyled content and improves smoothness of Quartz */
|
||||
enableSPA: boolean
|
||||
/** Whether to display Wikipedia-style popovers when hovering over links */
|
||||
@ -64,7 +46,7 @@ export interface GlobalConfiguration {
|
||||
/**
|
||||
* Allow to translate the date in the language of your choice.
|
||||
* Also used for UI translation (default: en-US)
|
||||
* Need to be formatted following BCP 47: https://en.wikipedia.org/wiki/IETF_language_tag
|
||||
* Need to be formated following BCP 47: https://en.wikipedia.org/wiki/IETF_language_tag
|
||||
* The first part is the language (en) and the second part is the script/region (US)
|
||||
* Language Codes: https://en.wikipedia.org/wiki/List_of_ISO_639_language_codes
|
||||
* Region Codes: https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2
|
||||
@ -82,11 +64,10 @@ export interface FullPageLayout {
|
||||
header: QuartzComponent[]
|
||||
beforeBody: QuartzComponent[]
|
||||
pageBody: QuartzComponent
|
||||
afterBody: QuartzComponent[]
|
||||
left: QuartzComponent[]
|
||||
right: QuartzComponent[]
|
||||
footer: QuartzComponent
|
||||
}
|
||||
|
||||
export type PageLayout = Pick<FullPageLayout, "beforeBody" | "left" | "right">
|
||||
export type SharedLayout = Pick<FullPageLayout, "head" | "header" | "footer" | "afterBody">
|
||||
export type SharedLayout = Pick<FullPageLayout, "head" | "header" | "footer">
|
||||
|
@ -71,10 +71,10 @@ export const BuildArgv = {
|
||||
default: false,
|
||||
describe: "run a local server to live-preview your Quartz",
|
||||
},
|
||||
watch: {
|
||||
fastRebuild: {
|
||||
boolean: true,
|
||||
default: false,
|
||||
describe: "watch for changes and rebuild automatically",
|
||||
describe: "[experimental] rebuild only the changed files",
|
||||
},
|
||||
baseDir: {
|
||||
string: true,
|
||||
|
@ -1,11 +1,11 @@
|
||||
import { promises } from "fs"
|
||||
import path from "path"
|
||||
import esbuild from "esbuild"
|
||||
import { styleText } from "util"
|
||||
import chalk from "chalk"
|
||||
import { sassPlugin } from "esbuild-sass-plugin"
|
||||
import fs from "fs"
|
||||
import { intro, outro, select, text } from "@clack/prompts"
|
||||
import { rm } from "fs/promises"
|
||||
import { rimraf } from "rimraf"
|
||||
import chokidar from "chokidar"
|
||||
import prettyBytes from "pretty-bytes"
|
||||
import { execSync, spawnSync } from "child_process"
|
||||
@ -15,7 +15,6 @@ import { WebSocketServer } from "ws"
|
||||
import { randomUUID } from "crypto"
|
||||
import { Mutex } from "async-mutex"
|
||||
import { CreateArgv } from "./args.js"
|
||||
import { globby } from "globby"
|
||||
import {
|
||||
exitIfCancel,
|
||||
escapePath,
|
||||
@ -33,44 +32,31 @@ 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`
|
||||
*/
|
||||
export async function handleCreate(argv) {
|
||||
console.log()
|
||||
intro(styleText(["bgGreen", "black"], ` Quartz v${version} `))
|
||||
const contentFolder = resolveContentPath(argv.directory)
|
||||
intro(chalk.bgGreen.black(` Quartz v${version} `))
|
||||
const contentFolder = path.join(cwd, argv.directory)
|
||||
let setupStrategy = argv.strategy?.toLowerCase()
|
||||
let linkResolutionStrategy = argv.links?.toLowerCase()
|
||||
const sourceDirectory = argv.source
|
||||
|
||||
// If all cmd arguments were provided, check if they're valid
|
||||
// If all cmd arguments were provided, check if theyre valid
|
||||
if (setupStrategy && linkResolutionStrategy) {
|
||||
// If setup isn't, "new", source argument is required
|
||||
if (setupStrategy !== "new") {
|
||||
// Error handling
|
||||
if (!sourceDirectory) {
|
||||
outro(
|
||||
styleText(
|
||||
"red",
|
||||
`Setup strategies (arg '${styleText(
|
||||
"yellow",
|
||||
chalk.red(
|
||||
`Setup strategies (arg '${chalk.yellow(
|
||||
`-${CreateArgv.strategy.alias[0]}`,
|
||||
)}') other than '${styleText(
|
||||
"yellow",
|
||||
)}') other than '${chalk.yellow(
|
||||
"new",
|
||||
)}' require content folder argument ('${styleText(
|
||||
"yellow",
|
||||
)}' require content folder argument ('${chalk.yellow(
|
||||
`-${CreateArgv.source.alias[0]}`,
|
||||
)}') to be set`,
|
||||
),
|
||||
@ -79,23 +65,19 @@ export async function handleCreate(argv) {
|
||||
} else {
|
||||
if (!fs.existsSync(sourceDirectory)) {
|
||||
outro(
|
||||
styleText(
|
||||
"red",
|
||||
`Input directory to copy/symlink 'content' from not found ('${styleText(
|
||||
"yellow",
|
||||
chalk.red(
|
||||
`Input directory to copy/symlink 'content' from not found ('${chalk.yellow(
|
||||
sourceDirectory,
|
||||
)}', invalid argument "${styleText("yellow", `-${CreateArgv.source.alias[0]}`)})`,
|
||||
)}', invalid argument "${chalk.yellow(`-${CreateArgv.source.alias[0]}`)})`,
|
||||
),
|
||||
)
|
||||
process.exit(1)
|
||||
} else if (!fs.lstatSync(sourceDirectory).isDirectory()) {
|
||||
outro(
|
||||
styleText(
|
||||
"red",
|
||||
`Source directory to copy/symlink 'content' from is not a directory (found file at '${styleText(
|
||||
"yellow",
|
||||
chalk.red(
|
||||
`Source directory to copy/symlink 'content' from is not a directory (found file at '${chalk.yellow(
|
||||
sourceDirectory,
|
||||
)}', invalid argument ${styleText("yellow", `-${CreateArgv.source.alias[0]}`)}")`,
|
||||
)}', invalid argument ${chalk.yellow(`-${CreateArgv.source.alias[0]}`)}")`,
|
||||
),
|
||||
)
|
||||
process.exit(1)
|
||||
@ -127,7 +109,7 @@ export async function handleCreate(argv) {
|
||||
if (contentStat.isSymbolicLink()) {
|
||||
await fs.promises.unlink(contentFolder)
|
||||
} else {
|
||||
await rm(contentFolder, { recursive: true, force: true })
|
||||
await rimraf(contentFolder)
|
||||
}
|
||||
}
|
||||
|
||||
@ -233,11 +215,7 @@ See the [documentation](https://quartz.jzhao.xyz) for how to get started.
|
||||
* @param {*} argv arguments for `build`
|
||||
*/
|
||||
export async function handleBuild(argv) {
|
||||
if (argv.serve) {
|
||||
argv.watch = true
|
||||
}
|
||||
|
||||
console.log(`\n${styleText(["bgGreen", "black"], ` Quartz v${version} `)} \n`)
|
||||
console.log(chalk.bgGreen.black(`\n Quartz v${version} \n`))
|
||||
const ctx = await esbuild.context({
|
||||
entryPoints: [fp],
|
||||
outfile: cacheFile,
|
||||
@ -258,11 +236,6 @@ export async function handleBuild(argv) {
|
||||
type: "css-text",
|
||||
cssImports: true,
|
||||
}),
|
||||
sassPlugin({
|
||||
filter: /\.inline\.scss$/,
|
||||
type: "css",
|
||||
cssImports: true,
|
||||
}),
|
||||
{
|
||||
name: "inline-script-loader",
|
||||
setup(build) {
|
||||
@ -312,13 +285,13 @@ export async function handleBuild(argv) {
|
||||
}
|
||||
|
||||
if (cleanupBuild) {
|
||||
console.log(styleText("yellow", "Detected a source code change, doing a hard rebuild..."))
|
||||
await cleanupBuild()
|
||||
console.log(chalk.yellow("Detected a source code change, doing a hard rebuild..."))
|
||||
}
|
||||
|
||||
const result = await ctx.rebuild().catch((err) => {
|
||||
console.error(`${styleText("red", "Couldn't parse Quartz configuration:")} ${fp}`)
|
||||
console.log(`Reason: ${styleText("grey", err)}`)
|
||||
console.error(`${chalk.red("Couldn't parse Quartz configuration:")} ${fp}`)
|
||||
console.log(`Reason: ${chalk.grey(err)}`)
|
||||
process.exit(1)
|
||||
})
|
||||
release()
|
||||
@ -343,10 +316,9 @@ export async function handleBuild(argv) {
|
||||
clientRefresh()
|
||||
}
|
||||
|
||||
let clientRefresh = () => {}
|
||||
if (argv.serve) {
|
||||
const connections = []
|
||||
clientRefresh = () => connections.forEach((conn) => conn.send("rebuild"))
|
||||
const clientRefresh = () => connections.forEach((conn) => conn.send("rebuild"))
|
||||
|
||||
if (argv.baseDir !== "" && !argv.baseDir.startsWith("/")) {
|
||||
argv.baseDir = "/" + argv.baseDir
|
||||
@ -356,8 +328,7 @@ export async function handleBuild(argv) {
|
||||
const server = http.createServer(async (req, res) => {
|
||||
if (argv.baseDir && !req.url?.startsWith(argv.baseDir)) {
|
||||
console.log(
|
||||
styleText(
|
||||
"red",
|
||||
chalk.red(
|
||||
`[404] ${req.url} (warning: link outside of site, this is likely a Quartz bug)`,
|
||||
),
|
||||
)
|
||||
@ -379,23 +350,12 @@ export async function handleBuild(argv) {
|
||||
source: "**/*.*",
|
||||
headers: [{ key: "Content-Disposition", value: "inline" }],
|
||||
},
|
||||
{
|
||||
source: "**/*.webp",
|
||||
headers: [{ key: "Content-Type", value: "image/webp" }],
|
||||
},
|
||||
// fixes bug where avif images are displayed as text instead of images (future proof)
|
||||
{
|
||||
source: "**/*.avif",
|
||||
headers: [{ key: "Content-Type", value: "image/avif" }],
|
||||
},
|
||||
],
|
||||
})
|
||||
const status = res.statusCode
|
||||
const statusString =
|
||||
status >= 200 && status < 300
|
||||
? styleText("green", `[${status}]`)
|
||||
: styleText("red", `[${status}]`)
|
||||
console.log(statusString + styleText("grey", ` ${argv.baseDir}${req.url}`))
|
||||
status >= 200 && status < 300 ? chalk.green(`[${status}]`) : chalk.red(`[${status}]`)
|
||||
console.log(statusString + chalk.grey(` ${argv.baseDir}${req.url}`))
|
||||
release()
|
||||
}
|
||||
|
||||
@ -404,10 +364,7 @@ export async function handleBuild(argv) {
|
||||
res.writeHead(302, {
|
||||
Location: newFp,
|
||||
})
|
||||
console.log(
|
||||
styleText("yellow", "[302]") +
|
||||
styleText("grey", ` ${argv.baseDir}${req.url} -> ${newFp}`),
|
||||
)
|
||||
console.log(chalk.yellow("[302]") + chalk.grey(` ${argv.baseDir}${req.url} -> ${newFp}`))
|
||||
res.end()
|
||||
}
|
||||
|
||||
@ -452,37 +409,25 @@ export async function handleBuild(argv) {
|
||||
|
||||
return serve()
|
||||
})
|
||||
|
||||
server.listen(argv.port)
|
||||
const wss = new WebSocketServer({ port: argv.wsPort })
|
||||
wss.on("connection", (ws) => connections.push(ws))
|
||||
console.log(
|
||||
styleText(
|
||||
"cyan",
|
||||
chalk.cyan(
|
||||
`Started a Quartz server listening at http://localhost:${argv.port}${argv.baseDir}`,
|
||||
),
|
||||
)
|
||||
} else {
|
||||
await build(clientRefresh)
|
||||
ctx.dispose()
|
||||
}
|
||||
|
||||
if (argv.watch) {
|
||||
const paths = await globby([
|
||||
"**/*.ts",
|
||||
"quartz/cli/*.js",
|
||||
"quartz/static/**/*",
|
||||
"**/*.tsx",
|
||||
"**/*.scss",
|
||||
"package.json",
|
||||
])
|
||||
console.log("hint: exit with ctrl+c")
|
||||
chokidar
|
||||
.watch(paths, { ignoreInitial: true })
|
||||
.on("add", () => build(clientRefresh))
|
||||
.on("change", () => build(clientRefresh))
|
||||
.on("unlink", () => build(clientRefresh))
|
||||
|
||||
console.log(styleText("grey", "hint: exit with ctrl+c"))
|
||||
.watch(["**/*.ts", "**/*.tsx", "**/*.scss", "package.json"], {
|
||||
ignoreInitial: true,
|
||||
})
|
||||
.on("all", async () => {
|
||||
build(clientRefresh)
|
||||
})
|
||||
} else {
|
||||
await build(() => {})
|
||||
ctx.dispose()
|
||||
}
|
||||
}
|
||||
|
||||
@ -491,8 +436,8 @@ export async function handleBuild(argv) {
|
||||
* @param {*} argv arguments for `update`
|
||||
*/
|
||||
export async function handleUpdate(argv) {
|
||||
const contentFolder = resolveContentPath(argv.directory)
|
||||
console.log(`\n${styleText(["bgGreen", "black"], ` Quartz v${version} `)} \n`)
|
||||
const contentFolder = path.join(cwd, argv.directory)
|
||||
console.log(chalk.bgGreen.black(`\n Quartz v${version} \n`))
|
||||
console.log("Backing up your content")
|
||||
execSync(
|
||||
`git remote show upstream || git remote add upstream https://github.com/jackyzha0/quartz.git`,
|
||||
@ -505,36 +450,18 @@ export async function handleUpdate(argv) {
|
||||
try {
|
||||
gitPull(UPSTREAM_NAME, QUARTZ_SOURCE_BRANCH)
|
||||
} catch {
|
||||
console.log(styleText("red", "An error occurred above while pulling updates."))
|
||||
console.log(chalk.red("An error occurred above while pulling updates."))
|
||||
await popContentFolder(contentFolder)
|
||||
return
|
||||
}
|
||||
|
||||
await popContentFolder(contentFolder)
|
||||
console.log("Ensuring dependencies are up to date")
|
||||
|
||||
/*
|
||||
On Windows, if the command `npm` is really `npm.cmd', this call fails
|
||||
as it will be unable to find `npm`. This is often the case on systems
|
||||
where `npm` is installed via a package manager.
|
||||
|
||||
This means `npx quartz update` will not actually update dependencies
|
||||
on Windows, without a manual `npm i` from the caller.
|
||||
|
||||
However, by spawning a shell, we are able to call `npm.cmd`.
|
||||
See: https://nodejs.org/api/child_process.html#spawning-bat-and-cmd-files-on-windows
|
||||
*/
|
||||
|
||||
const opts = { stdio: "inherit" }
|
||||
if (process.platform === "win32") {
|
||||
opts.shell = true
|
||||
}
|
||||
|
||||
const res = spawnSync("npm", ["i"], opts)
|
||||
const res = spawnSync("npm", ["i"], { stdio: "inherit" })
|
||||
if (res.status === 0) {
|
||||
console.log(styleText("green", "Done!"))
|
||||
console.log(chalk.green("Done!"))
|
||||
} else {
|
||||
console.log(styleText("red", "An error occurred above while installing dependencies."))
|
||||
console.log(chalk.red("An error occurred above while installing dependencies."))
|
||||
}
|
||||
}
|
||||
|
||||
@ -543,7 +470,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)
|
||||
}
|
||||
|
||||
@ -552,15 +479,15 @@ export async function handleRestore(argv) {
|
||||
* @param {*} argv arguments for `sync`
|
||||
*/
|
||||
export async function handleSync(argv) {
|
||||
const contentFolder = resolveContentPath(argv.directory)
|
||||
console.log(`\n${styleText(["bgGreen", "black"], ` Quartz v${version} `)}\n`)
|
||||
const contentFolder = path.join(cwd, argv.directory)
|
||||
console.log(chalk.bgGreen.black(`\n Quartz v${version} \n`))
|
||||
console.log("Backing up your content")
|
||||
|
||||
if (argv.commit) {
|
||||
const contentStat = await fs.promises.lstat(contentFolder)
|
||||
if (contentStat.isSymbolicLink()) {
|
||||
const linkTarg = await fs.promises.readlink(contentFolder)
|
||||
console.log(styleText("yellow", "Detected symlink, trying to dereference before committing"))
|
||||
console.log(chalk.yellow("Detected symlink, trying to dereference before committing"))
|
||||
|
||||
// stash symlink file
|
||||
await stashContentFolder(contentFolder)
|
||||
@ -595,7 +522,7 @@ export async function handleSync(argv) {
|
||||
try {
|
||||
gitPull(ORIGIN_NAME, QUARTZ_SOURCE_BRANCH)
|
||||
} catch {
|
||||
console.log(styleText("red", "An error occurred above while pulling updates."))
|
||||
console.log(chalk.red("An error occurred above while pulling updates."))
|
||||
await popContentFolder(contentFolder)
|
||||
return
|
||||
}
|
||||
@ -604,17 +531,14 @@ export async function handleSync(argv) {
|
||||
await popContentFolder(contentFolder)
|
||||
if (argv.push) {
|
||||
console.log("Pushing your changes")
|
||||
const currentBranch = execSync("git rev-parse --abbrev-ref HEAD").toString().trim()
|
||||
const res = spawnSync("git", ["push", "-uf", ORIGIN_NAME, currentBranch], {
|
||||
const res = spawnSync("git", ["push", "-uf", ORIGIN_NAME, QUARTZ_SOURCE_BRANCH], {
|
||||
stdio: "inherit",
|
||||
})
|
||||
if (res.status !== 0) {
|
||||
console.log(
|
||||
styleText("red", `An error occurred above while pushing to remote ${ORIGIN_NAME}.`),
|
||||
)
|
||||
console.log(chalk.red(`An error occurred above while pushing to remote ${ORIGIN_NAME}.`))
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
console.log(styleText("green", "Done!"))
|
||||
console.log(chalk.green("Done!"))
|
||||
}
|
||||
|
@ -1,5 +1,5 @@
|
||||
import { isCancel, outro } from "@clack/prompts"
|
||||
import { styleText } from "util"
|
||||
import chalk from "chalk"
|
||||
import { contentCacheFolder } from "./constants.js"
|
||||
import { spawnSync } from "child_process"
|
||||
import fs from "fs"
|
||||
@ -14,7 +14,7 @@ export function escapePath(fp) {
|
||||
|
||||
export function exitIfCancel(val) {
|
||||
if (isCancel(val)) {
|
||||
outro(styleText("red", "Exiting"))
|
||||
outro(chalk.red("Exiting"))
|
||||
process.exit(0)
|
||||
} else {
|
||||
return val
|
||||
@ -36,9 +36,9 @@ export function gitPull(origin, branch) {
|
||||
const flags = ["--no-rebase", "--autostash", "-s", "recursive", "-X", "ours", "--no-edit"]
|
||||
const out = spawnSync("git", ["pull", ...flags, origin, branch], { stdio: "inherit" })
|
||||
if (out.stderr) {
|
||||
throw new Error(styleText("red", `Error while pulling updates: ${out.stderr}`))
|
||||
throw new Error(chalk.red(`Error while pulling updates: ${out.stderr}`))
|
||||
} else if (out.status !== 0) {
|
||||
throw new Error(styleText("red", "Error while pulling updates"))
|
||||
throw new Error(chalk.red("Error while pulling updates"))
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -3,35 +3,19 @@ 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 defaultOptions: BacklinksOptions = {
|
||||
hideWhenEmpty: true,
|
||||
}
|
||||
|
||||
export default ((opts?: Partial<BacklinksOptions>) => {
|
||||
const options: BacklinksOptions = { ...defaultOptions, ...opts }
|
||||
const { OverflowList, overflowListAfterDOMLoaded } = OverflowListFactory()
|
||||
|
||||
const Backlinks: QuartzComponent = ({
|
||||
const Backlinks: QuartzComponent = ({
|
||||
fileData,
|
||||
allFiles,
|
||||
displayClass,
|
||||
cfg,
|
||||
}: QuartzComponentProps) => {
|
||||
}: 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>
|
||||
<ul class="overflow">
|
||||
{backlinkFiles.length > 0 ? (
|
||||
backlinkFiles.map((f) => (
|
||||
<li>
|
||||
@ -43,13 +27,10 @@ export default ((opts?: Partial<BacklinksOptions>) => {
|
||||
) : (
|
||||
<li>{i18n(cfg.locale).components.backlinks.noBacklinksFound}</li>
|
||||
)}
|
||||
</OverflowList>
|
||||
</ul>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Backlinks.css = style
|
||||
Backlinks.afterDOMLoaded = overflowListAfterDOMLoaded
|
||||
|
||||
return Backlinks
|
||||
}) satisfies QuartzComponentConstructor
|
||||
Backlinks.css = style
|
||||
export default (() => Backlinks) satisfies QuartzComponentConstructor
|
||||
|
@ -1,8 +1,8 @@
|
||||
import { QuartzComponent, QuartzComponentConstructor, QuartzComponentProps } from "./types"
|
||||
import breadcrumbsStyle from "./styles/breadcrumbs.scss"
|
||||
import { FullSlug, SimpleSlug, resolveRelative, simplifySlug } from "../util/path"
|
||||
import { FullSlug, SimpleSlug, joinSegments, resolveRelative } from "../util/path"
|
||||
import { QuartzPluginData } from "../plugins/vfile"
|
||||
import { classNames } from "../util/lang"
|
||||
import { trieFromAllFiles } from "../util/ctx"
|
||||
|
||||
type CrumbData = {
|
||||
displayName: string
|
||||
@ -22,6 +22,10 @@ interface BreadcrumbOptions {
|
||||
* Whether to look up frontmatter title for folders (could cause performance problems with big vaults)
|
||||
*/
|
||||
resolveFrontmatterTitle: boolean
|
||||
/**
|
||||
* Whether to display breadcrumbs on root `index.md`
|
||||
*/
|
||||
hideOnRoot: boolean
|
||||
/**
|
||||
* Whether to display the current page in the breadcrumbs.
|
||||
*/
|
||||
@ -32,6 +36,7 @@ const defaultOptions: BreadcrumbOptions = {
|
||||
spacerSymbol: "❯",
|
||||
rootName: "Home",
|
||||
resolveFrontmatterTitle: true,
|
||||
hideOnRoot: true,
|
||||
showCurrentPage: true,
|
||||
}
|
||||
|
||||
@ -43,37 +48,78 @@ function formatCrumb(displayName: string, baseSlug: FullSlug, currentSlug: Simpl
|
||||
}
|
||||
|
||||
export default ((opts?: Partial<BreadcrumbOptions>) => {
|
||||
// Merge options with defaults
|
||||
const options: BreadcrumbOptions = { ...defaultOptions, ...opts }
|
||||
|
||||
// computed index of folder name to its associated file data
|
||||
let folderIndex: Map<string, QuartzPluginData> | undefined
|
||||
|
||||
const Breadcrumbs: QuartzComponent = ({
|
||||
fileData,
|
||||
allFiles,
|
||||
displayClass,
|
||||
ctx,
|
||||
}: QuartzComponentProps) => {
|
||||
const trie = (ctx.trie ??= trieFromAllFiles(allFiles))
|
||||
const slugParts = fileData.slug!.split("/")
|
||||
const pathNodes = trie.ancestryChain(slugParts)
|
||||
|
||||
if (!pathNodes) {
|
||||
return null
|
||||
// Hide crumbs on root if enabled
|
||||
if (options.hideOnRoot && fileData.slug === "index") {
|
||||
return <></>
|
||||
}
|
||||
|
||||
const crumbs: CrumbData[] = pathNodes.map((node, idx) => {
|
||||
const crumb = formatCrumb(node.displayName, fileData.slug!, simplifySlug(node.slug))
|
||||
if (idx === 0) {
|
||||
crumb.displayName = options.rootName
|
||||
// Format entry for root element
|
||||
const firstEntry = formatCrumb(options.rootName, fileData.slug!, "/" as SimpleSlug)
|
||||
const crumbs: CrumbData[] = [firstEntry]
|
||||
|
||||
if (!folderIndex && options.resolveFrontmatterTitle) {
|
||||
folderIndex = new Map()
|
||||
// construct the index for the first time
|
||||
for (const file of allFiles) {
|
||||
const folderParts = file.slug?.split("/")
|
||||
if (folderParts?.at(-1) === "index") {
|
||||
folderIndex.set(folderParts.slice(0, -1).join("/"), file)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// For last node (current page), set empty path
|
||||
if (idx === pathNodes.length - 1) {
|
||||
crumb.path = ""
|
||||
// Split slug into hierarchy/parts
|
||||
const slugParts = fileData.slug?.split("/")
|
||||
if (slugParts) {
|
||||
// is tag breadcrumb?
|
||||
const isTagPath = slugParts[0] === "tags"
|
||||
|
||||
// full path until current part
|
||||
let currentPath = ""
|
||||
|
||||
for (let i = 0; i < slugParts.length - 1; i++) {
|
||||
let curPathSegment = slugParts[i]
|
||||
|
||||
// Try to resolve frontmatter folder title
|
||||
const currentFile = folderIndex?.get(slugParts.slice(0, i + 1).join("/"))
|
||||
if (currentFile) {
|
||||
const title = currentFile.frontmatter!.title
|
||||
if (title !== "index") {
|
||||
curPathSegment = title
|
||||
}
|
||||
}
|
||||
|
||||
return crumb
|
||||
// Add current slug to full path
|
||||
currentPath = joinSegments(currentPath, slugParts[i])
|
||||
const includeTrailingSlash = !isTagPath || i < 1
|
||||
|
||||
// Format and add current crumb
|
||||
const crumb = formatCrumb(
|
||||
curPathSegment,
|
||||
fileData.slug!,
|
||||
(currentPath + (includeTrailingSlash ? "/" : "")) as SimpleSlug,
|
||||
)
|
||||
crumbs.push(crumb)
|
||||
}
|
||||
|
||||
// Add current file to crumb (can directly use frontmatter title)
|
||||
if (options.showCurrentPage && slugParts.at(-1) !== "index") {
|
||||
crumbs.push({
|
||||
displayName: fileData.frontmatter!.title,
|
||||
path: "",
|
||||
})
|
||||
|
||||
if (!options.showCurrentPage) {
|
||||
crumbs.pop()
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
|
@ -1,62 +0,0 @@
|
||||
import { QuartzComponent, QuartzComponentConstructor, QuartzComponentProps } from "./types"
|
||||
import { classNames } from "../util/lang"
|
||||
// @ts-ignore
|
||||
import script from "./scripts/comments.inline"
|
||||
|
||||
type Options = {
|
||||
provider: "giscus"
|
||||
options: {
|
||||
repo: `${string}/${string}`
|
||||
repoId: string
|
||||
category: string
|
||||
categoryId: string
|
||||
themeUrl?: string
|
||||
lightTheme?: string
|
||||
darkTheme?: string
|
||||
mapping?: "url" | "title" | "og:title" | "specific" | "number" | "pathname"
|
||||
strict?: boolean
|
||||
reactionsEnabled?: boolean
|
||||
inputPosition?: "top" | "bottom"
|
||||
lang?: string
|
||||
}
|
||||
}
|
||||
|
||||
function boolToStringBool(b: boolean): string {
|
||||
return b ? "1" : "0"
|
||||
}
|
||||
|
||||
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")
|
||||
if (disableComment) {
|
||||
return <></>
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
class={classNames(displayClass, "giscus")}
|
||||
data-repo={opts.options.repo}
|
||||
data-repo-id={opts.options.repoId}
|
||||
data-category={opts.options.category}
|
||||
data-category-id={opts.options.categoryId}
|
||||
data-mapping={opts.options.mapping ?? "url"}
|
||||
data-strict={boolToStringBool(opts.options.strict ?? true)}
|
||||
data-reactions-enabled={boolToStringBool(opts.options.reactionsEnabled ?? true)}
|
||||
data-input-position={opts.options.inputPosition ?? "bottom"}
|
||||
data-light-theme={opts.options.lightTheme ?? "light"}
|
||||
data-dark-theme={opts.options.darkTheme ?? "dark"}
|
||||
data-theme-url={
|
||||
opts.options.themeUrl ?? `https://${cfg.baseUrl ?? "example.com"}/static/giscus`
|
||||
}
|
||||
data-lang={opts.options.lang ?? "en"}
|
||||
></div>
|
||||
)
|
||||
}
|
||||
|
||||
Comments.afterDOMLoaded = script
|
||||
|
||||
return Comments
|
||||
}) satisfies QuartzComponentConstructor<Options>
|
@ -1,22 +0,0 @@
|
||||
import { QuartzComponent, QuartzComponentConstructor, QuartzComponentProps } from "./types"
|
||||
|
||||
type ConditionalRenderConfig = {
|
||||
component: QuartzComponent
|
||||
condition: (props: QuartzComponentProps) => boolean
|
||||
}
|
||||
|
||||
export default ((config: ConditionalRenderConfig) => {
|
||||
const ConditionalRender: QuartzComponent = (props: QuartzComponentProps) => {
|
||||
if (config.condition(props)) {
|
||||
return <config.component {...props} />
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
ConditionalRender.afterDOMLoaded = config.component.afterDOMLoaded
|
||||
ConditionalRender.beforeDOMLoaded = config.component.beforeDOMLoaded
|
||||
ConditionalRender.css = config.component.css
|
||||
|
||||
return ConditionalRender
|
||||
}) satisfies QuartzComponentConstructor<ConditionalRenderConfig>
|
@ -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,38 +9,41 @@ import { classNames } from "../util/lang"
|
||||
|
||||
const Darkmode: QuartzComponent = ({ displayClass, cfg }: QuartzComponentProps) => {
|
||||
return (
|
||||
<button class={classNames(displayClass, "darkmode")}>
|
||||
<div class={classNames(displayClass, "darkmode")}>
|
||||
<input class="toggle" id="darkmode-toggle" type="checkbox" tabIndex={-1} />
|
||||
<label id="toggle-label-light" for="darkmode-toggle" tabIndex={-1}>
|
||||
<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"
|
||||
style="enable-background:new 0 0 35 35"
|
||||
xmlSpace="preserve"
|
||||
aria-label={i18n(cfg.locale).components.themeToggle.darkMode}
|
||||
>
|
||||
<title>{i18n(cfg.locale).components.themeToggle.darkMode}</title>
|
||||
<path d="M6,17.5C6,16.672,5.328,16,4.5,16h-3C0.672,16,0,16.672,0,17.5 S0.672,19,1.5,19h3C5.328,19,6,18.328,6,17.5z M7.5,26c-0.414,0-0.789,0.168-1.061,0.439l-2,2C4.168,28.711,4,29.086,4,29.5 C4,30.328,4.671,31,5.5,31c0.414,0,0.789-0.168,1.06-0.44l2-2C8.832,28.289,9,27.914,9,27.5C9,26.672,8.329,26,7.5,26z M17.5,6 C18.329,6,19,5.328,19,4.5v-3C19,0.672,18.329,0,17.5,0S16,0.672,16,1.5v3C16,5.328,16.671,6,17.5,6z M27.5,9 c0.414,0,0.789-0.168,1.06-0.439l2-2C30.832,6.289,31,5.914,31,5.5C31,4.672,30.329,4,29.5,4c-0.414,0-0.789,0.168-1.061,0.44 l-2,2C26.168,6.711,26,7.086,26,7.5C26,8.328,26.671,9,27.5,9z M6.439,8.561C6.711,8.832,7.086,9,7.5,9C8.328,9,9,8.328,9,7.5 c0-0.414-0.168-0.789-0.439-1.061l-2-2C6.289,4.168,5.914,4,5.5,4C4.672,4,4,4.672,4,5.5c0,0.414,0.168,0.789,0.439,1.06 L6.439,8.561z M33.5,16h-3c-0.828,0-1.5,0.672-1.5,1.5s0.672,1.5,1.5,1.5h3c0.828,0,1.5-0.672,1.5-1.5S34.328,16,33.5,16z M28.561,26.439C28.289,26.168,27.914,26,27.5,26c-0.828,0-1.5,0.672-1.5,1.5c0,0.414,0.168,0.789,0.439,1.06l2,2 C28.711,30.832,29.086,31,29.5,31c0.828,0,1.5-0.672,1.5-1.5c0-0.414-0.168-0.789-0.439-1.061L28.561,26.439z M17.5,29 c-0.829,0-1.5,0.672-1.5,1.5v3c0,0.828,0.671,1.5,1.5,1.5s1.5-0.672,1.5-1.5v-3C19,29.672,18.329,29,17.5,29z M17.5,7 C11.71,7,7,11.71,7,17.5S11.71,28,17.5,28S28,23.29,28,17.5S23.29,7,17.5,7z M17.5,25c-4.136,0-7.5-3.364-7.5-7.5 c0-4.136,3.364-7.5,7.5-7.5c4.136,0,7.5,3.364,7.5,7.5C25,21.636,21.636,25,17.5,25z"></path>
|
||||
</svg>
|
||||
</label>
|
||||
<label id="toggle-label-dark" for="darkmode-toggle" tabIndex={-1}>
|
||||
<svg
|
||||
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"
|
||||
style="enable-background:new 0 0 100 100"
|
||||
xmlSpace="preserve"
|
||||
aria-label={i18n(cfg.locale).components.themeToggle.lightMode}
|
||||
>
|
||||
<title>{i18n(cfg.locale).components.themeToggle.lightMode}</title>
|
||||
<path d="M96.76,66.458c-0.853-0.852-2.15-1.064-3.23-0.534c-6.063,2.991-12.858,4.571-19.655,4.571 C62.022,70.495,50.88,65.88,42.5,57.5C29.043,44.043,25.658,23.536,34.076,6.47c0.532-1.08,0.318-2.379-0.534-3.23 c-0.851-0.852-2.15-1.064-3.23-0.534c-4.918,2.427-9.375,5.619-13.246,9.491c-9.447,9.447-14.65,22.008-14.65,35.369 c0,13.36,5.203,25.921,14.65,35.368s22.008,14.65,35.368,14.65c13.361,0,25.921-5.203,35.369-14.65 c3.872-3.871,7.064-8.328,9.491-13.246C97.826,68.608,97.611,67.309,96.76,66.458z"></path>
|
||||
</svg>
|
||||
</button>
|
||||
</label>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
|
@ -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,6 +1,7 @@
|
||||
import { QuartzComponent, QuartzComponentConstructor, QuartzComponentProps } from "./types"
|
||||
|
||||
export default ((component: QuartzComponent) => {
|
||||
export default ((component?: QuartzComponent) => {
|
||||
if (component) {
|
||||
const Component = component
|
||||
const DesktopOnly: QuartzComponent = (props: QuartzComponentProps) => {
|
||||
return <Component displayClass="desktop-only" {...props} />
|
||||
@ -11,4 +12,7 @@ export default ((component: QuartzComponent) => {
|
||||
DesktopOnly.beforeDOMLoaded = component?.beforeDOMLoaded
|
||||
DesktopOnly.css = component?.css
|
||||
return DesktopOnly
|
||||
}) satisfies QuartzComponentConstructor<QuartzComponent>
|
||||
} else {
|
||||
return () => <></>
|
||||
}
|
||||
}) satisfies QuartzComponentConstructor
|
||||
|
@ -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,67 +27,72 @@ 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
|
||||
|
||||
function constructFileTree(allFiles: QuartzPluginData[]) {
|
||||
if (fileTree) {
|
||||
return
|
||||
}
|
||||
|
||||
// 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 = ({
|
||||
cfg,
|
||||
allFiles,
|
||||
displayClass,
|
||||
fileData,
|
||||
}: QuartzComponentProps) => {
|
||||
constructFileTree(allFiles)
|
||||
return (
|
||||
<div
|
||||
class={classNames(displayClass, "explorer")}
|
||||
<div class={classNames(displayClass, "explorer")}>
|
||||
<button
|
||||
type="button"
|
||||
id="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(),
|
||||
})}
|
||||
data-tree={jsonTree}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="explorer-toggle mobile-explorer hide-until-loaded"
|
||||
data-mobile={true}
|
||||
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}
|
||||
>
|
||||
<h2>{opts.title ?? i18n(cfg.locale).components.explorer.title}</h2>
|
||||
<h1>{opts.title ?? i18n(cfg.locale).components.explorer.title}</h1>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="14"
|
||||
@ -116,47 +108,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
|
||||
|
248
quartz/components/ExplorerNode.tsx
Normal file
@ -0,0 +1,248 @@
|
||||
// @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
|
||||
let folderPath = ""
|
||||
if (node.name !== "") {
|
||||
folderPath = joinSegments(fullPath ?? "", node.name)
|
||||
}
|
||||
|
||||
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={resolveRelative(fileData.slug!, folderPath as SimpleSlug)}
|
||||
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>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
@ -1,59 +0,0 @@
|
||||
import { concatenateResources } from "../util/resources"
|
||||
import { classNames } from "../util/lang"
|
||||
import { QuartzComponent, QuartzComponentConstructor, QuartzComponentProps } from "./types"
|
||||
|
||||
type FlexConfig = {
|
||||
components: {
|
||||
Component: QuartzComponent
|
||||
grow?: boolean
|
||||
shrink?: boolean
|
||||
basis?: string
|
||||
order?: number
|
||||
align?: "start" | "end" | "center" | "stretch"
|
||||
justify?: "start" | "end" | "center" | "between" | "around"
|
||||
}[]
|
||||
direction?: "row" | "row-reverse" | "column" | "column-reverse"
|
||||
wrap?: "nowrap" | "wrap" | "wrap-reverse"
|
||||
gap?: string
|
||||
}
|
||||
|
||||
export default ((config: FlexConfig) => {
|
||||
const Flex: QuartzComponent = (props: QuartzComponentProps) => {
|
||||
const direction = config.direction ?? "row"
|
||||
const wrap = config.wrap ?? "nowrap"
|
||||
const gap = config.gap ?? "1rem"
|
||||
|
||||
return (
|
||||
<div
|
||||
class={classNames(props.displayClass, "flex-component")}
|
||||
style={`flex-direction: ${direction}; flex-wrap: ${wrap}; gap: ${gap};`}
|
||||
>
|
||||
{config.components.map((c) => {
|
||||
const grow = c.grow ? 1 : 0
|
||||
const shrink = (c.shrink ?? true) ? 1 : 0
|
||||
const basis = c.basis ?? "auto"
|
||||
const order = c.order ?? 0
|
||||
const align = c.align ?? "center"
|
||||
const justify = c.justify ?? "center"
|
||||
|
||||
return (
|
||||
<div
|
||||
style={`flex-grow: ${grow}; flex-shrink: ${shrink}; flex-basis: ${basis}; order: ${order}; align-self: ${align}; justify-self: ${justify};`}
|
||||
>
|
||||
<c.Component {...props} />
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
Flex.afterDOMLoaded = concatenateResources(
|
||||
...config.components.map((c) => c.Component.afterDOMLoaded),
|
||||
)
|
||||
Flex.beforeDOMLoaded = concatenateResources(
|
||||
...config.components.map((c) => c.Component.beforeDOMLoaded),
|
||||
)
|
||||
Flex.css = concatenateResources(...config.components.map((c) => c.Component.css))
|
||||
return Flex
|
||||
}) satisfies QuartzComponentConstructor<FlexConfig>
|