Change to logseq?
This commit is contained in:
parent
36e3ad586c
commit
6d39da2914
190 changed files with 6294 additions and 18256 deletions
47
.github/workflows/ci.yaml
vendored
47
.github/workflows/ci.yaml
vendored
|
@ -1,47 +0,0 @@
|
|||
name: Build and Test
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches:
|
||||
- v4
|
||||
push:
|
||||
branches:
|
||||
- v4
|
||||
|
||||
jobs:
|
||||
build-and-test:
|
||||
if: ${{ github.repository == 'jackyzha0/quartz' }}
|
||||
strategy:
|
||||
matrix:
|
||||
os: [windows-latest, macos-latest, ubuntu-latest]
|
||||
runs-on: ${{ matrix.os }}
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version: 18
|
||||
|
||||
- name: Cache dependencies
|
||||
uses: actions/cache@v3
|
||||
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: Test
|
||||
run: npm test
|
||||
|
||||
- name: Ensure Quartz builds, check bundle info
|
||||
run: npx quartz build --bundleInfo
|
45
.github/workflows/deploy.yml
vendored
45
.github/workflows/deploy.yml
vendored
|
@ -1,45 +0,0 @@
|
|||
name: Deploy Quartz site to GitHub Pages
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- v4
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
pages: write
|
||||
id-token: write
|
||||
|
||||
concurrency:
|
||||
group: "pages"
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-22.04
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
with:
|
||||
fetch-depth: 0 # Fetch all history for git info
|
||||
- uses: actions/setup-node@v3
|
||||
with:
|
||||
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@v2
|
||||
with:
|
||||
path: public
|
||||
|
||||
deploy:
|
||||
needs: build
|
||||
environment:
|
||||
name: github-pages
|
||||
url: ${{ steps.deployment.outputs.page_url }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Deploy to GitHub Pages
|
||||
id: deployment
|
||||
uses: actions/deploy-pages@v2
|
17
.github/workflows/publish.yml
vendored
Normal file
17
.github/workflows/publish.yml
vendored
Normal file
|
@ -0,0 +1,17 @@
|
|||
on: [push]
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
name: Publish Logseq graph
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: logseq/publish-spa@v0.2.0
|
||||
- name: add a nojekyll file # to make sure asset paths are correctly identified
|
||||
run: touch $GITHUB_WORKSPACE/www/.nojekyll
|
||||
- name: Deploy 🚀
|
||||
uses: JamesIves/github-pages-deploy-action@v4
|
||||
with:
|
||||
folder: www
|
|
@ -1,90 +0,0 @@
|
|||
# Citizen Code of Conduct
|
||||
|
||||
## 1. Purpose
|
||||
|
||||
A primary goal of the Quartz community is to be inclusive to the largest number of contributors, with the most varied and diverse backgrounds possible. As such, we are committed to providing a friendly, safe and welcoming environment for all, regardless of gender, sexual orientation, ability, ethnicity, socioeconomic status, and religion (or lack thereof).
|
||||
|
||||
This code of conduct outlines our expectations for all those who participate in our community, as well as the consequences for unacceptable behavior.
|
||||
|
||||
We invite all those who participate in the Quartz community to help us create safe and positive experiences for everyone.
|
||||
|
||||
## 2. Open [Source/Culture/Tech] Citizenship
|
||||
|
||||
A supplemental goal of this Code of Conduct is to increase open [source/culture/tech] citizenship by encouraging participants to recognize and strengthen the relationships between our actions and their effects on our community.
|
||||
|
||||
Communities mirror the societies in which they exist and positive action is essential to counteract the many forms of inequality and abuses of power that exist in society.
|
||||
|
||||
If you see someone who is making an extra effort to ensure our community is welcoming, friendly, and encourages all participants to contribute to the fullest extent, we want to know.
|
||||
|
||||
## 3. Expected Behavior
|
||||
|
||||
The following behaviors are expected and requested of all community members:
|
||||
|
||||
- Participate in an authentic and active way. In doing so, you contribute to the health and longevity of this community.
|
||||
- Exercise consideration and respect in your speech and actions.
|
||||
- Attempt collaboration before conflict.
|
||||
- Refrain from demeaning, discriminatory, or harassing behavior and speech.
|
||||
- Be mindful of your surroundings and of your fellow participants. Alert community leaders if you notice a dangerous situation, someone in distress, or violations of this Code of Conduct, even if they seem inconsequential.
|
||||
- Remember that community event venues may be shared with members of the public; please be respectful to all patrons of these locations.
|
||||
|
||||
## 4. Unacceptable Behavior
|
||||
|
||||
The following behaviors are considered harassment and are unacceptable within our community:
|
||||
|
||||
- Violence, threats of violence or violent language directed against another person.
|
||||
- Sexist, racist, homophobic, transphobic, ableist or otherwise discriminatory jokes and language.
|
||||
- Posting or displaying sexually explicit or violent material.
|
||||
- Posting or threatening to post other people's personally identifying information ("doxing").
|
||||
- Personal insults, particularly those related to gender, sexual orientation, race, religion, or disability.
|
||||
- Inappropriate photography or recording.
|
||||
- Inappropriate physical contact. You should have someone's consent before touching them.
|
||||
- Unwelcome sexual attention. This includes, sexualized comments or jokes; inappropriate touching, groping, and unwelcomed sexual advances.
|
||||
- Deliberate intimidation, stalking or following (online or in person).
|
||||
- Advocating for, or encouraging, any of the above behavior.
|
||||
- Sustained disruption of community events, including talks and presentations.
|
||||
|
||||
## 5. Weapons Policy
|
||||
|
||||
No weapons will be allowed at Quartz community events, community spaces, or in other spaces covered by the scope of this Code of Conduct. Weapons include but are not limited to guns, explosives (including fireworks), and large knives such as those used for hunting or display, as well as any other item used for the purpose of causing injury or harm to others. Anyone seen in possession of one of these items will be asked to leave immediately, and will only be allowed to return without the weapon. Community members are further expected to comply with all state and local laws on this matter.
|
||||
|
||||
## 6. Consequences of Unacceptable Behavior
|
||||
|
||||
Unacceptable behavior from any community member, including sponsors and those with decision-making authority, will not be tolerated.
|
||||
|
||||
Anyone asked to stop unacceptable behavior is expected to comply immediately.
|
||||
|
||||
If a community member engages in unacceptable behavior, the community organizers may take any action they deem appropriate, up to and including a temporary ban or permanent expulsion from the community without warning (and without refund in the case of a paid event).
|
||||
|
||||
## 7. Reporting Guidelines
|
||||
|
||||
If you are subject to or witness unacceptable behavior, or have any other concerns, please notify a community organizer as soon as possible. j.zhao2k19@gmail.com.
|
||||
|
||||
Additionally, community organizers are available to help community members engage with local law enforcement or to otherwise help those experiencing unacceptable behavior feel safe. In the context of in-person events, organizers will also provide escorts as desired by the person experiencing distress.
|
||||
|
||||
## 8. Addressing Grievances
|
||||
|
||||
If you feel you have been falsely or unfairly accused of violating this Code of Conduct, you should notify @jackyzha0 with a concise description of your grievance. Your grievance will be handled in accordance with our existing governing policies.
|
||||
|
||||
## 9. Scope
|
||||
|
||||
We expect all community participants (contributors, paid or otherwise; sponsors; and other guests) to abide by this Code of Conduct in all community venues--online and in-person--as well as in all one-on-one communications pertaining to community business.
|
||||
|
||||
This code of conduct and its related procedures also applies to unacceptable behavior occurring outside the scope of community activities when such behavior has the potential to adversely affect the safety and well-being of community members.
|
||||
|
||||
## 10. Contact info
|
||||
|
||||
j.zhao2k19@gmail.com
|
||||
|
||||
## 11. License and attribution
|
||||
|
||||
The Citizen Code of Conduct is distributed by [Stumptown Syndicate](http://stumptownsyndicate.org) under a [Creative Commons Attribution-ShareAlike license](http://creativecommons.org/licenses/by-sa/3.0/).
|
||||
|
||||
Portions of text derived from the [Django Code of Conduct](https://www.djangoproject.com/conduct/) and the [Geek Feminism Anti-Harassment Policy](http://geekfeminism.wikia.com/wiki/Conference_anti-harassment/Policy).
|
||||
|
||||
_Revision 2.3. Posted 6 March 2017._
|
||||
|
||||
_Revision 2.2. Posted 4 February 2016._
|
||||
|
||||
_Revision 2.1. Posted 23 June 2014._
|
||||
|
||||
_Revision 2.0, adopted by the [Stumptown Syndicate](http://stumptownsyndicate.org) board on 10 January 2013. Posted 17 March 2013._
|
21
LICENSE.txt
21
LICENSE.txt
|
@ -1,21 +0,0 @@
|
|||
MIT License
|
||||
|
||||
Copyright (c) 2021 jackyzha0
|
||||
|
||||
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.
|
20
README.md
20
README.md
|
@ -1,20 +0,0 @@
|
|||
# Quartz v4
|
||||
|
||||
> “[One] who works with the door open gets all kinds of interruptions, but [they] also occasionally gets clues as to what the world is and what might be important.” — Richard Hamming
|
||||
|
||||
Quartz is a set of tools that helps you publish your [digital garden](https://jzhao.xyz/posts/networked-thought) and notes as a website for free.
|
||||
Quartz v4 features a from-the-ground rewrite focusing on end-user extensibility and ease-of-use.
|
||||
|
||||
**If you are looking for Quartz v3, you can find it on the [`hugo` branch](https://github.com/jackyzha0/quartz/tree/hugo).**
|
||||
|
||||
🔗 Read the documentation and get started: https://quartz.jzhao.xyz/
|
||||
|
||||
[Join the Discord Community](https://discord.gg/cRFFHYye7t)
|
||||
|
||||
## Sponsors
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/sponsors/jackyzha0">
|
||||
<img src="https://cdn.jsdelivr.net/gh/jackyzha0/jackyzha0/sponsorkit/sponsors.svg" />
|
||||
</a>
|
||||
</p>
|
BIN
bun.lockb
BIN
bun.lockb
Binary file not shown.
|
@ -1,52 +0,0 @@
|
|||
---
|
||||
title: Architecture
|
||||
---
|
||||
|
||||
Quartz is a static site generator. How does it work?
|
||||
|
||||
This question is best answered by tracing what happens when a user (you!) runs `npx quartz build` in the command line:
|
||||
|
||||
## On the server
|
||||
|
||||
1. After running `npx quartz build`, npm will look at `package.json` to find the `bin` entry for `quartz` which points at `./quartz/bootstrap-cli.mjs`.
|
||||
2. This file has a [shebang](<https://en.wikipedia.org/wiki/Shebang_(Unix)>) line at the top which tells npm to execute it using Node.
|
||||
3. `bootstrap-cli.mjs` is responsible for a few things:
|
||||
1. Parsing the command-line arguments using [yargs](http://yargs.js.org/).
|
||||
2. Transpiling and bundling the rest of Quartz (which is in Typescript) to regular JavaScript using [esbuild](https://esbuild.github.io/). The `esbuild` configuration here is slightly special as it also handles `.scss` file imports using [esbuild-sass-plugin v2](https://www.npmjs.com/package/esbuild-sass-plugin). Additionally, we bundle 'inline' client-side scripts (any `.inline.ts` file) that components declare using a custom `esbuild` plugin that runs another instance of `esbuild` which bundles for the browser instead of `node`. Modules of both types are imported as plain text.
|
||||
3. Running the local preview server if `--serve` is set. This starts two servers:
|
||||
1. A WebSocket server on port 3001 to handle hot-reload signals. This tracks all inbound connections and sends a 'rebuild' message a server-side change is detected (either content or configuration).
|
||||
2. An HTTP file-server on a user defined port (normally 8080) to serve the actual website files.
|
||||
4. If the `--serve` flag is set, it also starts a file watcher to detect source-code changes (e.g. anything that is `.ts`, `.tsx`, `.scss`, or packager files). On a change, we rebuild the module (step 2 above) using esbuild's [rebuild API](https://esbuild.github.io/api/#rebuild) which drastically reduces the build times.
|
||||
5. After transpiling the main Quartz build module (`quartz/build.ts`), we write it to a cache file `.quartz-cache/transpiled-build.mjs` and then dynamically import this using `await import(cacheFile)`. However, we need to be pretty smart about how to bust Node's [import cache](https://github.com/nodejs/modules/issues/307) so we add a random query string to fake Node into thinking it's a new module. This does, however, cause memory leaks so we just hope that the user doesn't hot-reload their configuration too many times in a single session :)) (it leaks about ~350kB memory on each reload). After importing the module, we then invoke it, passing in the command line arguments we parsed earlier along with a callback function to signal the client to refresh.
|
||||
4. In `build.ts`, we start by installing source map support manually to account for the query string cache busting hack we introduced earlier. Then, we start processing content:
|
||||
1. Clean the output directory.
|
||||
2. Recursively glob all files in the `content` folder, respecting the `.gitignore`.
|
||||
3. Parse the Markdown files.
|
||||
1. Quartz detects the number of threads available and chooses to spawn worker threads if there are >128 pieces of content to parse (rough heuristic). If it needs to spawn workers, it will invoke esbuild again to transpile the worker script `quartz/worker.ts`. Then, a work-stealing [workerpool](https://www.npmjs.com/package/workerpool) is then created and batches of 128 files are assigned to workers.
|
||||
2. Each worker (or just the main thread if there is no concurrency) creates a [unified](https://github.com/unifiedjs/unified) parser based off of the plugins defined in the [[configuration]].
|
||||
3. Parsing has three steps:
|
||||
1. Read the file into a [vfile](https://github.com/vfile/vfile).
|
||||
2. Applied plugin-defined text transformations over the content.
|
||||
3. Slugify the file path and store it in the data for the file. See the page on [[paths]] for more details about how path logic works in Quartz (spoiler: its complicated).
|
||||
4. Markdown parsing using [remark-parse](https://www.npmjs.com/package/remark-parse) (text to [mdast](https://github.com/syntax-tree/mdast)).
|
||||
5. Apply plugin-defined Markdown-to-Markdown transformations.
|
||||
6. Convert Markdown into HTML using [remark-rehype](https://github.com/remarkjs/remark-rehype) ([mdast](https://github.com/syntax-tree/mdast) to [hast](https://github.com/syntax-tree/hast)).
|
||||
7. Apply plugin-defined HTML-to-HTML transformations.
|
||||
4. Filter out unwanted content using plugins.
|
||||
5. Emit files using plugins.
|
||||
1. Gather all the static resources (e.g. external CSS, JS modules, etc.) each emitter plugin declares.
|
||||
2. Emitters that emit HTML files do a bit of extra work here as they need to transform the [hast](https://github.com/syntax-tree/hast) produced in the parse step to JSX. This is done using [hast-util-to-jsx-runtime](https://github.com/syntax-tree/hast-util-to-jsx-runtime) with the [Preact](https://preactjs.com/) runtime. Finally, the JSX is rendered to HTML using [preact-render-to-string](https://github.com/preactjs/preact-render-to-string) which statically renders the JSX to HTML (i.e. doesn't care about `useState`, `useEffect`, or any other React/Preact interactive bits). Here, we also do a bunch of fun stuff like assemble the page [[layout]] from `quartz.layout.ts`, assemble all the inline scripts that actually get shipped to the client, and all the transpiled styles. The bulk of this logic can be found in `quartz/components/renderPage.tsx`. Other fun things of note:
|
||||
1. CSS is minified and transformed using [Lightning CSS](https://github.com/parcel-bundler/lightningcss) to add vendor prefixes and do syntax lowering.
|
||||
2. Scripts are split into `beforeDOMLoaded` and `afterDOMLoaded` and are inserted in the `<head>` and `<body>` respectively.
|
||||
3. Finally, each emitter plugin is responsible for emitting and writing it's own emitted files to disk.
|
||||
6. If the `--serve` flag was detected, we also set up another file watcher to detect content changes (only `.md` files). We keep a content map that tracks the parsed AST and plugin data for each slug and update this on file changes. Newly added or modified paths are rebuilt and added to the content map. Then, all the filters and emitters are run over the resulting content map. This file watcher is debounced with a threshold of 250ms. On success, we send a client refresh signal using the passed in callback function.
|
||||
|
||||
## On the client
|
||||
|
||||
1. The browser opens a Quartz page and loads the HTML. The `<head>` also links to page styles (emitted to `public/index.css`) and page-critical JS (emitted to `public/prescript.js`)
|
||||
2. Then, once the body is loaded, the browser loads the non-critical JS (emitted to `public/postscript.js`)
|
||||
3. Once the page is done loading, the page will then dispatch a custom synthetic browser event `"nav"`. This is used so client-side scripts declared by components can 'setup' anything that requires access to the page DOM.
|
||||
1. If the [[SPA Routing|enableSPA option]] is enabled in the [[configuration]], this `"nav"` event is also fired on any client-navigation to allow for components to unregister and reregister any event handlers and state.
|
||||
2. If it's not, we wire up the `"nav"` event to just be fired a single time after page load to allow for consistency across how state is setup across both SPA and non-SPA contexts.
|
||||
|
||||
The architecture and design of the plugin system was intentionally left pretty vague here as this is described in much more depth in the guide on [[making plugins|making your own plugin]].
|
|
@ -1,233 +0,0 @@
|
|||
---
|
||||
title: Creating your own Quartz components
|
||||
---
|
||||
|
||||
> [!warning]
|
||||
> This guide assumes you have experience writing JavaScript and are familiar with TypeScript.
|
||||
|
||||
Normally on the web, we write layout code using HTML which looks something like the following:
|
||||
|
||||
```html
|
||||
<article>
|
||||
<h1>An article header</h1>
|
||||
<p>Some content</p>
|
||||
</article>
|
||||
```
|
||||
|
||||
This piece of HTML represents an article with a leading header that says "An article header" and a paragraph that contains the text "Some content". This is combined with CSS to style the page and JavaScript to add interactivity.
|
||||
|
||||
However, HTML doesn't let you create reusable templates. If you wanted to create a new page, you would need to copy and paste the above snippet and edit the header and content yourself. This isn't great if we have a lot of content on our site that shares a lot of similar layout. The smart people who created React also had similar complaints and invented the concept of Components -- JavaScript functions that return JSX -- to solve the code duplication problem.
|
||||
|
||||
In effect, components allow you to write a JavaScript function that takes some data and produces HTML as an output. **While Quartz doesn't use React, it uses the same component concept to allow you to easily express layout templates in your Quartz site.**
|
||||
|
||||
## An Example Component
|
||||
|
||||
### Constructor
|
||||
|
||||
Component files are written in `.tsx` files that live in the `quartz/components` folder. These are re-exported in `quartz/components/index.ts` so you can use them in layouts and other components more easily.
|
||||
|
||||
Each component file should have a default export that satisfies the `QuartzComponentConstructor` function signature. It's a function that takes in a single optional parameter `opts` and returns a Quartz Component. The type of the parameters `opts` is defined by the interface `Options` which you as the component creator also decide.
|
||||
|
||||
In your component, you can use the values from the configuration option to change the rendering behaviour inside of your component. For example, the component in the code snippet below will not render if the `favouriteNumber` option is below 0.
|
||||
|
||||
```tsx {11-17}
|
||||
interface Options {
|
||||
favouriteNumber: number
|
||||
}
|
||||
|
||||
const defaultOptions: Options = {
|
||||
favouriteNumber: 42,
|
||||
}
|
||||
|
||||
export default ((userOpts?: Options) => {
|
||||
const opts = { ...userOpts, ...defaultOpts }
|
||||
function YourComponent(props: QuartzComponentProps) {
|
||||
if (opts.favouriteNumber < 0) {
|
||||
return null
|
||||
}
|
||||
|
||||
return <p>My favourite number is {opts.favouriteNumber}</p>
|
||||
}
|
||||
|
||||
return YourComponent
|
||||
}) satisfies QuartzComponentConstructor
|
||||
```
|
||||
|
||||
### Props
|
||||
|
||||
The Quartz component itself (lines 11-17 highlighted above) looks like a React component. It takes in properties (sometimes called [props](https://react.dev/learn/passing-props-to-a-component)) and returns JSX.
|
||||
|
||||
All Quartz components accept the same set of props:
|
||||
|
||||
```tsx title="quartz/components/types.ts"
|
||||
// simplified for sake of demonstration
|
||||
export type QuartzComponentProps = {
|
||||
fileData: QuartzPluginData
|
||||
cfg: GlobalConfiguration
|
||||
tree: Node<QuartzPluginData>
|
||||
allFiles: QuartzPluginData[]
|
||||
displayClass?: "mobile-only" | "desktop-only"
|
||||
}
|
||||
```
|
||||
|
||||
- `fileData`: Any metadata [[making plugins|plugins]] may have added to the current page.
|
||||
- `fileData.slug`: slug of the current page.
|
||||
- `fileData.frontmatter`: any frontmatter parsed.
|
||||
- `cfg`: The `configuration` field in `quartz.config.ts`.
|
||||
- `tree`: the resulting [HTML AST](https://github.com/syntax-tree/hast) after processing and transforming the file. This is useful if you'd like to render the content using [hast-util-to-jsx-runtime](https://github.com/syntax-tree/hast-util-to-jsx-runtime) (you can find an example of this in `quartz/components/pages/Content.tsx`).
|
||||
- `allFiles`: Metadata for all files that have been parsed. Useful for doing page listings or figuring out the overall site structure.
|
||||
- `displayClass`: a utility class that indicates a preference from the user about how to render it in a mobile or desktop setting. Helpful if you want to conditionally hide a component on mobile or desktop.
|
||||
|
||||
### Styling
|
||||
|
||||
Quartz components can also define a `.css` property on the actual function component which will get picked up by Quartz. This is expected to be a CSS string which can either be inlined or imported from a `.scss` file.
|
||||
|
||||
Note that inlined styles **must** be plain vanilla CSS:
|
||||
|
||||
```tsx {6-10} title="quartz/components/YourComponent.tsx"
|
||||
export default (() => {
|
||||
function YourComponent() {
|
||||
return <p class="red-text">Example Component</p>
|
||||
}
|
||||
|
||||
YourComponent.css = `
|
||||
p.red-text {
|
||||
color: red;
|
||||
}
|
||||
`
|
||||
|
||||
return YourComponent
|
||||
}) satisfies QuartzComponentConstructor
|
||||
```
|
||||
|
||||
Imported styles, however, can be from SCSS files:
|
||||
|
||||
```tsx {1-2,9} title="quartz/components/YourComponent.tsx"
|
||||
// assuming your stylesheet is in quartz/components/styles/YourComponent.scss
|
||||
import styles from "./styles/YourComponent.scss"
|
||||
|
||||
export default (() => {
|
||||
function YourComponent() {
|
||||
return <p>Example Component</p>
|
||||
}
|
||||
|
||||
YourComponent.css = styles
|
||||
return YourComponent
|
||||
}) satisfies QuartzComponentConstructor
|
||||
```
|
||||
|
||||
> [!warning]
|
||||
> Quartz does not use CSS modules so any styles you declare here apply _globally_. If you only want it to apply to your component, make sure you use specific class names and selectors.
|
||||
|
||||
### Scripts and Interactivity
|
||||
|
||||
What about interactivity? Suppose you want to add an-click handler for example. Like the `.css` property on the component, you can also declare `.beforeDOMLoaded` and `.afterDOMLoaded` properties that are strings that contain the script.
|
||||
|
||||
```tsx title="quartz/components/YourComponent.tsx"
|
||||
export default (() => {
|
||||
function YourComponent() {
|
||||
return <button id="btn">Click me</button>
|
||||
}
|
||||
|
||||
YourComponent.beforeDOM = `
|
||||
console.log("hello from before the page loads!")
|
||||
`
|
||||
|
||||
YourComponent.afterDOM = `
|
||||
document.getElementById('btn').onclick = () => {
|
||||
alert('button clicked!')
|
||||
}
|
||||
`
|
||||
return YourComponent
|
||||
}) satisfies QuartzComponentConstructor
|
||||
```
|
||||
|
||||
> [!hint]
|
||||
> For those coming from React, Quartz components are different from React components in that it only uses JSX for templating and layout. Hooks like `useEffect`, `useState`, etc. are not rendered and other properties that accept functions like `onClick` handlers will not work. Instead, do it using a regular JS script that modifies the DOM element directly.
|
||||
|
||||
As the names suggest, the `.beforeDOMLoaded` scripts are executed _before_ the page is done loading so it doesn't have access to any elements on the page. This is mostly used to prefetch any critical data.
|
||||
|
||||
The `.afterDOMLoaded` script executes once the page has been completely loaded. This is a good place to setup anything that should last for the duration of a site visit (e.g. getting something saved from local storage).
|
||||
|
||||
If you need to create an `afterDOMLoaded` script that depends on _page specific_ elements that may change when navigating to a new page, you can listen for the `"nav"` event that gets fired whenever a page loads (which may happen on navigation if [[SPA Routing]] is enabled).
|
||||
|
||||
```ts
|
||||
document.addEventListener("nav", () => {
|
||||
// do page specific logic here
|
||||
// e.g. attach event listeners
|
||||
const toggleSwitch = document.querySelector("#switch") as HTMLInputElement
|
||||
toggleSwitch.removeEventListener("change", switchTheme)
|
||||
toggleSwitch.addEventListener("change", switchTheme)
|
||||
})
|
||||
```
|
||||
|
||||
It is best practice to also unmount any existing event handlers to prevent memory leaks.
|
||||
|
||||
#### Importing Code
|
||||
|
||||
Of course, it isn't always practical (nor desired!) to write your code as a string literal in the component.
|
||||
|
||||
Quartz supports importing component code through `.inline.ts` files.
|
||||
|
||||
```tsx title="quartz/components/YourComponent.tsx"
|
||||
// @ts-ignore: typescript doesn't know about our inline bundling system
|
||||
// so we need to silence the error
|
||||
import script from "./scripts/graph.inline"
|
||||
|
||||
export default (() => {
|
||||
function YourComponent() {
|
||||
return <button id="btn">Click me</button>
|
||||
}
|
||||
|
||||
YourComponent.afterDOM = script
|
||||
return YourComponent
|
||||
}) satisfies QuartzComponentConstructor
|
||||
```
|
||||
|
||||
```ts title="quartz/components/scripts/graph.inline.ts"
|
||||
// any imports here are bundled for the browser
|
||||
import * as d3 from "d3"
|
||||
|
||||
document.getElementById("btn").onclick = () => {
|
||||
alert("button clicked!")
|
||||
}
|
||||
```
|
||||
|
||||
Additionally, like what is shown in the example above, you can import packages in `.inline.ts` files. This will be bundled by Quartz and included in the actual script.
|
||||
|
||||
### Using a Component
|
||||
|
||||
After creating your custom component, re-export it in `quartz/components/index.ts`:
|
||||
|
||||
```ts title="quartz/components/index.ts" {4,10}
|
||||
import ArticleTitle from "./ArticleTitle"
|
||||
import Content from "./pages/Content"
|
||||
import Darkmode from "./Darkmode"
|
||||
import YourComponent from "./YourComponent"
|
||||
|
||||
export { ArticleTitle, Content, Darkmode, YourComponent }
|
||||
```
|
||||
|
||||
Then, you can use it like any other component in `quartz.layout.ts` via `Component.YourComponent()`. See the [[configuration#Layout|layout]] section for more details.
|
||||
|
||||
As Quartz components are just functions that return React components, you can compositionally use them in other Quartz components.
|
||||
|
||||
```tsx title="quartz/components/AnotherComponent.tsx"
|
||||
import YourComponent from "./YourComponent"
|
||||
|
||||
export default (() => {
|
||||
function AnotherComponent(props: QuartzComponentProps) {
|
||||
return (
|
||||
<div>
|
||||
<p>It's nested!</p>
|
||||
<YourComponent {...props} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return AnotherComponent
|
||||
}) satisfies QuartzComponentConstructor
|
||||
```
|
||||
|
||||
> [!hint]
|
||||
> Look in `quartz/components` for more examples of components in Quartz as reference for your own components!
|
|
@ -1,302 +0,0 @@
|
|||
---
|
||||
title: Making your own plugins
|
||||
---
|
||||
|
||||
> [!warning]
|
||||
> This part of the documentation will assume you have working knowledge in TypeScript and will include code snippets that describe the interface of what Quartz plugins should look like.
|
||||
|
||||
Quartz's plugins are a series of transformations over content. This is illustrated in the diagram of the processing pipeline below:
|
||||
|
||||
![[quartz transform pipeline.png]]
|
||||
|
||||
All plugins are defined as a function that takes in a single parameter for options `type OptionType = object | undefined` and return an object that corresponds to the type of plugin it is.
|
||||
|
||||
```ts
|
||||
type OptionType = object | undefined
|
||||
type QuartzPlugin<Options extends OptionType = undefined> = (opts?: Options) => QuartzPluginInstance
|
||||
type QuartzPluginInstance =
|
||||
| QuartzTransformerPluginInstance
|
||||
| QuartzFilterPluginInstance
|
||||
| QuartzEmitterPluginInstance
|
||||
```
|
||||
|
||||
The following sections will go into detail for what methods can be implemented for each plugin type. Before we do that, let's clarify a few more ambiguous types:
|
||||
|
||||
- `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 `ServerSlug` is)
|
||||
- `StaticResources` is defined in `quartz/resources.tsx`. It consists of
|
||||
- `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.
|
||||
|
||||
## Transformers
|
||||
|
||||
Transformers **map** over content, taking a Markdown file and outputting modified content or adding metadata to the file itself.
|
||||
|
||||
```ts
|
||||
export type QuartzTransformerPluginInstance = {
|
||||
name: string
|
||||
textTransform?: (ctx: BuildCtx, src: string | Buffer) => string | Buffer
|
||||
markdownPlugins?: (ctx: BuildCtx) => PluggableList
|
||||
htmlPlugins?: (ctx: BuildCtx) => PluggableList
|
||||
externalResources?: (ctx: BuildCtx) => Partial<StaticResources>
|
||||
}
|
||||
```
|
||||
|
||||
All transformer plugins must define at least a `name` field to register the plugin and a few optional functions that allow you to hook into various parts of transforming a single Markdown file.
|
||||
|
||||
- `textTransform` performs a text-to-text transformation _before_ a file is parsed into the [Markdown AST](https://github.com/syntax-tree/mdast).
|
||||
- `markdownPlugins` defines a list of [remark plugins](https://github.com/remarkjs/remark/blob/main/doc/plugins.md). `remark` is a tool that transforms Markdown to Markdown in a structured way.
|
||||
- `htmlPlugins` defines a list of [rehype plugins](https://github.com/rehypejs/rehype/blob/main/doc/plugins.md). Similar to how `remark` works, `rehype` is a tool that transforms HTML to HTML in a structured way.
|
||||
- `externalResources` defines any external resources the plugin may need to load on the client-side for it to work properly.
|
||||
|
||||
Normally for both `remark` and `rehype`, you can find existing plugins that you can use to . If you'd like to create your own `remark` or `rehype` plugin, checkout the [guide to creating a plugin](https://unifiedjs.com/learn/guide/create-a-plugin/) using `unified` (the underlying AST parser and transformer library).
|
||||
|
||||
A good example of a transformer plugin that borrows from the `remark` and `rehype` ecosystems is the [[Latex]] plugin:
|
||||
|
||||
```ts title="quartz/plugins/transformers/latex.ts"
|
||||
import remarkMath from "remark-math"
|
||||
import rehypeKatex from "rehype-katex"
|
||||
import rehypeMathjax from "rehype-mathjax/svg.js"
|
||||
import { QuartzTransformerPlugin } from "../types"
|
||||
|
||||
interface Options {
|
||||
renderEngine: "katex" | "mathjax"
|
||||
}
|
||||
|
||||
export const Latex: QuartzTransformerPlugin<Options> = (opts?: Options) => {
|
||||
const engine = opts?.renderEngine ?? "katex"
|
||||
return {
|
||||
name: "Latex",
|
||||
markdownPlugins() {
|
||||
return [remarkMath]
|
||||
},
|
||||
htmlPlugins() {
|
||||
if (engine === "katex") {
|
||||
// if you need to pass options into a plugin, you
|
||||
// can use a tuple of [plugin, options]
|
||||
return [[rehypeKatex, { output: "html" }]]
|
||||
} else {
|
||||
return [rehypeMathjax]
|
||||
}
|
||||
},
|
||||
externalResources() {
|
||||
if (engine === "katex") {
|
||||
return {
|
||||
css: ["https://cdn.jsdelivr.net/npm/katex@0.16.0/dist/katex.min.css"],
|
||||
js: [
|
||||
{
|
||||
src: "https://cdn.jsdelivr.net/npm/katex@0.16.7/dist/contrib/copy-tex.min.js",
|
||||
loadTime: "afterDOMReady",
|
||||
contentType: "external",
|
||||
},
|
||||
],
|
||||
}
|
||||
} else {
|
||||
return {}
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Another common thing that transformer plugins will do is parse a file and add extra data for that file:
|
||||
|
||||
```ts
|
||||
export const AddWordCount: QuartzTransformerPlugin = () => {
|
||||
return {
|
||||
name: "AddWordCount",
|
||||
markdownPlugins() {
|
||||
return [
|
||||
() => {
|
||||
return (tree, file) => {
|
||||
// tree is an `mdast` root element
|
||||
// file is a `vfile`
|
||||
const text = file.value
|
||||
const words = text.split(" ").length
|
||||
file.data.wordcount = words
|
||||
}
|
||||
},
|
||||
]
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// tell typescript about our custom data fields we are adding
|
||||
// other plugins will then also be aware of this data field
|
||||
declare module "vfile" {
|
||||
interface DataMap {
|
||||
wordcount: number
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Finally, you can also perform transformations over Markdown or HTML ASTs using the `visit` function from the `unist-util-visit` package or the `findAndReplace` function from the `mdast-util-find-and-replace` package.
|
||||
|
||||
```ts
|
||||
export const TextTransforms: QuartzTransformerPlugin = () => {
|
||||
return {
|
||||
name: "TextTransforms",
|
||||
markdownPlugins() {
|
||||
return [() => {
|
||||
return (tree, file) => {
|
||||
// replace _text_ with the italics version
|
||||
findAndReplace(tree, /_(.+)_/, (_value: string, ...capture: string[]) => {
|
||||
// inner is the text inside of the () of the regex
|
||||
const [inner] = capture
|
||||
// return an mdast node
|
||||
// https://github.com/syntax-tree/mdast
|
||||
return {
|
||||
type: "emphasis",
|
||||
children: [{ type: 'text', value: inner }]
|
||||
}
|
||||
})
|
||||
|
||||
// remove all links (replace with just the link content)
|
||||
// match by 'type' field on an mdast node
|
||||
// https://github.com/syntax-tree/mdast#link in this example
|
||||
visit(tree, "link", (link: Link) => {
|
||||
return {
|
||||
type: "paragraph"
|
||||
children: [{ type: 'text', value: link.title }]
|
||||
}
|
||||
})
|
||||
}
|
||||
}]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
All transformer plugins can be found under `quartz/plugins/transformers`. If you decide to write your own transformer plugin, don't forget to re-export it under `quartz/plugins/transformers/index.ts`
|
||||
|
||||
A parting word: transformer plugins are quite complex so don't worry if you don't get them right away. Take a look at the built in transformers and see how they operate over content to get a better sense for how to accomplish what you are trying to do.
|
||||
|
||||
## Filters
|
||||
|
||||
Filters **filter** content, taking the output of all the transformers and determining what files to actually keep and what to discard.
|
||||
|
||||
```ts
|
||||
export type QuartzFilterPlugin<Options extends OptionType = undefined> = (
|
||||
opts?: Options,
|
||||
) => QuartzFilterPluginInstance
|
||||
|
||||
export type QuartzFilterPluginInstance = {
|
||||
name: string
|
||||
shouldPublish(ctx: BuildCtx, content: ProcessedContent): boolean
|
||||
}
|
||||
```
|
||||
|
||||
A filter plugin must define a `name` field and a `shouldPublish` function that takes in a piece of content that has been processed by all the transformers and returns a `true` or `false` depending on whether it should be passed to the emitter plugins or not.
|
||||
|
||||
For example, here is the built-in plugin for removing drafts:
|
||||
|
||||
```ts title="quartz/plugins/filters/draft.ts"
|
||||
import { QuartzFilterPlugin } from "../types"
|
||||
|
||||
export const RemoveDrafts: QuartzFilterPlugin<{}> = () => ({
|
||||
name: "RemoveDrafts",
|
||||
shouldPublish(_ctx, [_tree, vfile]) {
|
||||
// uses frontmatter parsed from transformers
|
||||
const draftFlag: boolean = vfile.data?.frontmatter?.draft ?? false
|
||||
return !draftFlag
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
## Emitters
|
||||
|
||||
Emitters **reduce** over content, taking in a list of all the transformed and filtered content and creating output files.
|
||||
|
||||
```ts
|
||||
export type QuartzEmitterPlugin<Options extends OptionType = undefined> = (
|
||||
opts?: Options,
|
||||
) => QuartzEmitterPluginInstance
|
||||
|
||||
export type QuartzEmitterPluginInstance = {
|
||||
name: string
|
||||
emit(
|
||||
ctx: BuildCtx,
|
||||
content: ProcessedContent[],
|
||||
resources: StaticResources,
|
||||
emitCallback: EmitCallback,
|
||||
): Promise<FilePath[]>
|
||||
getQuartzComponents(ctx: BuildCtx): QuartzComponent[]
|
||||
}
|
||||
```
|
||||
|
||||
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 `emitCallback` if you are creating files that contain text. The `emitCallback` function is the 4th argument of the emit function. It's interface looks something like this:
|
||||
|
||||
```ts
|
||||
export type EmitCallback = (data: {
|
||||
// the name of the file to emit (not including the file extension)
|
||||
slug: ServerSlug
|
||||
// the file extension
|
||||
ext: `.${string}` | ""
|
||||
// the file content to add
|
||||
content: string
|
||||
}) => Promise<FilePath>
|
||||
```
|
||||
|
||||
This is a thin wrapper around writing to the appropriate output folder and ensuring that intermediate directories exist. If you choose to use the native Node `fs` APIs, ensure you emit to the `argv.output` folder as well.
|
||||
|
||||
If you are creating an emitter plugin that needs to render components, there are three more things to be aware of:
|
||||
|
||||
- Your component should use `getQuartzComponents` to declare a list of `QuartzComponents` that it uses to construct the page. See the page on [[creating components]] for more information.
|
||||
- You can use the `renderPage` function defined in `quartz/components/renderPage.tsx` to render Quartz components into HTML.
|
||||
- If you need to render an HTML AST to JSX, you can use the `toJsxRuntime` function from `hast-util-to-jsx-runtime` library. An example of this can be found in `quartz/components/pages/Content.tsx`.
|
||||
|
||||
For example, the following is a simplified version of the content page plugin that renders every single page.
|
||||
|
||||
```tsx title="quartz/plugins/emitters/contentPage.tsx"
|
||||
export const ContentPage: QuartzEmitterPlugin = () => {
|
||||
// construct the layout
|
||||
const layout: FullPageLayout = {
|
||||
...sharedPageComponents,
|
||||
...defaultContentPageLayout,
|
||||
pageBody: Content(),
|
||||
}
|
||||
const { head, header, beforeBody, pageBody, left, right, footer } = layout
|
||||
return {
|
||||
name: "ContentPage",
|
||||
getQuartzComponents() {
|
||||
return [head, ...header, ...beforeBody, pageBody, ...left, ...right, footer]
|
||||
},
|
||||
async emit(ctx, content, resources, emit): Promise<FilePath[]> {
|
||||
const cfg = ctx.cfg.configuration
|
||||
const fps: FilePath[] = []
|
||||
const allFiles = content.map((c) => c[1].data)
|
||||
for (const [tree, file] of content) {
|
||||
const slug = canonicalizeServer(file.data.slug!)
|
||||
const externalResources = pageResources(slug, resources)
|
||||
const componentData: QuartzComponentProps = {
|
||||
fileData: file.data,
|
||||
externalResources,
|
||||
cfg,
|
||||
children: [],
|
||||
tree,
|
||||
allFiles,
|
||||
}
|
||||
|
||||
const content = renderPage(slug, componentData, opts, externalResources)
|
||||
const fp = await emit({
|
||||
content,
|
||||
slug: file.data.slug!,
|
||||
ext: ".html",
|
||||
})
|
||||
|
||||
fps.push(fp)
|
||||
}
|
||||
return fps
|
||||
},
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Note that it takes in a `FullPageLayout` as the options. It's made by combining a `SharedLayout` and a `PageLayout` both of which are provided through the `quartz.layout.ts` file.
|
||||
|
||||
> [!hint]
|
||||
> Look in `quartz/plugins` for more examples of plugins in Quartz as reference for your own plugins!
|
|
@ -1,51 +0,0 @@
|
|||
---
|
||||
title: Paths in Quartz
|
||||
---
|
||||
|
||||
Paths are pretty complex to reason about because, especially for a static site generator, they can come from so many places.
|
||||
|
||||
A full file path to a piece of content? Also a path. What about a slug for a piece of content? Yet another path.
|
||||
|
||||
It would be silly to type these all as `string` and call it a day as it's pretty common to accidentally mistake one type of path for another. Unfortunately, TypeScript does not have [nominal types](https://en.wikipedia.org/wiki/Nominal_type_system) for type aliases meaning even if you made custom types of a server-side slug or a client-slug slug, you can still accidentally assign one to another and TypeScript wouldn't catch it.
|
||||
|
||||
Luckily, we can mimic nominal typing using [brands](https://www.typescriptlang.org/play#example/nominal-typing).
|
||||
|
||||
```typescript
|
||||
// instead of
|
||||
type FullSlug = string
|
||||
|
||||
// we do
|
||||
type FullSlug = string & { __brand: "full" }
|
||||
|
||||
// that way, the following will fail typechecking
|
||||
const slug: FullSlug = "some random string"
|
||||
```
|
||||
|
||||
While this prevents most typing mistakes _within_ our nominal typing system (e.g. mistaking a server slug for a client slug), it doesn't prevent us from _accidentally_ mistaking a string for a client slug when we forcibly cast it.
|
||||
|
||||
Thus, we still need to be careful when casting from a string to one of these nominal types in the 'entrypoints', illustrated with hexagon shapes in the diagram below.
|
||||
|
||||
The following diagram draws the relationships between all the path sources, nominal path types, and what functions in `quartz/path.ts` convert between them.
|
||||
|
||||
```mermaid
|
||||
graph LR
|
||||
Browser{{Browser}} --> Window{{Body}} & LinkElement{{Link Element}}
|
||||
Window --"getFullSlug()"--> FullSlug[Full Slug]
|
||||
LinkElement --".href"--> Relative[Relative URL]
|
||||
FullSlug --"simplifySlug()" --> SimpleSlug[Simple Slug]
|
||||
SimpleSlug --"pathToRoot()"--> Relative
|
||||
SimpleSlug --"resolveRelative()" --> Relative
|
||||
MD{{Markdown File}} --> FilePath{{File Path}} & Links[Markdown links]
|
||||
Links --"transformLink()"--> Relative
|
||||
FilePath --"slugifyFilePath()"--> FullSlug[Full Slug]
|
||||
style FullSlug stroke-width:4px
|
||||
```
|
||||
|
||||
Here are the main types of slugs with a rough description of each type of path:
|
||||
|
||||
- `FilePath`: a real file path to a file on disk. Cannot be relative and must have a file extension.
|
||||
- `FullSlug`: cannot be relative and may not have leading or trailing slashes. It can have `index` as it's last segment. Use this wherever possible is it's the most 'general' interpretation of a slug.
|
||||
- `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/path.test.ts`.
|
|
@ -1,48 +0,0 @@
|
|||
---
|
||||
title: Authoring Content
|
||||
---
|
||||
|
||||
All of the content in your Quartz should go in the `/content` folder. The content for the home page of your Quartz lives in `content/index.md`. If you've [[index#🪴 Get Started|setup Quartz]] already, this folder should already be initailized. Any Markdown in this folder will get processed by Quartz.
|
||||
|
||||
It is recommended that you use [Obsidian](https://obsidian.md/) as a way to edit and maintain your Quartz. It comes with a nice editor and graphical interface to preview, edit, and link your local files and attachments.
|
||||
|
||||
Got everything setup? Let's [[build]] and preview your Quartz locally!
|
||||
|
||||
## Syntax
|
||||
|
||||
As Quartz uses Markdown files as the main way of writing content, it fully supports Markdown syntax. By default, Quartz also ships with a few syntax extensions like [Github Flavored Markdown](https://docs.github.com/en/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax) (footnotes, strikethrough, tables, tasklists) and [Obsidian Flavored Markdown](https://help.obsidian.md/Editing+and+formatting/Obsidian+Flavored+Markdown) ([[callouts]], [[wikilinks]]).
|
||||
|
||||
Additionally, Quartz also allows you to specify additional metadata in your notes called **frontmatter**.
|
||||
|
||||
```md title="content/note.md"
|
||||
---
|
||||
title: Example Title
|
||||
draft: false
|
||||
tags:
|
||||
- example-tag
|
||||
---
|
||||
|
||||
The rest of your content lives here. You can use **Markdown** here :)
|
||||
```
|
||||
|
||||
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.
|
||||
- `aliases`: Other names for this note. This is a list of strings.
|
||||
- `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.
|
||||
|
||||
## Syncing your Content
|
||||
|
||||
When your Quartz is at a point you're happy with, you can save your changes to GitHub by doing `npx quartz sync`.
|
||||
|
||||
> [!hint] Flags and options
|
||||
> For full help options, you can run `npx quartz sync --help`.
|
||||
>
|
||||
> Most of these have sensible defaults but you can override them if you have a custom setup:
|
||||
>
|
||||
> - `-d` or `--directory`: the content folder. This is normally just `content`
|
||||
> - `-v` or `--verbose`: print out extra logging information
|
||||
> - `--commit` or `--no-commit`: whether to make a `git` commit for your changes
|
||||
> - `--push` or `--no-push`: whether to push updates to your GitHub fork of Quartz
|
||||
> - `--pull` or `--no-pull`: whether to try and pull in any updates from your GitHub fork (i.e. from other devices) before pushing
|
|
@ -1,23 +0,0 @@
|
|||
---
|
||||
title: "Building your Quartz"
|
||||
---
|
||||
|
||||
Once you've [[index#🪴 Get Started|initialized]] Quartz, let's see what it looks like locally:
|
||||
|
||||
```bash
|
||||
npx quartz build --serve
|
||||
```
|
||||
|
||||
This will start a local web server to run your Quartz on your computer. Open a web browser and visit `http://localhost:8080/` to view it.
|
||||
|
||||
> [!hint] Flags and options
|
||||
> For full help options, you can run `npx quartz build --help`.
|
||||
>
|
||||
> Most of these have sensible defaults but you can override them if you have a custom setup:
|
||||
>
|
||||
> - `-d` or `--directory`: the content folder. This is normally just `content`
|
||||
> - `-v` or `--verbose`: print out extra logging information
|
||||
> - `-o` or `--output`: the output folder. This is normally just `public`
|
||||
> - `--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
|
|
@ -1,82 +0,0 @@
|
|||
---
|
||||
title: Configuration
|
||||
---
|
||||
|
||||
Quartz is meant to be extremely configurable, even if you don't know any coding. Most of the configuration you should need can be done by just editing `quartz.config.ts` or changing [[layout|the layout]] in `quartz.layout.ts`.
|
||||
|
||||
> [!tip]
|
||||
> If you edit Quartz configuration using a text-editor that has TypeScript language support like VSCode, it will warn you when you you've made an error in your configuration, helping you avoid configuration mistakes!
|
||||
|
||||
The configuration of Quartz can be broken down into two main parts:
|
||||
|
||||
```ts title="quartz.config.ts"
|
||||
const config: QuartzConfig = {
|
||||
configuration: { ... },
|
||||
plugins: { ... },
|
||||
}
|
||||
```
|
||||
|
||||
## General Configuration
|
||||
|
||||
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.
|
||||
- `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: 'plausible' }`: use [Plausible](https://plausible.io/), a privacy-friendly alternative to Google Analytics; or
|
||||
- `{ provider: 'google', tagId: <your-google-tag> }`: use Google Analytics
|
||||
- `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`
|
||||
- Note that Quartz 4 will avoid using this as much as possible and use relative URLs whenever it can to make sure your site works no matter _where_ you end up actually deploying it.
|
||||
- `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.
|
||||
- `typography`: what fonts to use. Any font available on [Google Fonts](https://fonts.google.com/) works here.
|
||||
- `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
|
||||
- `gray`: graph links, heavier borders
|
||||
- `darkgray`: body text
|
||||
- `dark`: header text and icons
|
||||
- `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]]
|
||||
|
||||
## Plugins
|
||||
|
||||
You can think of Quartz plugins as a series of transformations over content.
|
||||
|
||||
![[quartz transform pipeline.png]]
|
||||
|
||||
```ts
|
||||
plugins: {
|
||||
transformers: [...],
|
||||
filters: [...],
|
||||
emitters: [...],
|
||||
}
|
||||
```
|
||||
|
||||
- [[making plugins#Transformers|Transformers]] **map** over content (e.g. parsing frontmatter, generating a description)
|
||||
- [[making plugins#Filters|Filters]] **filter** content (e.g. filtering out drafts)
|
||||
- [[making plugins#Emitters|Emitters]] **reduce** over content (e.g. creating an RSS feed or pages that list all files with a specific tag)
|
||||
|
||||
By adding, removing, and reordering plugins from the `tranformers`, `filters`, and `emitters` fields, you can customize the behaviour of Quartz.
|
||||
|
||||
> [!note]
|
||||
> Each node is modified by every transformer _in order_. Some transformers are position-sensitive so you may need to take special note of whether it needs come before or after any other particular plugins.
|
||||
|
||||
Additionally, plugins may also have their own configuration settings that you can pass in. For example, the [[Latex]] plugin allows you to pass in a field specifying the `renderEngine` to choose between Katex and MathJax.
|
||||
|
||||
```ts
|
||||
transformers: [
|
||||
Plugin.FrontMatter(), // uses default options
|
||||
Plugin.Latex({ renderEngine: "katex" }), // specify some options
|
||||
]
|
||||
```
|
||||
|
||||
If you'd like to make your own plugins, read the guide on [[making plugins]] for more information.
|
|
@ -1,63 +0,0 @@
|
|||
---
|
||||
tags:
|
||||
- plugin/transformer
|
||||
---
|
||||
|
||||
Quartz uses [Katex](https://katex.org/) by default to typeset both inline and block math expressions at build time.
|
||||
|
||||
## Syntax
|
||||
|
||||
### Block Math
|
||||
|
||||
Block math can be rendered by delimiting math expression with `$$`.
|
||||
|
||||
```
|
||||
$$
|
||||
f(x) = \int_{-\infty}^\infty
|
||||
f\hat(\xi),e^{2 \pi i \xi x}
|
||||
\,d\xi
|
||||
$$
|
||||
```
|
||||
|
||||
$$
|
||||
f(x) = \int_{-\infty}^\infty
|
||||
f\hat(\xi),e^{2 \pi i \xi x}
|
||||
\,d\xi
|
||||
$$
|
||||
|
||||
$$
|
||||
\begin{aligned}
|
||||
a &= b + c \\ &= e + f \\
|
||||
\end{aligned}
|
||||
$$
|
||||
|
||||
$$
|
||||
\begin{bmatrix}
|
||||
1 & 2 & 3 \\
|
||||
a & b & c
|
||||
\end{bmatrix}
|
||||
$$
|
||||
|
||||
### Inline Math
|
||||
|
||||
Similarly, inline math can be rendered by delimiting math expression with a single `$`. For example, `$e^{i\pi} = -1$` produces $e^{i\pi} = -1$
|
||||
|
||||
### Escaping symbols
|
||||
|
||||
There will be cases where you may have more than one `$` in a paragraph at once which may accidentally trigger MathJax/Katex.
|
||||
|
||||
To get around this, you can escape the dollar sign by doing `\$` instead.
|
||||
|
||||
For example:
|
||||
|
||||
- Incorrect: `I have $1 and you have $2` produces I have $1 and you have $2
|
||||
- Correct: `I have \$1 and you have \$2` produces I have \$1 and you have \$2
|
||||
|
||||
## MathJax
|
||||
|
||||
In `quartz.config.ts`, you can configure Quartz to use [MathJax SVG rendering](https://docs.mathjax.org/en/latest/output/svg.html) by replacing `Plugin.Latex({ renderEngine: 'katex' })` with `Plugin.Latex({ renderEngine: 'mathjax' })`
|
||||
|
||||
## Customization
|
||||
|
||||
- Removing Latex support: remove all instances of `Plugin.Latex()` from `quartz.config.ts`.
|
||||
- Plugin: `quartz/plugins/transformers/latex.ts`
|
|
@ -1,28 +0,0 @@
|
|||
Quartz supports Mermaid which allows you to add diagrams and charts to your notes. Mermaid supports a range of diagrams, such as [flow charts](https://mermaid.js.org/syntax/flowchart.html), [sequence diagrams](https://mermaid.js.org/syntax/sequenceDiagram.html), and [timelines](https://mermaid.js.org/syntax/timeline.html). This is enabled as a part of [[Obsidian compatibility]] and can be configured and enabled/disabled from that plugin.
|
||||
|
||||
By default, Quartz will render Mermaid diagrams to match the site theme.
|
||||
|
||||
> [!warning]
|
||||
> Wondering why Mermaid diagrams may not be showing up even if you have them enabled? You may need to reorder your plugins so that `Plugin.ObsidianFlavoredMarkdown()` is _after_ `Plugin.SyntaxHighlighting()`.
|
||||
|
||||
## Syntax
|
||||
|
||||
To add a Mermaid diagram, create a mermaid code block.
|
||||
|
||||
````
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
Alice->>+John: Hello John, how are you?
|
||||
Alice->>+John: John, can you hear me?
|
||||
John-->>-Alice: Hi Alice, I can hear you!
|
||||
John-->>-Alice: I feel great!
|
||||
```
|
||||
````
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
Alice->>+John: Hello John, how are you?
|
||||
Alice->>+John: John, can you hear me?
|
||||
John-->>-Alice: Hi Alice, I can hear you!
|
||||
John-->>-Alice: I feel great!
|
||||
```
|
|
@ -1,31 +0,0 @@
|
|||
---
|
||||
tags:
|
||||
- plugin/transformer
|
||||
---
|
||||
|
||||
Quartz was originally designed as a tool to publish Obsidian vaults as websites. Even as the scope of Quartz has widened over time, it hasn't lost the ability to seamlessly interoperate with Obsidian.
|
||||
|
||||
By default, Quartz ships with `Plugin.ObsidianFlavoredMarkdown` which is a transformer plugin that adds support for [Obsidian Flavored Markdown](https://help.obsidian.md/Editing+and+formatting/Obsidian+Flavored+Markdown). This includes support for features like [[wikilinks]] and [[Mermaid diagrams]].
|
||||
|
||||
It also ships with support for [frontmatter parsing](https://help.obsidian.md/Editing+and+formatting/Properties) with the same fields that Obsidian uses through the `Plugin.FrontMatter` transformer plugin.
|
||||
|
||||
Finally, Quartz also provides `Plugin.CrawlLinks` which allows you to customize Quartz's link resolution behaviour to match Obsidian.
|
||||
|
||||
## Configuration
|
||||
|
||||
- Frontmatter parsing:
|
||||
- Disabling: remove all instances of `Plugin.FrontMatter()` from `quartz.config.ts`.
|
||||
- Customize default values for frontmatter: edit `quartz/plugins/transformers/frontmatter.ts`
|
||||
- Obsidian Flavored Markdown:
|
||||
- Disabling: remove all instances of `Plugin.ObsidianFlavoredMarkdown()` from `quartz.config.ts`
|
||||
- Customizing features: `Plugin.ObsidianFlavoredMarkdown` has several other options to toggle on and off:
|
||||
- `comments`: whether to enable `%%` style Obsidian comments. Defaults to `true`
|
||||
- `highlight`: whether to enable `==` style highlights. Defaults to `true`
|
||||
- `wikilinks`: whether to enable turning [[wikilinks]] into regular links. Defaults to `true`
|
||||
- `callouts`: whether to enable [[callouts]]. Defaults to `true`
|
||||
- `mermaid`: whether to enable [[Mermaid diagrams]]. Defaults to `true`
|
||||
- `parseTags`: whether to try and parse tags in the content body. Defaults to `true`
|
||||
- `enableInHtmlEmbed`: whether to try and parse Obsidian flavoured markdown in raw HTML. Defaults to `false`
|
||||
- Link resolution behaviour:
|
||||
- Disabling: remove all instances of `Plugin.CrawlLinks()` from `quartz.config.ts`
|
||||
- Changing link resolution preference: set `markdownLinkResolution` to one of `absolute`, `relative` or `shortest`
|
|
@ -1,38 +0,0 @@
|
|||
---
|
||||
tags:
|
||||
- plugin/transformer
|
||||
---
|
||||
|
||||
[org-roam](https://www.orgroam.com/) is a plain-text personal knowledge management system for [emacs](https://en.wikipedia.org/wiki/Emacs). [ox-hugo](https://github.com/kaushalmodi/ox-hugo) is org exporter backend that exports `org-mode` files to [Hugo](https://gohugo.io/) compatible Markdown.
|
||||
|
||||
Because the Markdown generated by ox-hugo is not pure Markdown but Hugo specific, we need to transform it to fit into Quartz. This is done by `Plugin.OxHugoFlavouredMarkdown`. Even though this [[making plugins|plugin]] was written with `ox-hugo` in mind, it should work for any Hugo specific Markdown.
|
||||
|
||||
```typescript title="quartz.config.ts"
|
||||
plugins: {
|
||||
transformers: [
|
||||
Plugin.FrontMatter({ delims: "+++", language: "toml" }), // if toml frontmatter
|
||||
// ...
|
||||
Plugin.OxHugoFlavouredMarkdown(),
|
||||
Plugin.GitHubFlavoredMarkdown(),
|
||||
// ...
|
||||
],
|
||||
},
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
Quartz by default doesn't understand `org-roam` files as they aren't Markdown. You're responsible for using an external tool like `ox-hugo` to export the `org-roam` files as Markdown content to Quartz and managing the static assets so that they're available in the final output.
|
||||
|
||||
## Configuration
|
||||
|
||||
- Link resolution
|
||||
- `wikilinks`: Whether to replace `{{ relref }}` with Quartz [[wikilinks]]
|
||||
- `removePredefinedAnchor`: Whether to remove [pre-defined anchor set by ox-hugo](https://ox-hugo.scripter.co/doc/anchors/).
|
||||
- Image handling
|
||||
- `replaceFigureWithMdImg`: Whether to replace `<figure/>` with `![]()`
|
||||
- Formatting
|
||||
- `removeHugoShortcode`: Whether to remove hugo shortcode syntax (`{{}}`)
|
||||
|
||||
> [!warning]
|
||||
>
|
||||
> While you can use `Plugin.OxHugoFlavoredMarkdown` and `Plugin.ObsidianFlavoredMarkdown` together, it's not recommended because it might mutate the file in unexpected ways. Use with caution.
|
|
@ -1,7 +0,0 @@
|
|||
Quartz creates 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.
|
||||
|
||||
## Configuration
|
||||
|
||||
- Remove RSS feed: set the `enableRSS` field of `Plugin.ContentIndex` in `quartz.config.ts` to be `false`.
|
||||
- Change number of entries: set the `rssLimit` field of `Plugin.ContentIndex` to be the desired value. It defaults to latest 10 items.
|
||||
- Use rich HTML output in RSS: set `rssFullHtml` field of `Plugin.ContentIndex` to be `true`.
|
|
@ -1,7 +0,0 @@
|
|||
Single-page-app style rendering. This prevents flashes of unstyled content and improves the smoothness of Quartz.
|
||||
|
||||
Under the hood, this is done by hijacking page navigations and instead fetching the HTML via a `GET` request and then diffing and selectively replacing parts of the page using [micromorph](https://github.com/natemoo-re/micromorph). This allows us to change the content of the page without fully refreshing the page, reducing the amount of content that the browser needs to load.
|
||||
|
||||
## Configuration
|
||||
|
||||
- Disable SPA Routing: set the `enableSPA` field of the [[configuration]] in `quartz.config.ts` to be `false`.
|
|
@ -1,14 +0,0 @@
|
|||
---
|
||||
title: Backlinks
|
||||
tags:
|
||||
- component
|
||||
---
|
||||
|
||||
A backlink for a note is a link from another note to that note. Links in the backlink pane also feature rich [[popover previews]] if you have that feature enabled.
|
||||
|
||||
## Customization
|
||||
|
||||
- Removing backlinks: delete all usages of `Component.Backlinks()` from `quartz.layout.ts`.
|
||||
- Component: `quartz/components/Backlinks.tsx`
|
||||
- Style: `quartz/components/styles/backlinks.scss`
|
||||
- Script: `quartz/components/scripts/search.inline.ts`
|
|
@ -1,86 +0,0 @@
|
|||
---
|
||||
title: Callouts
|
||||
tags:
|
||||
- plugin/transformer
|
||||
---
|
||||
|
||||
Quartz supports the same Admonition-callout syntax as Obsidian.
|
||||
|
||||
This includes
|
||||
|
||||
- 12 Distinct callout types (each with several aliases)
|
||||
- Collapsable callouts
|
||||
|
||||
```
|
||||
> [!info] Title
|
||||
> This is a callout!
|
||||
```
|
||||
|
||||
See [documentation on supported types and syntax here](https://help.obsidian.md/Editing+and+formatting/Callouts).
|
||||
|
||||
> [!warning]
|
||||
> Wondering why callouts may not be showing up even if you have them enabled? You may need to reorder your plugins so that `Plugin.ObsidianFlavoredMarkdown()` is _after_ `Plugin.SyntaxHighlighting()`.
|
||||
|
||||
## Customization
|
||||
|
||||
- Disable callouts: simply pass `callouts: false` to the plugin: `Plugin.ObsidianFlavoredMarkdown({ callouts: false })`
|
||||
- Editing icons: `quartz/plugins/transformers/ofm.ts`
|
||||
|
||||
## Showcase
|
||||
|
||||
> [!info]
|
||||
> Default title
|
||||
|
||||
> [!question]+ Can callouts be nested?
|
||||
>
|
||||
> > [!todo]- Yes!, they can.
|
||||
> >
|
||||
> > > [!example] You can even use multiple layers of nesting.
|
||||
|
||||
> [!EXAMPLE] Examples
|
||||
>
|
||||
> Aliases: example
|
||||
|
||||
> [!note] Notes
|
||||
>
|
||||
> Aliases: note
|
||||
|
||||
> [!abstract] Summaries
|
||||
>
|
||||
> Aliases: abstract, summary, tldr
|
||||
|
||||
> [!info] Info
|
||||
>
|
||||
> Aliases: info, todo
|
||||
|
||||
> [!tip] Hint
|
||||
>
|
||||
> Aliases: tip, hint, important
|
||||
|
||||
> [!success] Success
|
||||
>
|
||||
> Aliases: success, check, done
|
||||
|
||||
> [!question] Question
|
||||
>
|
||||
> Aliases: question, help, faq
|
||||
|
||||
> [!warning] Warning
|
||||
>
|
||||
> Aliases: warning, caution, attention
|
||||
|
||||
> [!failure] Failure
|
||||
>
|
||||
> Aliases: failure, fail, missing
|
||||
|
||||
> [!danger] Error
|
||||
>
|
||||
> Aliases: danger, error
|
||||
|
||||
> [!bug] Bug
|
||||
>
|
||||
> Aliases: bug
|
||||
|
||||
> [!quote] Quote
|
||||
>
|
||||
> Aliases: quote, cite
|
|
@ -1,14 +0,0 @@
|
|||
---
|
||||
title: "Darkmode"
|
||||
tags:
|
||||
- component
|
||||
---
|
||||
|
||||
Quartz supports darkmode out of the box that respects the user's theme preference. Any future manual toggles of the darkmode switch will be saved in the browser's local storage so it can be persisted across future page loads.
|
||||
|
||||
## Customization
|
||||
|
||||
- Removing darkmode: delete all usages of `Component.Darkmode()` from `quartz.layout.ts`.
|
||||
- Component: `quartz/components/Darkmode.tsx`
|
||||
- Style: `quartz/components/styles/darkmode.scss`
|
||||
- Script: `quartz/components/scripts/darkmode.inline.ts`
|
|
@ -1,227 +0,0 @@
|
|||
---
|
||||
title: "Explorer"
|
||||
tags:
|
||||
- component
|
||||
---
|
||||
|
||||
Quartz features an explorer that allows you to navigate all files and folders on your site. It supports nested folders and is highly customizable.
|
||||
|
||||
By default, it shows all folders and files on your page. To display the explorer in a different spot, you can edit the [[layout]].
|
||||
|
||||
> [!info]
|
||||
> The explorer uses local storage by default to save the state of your explorer. This is done to ensure a smooth experience when navigating to different pages.
|
||||
>
|
||||
> To clear/delete the explorer state from local storage, delete the `fileTree` entry (guide on how to delete a key from local storage in chromium based browsers can be found [here](https://docs.devolutions.net/kb/general-knowledge-base/clear-browser-local-storage/clear-chrome-local-storage/)). You can disable this by passing `useSavedState: false` as an argument.
|
||||
|
||||
## Customization
|
||||
|
||||
Most configuration can be done by passing in options to `Component.Explorer()`.
|
||||
|
||||
For example, here's what the default configuration looks like:
|
||||
|
||||
```typescript title="quartz.layout.ts"
|
||||
Component.Explorer({
|
||||
title: "Explorer", // title of the explorer component
|
||||
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, // wether to use local storage to save "state" (which folders are opened) of explorer
|
||||
// Sort order: folders first, then files. Sort folders and files alphabetically
|
||||
sortFn: (a, b) => {
|
||||
... // default implementation shown later
|
||||
},
|
||||
filterFn: undefined,
|
||||
mapFn: undefined,
|
||||
// what order to apply functions in
|
||||
order: ["filter", "map", "sort"],
|
||||
})
|
||||
```
|
||||
|
||||
When passing in your own options, you can omit any or all of these fields if you'd like to keep the default value for that field.
|
||||
|
||||
Want to customize it even more?
|
||||
|
||||
- Removing table of contents: 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:
|
||||
- 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 `FileNode` class, which has the following properties:
|
||||
|
||||
```ts title="quartz/components/ExplorerNode.tsx" {2-5}
|
||||
export class FileNode {
|
||||
children: FileNode[] // children of current node
|
||||
name: string // name of node (only useful for folders)
|
||||
file: QuartzPluginData | null // set if node is a file, see `QuartzPluginData` for more detail
|
||||
depth: number // depth of current node
|
||||
|
||||
... // rest of implementation
|
||||
}
|
||||
```
|
||||
|
||||
Every function you can pass is optional. By default, only a `sort` function will be used:
|
||||
|
||||
```ts title="Default sort function"
|
||||
// Sort order: folders first, then files. Sort folders and files alphabetically
|
||||
Component.Explorer({
|
||||
sortFn: (a, b) => {
|
||||
if ((!a.file && !b.file) || (a.file && b.file)) {
|
||||
return a.name.localeCompare(b.name)
|
||||
}
|
||||
if (a.file && !b.file) {
|
||||
return 1
|
||||
} else {
|
||||
return -1
|
||||
}
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
You can pass your own functions for `sortFn`, `filterFn` and `mapFn`. All functions will be executed in the order provided by the `order` option (see [[#Customization]]). These functions behave similarly to their `Array.prototype` counterpart, except they modify the entire `FileNode` tree in place instead of returning a new one.
|
||||
|
||||
For more information on how to use `sort`, `filter` and `map`, you can check [Array.prototype.sort()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort), [Array.prototype.filter()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) and [Array.prototype.map()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map).
|
||||
|
||||
Type definitions look like this:
|
||||
|
||||
```ts
|
||||
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, 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.name.localeCompare(b.name)
|
||||
}
|
||||
if (a.file && !b.file) {
|
||||
return -1
|
||||
} else {
|
||||
return 1
|
||||
}
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
### Change display names (`map`)
|
||||
|
||||
Using this example, the display names of all `FileNodes` (folders + files) will be converted to full upper case.
|
||||
|
||||
```ts title="quartz.layout.ts"
|
||||
Component.Explorer({
|
||||
mapFn: (node) => {
|
||||
node.name = node.name.toUpperCase()
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
### Remove list of elements (`filter`)
|
||||
|
||||
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", "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.
|
||||
|
||||
## Advanced examples
|
||||
|
||||
### Add emoji prefix
|
||||
|
||||
To add emoji prefixes (📁 for folders, 📄 for files), you could use a map function like this:
|
||||
|
||||
```ts title="quartz.layout.ts"
|
||||
Component.Explorer({
|
||||
mapFn: (node) => {
|
||||
// dont change name of root node
|
||||
if (node.depth > 0) {
|
||||
// set emoji for file/folder
|
||||
if (node.file) {
|
||||
node.name = "📄 " + node.name
|
||||
} else {
|
||||
node.name = "📁 " + node.name
|
||||
}
|
||||
}
|
||||
},
|
||||
}})
|
||||
```
|
||||
|
||||
### 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.
|
||||
|
||||
> [!tip]
|
||||
> When writing more complicated functions, the `layout` file can start to look very cramped.
|
||||
> You can fix this by defining your functions in another file.
|
||||
>
|
||||
> ```ts title="functions.ts"
|
||||
> import { Options } from "./quartz/components/ExplorerNode"
|
||||
> export const mapFn: Options["mapFn"] = (node) => {
|
||||
> // implement your function here
|
||||
> }
|
||||
> export const filterFn: Options["filterFn"] = (node) => {
|
||||
> // implement your function here
|
||||
> }
|
||||
> export const sortFn: Options["sortFn"] = (a, b) => {
|
||||
> // implement your function here
|
||||
> }
|
||||
> ```
|
||||
>
|
||||
> You can then import them like this:
|
||||
>
|
||||
> ```ts title="quartz.layout.ts"
|
||||
> import { mapFn, filterFn, sortFn } from "./functions.ts"
|
||||
> Component.Explorer({
|
||||
> mapFn: mapFn,
|
||||
> filterFn: filterFn,
|
||||
> sortFn: sortFn,
|
||||
> })
|
||||
> ```
|
|
@ -1,32 +0,0 @@
|
|||
---
|
||||
title: Folder and Tag Listings
|
||||
tags:
|
||||
- plugin/emitter
|
||||
---
|
||||
|
||||
Quartz creates listing pages for any folders and tags you have.
|
||||
|
||||
## Folder Listings
|
||||
|
||||
Quartz will generate an index page for all the pages under that folder. This includes any content that is multiple levels deep.
|
||||
|
||||
Additionally, Quartz will also generate pages for subfolders. Say you have a note in a nested folder `content/abc/def/note.md`. Then, Quartz would generate a page for all the notes under `abc` _and_ a page for all the notes under `abc/def`.
|
||||
|
||||
By default, Quartz will title the page `Folder: <name of folder>` and no description. You can override this by creating an `index.md` file in the folder with the `title` [[authoring content#Syntax|frontmatter]] field. Any content you write in this file will also be used in the description of the folder.
|
||||
|
||||
For example, for the folder `content/posts`, you can add another file `content/posts/index.md` to add a specific description for it.
|
||||
|
||||
## Tag Listings
|
||||
|
||||
Quartz will also create an index page for each unique tag in your vault and render a list of all notes with that tag.
|
||||
|
||||
Quartz also supports tag hierarchies as well (e.g. `plugin/emitter`) and will also render a separate tag page for each layer of the tag hierarchy. It will also create a default global tag index page at `/tags` that displays a list of all the tags in your Quartz.
|
||||
|
||||
Like folder listings, you can also provide a description and title for a tag page by creating a file for each tag. For example, if you wanted to create a custom description for the #component tag, you would create a file at `content/tags/component.md` with a title and description.
|
||||
|
||||
## Customization
|
||||
|
||||
The layout for both the folder and content pages can be customized. By default, they use the `defaultListPageLayout` in `quartz.layouts.ts`. If you'd like to make more involved changes to the layout and don't mind editing some [[creating components|Quartz components]], you can take a look at `quartz/components/pages/FolderContent.tsx` and `quartz/components/pages/TagContent.tsx` respectively.
|
||||
|
||||
- Removing folder listings: remove `Plugin.FolderPage()` from `emitters` in `quartz.config.ts`
|
||||
- Removing tag listings: remove `Plugin.TagPage()` from `emitters` in `quartz.config.ts`
|
|
@ -1,30 +0,0 @@
|
|||
---
|
||||
title: Full-text Search
|
||||
tags:
|
||||
- component
|
||||
---
|
||||
|
||||
Full-text search in Quartz is powered by [Flexsearch](https://github.com/nextapps-de/flexsearch). It's fast enough to return search results in under 10ms for Quartzs as large as half a million words.
|
||||
|
||||
It can be opened by either clicking on the search bar or pressing `⌘`/`ctrl` + `K`. The top 5 search results are shown on each query. Matching subterms are highlighted and the most relevant 30 words are excerpted. Clicking on a search result will navigate to that page.
|
||||
|
||||
To search content by tags, you can either press `⌘`/`ctrl` + `shift` + `K` or start your query with `#` (e.g. `#components`).
|
||||
|
||||
This component is also keyboard accessible: Tab and Shift+Tab will cycle forward and backward through search results and Enter will navigate to the highlighted result (first result by default). You are also able to navigate search results using `ArrowUp` and `ArrowDown`.
|
||||
|
||||
> [!info]
|
||||
> Search requires the `ContentIndex` emitter plugin to be present in the [[configuration]].
|
||||
|
||||
### Indexing Behaviour
|
||||
|
||||
By default, it indexes every page on the site with **Markdown syntax removed**. This means link URLs for instance are not indexed.
|
||||
|
||||
It properly tokenizes Chinese, Korean, and Japenese characters and constructs separate indexes for the title, content and tags, weighing title matches above content matches.
|
||||
|
||||
## Customization
|
||||
|
||||
- Removing search: delete all usages of `Component.Search()` from `quartz.layout.ts`.
|
||||
- Component: `quartz/components/Search.tsx`
|
||||
- Style: `quartz/components/styles/search.scss`
|
||||
- Script: `quartz/components/scripts/search.inline.ts`
|
||||
- You can edit `contextWindowWords`, `numSearchResults` or `numTagResults` to suit your needs
|
|
@ -1,59 +0,0 @@
|
|||
---
|
||||
title: "Graph View"
|
||||
tags:
|
||||
- component
|
||||
---
|
||||
|
||||
Quartz features a graph-view that can show both a local graph view and a global graph view.
|
||||
|
||||
- The local graph view shows files that either link to the current file or are linked from the current file. In other words, it shows all notes that are _at most_ one hop away.
|
||||
- The global graph view can be toggled by clicking the graph icon on the top-right of the local graph view. It shows _all_ the notes in your graph and how they connect to each other.
|
||||
|
||||
By default, the node radius is proportional to the total number of incoming and outgoing internal links from that file.
|
||||
|
||||
Additionally, similar to how browsers highlight visited links a different colour, the graph view will also show nodes that you have visited in a different colour.
|
||||
|
||||
> [!info]
|
||||
> Graph View requires the `ContentIndex` emitter plugin to be present in the [[configuration]].
|
||||
|
||||
## Customization
|
||||
|
||||
Most configuration can be done by passing in options to `Component.Graph()`.
|
||||
|
||||
For example, here's what the default configuration looks like:
|
||||
|
||||
```typescript title="quartz.layout.ts"
|
||||
Component.Graph({
|
||||
localGraph: {
|
||||
drag: true, // whether to allow panning the view around
|
||||
zoom: true, // whether to allow zooming in and out
|
||||
depth: 1, // how many hops of notes to display
|
||||
scale: 1.1, // default view scale
|
||||
repelForce: 0.5, // how much nodes should repel each other
|
||||
centerForce: 0.3, // how much force to use when trying to center the nodes
|
||||
linkDistance: 30, // how long should the links be by default?
|
||||
fontSize: 0.6, // what size should the node labels be?
|
||||
opacityScale: 1, // how quickly do we fade out the labels when zooming out?
|
||||
},
|
||||
globalGraph: {
|
||||
drag: true,
|
||||
zoom: true,
|
||||
depth: -1,
|
||||
scale: 0.9,
|
||||
repelForce: 0.5,
|
||||
centerForce: 0.3,
|
||||
linkDistance: 30,
|
||||
fontSize: 0.6,
|
||||
opacityScale: 1,
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
When passing in your own options, you can omit any or all of these fields if you'd like to keep the default value for that field.
|
||||
|
||||
Want to customize it even more?
|
||||
|
||||
- Removing graph view: delete all usages of `Component.Graph()` from `quartz.layout.ts`.
|
||||
- Component: `quartz/components/Graph.tsx`
|
||||
- Style: `quartz/components/styles/graph.scss`
|
||||
- Script: `quartz/components/scripts/graph.inline.ts`
|
|
@ -1,3 +0,0 @@
|
|||
---
|
||||
title: Feature List
|
||||
---
|
|
@ -1,15 +0,0 @@
|
|||
---
|
||||
title: Popover Previews
|
||||
---
|
||||
|
||||
Like Wikipedia, when you hover over a link in Quartz, there is a popup of a page preview that you can scroll to see the entire content. Links to headers will also scroll the popup to show that specific header in view.
|
||||
|
||||
By default, Quartz only fetches previews for pages inside your vault due to [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS). It does this by selecting all HTML elements with the `popover-hint` class. For most pages, this includes the page title, page metadata like words and time to read, tags, and the actual page content.
|
||||
|
||||
When [[creating components|creating your own components]], you can include this `popover-hint` class to also include it in the popover.
|
||||
|
||||
## Configuration
|
||||
|
||||
- Remove popovers: set the `enablePopovers` field in `quartz.config.ts` to be `false`.
|
||||
- Style: `quartz/components/styles/popover.scss`
|
||||
- Script: `quartz/components/scripts/popover.inline.ts`
|
|
@ -1,27 +0,0 @@
|
|||
---
|
||||
title: Private Pages
|
||||
tags:
|
||||
- plugin/filter
|
||||
---
|
||||
|
||||
There may be some notes you want to avoid publishing as a website. Quartz supports this through two mechanisms which can be used in conjunction:
|
||||
|
||||
## Filter Plugins
|
||||
|
||||
[[making plugins#Filters|Filter plugins]] are plugins that filter out content based off of certain criteria. By default, Quartz uses the `Plugin.RemoveDrafts` plugin which filters out any note that has `draft: true` in the frontmatter.
|
||||
|
||||
If you'd like to only publish a select number of notes, you can instead use `Plugin.ExplicitPublish` which will filter out all notes except for any that have `publish: true` in the frontmatter.
|
||||
|
||||
## `ignorePatterns`
|
||||
|
||||
This is a field in `quartz.config.ts` under the main [[configuration]] which allows you to specify a list of patterns to effectively exclude from parsing all together. Any valid [glob](https://github.com/mrmlnc/fast-glob#pattern-syntax) pattern works here.
|
||||
|
||||
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
|
||||
- `**/private`: exclude any files or folders named `private` at any level of nesting
|
||||
|
||||
> [!warning]
|
||||
> Marking something as private via either a plugin or through the `ignorePatterns` pattern will only prevent a page from being included in the final built site. If your GitHub repository is public, also be sure to include an ignore for those in the `.gitignore` of your Quartz. See the `git` [documentation](https://git-scm.com/docs/gitignore#_pattern_format) for more information.
|
|
@ -1,16 +0,0 @@
|
|||
---
|
||||
title: Recent Notes
|
||||
tags: component
|
||||
---
|
||||
|
||||
Quartz can generate a list of recent notes for based on some filtering and sorting criteria. Though this component isn't included in any [[layout]] by default, you can add it by using `Component.RecentNotes`.
|
||||
|
||||
## Customization
|
||||
|
||||
- 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 })`
|
||||
- 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.
|
||||
- Component: `quartz/components/RecentNotes.tsx`
|
||||
- Style: `quartz/components/styles/recentNotes.scss`
|
|
@ -1,135 +0,0 @@
|
|||
---
|
||||
title: Syntax Highlighting
|
||||
tags:
|
||||
- plugin/transformer
|
||||
---
|
||||
|
||||
Syntax highlighting in Quartz is completely done at build-time. This means that Quartz only ships pre-calculated CSS to highlight the right words so there is no heavy client-side bundle that does the syntax highlighting.
|
||||
|
||||
And, unlike some client-side highlighters, it has a full TextMate parser grammar instead of using Regexes, allowing for highly accurate code highlighting.
|
||||
|
||||
In short, it generates HTML that looks exactly like your code in an editor like VS Code. Under the hood, it's powered by [Rehype Pretty Code](https://rehype-pretty-code.netlify.app/) which uses [Shiki](https://github.com/shikijs/shiki).
|
||||
|
||||
> [!warning]
|
||||
> Syntax highlighting does have an impact on build speed if you have a lot of code snippets in your notes.
|
||||
|
||||
## Formatting
|
||||
|
||||
Text inside `backticks` on a line will be formatted like code.
|
||||
|
||||
````
|
||||
```ts
|
||||
export function trimPathSuffix(fp: string): string {
|
||||
fp = clientSideSlug(fp)
|
||||
let [cleanPath, anchor] = fp.split("#", 2)
|
||||
anchor = anchor === undefined ? "" : "#" + anchor
|
||||
|
||||
return cleanPath + anchor
|
||||
}
|
||||
```
|
||||
````
|
||||
|
||||
```ts
|
||||
export function trimPathSuffix(fp: string): string {
|
||||
fp = clientSideSlug(fp)
|
||||
let [cleanPath, anchor] = fp.split("#", 2)
|
||||
anchor = anchor === undefined ? "" : "#" + anchor
|
||||
|
||||
return cleanPath + anchor
|
||||
}
|
||||
```
|
||||
|
||||
### Titles
|
||||
|
||||
Add a file title to your code block, with text inside double quotes (`""`):
|
||||
|
||||
````
|
||||
```js title="..."
|
||||
|
||||
```
|
||||
````
|
||||
|
||||
```ts title="quartz/path.ts"
|
||||
export function trimPathSuffix(fp: string): string {
|
||||
fp = clientSideSlug(fp)
|
||||
let [cleanPath, anchor] = fp.split("#", 2)
|
||||
anchor = anchor === undefined ? "" : "#" + anchor
|
||||
|
||||
return cleanPath + anchor
|
||||
}
|
||||
```
|
||||
|
||||
### Line highlighting
|
||||
|
||||
Place a numeric range inside `{}`.
|
||||
|
||||
````
|
||||
```js {1-3,4}
|
||||
|
||||
```
|
||||
````
|
||||
|
||||
```ts {2-3,6}
|
||||
export function trimPathSuffix(fp: string): string {
|
||||
fp = clientSideSlug(fp)
|
||||
let [cleanPath, anchor] = fp.split("#", 2)
|
||||
anchor = anchor === undefined ? "" : "#" + anchor
|
||||
|
||||
return cleanPath + anchor
|
||||
}
|
||||
```
|
||||
|
||||
### Word highlighting
|
||||
|
||||
A series of characters, like a literal regex.
|
||||
|
||||
````
|
||||
```js /useState/
|
||||
const [age, setAge] = useState(50);
|
||||
const [name, setName] = useState('Taylor');
|
||||
```
|
||||
````
|
||||
|
||||
```js /useState/
|
||||
const [age, setAge] = useState(50)
|
||||
const [name, setName] = useState("Taylor")
|
||||
```
|
||||
|
||||
### Line numbers
|
||||
|
||||
Syntax highlighting has line numbers configured automatically. If you want to start line numbers at a specific number, use `showLineNumbers{number}`:
|
||||
|
||||
````
|
||||
```js showLineNumbers{number}
|
||||
|
||||
```
|
||||
````
|
||||
|
||||
```ts showLineNumbers{20}
|
||||
export function trimPathSuffix(fp: string): string {
|
||||
fp = clientSideSlug(fp)
|
||||
let [cleanPath, anchor] = fp.split("#", 2)
|
||||
anchor = anchor === undefined ? "" : "#" + anchor
|
||||
|
||||
return cleanPath + anchor
|
||||
}
|
||||
```
|
||||
|
||||
### Escaping code blocks
|
||||
|
||||
You can format a codeblock inside of a codeblock by wrapping it with another level of backtick fences that has one more backtick than the previous fence.
|
||||
|
||||
`````
|
||||
````
|
||||
```js /useState/
|
||||
const [age, setAge] = useState(50);
|
||||
const [name, setName] = useState('Taylor');
|
||||
```
|
||||
````
|
||||
`````
|
||||
|
||||
## Customization
|
||||
|
||||
- Removing syntax highlighting: delete all usages of `Plugin.SyntaxHighlighting()` from `quartz.config.ts`.
|
||||
- Style: By default, Quartz uses derivatives of the GitHub light and dark themes. You can customize the colours in the `quartz/styles/syntax.scss` file.
|
||||
- Plugin: `quartz/plugins/transformers/syntax.ts`
|
|
@ -1,24 +0,0 @@
|
|||
---
|
||||
title: "Table of Contents"
|
||||
tags:
|
||||
- component
|
||||
- plugin/transformer
|
||||
---
|
||||
|
||||
Quartz can automatically generate a table of contents from a list of headings on each page. It will also show you your current scroll position on the site by marking headings you've scrolled through with a different colour.
|
||||
|
||||
By default, it will show all headers from H1 (`# Title`) all the way to H3 (`### Title`) and will only show the table of contents if there is more than 1 header on the page.
|
||||
|
||||
> [!info]
|
||||
> This feature requires both `Plugin.TableOfContents` in your `quartz.config.ts` and `Component.TableOfContents` in your `quartz.layout.ts` to function correctly.
|
||||
|
||||
## Customization
|
||||
|
||||
- Removing table of contents: remove all instances of `Plugin.TableOfContents()` from `quartz.config.ts`. and `Component.TableOfContents()` from `quartz.layout.ts`
|
||||
- Changing the max depth: pass in a parameter to `Plugin.TableOfContents({ maxDepth: 4 })`
|
||||
- Changing the minimum number of entries in the Table of Contents before it renders: pass in a parameter to `Plugin.TableOfContents({ minEntries: 3 })`
|
||||
- Component: `quartz/components/TableOfContents.tsx`
|
||||
- Style:
|
||||
- Modern (default): `quartz/components/styles/toc.scss`
|
||||
- Legacy Quartz 3 style: `quartz/components/styles/legacyToc.scss`
|
||||
- Script: `quartz/components/scripts/toc.inline.ts`
|
|
@ -1,23 +0,0 @@
|
|||
---
|
||||
draft: true
|
||||
---
|
||||
|
||||
## 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
|
|
@ -1,16 +0,0 @@
|
|||
---
|
||||
title: Wikilinks
|
||||
---
|
||||
|
||||
Wikilinks were pioneered by earlier internet wikis to make it easier to write links across pages without needing to write Markdown or HTML links each time.
|
||||
|
||||
Quartz supports Wikilinks by default and these links are resolved by Quartz using `Plugin.CrawlLinks`. See the [Obsidian Help page on Internal Links](https://help.obsidian.md/Linking+notes+and+files/Internal+links) for more information on Wikilink syntax.
|
||||
|
||||
This is enabled as a part of [[Obsidian compatibility]] and can be configured and enabled/disabled from that plugin.
|
||||
|
||||
## Syntax
|
||||
|
||||
- `[[Path to file]]`: produces a link to `Path to file.md` (or `Path-to-file.md`) with the text `Path to file`
|
||||
- `[[Path to file | Here's the title override]]`: produces a link to `Path to file.md` with the text `Here's the title override`
|
||||
- `[[Path to file#Anchor]]`: produces a link to the anchor `Anchor` in the file `Path to file.md`
|
||||
- `[[Path to file#^block-ref]]`: produces a link to the specific block `block-ref` in the file `Path to file.md`
|
168
docs/hosting.md
168
docs/hosting.md
|
@ -1,168 +0,0 @@
|
|||
---
|
||||
title: Hosting
|
||||
---
|
||||
|
||||
Quartz effectively turns your Markdown files and other resources into a bundle of HTML, JS, and CSS files (a website!).
|
||||
|
||||
However, if you'd like to publish your site to the world, you need a way to host it online. This guide will detail how to deploy with either GitHub Pages or Cloudflare pages but any service that allows you to deploy static HTML should work as well (e.g. Netlify, Replit, etc.)
|
||||
|
||||
> [!hint]
|
||||
> Some Quartz features (like [[RSS Feed]] and sitemap generation) require `baseUrl` to be configured properly in your [[configuration]] to work properly. Make sure you set this before deploying!
|
||||
|
||||
## Cloudflare Pages
|
||||
|
||||
1. Log in to the [Cloudflare dashboard](https://dash.cloudflare.com/) and select your account.
|
||||
2. In Account Home, select **Workers & Pages** > **Create application** > **Pages** > **Connect to Git**.
|
||||
3. Select the new GitHub repository that you created and, in the **Set up builds and deployments** section, provide the following information:
|
||||
|
||||
| Configuration option | Value |
|
||||
| ---------------------- | ------------------ |
|
||||
| Production branch | `v4` |
|
||||
| Framework preset | `None` |
|
||||
| Build command | `npx quartz build` |
|
||||
| Build output directory | `public` |
|
||||
|
||||
Press "Save and deploy" and Cloudflare should have a deployed version of your site in about a minute. Then, every time you sync your Quartz changes to GitHub, your site should be updated.
|
||||
|
||||
To add a custom domain, check out [Cloudflare's documentation](https://developers.cloudflare.com/pages/platform/custom-domains/).
|
||||
|
||||
## GitHub Pages
|
||||
|
||||
Like Quartz 3, you can deploy the site generated by Quartz 4 via GitHub Pages.
|
||||
|
||||
> [!warning]
|
||||
> Quartz generates files in the format of `file.html` instead of `file/index.html` which means the trailing slashes for _non-folder paths_ are dropped. As GitHub pages does not do this redirect, this may cause existing links to your site that use trailing slashes to break. If not breaking existing links is important to you, consider using [[#Cloudflare Pages]].
|
||||
|
||||
In your local Quartz, create a new file `quartz/.github/workflows/deploy.yml`.
|
||||
|
||||
```yaml title="quartz/.github/workflows/deploy.yml"
|
||||
name: Deploy Quartz site to GitHub Pages
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- v4
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
pages: write
|
||||
id-token: write
|
||||
|
||||
concurrency:
|
||||
group: "pages"
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-22.04
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
with:
|
||||
fetch-depth: 0 # Fetch all history for git info
|
||||
- uses: actions/setup-node@v3
|
||||
with:
|
||||
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@v2
|
||||
with:
|
||||
path: public
|
||||
|
||||
deploy:
|
||||
needs: build
|
||||
environment:
|
||||
name: github-pages
|
||||
url: ${{ steps.deployment.outputs.page_url }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Deploy to GitHub Pages
|
||||
id: deployment
|
||||
uses: actions/deploy-pages@v2
|
||||
```
|
||||
|
||||
Then:
|
||||
|
||||
1. Head to "Settings" tab of your forked repository and in the sidebar, click "Pages". Under "Source", select "GitHub Actions".
|
||||
2. Commit these changes by doing `npx quartz sync`. This should deploy your site to `<github-username>.github.io/<repository-name>`.
|
||||
|
||||
> [!hint]
|
||||
> If you get an error about not being allowed to deploy to `github-pages` due to environment protection rules, make sure you remove any existing GitHub pages environments.
|
||||
>
|
||||
> You can do this by going to your Settings page on your GitHub fork and going to the Environments tab and pressing the trash icon. The GitHub action will recreate the environment for you correctly the next time you sync your Quartz.
|
||||
|
||||
### Custom Domain
|
||||
|
||||
Here's how to add a custom domain to your GitHub pages deployment.
|
||||
|
||||
1. Head to the "Settings" tab of your forked repository.
|
||||
2. In the "Code and automation" section of the sidebar, click "Pages".
|
||||
3. Under "Custom Domain", type your custom domain and click "Save".
|
||||
4. This next step depends on whether you are using an apex domain (`example.com`) or a subdomain (`subdomain.example.com`).
|
||||
- If you are using an apex domain, navigate to your DNS provider and create an `A` record that points your apex domain to GitHub's name servers which have the following IP addresses:
|
||||
- `185.199.108.153`
|
||||
- `185.199.109.153`
|
||||
- `185.199.110.153`
|
||||
- `185.199.111.153`
|
||||
- If you are using a subdomain, navigate to your DNS provider and create a `CNAME` record that points your subdomain to the default domain for your site. For example, if you want to use the subdomain `quartz.example.com` for your user site, create a `CNAME` record that points `quartz.example.com` to `<github-username>.github.io`.
|
||||
|
||||
![[dns records.png]]_The above shows a screenshot of Google Domains configured for both `jzhao.xyz` (an apex domain) and `quartz.jzhao.xyz` (a subdomain)._
|
||||
|
||||
See the [GitHub documentation](https://docs.github.com/en/pages/configuring-a-custom-domain-for-your-github-pages-site/managing-a-custom-domain-for-your-github-pages-site#configuring-a-subdomain) for more detail about how to setup your own custom domain with GitHub Pages.
|
||||
|
||||
> [!question] Why aren't my changes showing up?
|
||||
> There could be many different reasons why your changes aren't showing up but the most likely reason is that you forgot to push your changes to GitHub.
|
||||
>
|
||||
> Make sure you save your changes to Git and sync it to GitHub by doing `npx quartz sync`. This will also make sure to pull any updates you may have made from other devices so you have them locally.
|
||||
|
||||
## Vercel
|
||||
|
||||
### Fix URLs
|
||||
|
||||
Before deploying to Vercel, a `vercel.json` file is required at the root of the project directory. It needs to contain the following configuration so that URLs don't require the `.html` extension:
|
||||
|
||||
```json title="vercel.json"
|
||||
{
|
||||
"cleanUrls": true
|
||||
}
|
||||
```
|
||||
|
||||
### Deploy to Vercel
|
||||
|
||||
1. Log in to the [Vercel Dashboard](https://vercel.com/dashboard) and click "Add New..." > Project
|
||||
2. Import the Git repository containing your Quartz project.
|
||||
3. Give the project a name (lowercase characters and hyphens only)
|
||||
4. Check that these configuration options are set:
|
||||
|
||||
| Configuration option | Value |
|
||||
| ----------------------------------------- | ------------------ |
|
||||
| Framework Preset | `Other` |
|
||||
| Root Directory | `./` |
|
||||
| Build and Output Settings > Build Command | `npx quartz build` |
|
||||
|
||||
5. Press Deploy. Once it's live, you'll have 2 `*.vercel.app` URLs to view the page.
|
||||
|
||||
### Custom Domain
|
||||
|
||||
> [!note]
|
||||
> If there is something already hosted on the domain, these steps will not work without replacing the previous content. As a workaround, you could use Next.js rewrites or use the next section to create a subdomain.
|
||||
|
||||
1. Update the `baseUrl` in `quartz.config.js` if necessary.
|
||||
2. Go to the [Domains - Dashboard](https://vercel.com/dashboard/domains) page in Vercel.
|
||||
3. Connect the domain to Vercel
|
||||
4. Press "Add" to connect a custom domain to Vercel.
|
||||
5. Select your Quartz repository and press Continue.
|
||||
6. Enter the domain you want to connect it to.
|
||||
7. Follow the instructions to update your DNS records until you see "Valid Configuration"
|
||||
|
||||
### Use a Subdomain
|
||||
|
||||
Using `docs.example.com` is an example of a subdomain. They're a simple way of connecting multiple deployments to one domain.
|
||||
|
||||
1. Update the `baseUrl` in `quartz.config.js` if necessary.
|
||||
2. Ensure your domain has been added to the [Domains - Dashboard](https://vercel.com/dashboard/domains) page in Vercel.
|
||||
3. Go to the [Vercel Dashboard](https://vercel.com/dashboard) and select your Quartz project.
|
||||
4. Go to the Settings tab and then click Domains in the sidebar
|
||||
5. Enter your subdomain into the field and press Add
|
Binary file not shown.
Before Width: | Height: | Size: 76 KiB |
Binary file not shown.
Before Width: | Height: | Size: 55 KiB |
Binary file not shown.
Before Width: | Height: | Size: 72 KiB |
|
@ -1,45 +0,0 @@
|
|||
---
|
||||
title: Welcome to Quartz 4
|
||||
---
|
||||
|
||||
Quartz is a fast, batteries-included static-site generator that transforms Markdown content into fully functional websites. Thousands of students, developers, and teachers are [[showcase|already using Quartz]] to publish personal notes, wikis, and [digital gardens](https://jzhao.xyz/posts/networked-thought) to the web.
|
||||
|
||||
## 🪴 Get Started
|
||||
|
||||
Quartz requires **at least [Node](https://nodejs.org/) v18.14** 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:
|
||||
|
||||
```shell
|
||||
git clone https://github.com/jackyzha0/quartz.git
|
||||
cd quartz
|
||||
npm i
|
||||
npx quartz create
|
||||
```
|
||||
|
||||
This will guide you through initializing your Quartz with content. Once you've done so, see how to:
|
||||
|
||||
1. [[authoring content|Author content]] in Quartz
|
||||
2. [[configuration|Configure]] Quartz's behaviour
|
||||
3. Change Quartz's [[layout]]
|
||||
4. [[build|Build and preview]] Quartz
|
||||
5. [[hosting|Host]] Quartz online
|
||||
|
||||
> [!info]
|
||||
> Coming from Quartz 3? See the [[migrating from Quartz 3|migration guide]] for the differences between Quartz 3 and Quartz 4 and how to migrate.
|
||||
|
||||
## 🔧 Features
|
||||
|
||||
- [[Obsidian compatibility]], [[full-text search]], [[graph view]], note transclusion, [[wikilinks]], [[backlinks]], [[Latex]], [[syntax highlighting]], [[popover previews]], 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.
|
||||
|
||||
### 🚧 Troubleshooting + Updating
|
||||
|
||||
Having trouble with Quartz? Try searching for your issue using the search feature. If you haven't already, [[upgrading|upgrade]] to the newest version of Quartz to see if this fixes your issue.
|
||||
|
||||
If you're still having trouble, feel free to [submit an issue](https://github.com/jackyzha0/quartz/issues) if you feel you found a bug or ask for help in our [Discord Community](https://discord.gg/cRFFHYye7t).
|
|
@ -1,42 +0,0 @@
|
|||
---
|
||||
title: Layout
|
||||
---
|
||||
|
||||
Certain emitters may also output [HTML](https://developer.mozilla.org/en-US/docs/Web/HTML) files. To enable easy customization, these emitters allow you to fully rearrange the layout of the page. The default page layouts can be found in `quartz.layout.ts`.
|
||||
|
||||
Each page is composed of multiple different sections which contain `QuartzComponents`. The following code snippet lists all of the valid sections that you can add components to:
|
||||
|
||||
```typescript title="quartz/cfg.ts"
|
||||
export interface FullPageLayout {
|
||||
head: QuartzComponent // single component
|
||||
header: QuartzComponent[] // laid out horizontally
|
||||
beforeBody: QuartzComponent[] // laid out vertically
|
||||
pageBody: QuartzComponent // single component
|
||||
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:
|
||||
|
||||
![[quartz layout.png|800]]
|
||||
|
||||
> [!note]
|
||||
> There are two additional layout fields that are _not_ shown in the above diagram.
|
||||
>
|
||||
> 1. `head` is a single component that renders the `<head>` [tag](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/head) in the HTML. This doesn't appear visually on the page and is only is responsible for metadata about the document like the tab title, scripts, and styles.
|
||||
> 2. `header` is a set of components that are laid out horizontally and appears _before_ the `beforeBody` section. This enables you to replicate the old Quartz 3 header bar where the title, search bar, and dark mode toggle. By default, Quartz 4 doesn't place any components in the `header`.
|
||||
|
||||
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. You can also checkout the guide on [[creating components]] if you're interested in further customizing the behaviour of Quartz.
|
||||
|
||||
### Style
|
||||
|
||||
Most meaningful style changes like colour scheme and font can be done simply through the [[configuration#General Configuration|general configuration]] options. However, if you'd like to make more involved style changes, you can do this by writing your own styles. Quartz 4, like Quartz 3, uses [Sass](https://sass-lang.com/guide/) for styling.
|
||||
|
||||
You can see the base style sheet in `quartz/styles/base.scss` and write your own in `quartz/styles/custom.scss`.
|
||||
|
||||
> [!note]
|
||||
> Some components may provide their own styling as well! For example, `quartz/components/Darkmode.tsx` imports styles from `quartz/components/styles/darkmode.scss`. If you'd like to customize styling for a specific component, double check the component definition to see how its styles are defined.
|
|
@ -1,41 +0,0 @@
|
|||
---
|
||||
title: "Migrating from Quartz 3"
|
||||
---
|
||||
|
||||
As you already have Quartz locally, you don't need to fork or clone it again. Simply just checkout the alpha branch, install the dependencies, and import your old vault.
|
||||
|
||||
```bash
|
||||
git fetch
|
||||
git checkout v4
|
||||
git pull upstream v4
|
||||
npm i
|
||||
npx quartz create
|
||||
```
|
||||
|
||||
If you get an error like `fatal: 'upstream' does not appear to be a git repository`, make sure you add `upstream` as a remote origin:
|
||||
|
||||
```shell
|
||||
git remote add upstream https://github.com/jackyzha0/quartz.git
|
||||
```
|
||||
|
||||
When running `npx quartz create`, you will be prompted as to how to initialize your content folder. Here, you can choose to import or link your previous content folder and Quartz should work just as you expect it to.
|
||||
|
||||
> [!note]
|
||||
> If the existing content folder you'd like to use is at the _same_ path on a different branch, clone the repo again somewhere at a _different_ path in order to use it.
|
||||
|
||||
## Key changes
|
||||
|
||||
1. **Removing Hugo and `hugo-obsidian`**: Hugo worked well for earlier versions of Quartz but it also made it hard for people outside of the Golang and Hugo communities to fully understand what Quartz was doing under the hood and be able to properly customize it to their needs. Quartz 4 now uses a Node-based static-site generation process which should lead to a much more helpful error messages and an overall smoother user experience.
|
||||
2. **Full-hot reload**: The many rough edges of how `hugo-obsidian` integrated with Hugo meant that watch mode didn't re-trigger `hugo-obsidian` to update the content index. This lead to a lot of weird cases where the watch mode output wasn't accurate. Quartz 4 now uses a cohesive parse, filter, and emit pipeline which gets run on every change so hot-reloads are always accurate.
|
||||
3. **Replacing Go template syntax with JSX**: Quartz 3 used [Go templates](https://pkg.go.dev/text/template) to create layouts for pages. However, the syntax isn't great for doing any sort of complex rendering (like [text processing](https://github.com/jackyzha0/quartz/blob/hugo/layouts/partials/textprocessing.html)) and it got very difficult to make any meaningful layout changes to Quartz 3. Quartz 4 uses an extension of JavaScript syntax called JSX which allows you to write layout code that looks like HTML in JavaScript which is significantly easier to understand and maintain.
|
||||
4. **A new extensible [[configuration]] and [[configuration#Plugins|plugin]] system**: Quartz 3 was hard to configure without technical knowledge of how Hugo's partials worked. Extensions were even hard to make. Quartz 4's configuration and plugin system is designed to be extended by users while making updating to new versions of Quartz easy.
|
||||
|
||||
## Things to update
|
||||
|
||||
- You will need to update your deploy scripts. See the [[hosting]] guide for more details.
|
||||
- Ensure that your default branch on GitHub is updated from `hugo` to `v4`.
|
||||
- [[folder and tag listings|Folder and tag listings]] have also changed.
|
||||
- Folder descriptions should go under `content/<folder-name>/index.md` where `<folder-name>` is the name of the folder.
|
||||
- Tag descriptions should go under `content/tags/<tag-name>.md` where `<tag-name>` is the name of the tag.
|
||||
- Some HTML layout may not be the same between Quartz 3 and Quartz 4. If you depended on a particular HTML hierarchy or class names, you may need to update your custom CSS to reflect these changes.
|
||||
- If you customized the layout of Quartz 3, you may need to translate these changes from Go templates back to JSX as Quartz 4 no longer uses Hugo. For components, check out the guide on [[creating components]] for more details on this.
|
|
@ -1,28 +0,0 @@
|
|||
---
|
||||
title: Philosophy of Quartz
|
||||
---
|
||||
|
||||
## A garden should be a true hypertext
|
||||
|
||||
> The garden is the web as topology. Every walk through the garden creates new paths, new meanings, and when we add things to the garden we add them in a way that allows many future, unpredicted relationships.
|
||||
>
|
||||
> _(The Garden and the Stream)_
|
||||
|
||||
The problem with the file cabinet is that it focuses on efficiency of access and interoperability rather than generativity and creativity. Thinking is not linear, nor is it hierarchical. In fact, not many things are linear or hierarchical at all. Then why is it that most tools and thinking strategies assume a nice chronological or hierarchical order for my thought processes? The ideal tool for thought for me would embrace the messiness of my mind, and organically help insights emerge from chaos instead of forcing an artificial order. A rhizomatic, not arboresecent, form of note taking.
|
||||
|
||||
My goal with a digital garden is not purely as an organizing system and information store (though it works nicely for that). I want my digital garden to be a playground for new ways ideas can connect together. As a result, existing formal organizing systems like Zettelkasten or the hierarchical folder structures of Notion don’t work well for me. There is way too much upfront friction that by the time I’ve thought about how to organize my thought into folders categories, I’ve lost it.
|
||||
|
||||
Quartz embraces the inherent rhizomatic and web-like nature of our thinking and tries to encourage note-taking in a similar form.
|
||||
|
||||
---
|
||||
|
||||
## A garden should be shared
|
||||
|
||||
The goal of digital gardening should be to tap into your network’s collective intelligence to create constructive feedback loops. If done well, I have a shareable representation of my thoughts that I can send out into the world and people can respond. Even for my most half-baked thoughts, this helps me create a feedback cycle to strengthen and fully flesh out that idea.
|
||||
|
||||
Quartz is designed first and foremost as a tool for publishing [digital gardens](https://jzhao.xyz/posts/networked-thought) to the web. To me, digital gardening is not just passive knowledge collection. It’s a form of expression and sharing.
|
||||
|
||||
> “[One] who works with the door open gets all kinds of interruptions, but [they] also occasionally gets clues as to what the world is and what might be important.”
|
||||
> — Richard Hamming
|
||||
|
||||
**The goal of Quartz is to make sharing your digital garden free and simple.** At its core, Quartz is designed to be easy to use enough for non-technical people to get going but also powerful enough that senior developers can tweak it to work how they'd like it to work.
|
|
@ -1,21 +0,0 @@
|
|||
---
|
||||
title: "Quartz Showcase"
|
||||
---
|
||||
|
||||
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/)
|
||||
- [Brandon Boswell's Garden](https://brandonkboswell.com)
|
||||
- [Scaling Synthesis - A hypertext research notebook](https://scalingsynthesis.com/)
|
||||
- [AWAGMI Intern Notes](https://notes.awagmi.xyz/)
|
||||
- [Course notes for Information Technology Advanced Theory](https://a2itnotes.github.io/quartz/)
|
||||
- [Data Dictionary 🧠](https://glossary.airbyte.com/)
|
||||
- [sspaeti.com's Second Brain](https://brain.sspaeti.com/)
|
||||
- [oldwinter の数字花园](https://garden.oldwinter.top/)
|
||||
- [Abhijeet's Math Wiki](https://abhmul.github.io/quartz/Math-Wiki/)
|
||||
- [Mike's AI Garden 🤖🪴](https://mwalton.me/)
|
||||
- [Matt Dunn's Second Brain](https://mattdunn.info/)
|
||||
- [Pelayo Arbues' Notes](https://pelayoarbues.github.io/)
|
||||
|
||||
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/content/showcase.md)!
|
|
@ -1,5 +0,0 @@
|
|||
---
|
||||
title: Components
|
||||
---
|
||||
|
||||
Want to create your own custom component? Check out the advanced guide on [[creating components]] for more information.
|
|
@ -1,19 +0,0 @@
|
|||
---
|
||||
title: "Upgrading Quartz"
|
||||
---
|
||||
|
||||
> [!note]
|
||||
> This is specifically a guide for upgrading Quartz 4 version to a more recent update. If you are coming from Quartz 3, check out the [[migrating from Quartz 3|migration guide]] for more info.
|
||||
|
||||
To fetch the latest Quartz updates, simply run
|
||||
|
||||
```bash
|
||||
npx quartz update
|
||||
```
|
||||
|
||||
As Quartz uses [git](https://git-scm.com/) under the hood for versioning, updating effectively 'pulls' in the updates from the official Quartz GitHub repository. If you have local changes that might conflict with the updates, you may need to resolve these manually yourself (or, pull manually using `git pull origin upstream`).
|
||||
|
||||
> [!hint]
|
||||
> Quartz will try to cache your content before updating to try and prevent merge conflicts. If you get a conflict mid-merge, you can stop the merge and then run `npx quartz restore` to restore your content from the cache.
|
||||
|
||||
If you have the [GitHub desktop app](https://desktop.github.com/), this will automatically open to help you resolve the conflicts. Otherwise, you will need to resolve this in a text editor like VSCode. For more help on resolving conflicts manually, check out the [GitHub guide on resolving merge conflicts](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/addressing-merge-conflicts/resolving-a-merge-conflict-using-the-command-line#competing-line-change-merge-conflicts).
|
12
globals.d.ts
vendored
12
globals.d.ts
vendored
|
@ -1,12 +0,0 @@
|
|||
export declare global {
|
||||
interface Document {
|
||||
addEventListener<K extends keyof CustomEventMap>(
|
||||
type: K,
|
||||
listener: (this: Document, ev: CustomEventMap[K]) => void,
|
||||
): void
|
||||
dispatchEvent<K extends keyof CustomEventMap>(ev: CustomEventMap[K]): void
|
||||
}
|
||||
interface Window {
|
||||
spaNavigate(url: URL, isBack: boolean = false)
|
||||
}
|
||||
}
|
11
index.d.ts
vendored
11
index.d.ts
vendored
|
@ -1,11 +0,0 @@
|
|||
declare module "*.scss" {
|
||||
const content: string
|
||||
export = content
|
||||
}
|
||||
|
||||
// dom custom event
|
||||
interface CustomEventMap {
|
||||
nav: CustomEvent<{ url: FullSlug }>
|
||||
}
|
||||
|
||||
declare const fetchData: Promise<ContentIndex>
|
6208
package-lock.json
generated
6208
package-lock.json
generated
File diff suppressed because it is too large
Load diff
109
package.json
109
package.json
|
@ -1,109 +0,0 @@
|
|||
{
|
||||
"name": "@jackyzha0/quartz",
|
||||
"description": "🌱 publish your digital garden and notes as a website",
|
||||
"private": true,
|
||||
"version": "4.0.11",
|
||||
"type": "module",
|
||||
"author": "jackyzha0 <j.zhao2k19@gmail.com>",
|
||||
"license": "MIT",
|
||||
"homepage": "https://quartz.jzhao.xyz",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/jackyzha0/quartz.git"
|
||||
},
|
||||
"scripts": {
|
||||
"docs": "npx quartz build --serve -d docs",
|
||||
"check": "tsc --noEmit && npx prettier . --check",
|
||||
"format": "npx prettier . --write",
|
||||
"test": "tsx ./quartz/util/path.test.ts",
|
||||
"profile": "0x -D prof ./quartz/bootstrap-cli.mjs build --concurrency=1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18.14"
|
||||
},
|
||||
"keywords": [
|
||||
"site generator",
|
||||
"ssg",
|
||||
"digital-garden",
|
||||
"markdown",
|
||||
"blog",
|
||||
"quartz"
|
||||
],
|
||||
"bin": {
|
||||
"quartz": "./quartz/bootstrap-cli.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"@clack/prompts": "^0.6.3",
|
||||
"@floating-ui/dom": "^1.4.0",
|
||||
"@napi-rs/simple-git": "0.1.9",
|
||||
"async-mutex": "^0.4.0",
|
||||
"chalk": "^4.1.2",
|
||||
"chokidar": "^3.5.3",
|
||||
"cli-spinner": "^0.2.10",
|
||||
"d3": "^7.8.5",
|
||||
"esbuild-sass-plugin": "^2.12.0",
|
||||
"flexsearch": "0.7.21",
|
||||
"github-slugger": "^2.0.0",
|
||||
"globby": "^13.1.4",
|
||||
"gray-matter": "^4.0.3",
|
||||
"hast-util-to-html": "^8.0.4",
|
||||
"hast-util-to-jsx-runtime": "^1.2.0",
|
||||
"hast-util-to-string": "^2.0.0",
|
||||
"is-absolute-url": "^4.0.1",
|
||||
"js-yaml": "^4.1.0",
|
||||
"lightningcss": "1.21.7",
|
||||
"mdast-util-find-and-replace": "^2.2.2",
|
||||
"mdast-util-to-hast": "^12.3.0",
|
||||
"mdast-util-to-string": "^3.2.0",
|
||||
"micromorph": "^0.4.5",
|
||||
"plausible-tracker": "^0.3.8",
|
||||
"preact": "^10.14.1",
|
||||
"preact-render-to-string": "^6.0.3",
|
||||
"pretty-bytes": "^6.1.0",
|
||||
"pretty-time": "^1.1.0",
|
||||
"reading-time": "^1.5.0",
|
||||
"rehype-autolink-headings": "^6.1.1",
|
||||
"rehype-katex": "^6.0.3",
|
||||
"rehype-mathjax": "^4.0.3",
|
||||
"rehype-pretty-code": "^0.10.0",
|
||||
"rehype-raw": "^6.1.1",
|
||||
"rehype-slug": "^5.1.0",
|
||||
"remark": "^14.0.2",
|
||||
"remark-breaks": "^3.0.3",
|
||||
"remark-frontmatter": "^4.0.1",
|
||||
"remark-gfm": "^3.0.1",
|
||||
"remark-math": "^5.1.1",
|
||||
"remark-parse": "^10.0.1",
|
||||
"remark-rehype": "^10.1.0",
|
||||
"remark-smartypants": "^2.0.0",
|
||||
"rimraf": "^5.0.1",
|
||||
"serve-handler": "^6.1.5",
|
||||
"shiki": "^0.14.4",
|
||||
"source-map-support": "^0.5.21",
|
||||
"to-vfile": "^7.2.4",
|
||||
"toml": "^3.0.0",
|
||||
"unified": "^10.1.2",
|
||||
"unist-util-visit": "^4.1.2",
|
||||
"vfile": "^5.3.7",
|
||||
"workerpool": "^6.4.0",
|
||||
"ws": "^8.13.0",
|
||||
"yargs": "^17.7.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/cli-spinner": "^0.2.1",
|
||||
"@types/d3": "^7.4.0",
|
||||
"@types/flexsearch": "^0.7.3",
|
||||
"@types/hast": "^2.3.4",
|
||||
"@types/js-yaml": "^4.0.5",
|
||||
"@types/node": "^20.1.2",
|
||||
"@types/pretty-time": "^1.1.2",
|
||||
"@types/source-map-support": "^0.5.6",
|
||||
"@types/workerpool": "^6.4.0",
|
||||
"@types/ws": "^8.5.5",
|
||||
"@types/yargs": "^17.0.24",
|
||||
"esbuild": "0.19.2",
|
||||
"prettier": "^3.0.0",
|
||||
"tsx": "^3.12.7",
|
||||
"typescript": "^5.0.4"
|
||||
}
|
||||
}
|
|
@ -1,77 +0,0 @@
|
|||
import { QuartzConfig } from "./quartz/cfg"
|
||||
import * as Plugin from "./quartz/plugins"
|
||||
|
||||
const config: QuartzConfig = {
|
||||
configuration: {
|
||||
pageTitle: "🪴 Quartz 4.0",
|
||||
enableSPA: true,
|
||||
enablePopovers: true,
|
||||
analytics: {
|
||||
provider: "plausible",
|
||||
},
|
||||
baseUrl: "notes.flup.dev",
|
||||
ignorePatterns: ["private", "templates", ".obsidian"],
|
||||
defaultDateType: "created",
|
||||
theme: {
|
||||
typography: {
|
||||
header: "Schibsted Grotesk",
|
||||
body: "Source Sans Pro",
|
||||
code: "IBM Plex Mono",
|
||||
},
|
||||
colors: {
|
||||
lightMode: {
|
||||
light: "#faf8f8",
|
||||
lightgray: "#e5e5e5",
|
||||
gray: "#b8b8b8",
|
||||
darkgray: "#4e4e4e",
|
||||
dark: "#2b2b2b",
|
||||
secondary: "#284b63",
|
||||
tertiary: "#84a59d",
|
||||
highlight: "rgba(143, 159, 169, 0.15)",
|
||||
},
|
||||
darkMode: {
|
||||
light: "#161618",
|
||||
lightgray: "#393639",
|
||||
gray: "#646464",
|
||||
darkgray: "#d4d4d4",
|
||||
dark: "#ebebec",
|
||||
secondary: "#7b97aa",
|
||||
tertiary: "#84a59d",
|
||||
highlight: "rgba(143, 159, 169, 0.15)",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
plugins: {
|
||||
transformers: [
|
||||
Plugin.FrontMatter(),
|
||||
Plugin.TableOfContents(),
|
||||
Plugin.CreatedModifiedDate({
|
||||
priority: ["frontmatter", "filesystem"], // you can add 'git' here for last modified from Git but this makes the build slower
|
||||
}),
|
||||
Plugin.SyntaxHighlighting(),
|
||||
Plugin.ObsidianFlavoredMarkdown({ enableInHtmlEmbed: false }),
|
||||
Plugin.GitHubFlavoredMarkdown(),
|
||||
Plugin.CrawlLinks({ markdownLinkResolution: "shortest" }),
|
||||
Plugin.Latex({ renderEngine: "katex" }),
|
||||
Plugin.Description(),
|
||||
],
|
||||
filters: [Plugin.RemoveDrafts()],
|
||||
emitters: [
|
||||
Plugin.AliasRedirects(),
|
||||
Plugin.ComponentResources({ fontOrigin: "googleFonts" }),
|
||||
Plugin.ContentPage(),
|
||||
Plugin.FolderPage(),
|
||||
Plugin.TagPage(),
|
||||
Plugin.ContentIndex({
|
||||
enableSiteMap: true,
|
||||
enableRSS: true,
|
||||
}),
|
||||
Plugin.Assets(),
|
||||
Plugin.Static(),
|
||||
Plugin.NotFoundPage(),
|
||||
],
|
||||
},
|
||||
}
|
||||
|
||||
export default config
|
|
@ -1,43 +0,0 @@
|
|||
import { PageLayout, SharedLayout } from "./quartz/cfg"
|
||||
import * as Component from "./quartz/components"
|
||||
|
||||
// components shared across all pages
|
||||
export const sharedPageComponents: SharedLayout = {
|
||||
head: Component.Head(),
|
||||
header: [],
|
||||
footer: Component.Footer({
|
||||
links: {
|
||||
GitHub: "https://github.com/jackyzha0/quartz",
|
||||
"Discord Community": "https://discord.gg/cRFFHYye7t",
|
||||
},
|
||||
}),
|
||||
}
|
||||
|
||||
// components for pages that display a single page (e.g. a single note)
|
||||
export const defaultContentPageLayout: PageLayout = {
|
||||
beforeBody: [Component.ArticleTitle(), Component.ContentMeta(), Component.TagList()],
|
||||
left: [
|
||||
Component.PageTitle(),
|
||||
Component.MobileOnly(Component.Spacer()),
|
||||
Component.Search(),
|
||||
Component.Darkmode(),
|
||||
Component.DesktopOnly(Component.Explorer()),
|
||||
],
|
||||
right: [
|
||||
Component.Graph(),
|
||||
Component.DesktopOnly(Component.TableOfContents()),
|
||||
Component.Backlinks(),
|
||||
],
|
||||
}
|
||||
|
||||
// components for pages that display lists of pages (e.g. tags or folders)
|
||||
export const defaultListPageLayout: PageLayout = {
|
||||
beforeBody: [Component.ArticleTitle()],
|
||||
left: [
|
||||
Component.PageTitle(),
|
||||
Component.MobileOnly(Component.Spacer()),
|
||||
Component.Search(),
|
||||
Component.Darkmode(),
|
||||
],
|
||||
right: [],
|
||||
}
|
|
@ -1,41 +0,0 @@
|
|||
#!/usr/bin/env node
|
||||
import yargs from "yargs"
|
||||
import { hideBin } from "yargs/helpers"
|
||||
import {
|
||||
handleBuild,
|
||||
handleCreate,
|
||||
handleUpdate,
|
||||
handleRestore,
|
||||
handleSync,
|
||||
} from "./cli/handlers.js"
|
||||
import { CommonArgv, BuildArgv, CreateArgv, SyncArgv } from "./cli/args.js"
|
||||
import { version } from "./cli/constants.js"
|
||||
|
||||
yargs(hideBin(process.argv))
|
||||
.scriptName("quartz")
|
||||
.version(version)
|
||||
.usage("$0 <cmd> [args]")
|
||||
.command("create", "Initialize Quartz", CreateArgv, async (argv) => {
|
||||
await handleCreate(argv)
|
||||
})
|
||||
.command("update", "Get the latest Quartz updates", CommonArgv, async (argv) => {
|
||||
await handleUpdate(argv)
|
||||
})
|
||||
.command(
|
||||
"restore",
|
||||
"Try to restore your content folder from the cache",
|
||||
CommonArgv,
|
||||
async (argv) => {
|
||||
await handleRestore(argv)
|
||||
},
|
||||
)
|
||||
.command("sync", "Sync your Quartz to and from GitHub.", SyncArgv, async (argv) => {
|
||||
await handleSync(argv)
|
||||
})
|
||||
.command("build", "Build Quartz into a bundle of static HTML files", BuildArgv, async (argv) => {
|
||||
await handleBuild(argv)
|
||||
})
|
||||
.showHelpOnFail(false)
|
||||
.help()
|
||||
.strict()
|
||||
.demandCommand().argv
|
|
@ -1,7 +0,0 @@
|
|||
#!/usr/bin/env node
|
||||
import workerpool from "workerpool"
|
||||
const cacheFile = "./.quartz-cache/transpiled-worker.mjs"
|
||||
const { parseFiles } = await import(cacheFile)
|
||||
workerpool.worker({
|
||||
parseFiles,
|
||||
})
|
183
quartz/build.ts
183
quartz/build.ts
|
@ -1,183 +0,0 @@
|
|||
import sourceMapSupport from "source-map-support"
|
||||
sourceMapSupport.install(options)
|
||||
import path from "path"
|
||||
import { PerfTimer } from "./util/perf"
|
||||
import { rimraf } from "rimraf"
|
||||
import { isGitIgnored } from "globby"
|
||||
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 chokidar from "chokidar"
|
||||
import { ProcessedContent } from "./plugins/vfile"
|
||||
import { Argv, BuildCtx } from "./util/ctx"
|
||||
import { glob, toPosixPath } from "./util/glob"
|
||||
import { trace } from "./util/trace"
|
||||
import { options } from "./util/sourcemap"
|
||||
import { Mutex } from "async-mutex"
|
||||
|
||||
async function buildQuartz(argv: Argv, mut: Mutex, clientRefresh: () => void) {
|
||||
const ctx: BuildCtx = {
|
||||
argv,
|
||||
cfg,
|
||||
allSlugs: [],
|
||||
}
|
||||
|
||||
const perf = new PerfTimer()
|
||||
const output = argv.output
|
||||
|
||||
const pluginCount = Object.values(cfg.plugins).flat().length
|
||||
const pluginNames = (key: "transformers" | "filters" | "emitters") =>
|
||||
cfg.plugins[key].map((plugin) => plugin.name)
|
||||
if (argv.verbose) {
|
||||
console.log(`Loaded ${pluginCount} plugins`)
|
||||
console.log(` Transformers: ${pluginNames("transformers").join(", ")}`)
|
||||
console.log(` Filters: ${pluginNames("filters").join(", ")}`)
|
||||
console.log(` Emitters: ${pluginNames("emitters").join(", ")}`)
|
||||
}
|
||||
|
||||
const release = await mut.acquire()
|
||||
perf.addEvent("clean")
|
||||
await rimraf(output)
|
||||
console.log(`Cleaned output directory \`${output}\` in ${perf.timeSince("clean")}`)
|
||||
|
||||
perf.addEvent("glob")
|
||||
const allFiles = await glob("**/*.*", argv.directory, cfg.configuration.ignorePatterns)
|
||||
const fps = allFiles.filter((fp) => fp.endsWith(".md")).sort()
|
||||
console.log(
|
||||
`Found ${fps.length} input files from \`${argv.directory}\` in ${perf.timeSince("glob")}`,
|
||||
)
|
||||
|
||||
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)
|
||||
await emitContent(ctx, filteredContent)
|
||||
console.log(chalk.green(`Done processing ${fps.length} files in ${perf.timeSince()}`))
|
||||
release()
|
||||
|
||||
if (argv.serve) {
|
||||
return startServing(ctx, mut, parsedFiles, clientRefresh)
|
||||
}
|
||||
}
|
||||
|
||||
// setup watcher for rebuilds
|
||||
async function startServing(
|
||||
ctx: BuildCtx,
|
||||
mut: Mutex,
|
||||
initialContent: ProcessedContent[],
|
||||
clientRefresh: () => void,
|
||||
) {
|
||||
const { argv } = ctx
|
||||
|
||||
const ignored = await isGitIgnored()
|
||||
const contentMap = new Map<FilePath, ProcessedContent>()
|
||||
for (const content of initialContent) {
|
||||
const [_tree, vfile] = content
|
||||
contentMap.set(vfile.data.filePath!, content)
|
||||
}
|
||||
|
||||
const initialSlugs = ctx.allSlugs
|
||||
let lastBuildMs = 0
|
||||
const toRebuild: Set<FilePath> = new Set()
|
||||
const toRemove: Set<FilePath> = new Set()
|
||||
const trackedAssets: Set<FilePath> = new Set()
|
||||
async function rebuild(fp: string, action: "add" | "change" | "delete") {
|
||||
// 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)
|
||||
}
|
||||
|
||||
// debounce rebuilds every 250ms
|
||||
|
||||
const buildStart = new Date().getTime()
|
||||
lastBuildMs = buildStart
|
||||
const release = await mut.acquire()
|
||||
if (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(argv.output)
|
||||
await emitContent(ctx, filteredContent)
|
||||
console.log(chalk.green(`Done rebuilding in ${perf.timeSince()}`))
|
||||
} catch {
|
||||
console.log(chalk.yellow(`Rebuild failed. Waiting on a change to fix the error...`))
|
||||
}
|
||||
|
||||
clientRefresh()
|
||||
toRebuild.clear()
|
||||
toRemove.clear()
|
||||
release()
|
||||
}
|
||||
|
||||
const watcher = chokidar.watch(".", {
|
||||
persistent: true,
|
||||
cwd: argv.directory,
|
||||
ignoreInitial: true,
|
||||
})
|
||||
|
||||
watcher
|
||||
.on("add", (fp) => rebuild(fp, "add"))
|
||||
.on("change", (fp) => rebuild(fp, "change"))
|
||||
.on("unlink", (fp) => rebuild(fp, "delete"))
|
||||
|
||||
return async () => {
|
||||
await watcher.close()
|
||||
}
|
||||
}
|
||||
|
||||
export default async (argv: Argv, mut: Mutex, clientRefresh: () => void) => {
|
||||
try {
|
||||
return await buildQuartz(argv, mut, clientRefresh)
|
||||
} catch (err) {
|
||||
trace("\nExiting Quartz due to a fatal error", err as Error)
|
||||
}
|
||||
}
|
|
@ -1,55 +0,0 @@
|
|||
import { ValidDateType } from "./components/Date"
|
||||
import { QuartzComponent } from "./components/types"
|
||||
import { PluginTypes } from "./plugins/types"
|
||||
import { Theme } from "./util/theme"
|
||||
|
||||
export type Analytics =
|
||||
| null
|
||||
| {
|
||||
provider: "plausible"
|
||||
}
|
||||
| {
|
||||
provider: "google"
|
||||
tagId: string
|
||||
}
|
||||
| {
|
||||
provider: "umami"
|
||||
websiteId: string
|
||||
}
|
||||
|
||||
export interface GlobalConfiguration {
|
||||
pageTitle: 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 */
|
||||
enablePopovers: boolean
|
||||
/** Analytics mode */
|
||||
analytics: Analytics
|
||||
/** Glob patterns to not search */
|
||||
ignorePatterns: string[]
|
||||
/** Whether to use created, modified, or published as the default type of date */
|
||||
defaultDateType: ValidDateType
|
||||
/** Base URL to use for CNAME files, sitemaps, and RSS feeds that require an absolute URL.
|
||||
* Quartz will avoid using this as much as possible and use relative URLs most of the time
|
||||
*/
|
||||
baseUrl?: string
|
||||
theme: Theme
|
||||
}
|
||||
|
||||
export interface QuartzConfig {
|
||||
configuration: GlobalConfiguration
|
||||
plugins: PluginTypes
|
||||
}
|
||||
|
||||
export interface FullPageLayout {
|
||||
head: QuartzComponent
|
||||
header: QuartzComponent[]
|
||||
beforeBody: QuartzComponent[]
|
||||
pageBody: QuartzComponent
|
||||
left: QuartzComponent[]
|
||||
right: QuartzComponent[]
|
||||
footer: QuartzComponent
|
||||
}
|
||||
|
||||
export type PageLayout = Pick<FullPageLayout, "beforeBody" | "left" | "right">
|
||||
export type SharedLayout = Pick<FullPageLayout, "head" | "header" | "footer">
|
|
@ -1,98 +0,0 @@
|
|||
export const CommonArgv = {
|
||||
directory: {
|
||||
string: true,
|
||||
alias: ["d"],
|
||||
default: "content",
|
||||
describe: "directory to look for content files",
|
||||
},
|
||||
verbose: {
|
||||
boolean: true,
|
||||
alias: ["v"],
|
||||
default: false,
|
||||
describe: "print out extra logging information",
|
||||
},
|
||||
}
|
||||
|
||||
export const CreateArgv = {
|
||||
...CommonArgv,
|
||||
source: {
|
||||
string: true,
|
||||
alias: ["s"],
|
||||
describe: "source directory to copy/create symlink from",
|
||||
},
|
||||
strategy: {
|
||||
string: true,
|
||||
alias: ["X"],
|
||||
choices: ["new", "copy", "symlink"],
|
||||
describe: "strategy for content folder setup",
|
||||
},
|
||||
links: {
|
||||
string: true,
|
||||
alias: ["l"],
|
||||
choices: ["absolute", "shortest", "relative"],
|
||||
describe: "strategy to resolve links",
|
||||
},
|
||||
}
|
||||
|
||||
export const SyncArgv = {
|
||||
...CommonArgv,
|
||||
commit: {
|
||||
boolean: true,
|
||||
default: true,
|
||||
describe: "create a git commit for your unsaved changes",
|
||||
},
|
||||
push: {
|
||||
boolean: true,
|
||||
default: true,
|
||||
describe: "push updates to your Quartz fork",
|
||||
},
|
||||
pull: {
|
||||
boolean: true,
|
||||
default: true,
|
||||
describe: "pull updates from your Quartz fork",
|
||||
},
|
||||
}
|
||||
|
||||
export const BuildArgv = {
|
||||
...CommonArgv,
|
||||
output: {
|
||||
string: true,
|
||||
alias: ["o"],
|
||||
default: "public",
|
||||
describe: "output folder for files",
|
||||
},
|
||||
serve: {
|
||||
boolean: true,
|
||||
default: false,
|
||||
describe: "run a local server to live-preview your Quartz",
|
||||
},
|
||||
baseDir: {
|
||||
string: true,
|
||||
default: "",
|
||||
describe: "base path to serve your local server on",
|
||||
},
|
||||
port: {
|
||||
number: true,
|
||||
default: 8080,
|
||||
describe: "port to serve Quartz on",
|
||||
},
|
||||
wsPort: {
|
||||
number: true,
|
||||
default: 3001,
|
||||
describe: "port to use for WebSocket-based hot-reload notifications",
|
||||
},
|
||||
remoteDevHost: {
|
||||
string: true,
|
||||
default: "",
|
||||
describe: "A URL override for the websocket connection if you are not developing on localhost",
|
||||
},
|
||||
bundleInfo: {
|
||||
boolean: true,
|
||||
default: false,
|
||||
describe: "show detailed bundle information",
|
||||
},
|
||||
concurrency: {
|
||||
number: true,
|
||||
describe: "how many threads to use to parse notes",
|
||||
},
|
||||
}
|
|
@ -1,15 +0,0 @@
|
|||
import path from "path"
|
||||
import { readFileSync } from "fs"
|
||||
|
||||
/**
|
||||
* All constants relating to helpers or handlers
|
||||
*/
|
||||
export const ORIGIN_NAME = "origin"
|
||||
export const UPSTREAM_NAME = "upstream"
|
||||
export const QUARTZ_SOURCE_BRANCH = "v4"
|
||||
export const cwd = process.cwd()
|
||||
export const cacheDir = path.join(cwd, ".quartz-cache")
|
||||
export const cacheFile = "./quartz/.quartz-cache/transpiled-build.mjs"
|
||||
export const fp = "./quartz/build.ts"
|
||||
export const { version } = JSON.parse(readFileSync("./package.json").toString())
|
||||
export const contentCacheFolder = path.join(cacheDir, "content-cache")
|
|
@ -1,511 +0,0 @@
|
|||
import { promises, readFileSync } from "fs"
|
||||
import path from "path"
|
||||
import esbuild from "esbuild"
|
||||
import chalk from "chalk"
|
||||
import { sassPlugin } from "esbuild-sass-plugin"
|
||||
import fs from "fs"
|
||||
import { intro, outro, select, text } from "@clack/prompts"
|
||||
import { rimraf } from "rimraf"
|
||||
import chokidar from "chokidar"
|
||||
import prettyBytes from "pretty-bytes"
|
||||
import { execSync, spawnSync } from "child_process"
|
||||
import http from "http"
|
||||
import serveHandler from "serve-handler"
|
||||
import { WebSocketServer } from "ws"
|
||||
import { randomUUID } from "crypto"
|
||||
import { Mutex } from "async-mutex"
|
||||
import { CreateArgv } from "./args.js"
|
||||
import {
|
||||
exitIfCancel,
|
||||
escapePath,
|
||||
gitPull,
|
||||
popContentFolder,
|
||||
stashContentFolder,
|
||||
} from "./helpers.js"
|
||||
import {
|
||||
UPSTREAM_NAME,
|
||||
QUARTZ_SOURCE_BRANCH,
|
||||
ORIGIN_NAME,
|
||||
version,
|
||||
fp,
|
||||
cacheFile,
|
||||
cwd,
|
||||
} from "./constants.js"
|
||||
|
||||
/**
|
||||
* Handles `npx quartz create`
|
||||
* @param {*} argv arguments for `create`
|
||||
*/
|
||||
export async function handleCreate(argv) {
|
||||
console.log()
|
||||
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 theyre valid
|
||||
if (setupStrategy && linkResolutionStrategy) {
|
||||
// If setup isn't, "new", source argument is required
|
||||
if (setupStrategy !== "new") {
|
||||
// Error handling
|
||||
if (!sourceDirectory) {
|
||||
outro(
|
||||
chalk.red(
|
||||
`Setup strategies (arg '${chalk.yellow(
|
||||
`-${CreateArgv.strategy.alias[0]}`,
|
||||
)}') other than '${chalk.yellow(
|
||||
"new",
|
||||
)}' require content folder argument ('${chalk.yellow(
|
||||
`-${CreateArgv.source.alias[0]}`,
|
||||
)}') to be set`,
|
||||
),
|
||||
)
|
||||
process.exit(1)
|
||||
} else {
|
||||
if (!fs.existsSync(sourceDirectory)) {
|
||||
outro(
|
||||
chalk.red(
|
||||
`Input directory to copy/symlink 'content' from not found ('${chalk.yellow(
|
||||
sourceDirectory,
|
||||
)}', invalid argument "${chalk.yellow(`-${CreateArgv.source.alias[0]}`)})`,
|
||||
),
|
||||
)
|
||||
process.exit(1)
|
||||
} else if (!fs.lstatSync(sourceDirectory).isDirectory()) {
|
||||
outro(
|
||||
chalk.red(
|
||||
`Source directory to copy/symlink 'content' from is not a directory (found file at '${chalk.yellow(
|
||||
sourceDirectory,
|
||||
)}', invalid argument ${chalk.yellow(`-${CreateArgv.source.alias[0]}`)}")`,
|
||||
),
|
||||
)
|
||||
process.exit(1)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Use cli process if cmd args werent provided
|
||||
if (!setupStrategy) {
|
||||
setupStrategy = exitIfCancel(
|
||||
await select({
|
||||
message: `Choose how to initialize the content in \`${contentFolder}\``,
|
||||
options: [
|
||||
{ value: "new", label: "Empty Quartz" },
|
||||
{ value: "copy", label: "Copy an existing folder", hint: "overwrites `content`" },
|
||||
{
|
||||
value: "symlink",
|
||||
label: "Symlink an existing folder",
|
||||
hint: "don't select this unless you know what you are doing!",
|
||||
},
|
||||
],
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
async function rmContentFolder() {
|
||||
const contentStat = await fs.promises.lstat(contentFolder)
|
||||
if (contentStat.isSymbolicLink()) {
|
||||
await fs.promises.unlink(contentFolder)
|
||||
} else {
|
||||
await rimraf(contentFolder)
|
||||
}
|
||||
}
|
||||
|
||||
await fs.promises.unlink(path.join(contentFolder, ".gitkeep"))
|
||||
if (setupStrategy === "copy" || setupStrategy === "symlink") {
|
||||
let originalFolder = sourceDirectory
|
||||
|
||||
// If input directory was not passed, use cli
|
||||
if (!sourceDirectory) {
|
||||
originalFolder = escapePath(
|
||||
exitIfCancel(
|
||||
await text({
|
||||
message: "Enter the full path to existing content folder",
|
||||
placeholder:
|
||||
"On most terminal emulators, you can drag and drop a folder into the window and it will paste the full path",
|
||||
validate(fp) {
|
||||
const fullPath = escapePath(fp)
|
||||
if (!fs.existsSync(fullPath)) {
|
||||
return "The given path doesn't exist"
|
||||
} else if (!fs.lstatSync(fullPath).isDirectory()) {
|
||||
return "The given path is not a folder"
|
||||
}
|
||||
},
|
||||
}),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
await rmContentFolder()
|
||||
if (setupStrategy === "copy") {
|
||||
await fs.promises.cp(originalFolder, contentFolder, {
|
||||
recursive: true,
|
||||
preserveTimestamps: true,
|
||||
})
|
||||
} else if (setupStrategy === "symlink") {
|
||||
await fs.promises.symlink(originalFolder, contentFolder, "dir")
|
||||
}
|
||||
} else if (setupStrategy === "new") {
|
||||
await fs.promises.writeFile(
|
||||
path.join(contentFolder, "index.md"),
|
||||
`---
|
||||
title: Welcome to Quartz
|
||||
---
|
||||
|
||||
This is a blank Quartz installation.
|
||||
See the [documentation](https://quartz.jzhao.xyz) for how to get started.
|
||||
`,
|
||||
)
|
||||
}
|
||||
|
||||
// Use cli process if cmd args werent provided
|
||||
if (!linkResolutionStrategy) {
|
||||
// get a preferred link resolution strategy
|
||||
linkResolutionStrategy = exitIfCancel(
|
||||
await select({
|
||||
message: `Choose how Quartz should resolve links in your content. You can change this later in \`quartz.config.ts\`.`,
|
||||
options: [
|
||||
{
|
||||
value: "absolute",
|
||||
label: "Treat links as absolute path",
|
||||
hint: "for content made for Quartz 3 and Hugo",
|
||||
},
|
||||
{
|
||||
value: "shortest",
|
||||
label: "Treat links as shortest path",
|
||||
hint: "for most Obsidian vaults",
|
||||
},
|
||||
{
|
||||
value: "relative",
|
||||
label: "Treat links as relative paths",
|
||||
hint: "for just normal Markdown files",
|
||||
},
|
||||
],
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
// now, do config changes
|
||||
const configFilePath = path.join(cwd, "quartz.config.ts")
|
||||
let configContent = await fs.promises.readFile(configFilePath, { encoding: "utf-8" })
|
||||
configContent = configContent.replace(
|
||||
/markdownLinkResolution: '(.+)'/,
|
||||
`markdownLinkResolution: '${linkResolutionStrategy}'`,
|
||||
)
|
||||
await fs.promises.writeFile(configFilePath, configContent)
|
||||
|
||||
outro(`You're all set! Not sure what to do next? Try:
|
||||
• Customizing Quartz a bit more by editing \`quartz.config.ts\`
|
||||
• Running \`npx quartz build --serve\` to preview your Quartz locally
|
||||
• Hosting your Quartz online (see: https://quartz.jzhao.xyz/hosting)
|
||||
`)
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles `npx quartz build`
|
||||
* @param {*} argv arguments for `build`
|
||||
*/
|
||||
export async function handleBuild(argv) {
|
||||
console.log(chalk.bgGreen.black(`\n Quartz v${version} \n`))
|
||||
const ctx = await esbuild.context({
|
||||
entryPoints: [fp],
|
||||
outfile: cacheFile,
|
||||
bundle: true,
|
||||
keepNames: true,
|
||||
minifyWhitespace: true,
|
||||
minifySyntax: true,
|
||||
platform: "node",
|
||||
format: "esm",
|
||||
jsx: "automatic",
|
||||
jsxImportSource: "preact",
|
||||
packages: "external",
|
||||
metafile: true,
|
||||
sourcemap: true,
|
||||
sourcesContent: false,
|
||||
plugins: [
|
||||
sassPlugin({
|
||||
type: "css-text",
|
||||
cssImports: true,
|
||||
}),
|
||||
{
|
||||
name: "inline-script-loader",
|
||||
setup(build) {
|
||||
build.onLoad({ filter: /\.inline\.(ts|js)$/ }, async (args) => {
|
||||
let text = await promises.readFile(args.path, "utf8")
|
||||
|
||||
// remove default exports that we manually inserted
|
||||
text = text.replace("export default", "")
|
||||
text = text.replace("export", "")
|
||||
|
||||
const sourcefile = path.relative(path.resolve("."), args.path)
|
||||
const resolveDir = path.dirname(sourcefile)
|
||||
const transpiled = await esbuild.build({
|
||||
stdin: {
|
||||
contents: text,
|
||||
loader: "ts",
|
||||
resolveDir,
|
||||
sourcefile,
|
||||
},
|
||||
write: false,
|
||||
bundle: true,
|
||||
platform: "browser",
|
||||
format: "esm",
|
||||
})
|
||||
const rawMod = transpiled.outputFiles[0].text
|
||||
return {
|
||||
contents: rawMod,
|
||||
loader: "text",
|
||||
}
|
||||
})
|
||||
},
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
const buildMutex = new Mutex()
|
||||
let lastBuildMs = 0
|
||||
let cleanupBuild = null
|
||||
const build = async (clientRefresh) => {
|
||||
const buildStart = new Date().getTime()
|
||||
lastBuildMs = buildStart
|
||||
const release = await buildMutex.acquire()
|
||||
if (lastBuildMs > buildStart) {
|
||||
release()
|
||||
return
|
||||
}
|
||||
|
||||
if (cleanupBuild) {
|
||||
await cleanupBuild()
|
||||
console.log(chalk.yellow("Detected a source code change, doing a hard rebuild..."))
|
||||
}
|
||||
|
||||
const result = await ctx.rebuild().catch((err) => {
|
||||
console.error(`${chalk.red("Couldn't parse Quartz configuration:")} ${fp}`)
|
||||
console.log(`Reason: ${chalk.grey(err)}`)
|
||||
process.exit(1)
|
||||
})
|
||||
release()
|
||||
|
||||
if (argv.bundleInfo) {
|
||||
const outputFileName = "quartz/.quartz-cache/transpiled-build.mjs"
|
||||
const meta = result.metafile.outputs[outputFileName]
|
||||
console.log(
|
||||
`Successfully transpiled ${Object.keys(meta.inputs).length} files (${prettyBytes(
|
||||
meta.bytes,
|
||||
)})`,
|
||||
)
|
||||
console.log(await esbuild.analyzeMetafile(result.metafile, { color: true }))
|
||||
}
|
||||
|
||||
// bypass module cache
|
||||
// https://github.com/nodejs/modules/issues/307
|
||||
const { default: buildQuartz } = await import(`../../${cacheFile}?update=${randomUUID()}`)
|
||||
// ^ this import is relative, so base "cacheFile" path can't be used
|
||||
|
||||
cleanupBuild = await buildQuartz(argv, buildMutex, clientRefresh)
|
||||
clientRefresh()
|
||||
}
|
||||
|
||||
if (argv.serve) {
|
||||
const connections = []
|
||||
const clientRefresh = () => connections.forEach((conn) => conn.send("rebuild"))
|
||||
|
||||
if (argv.baseDir !== "" && !argv.baseDir.startsWith("/")) {
|
||||
argv.baseDir = "/" + argv.baseDir
|
||||
}
|
||||
|
||||
await build(clientRefresh)
|
||||
const server = http.createServer(async (req, res) => {
|
||||
if (argv.baseDir && !req.url?.startsWith(argv.baseDir)) {
|
||||
console.log(
|
||||
chalk.red(
|
||||
`[404] ${req.url} (warning: link outside of site, this is likely a Quartz bug)`,
|
||||
),
|
||||
)
|
||||
res.writeHead(404)
|
||||
res.end()
|
||||
return
|
||||
}
|
||||
|
||||
// strip baseDir prefix
|
||||
req.url = req.url?.slice(argv.baseDir.length)
|
||||
|
||||
const serve = async () => {
|
||||
const release = await buildMutex.acquire()
|
||||
await serveHandler(req, res, {
|
||||
public: argv.output,
|
||||
directoryListing: false,
|
||||
headers: [
|
||||
{
|
||||
source: "**/*.html",
|
||||
headers: [{ key: "Content-Disposition", value: "inline" }],
|
||||
},
|
||||
],
|
||||
})
|
||||
const status = res.statusCode
|
||||
const statusString =
|
||||
status >= 200 && status < 300 ? chalk.green(`[${status}]`) : chalk.red(`[${status}]`)
|
||||
console.log(statusString + chalk.grey(` ${argv.baseDir}${req.url}`))
|
||||
release()
|
||||
}
|
||||
|
||||
const redirect = (newFp) => {
|
||||
newFp = argv.baseDir + newFp
|
||||
res.writeHead(302, {
|
||||
Location: newFp,
|
||||
})
|
||||
console.log(chalk.yellow("[302]") + chalk.grey(` ${argv.baseDir}${req.url} -> ${newFp}`))
|
||||
res.end()
|
||||
}
|
||||
|
||||
let fp = req.url?.split("?")[0] ?? "/"
|
||||
|
||||
// handle redirects
|
||||
if (fp.endsWith("/")) {
|
||||
// /trailing/
|
||||
// does /trailing/index.html exist? if so, serve it
|
||||
const indexFp = path.posix.join(fp, "index.html")
|
||||
if (fs.existsSync(path.posix.join(argv.output, indexFp))) {
|
||||
req.url = fp
|
||||
return serve()
|
||||
}
|
||||
|
||||
// does /trailing.html exist? if so, redirect to /trailing
|
||||
let base = fp.slice(0, -1)
|
||||
if (path.extname(base) === "") {
|
||||
base += ".html"
|
||||
}
|
||||
if (fs.existsSync(path.posix.join(argv.output, base))) {
|
||||
return redirect(fp.slice(0, -1))
|
||||
}
|
||||
} else {
|
||||
// /regular
|
||||
// does /regular.html exist? if so, serve it
|
||||
let base = fp
|
||||
if (path.extname(base) === "") {
|
||||
base += ".html"
|
||||
}
|
||||
if (fs.existsSync(path.posix.join(argv.output, base))) {
|
||||
req.url = fp
|
||||
return serve()
|
||||
}
|
||||
|
||||
// does /regular/index.html exist? if so, redirect to /regular/
|
||||
let indexFp = path.posix.join(fp, "index.html")
|
||||
if (fs.existsSync(path.posix.join(argv.output, indexFp))) {
|
||||
return redirect(fp + "/")
|
||||
}
|
||||
}
|
||||
|
||||
return serve()
|
||||
})
|
||||
server.listen(argv.port)
|
||||
const wss = new WebSocketServer({ port: argv.wsPort })
|
||||
wss.on("connection", (ws) => connections.push(ws))
|
||||
console.log(
|
||||
chalk.cyan(
|
||||
`Started a Quartz server listening at http://localhost:${argv.port}${argv.baseDir}`,
|
||||
),
|
||||
)
|
||||
console.log("hint: exit with ctrl+c")
|
||||
chokidar
|
||||
.watch(["**/*.ts", "**/*.tsx", "**/*.scss", "package.json"], {
|
||||
ignoreInitial: true,
|
||||
})
|
||||
.on("all", async () => {
|
||||
build(clientRefresh)
|
||||
})
|
||||
} else {
|
||||
await build(() => {})
|
||||
ctx.dispose()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles `npx quartz update`
|
||||
* @param {*} argv arguments for `update`
|
||||
*/
|
||||
export async function handleUpdate(argv) {
|
||||
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`,
|
||||
)
|
||||
await stashContentFolder(contentFolder)
|
||||
console.log(
|
||||
"Pulling updates... you may need to resolve some `git` conflicts if you've made changes to components or plugins.",
|
||||
)
|
||||
gitPull(UPSTREAM_NAME, QUARTZ_SOURCE_BRANCH)
|
||||
await popContentFolder(contentFolder)
|
||||
console.log("Ensuring dependencies are up to date")
|
||||
spawnSync("npm", ["i"], { stdio: "inherit" })
|
||||
console.log(chalk.green("Done!"))
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles `npx quartz restore`
|
||||
* @param {*} argv arguments for `restore`
|
||||
*/
|
||||
export async function handleRestore(argv) {
|
||||
const contentFolder = path.join(cwd, argv.directory)
|
||||
await popContentFolder(contentFolder)
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles `npx quartz sync`
|
||||
* @param {*} argv arguments for `sync`
|
||||
*/
|
||||
export async function handleSync(argv) {
|
||||
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(chalk.yellow("Detected symlink, trying to dereference before committing"))
|
||||
|
||||
// stash symlink file
|
||||
await stashContentFolder(contentFolder)
|
||||
|
||||
// follow symlink and copy content
|
||||
await fs.promises.cp(linkTarg, contentFolder, {
|
||||
recursive: true,
|
||||
preserveTimestamps: true,
|
||||
})
|
||||
}
|
||||
|
||||
const currentTimestamp = new Date().toLocaleString("en-US", {
|
||||
dateStyle: "medium",
|
||||
timeStyle: "short",
|
||||
})
|
||||
spawnSync("git", ["add", "."], { stdio: "inherit" })
|
||||
spawnSync("git", ["commit", "-m", `Quartz sync: ${currentTimestamp}`], { stdio: "inherit" })
|
||||
|
||||
if (contentStat.isSymbolicLink()) {
|
||||
// put symlink back
|
||||
await popContentFolder(contentFolder)
|
||||
}
|
||||
}
|
||||
|
||||
await stashContentFolder(contentFolder)
|
||||
|
||||
if (argv.pull) {
|
||||
console.log(
|
||||
"Pulling updates from your repository. You may need to resolve some `git` conflicts if you've made changes to components or plugins.",
|
||||
)
|
||||
gitPull(ORIGIN_NAME, QUARTZ_SOURCE_BRANCH)
|
||||
}
|
||||
|
||||
await popContentFolder(contentFolder)
|
||||
if (argv.push) {
|
||||
console.log("Pushing your changes")
|
||||
spawnSync("git", ["push", "-f", ORIGIN_NAME, QUARTZ_SOURCE_BRANCH], { stdio: "inherit" })
|
||||
}
|
||||
|
||||
console.log(chalk.green("Done!"))
|
||||
}
|
|
@ -1,52 +0,0 @@
|
|||
import { isCancel, outro } from "@clack/prompts"
|
||||
import chalk from "chalk"
|
||||
import { contentCacheFolder } from "./constants.js"
|
||||
import { spawnSync } from "child_process"
|
||||
import fs from "fs"
|
||||
|
||||
export function escapePath(fp) {
|
||||
return fp
|
||||
.replace(/\\ /g, " ") // unescape spaces
|
||||
.replace(/^".*"$/, "$1")
|
||||
.replace(/^'.*"$/, "$1")
|
||||
.trim()
|
||||
}
|
||||
|
||||
export function exitIfCancel(val) {
|
||||
if (isCancel(val)) {
|
||||
outro(chalk.red("Exiting"))
|
||||
process.exit(0)
|
||||
} else {
|
||||
return val
|
||||
}
|
||||
}
|
||||
|
||||
export async function stashContentFolder(contentFolder) {
|
||||
await fs.promises.rm(contentCacheFolder, { force: true, recursive: true })
|
||||
await fs.promises.cp(contentFolder, contentCacheFolder, {
|
||||
force: true,
|
||||
recursive: true,
|
||||
verbatimSymlinks: true,
|
||||
preserveTimestamps: true,
|
||||
})
|
||||
await fs.promises.rm(contentFolder, { force: true, recursive: true })
|
||||
}
|
||||
|
||||
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(`Error while pulling updates: ${out.stderr}`)
|
||||
}
|
||||
}
|
||||
|
||||
export async function popContentFolder(contentFolder) {
|
||||
await fs.promises.rm(contentFolder, { force: true, recursive: true })
|
||||
await fs.promises.cp(contentCacheFolder, contentFolder, {
|
||||
force: true,
|
||||
recursive: true,
|
||||
verbatimSymlinks: true,
|
||||
preserveTimestamps: true,
|
||||
})
|
||||
await fs.promises.rm(contentCacheFolder, { force: true, recursive: true })
|
||||
}
|
|
@ -1,17 +0,0 @@
|
|||
import { QuartzComponentConstructor, QuartzComponentProps } from "./types"
|
||||
|
||||
function ArticleTitle({ fileData }: QuartzComponentProps) {
|
||||
const title = fileData.frontmatter?.title
|
||||
if (title) {
|
||||
return <h1 class="article-title">{title}</h1>
|
||||
} else {
|
||||
return null
|
||||
}
|
||||
}
|
||||
ArticleTitle.css = `
|
||||
.article-title {
|
||||
margin: 2rem 0 0 0;
|
||||
}
|
||||
`
|
||||
|
||||
export default (() => ArticleTitle) satisfies QuartzComponentConstructor
|
|
@ -1,29 +0,0 @@
|
|||
import { QuartzComponentConstructor, QuartzComponentProps } from "./types"
|
||||
import style from "./styles/backlinks.scss"
|
||||
import { resolveRelative, simplifySlug } from "../util/path"
|
||||
|
||||
function Backlinks({ fileData, allFiles }: QuartzComponentProps) {
|
||||
const slug = simplifySlug(fileData.slug!)
|
||||
const backlinkFiles = allFiles.filter((file) => file.links?.includes(slug))
|
||||
return (
|
||||
<div class="backlinks">
|
||||
<h3>Backlinks</h3>
|
||||
<ul class="overflow">
|
||||
{backlinkFiles.length > 0 ? (
|
||||
backlinkFiles.map((f) => (
|
||||
<li>
|
||||
<a href={resolveRelative(fileData.slug!, f.slug!)} class="internal">
|
||||
{f.frontmatter?.title}
|
||||
</a>
|
||||
</li>
|
||||
))
|
||||
) : (
|
||||
<li>No backlinks found</li>
|
||||
)}
|
||||
</ul>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
Backlinks.css = style
|
||||
export default (() => Backlinks) satisfies QuartzComponentConstructor
|
|
@ -1,13 +0,0 @@
|
|||
// @ts-ignore
|
||||
import clipboardScript from "./scripts/clipboard.inline"
|
||||
import clipboardStyle from "./styles/clipboard.scss"
|
||||
import { QuartzComponentConstructor, QuartzComponentProps } from "./types"
|
||||
|
||||
function Body({ children }: QuartzComponentProps) {
|
||||
return <div id="quartz-body">{children}</div>
|
||||
}
|
||||
|
||||
Body.afterDOMLoaded = clipboardScript
|
||||
Body.css = clipboardStyle
|
||||
|
||||
export default (() => Body) satisfies QuartzComponentConstructor
|
|
@ -1,30 +0,0 @@
|
|||
import { formatDate, getDate } from "./Date"
|
||||
import { QuartzComponentConstructor, QuartzComponentProps } from "./types"
|
||||
import readingTime from "reading-time"
|
||||
|
||||
export default (() => {
|
||||
function ContentMetadata({ cfg, fileData }: QuartzComponentProps) {
|
||||
const text = fileData.text
|
||||
if (text) {
|
||||
const segments: string[] = []
|
||||
const { text: timeTaken, words: _words } = readingTime(text)
|
||||
|
||||
if (fileData.dates) {
|
||||
segments.push(formatDate(getDate(cfg, fileData)!))
|
||||
}
|
||||
|
||||
segments.push(timeTaken)
|
||||
return <p class="content-meta">{segments.join(", ")}</p>
|
||||
} else {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
ContentMetadata.css = `
|
||||
.content-meta {
|
||||
margin-top: 0;
|
||||
color: var(--gray);
|
||||
}
|
||||
`
|
||||
return ContentMetadata
|
||||
}) satisfies QuartzComponentConstructor
|
|
@ -1,51 +0,0 @@
|
|||
// @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 { QuartzComponentConstructor } from "./types"
|
||||
|
||||
function Darkmode() {
|
||||
return (
|
||||
<div class="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"
|
||||
id="dayIcon"
|
||||
x="0px"
|
||||
y="0px"
|
||||
viewBox="0 0 35 35"
|
||||
style="enable-background:new 0 0 35 35;"
|
||||
xmlSpace="preserve"
|
||||
>
|
||||
<title>Light mode</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"
|
||||
id="nightIcon"
|
||||
x="0px"
|
||||
y="0px"
|
||||
viewBox="0 0 100 100"
|
||||
style="enable-background='new 0 0 100 100'"
|
||||
xmlSpace="preserve"
|
||||
>
|
||||
<title>Dark mode</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>
|
||||
</label>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
Darkmode.beforeDOMLoaded = darkmodeScript
|
||||
Darkmode.css = styles
|
||||
|
||||
export default (() => Darkmode) satisfies QuartzComponentConstructor
|
|
@ -1,29 +0,0 @@
|
|||
import { GlobalConfiguration } from "../cfg"
|
||||
import { QuartzPluginData } from "../plugins/vfile"
|
||||
|
||||
interface Props {
|
||||
date: Date
|
||||
}
|
||||
|
||||
export type ValidDateType = keyof Required<QuartzPluginData>["dates"]
|
||||
|
||||
export function getDate(cfg: GlobalConfiguration, data: QuartzPluginData): Date | undefined {
|
||||
if (!cfg.defaultDateType) {
|
||||
throw new Error(
|
||||
`Field 'defaultDateType' was not set in the configuration object of quartz.config.ts. See https://quartz.jzhao.xyz/configuration#general-configuration for more details.`,
|
||||
)
|
||||
}
|
||||
return data.dates?.[cfg.defaultDateType]
|
||||
}
|
||||
|
||||
export function formatDate(d: Date): string {
|
||||
return d.toLocaleDateString("en-US", {
|
||||
year: "numeric",
|
||||
month: "short",
|
||||
day: "2-digit",
|
||||
})
|
||||
}
|
||||
|
||||
export function Date({ date }: Props) {
|
||||
return <>{formatDate(date)}</>
|
||||
}
|
|
@ -1,18 +0,0 @@
|
|||
import { QuartzComponent, QuartzComponentConstructor, QuartzComponentProps } from "./types"
|
||||
|
||||
export default ((component?: QuartzComponent) => {
|
||||
if (component) {
|
||||
const Component = component
|
||||
function DesktopOnly(props: QuartzComponentProps) {
|
||||
return <Component displayClass="desktop-only" {...props} />
|
||||
}
|
||||
|
||||
DesktopOnly.displayName = component.displayName
|
||||
DesktopOnly.afterDOMLoaded = component?.afterDOMLoaded
|
||||
DesktopOnly.beforeDOMLoaded = component?.beforeDOMLoaded
|
||||
DesktopOnly.css = component?.css
|
||||
return DesktopOnly
|
||||
} else {
|
||||
return () => <></>
|
||||
}
|
||||
}) satisfies QuartzComponentConstructor
|
|
@ -1,110 +0,0 @@
|
|||
import { QuartzComponentConstructor, QuartzComponentProps } from "./types"
|
||||
import explorerStyle from "./styles/explorer.scss"
|
||||
|
||||
// @ts-ignore
|
||||
import script from "./scripts/explorer.inline"
|
||||
import { ExplorerNode, FileNode, Options } from "./ExplorerNode"
|
||||
|
||||
// Options interface defined in `ExplorerNode` to avoid circular dependency
|
||||
const defaultOptions = {
|
||||
title: "Explorer",
|
||||
folderClickBehavior: "collapse",
|
||||
folderDefaultState: "collapsed",
|
||||
useSavedState: true,
|
||||
// Sort order: folders first, then files. Sort folders and files alphabetically
|
||||
sortFn: (a, b) => {
|
||||
if ((!a.file && !b.file) || (a.file && b.file)) {
|
||||
return a.name.localeCompare(b.name)
|
||||
}
|
||||
if (a.file && !b.file) {
|
||||
return 1
|
||||
} else {
|
||||
return -1
|
||||
}
|
||||
},
|
||||
order: ["filter", "map", "sort"],
|
||||
} satisfies Options
|
||||
|
||||
export default ((userOpts?: Partial<Options>) => {
|
||||
function Explorer({ allFiles, displayClass, fileData }: QuartzComponentProps) {
|
||||
// Parse config
|
||||
const opts: Options = { ...defaultOptions, ...userOpts }
|
||||
|
||||
// Construct tree from allFiles
|
||||
const fileTree = new FileNode("")
|
||||
allFiles.forEach((file) => fileTree.add(file, 1))
|
||||
|
||||
/**
|
||||
* Keys of this object must match corresponding function name of `FileNode`,
|
||||
* while values must be the argument that will be passed to the function.
|
||||
*
|
||||
* e.g. entry for FileNode.sort: `sort: opts.sortFn` (value is sort function from options)
|
||||
*/
|
||||
const functions = {
|
||||
map: opts.mapFn,
|
||||
sort: opts.sortFn,
|
||||
filter: opts.filterFn,
|
||||
}
|
||||
|
||||
// Execute all functions (sort, filter, map) that were provided (if none were provided, only default "sort" is applied)
|
||||
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 (functions[functionName]) {
|
||||
// for every entry in order, call matching function in FileNode and pass matching argument
|
||||
// e.g. i = 0; functionName = "filter"
|
||||
// converted to: (if opts.filterFn) => fileTree.filter(opts.filterFn)
|
||||
|
||||
// @ts-ignore
|
||||
// typescript cant statically check these dynamic references, so manually make sure reference is valid and ignore warning
|
||||
fileTree[functionName].call(fileTree, functions[functionName])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Get all folders of tree. Initialize with collapsed state
|
||||
const folders = fileTree.getFolderPaths(opts.folderDefaultState === "collapsed")
|
||||
|
||||
// Stringify to pass json tree as data attribute ([data-tree])
|
||||
const jsonTree = JSON.stringify(folders)
|
||||
|
||||
return (
|
||||
<div class={`explorer ${displayClass}`}>
|
||||
<button
|
||||
type="button"
|
||||
id="explorer"
|
||||
data-behavior={opts.folderClickBehavior}
|
||||
data-collapsed={opts.folderDefaultState}
|
||||
data-savestate={opts.useSavedState}
|
||||
data-tree={jsonTree}
|
||||
>
|
||||
<h3>{opts.title}</h3>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="14"
|
||||
height="14"
|
||||
viewBox="5 8 14 8"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
class="fold"
|
||||
>
|
||||
<polyline points="6 9 12 15 18 9"></polyline>
|
||||
</svg>
|
||||
</button>
|
||||
<div id="explorer-content">
|
||||
<ul class="overflow" id="explorer-ul">
|
||||
<ExplorerNode node={fileTree} opts={opts} fileData={fileData} />
|
||||
<div id="explorer-end" />
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
Explorer.css = explorerStyle
|
||||
Explorer.afterDOMLoaded = script
|
||||
return Explorer
|
||||
}) satisfies QuartzComponentConstructor
|
|
@ -1,215 +0,0 @@
|
|||
// @ts-ignore
|
||||
import { QuartzPluginData } from "../plugins/vfile"
|
||||
import { resolveRelative } 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
|
||||
}
|
||||
|
||||
// Structure to add all files into a tree
|
||||
export class FileNode {
|
||||
children: FileNode[]
|
||||
name: string
|
||||
file: QuartzPluginData | null
|
||||
depth: number
|
||||
|
||||
constructor(name: string, file?: QuartzPluginData, depth?: number) {
|
||||
this.children = []
|
||||
this.name = name
|
||||
this.file = file ? structuredClone(file) : null
|
||||
this.depth = depth ?? 0
|
||||
}
|
||||
|
||||
private insert(file: DataWrapper) {
|
||||
if (file.path.length === 1) {
|
||||
this.children.push(new FileNode(file.file.frontmatter!.title, file.file, this.depth + 1))
|
||||
} else {
|
||||
const next = file.path[0]
|
||||
file.path = file.path.splice(1)
|
||||
for (const child of this.children) {
|
||||
if (child.name === next) {
|
||||
child.insert(file)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
const newChild = new FileNode(next, undefined, this.depth + 1)
|
||||
newChild.insert(file)
|
||||
this.children.push(newChild)
|
||||
}
|
||||
}
|
||||
|
||||
// Add new file to tree
|
||||
add(file: QuartzPluginData, splice: number = 0) {
|
||||
this.insert({ file, path: file.filePath!.split("/").splice(splice) })
|
||||
}
|
||||
|
||||
// Print tree structure (for debugging)
|
||||
print(depth: number = 0) {
|
||||
let folderChar = ""
|
||||
if (!this.file) folderChar = "|"
|
||||
console.log("-".repeat(depth), folderChar, this.name, this.depth)
|
||||
this.children.forEach((e) => e.print(depth + 1))
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 = currentPath + (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 pathOld = fullPath ? fullPath : ""
|
||||
let folderPath = ""
|
||||
if (node.name !== "") {
|
||||
folderPath = `${pathOld}/${node.name}`
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
{node.file ? (
|
||||
// Single file node
|
||||
<li key={node.file.slug}>
|
||||
<a href={resolveRelative(fileData.slug!, node.file.slug!)} data-for={node.file.slug}>
|
||||
{node.name}
|
||||
</a>
|
||||
</li>
|
||||
) : (
|
||||
<div>
|
||||
{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 */}
|
||||
<li key={node.name} data-folderpath={folderPath}>
|
||||
{folderBehavior === "link" ? (
|
||||
<a href={`${folderPath}`} data-for={node.name} class="folder-title">
|
||||
{node.name}
|
||||
</a>
|
||||
) : (
|
||||
<button class="folder-button">
|
||||
<h3 class="folder-title">{node.name}</h3>
|
||||
</button>
|
||||
)}
|
||||
</li>
|
||||
</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>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
|
@ -1,32 +0,0 @@
|
|||
import { QuartzComponentConstructor } from "./types"
|
||||
import style from "./styles/footer.scss"
|
||||
import { version } from "../../package.json"
|
||||
|
||||
interface Options {
|
||||
links: Record<string, string>
|
||||
}
|
||||
|
||||
export default ((opts?: Options) => {
|
||||
function Footer() {
|
||||
const year = new Date().getFullYear()
|
||||
const links = opts?.links ?? []
|
||||
return (
|
||||
<footer>
|
||||
<hr />
|
||||
<p>
|
||||
Created with <a href="https://quartz.jzhao.xyz/">Quartz v{version}</a>, © {year}
|
||||
</p>
|
||||
<ul>
|
||||
{Object.entries(links).map(([text, link]) => (
|
||||
<li>
|
||||
<a href={link}>{text}</a>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</footer>
|
||||
)
|
||||
}
|
||||
|
||||
Footer.css = style
|
||||
return Footer
|
||||
}) satisfies QuartzComponentConstructor
|
|
@ -1,100 +0,0 @@
|
|||
import { QuartzComponentConstructor } from "./types"
|
||||
// @ts-ignore
|
||||
import script from "./scripts/graph.inline"
|
||||
import style from "./styles/graph.scss"
|
||||
|
||||
export interface D3Config {
|
||||
drag: boolean
|
||||
zoom: boolean
|
||||
depth: number
|
||||
scale: number
|
||||
repelForce: number
|
||||
centerForce: number
|
||||
linkDistance: number
|
||||
fontSize: number
|
||||
opacityScale: number
|
||||
removeTags: string[]
|
||||
showTags: boolean
|
||||
}
|
||||
|
||||
interface GraphOptions {
|
||||
localGraph: Partial<D3Config> | undefined
|
||||
globalGraph: Partial<D3Config> | undefined
|
||||
}
|
||||
|
||||
const defaultOptions: GraphOptions = {
|
||||
localGraph: {
|
||||
drag: true,
|
||||
zoom: true,
|
||||
depth: 1,
|
||||
scale: 1.1,
|
||||
repelForce: 0.5,
|
||||
centerForce: 0.3,
|
||||
linkDistance: 30,
|
||||
fontSize: 0.6,
|
||||
opacityScale: 1,
|
||||
showTags: true,
|
||||
removeTags: [],
|
||||
},
|
||||
globalGraph: {
|
||||
drag: true,
|
||||
zoom: true,
|
||||
depth: -1,
|
||||
scale: 0.9,
|
||||
repelForce: 0.5,
|
||||
centerForce: 0.3,
|
||||
linkDistance: 30,
|
||||
fontSize: 0.6,
|
||||
opacityScale: 1,
|
||||
showTags: true,
|
||||
removeTags: [],
|
||||
},
|
||||
}
|
||||
|
||||
export default ((opts?: GraphOptions) => {
|
||||
function Graph() {
|
||||
const localGraph = { ...defaultOptions.localGraph, ...opts?.localGraph }
|
||||
const globalGraph = { ...defaultOptions.globalGraph, ...opts?.globalGraph }
|
||||
return (
|
||||
<div class="graph">
|
||||
<h3>Graph View</h3>
|
||||
<div class="graph-outer">
|
||||
<div id="graph-container" data-cfg={JSON.stringify(localGraph)}></div>
|
||||
<svg
|
||||
version="1.1"
|
||||
id="global-graph-icon"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
xmlnsXlink="http://www.w3.org/1999/xlink"
|
||||
x="0px"
|
||||
y="0px"
|
||||
viewBox="0 0 55 55"
|
||||
fill="currentColor"
|
||||
xmlSpace="preserve"
|
||||
>
|
||||
<path
|
||||
d="M49,0c-3.309,0-6,2.691-6,6c0,1.035,0.263,2.009,0.726,2.86l-9.829,9.829C32.542,17.634,30.846,17,29,17
|
||||
s-3.542,0.634-4.898,1.688l-7.669-7.669C16.785,10.424,17,9.74,17,9c0-2.206-1.794-4-4-4S9,6.794,9,9s1.794,4,4,4
|
||||
c0.74,0,1.424-0.215,2.019-0.567l7.669,7.669C21.634,21.458,21,23.154,21,25s0.634,3.542,1.688,4.897L10.024,42.562
|
||||
C8.958,41.595,7.549,41,6,41c-3.309,0-6,2.691-6,6s2.691,6,6,6s6-2.691,6-6c0-1.035-0.263-2.009-0.726-2.86l12.829-12.829
|
||||
c1.106,0.86,2.44,1.436,3.898,1.619v10.16c-2.833,0.478-5,2.942-5,5.91c0,3.309,2.691,6,6,6s6-2.691,6-6c0-2.967-2.167-5.431-5-5.91
|
||||
v-10.16c1.458-0.183,2.792-0.759,3.898-1.619l7.669,7.669C41.215,39.576,41,40.26,41,41c0,2.206,1.794,4,4,4s4-1.794,4-4
|
||||
s-1.794-4-4-4c-0.74,0-1.424,0.215-2.019,0.567l-7.669-7.669C36.366,28.542,37,26.846,37,25s-0.634-3.542-1.688-4.897l9.665-9.665
|
||||
C46.042,11.405,47.451,12,49,12c3.309,0,6-2.691,6-6S52.309,0,49,0z M11,9c0-1.103,0.897-2,2-2s2,0.897,2,2s-0.897,2-2,2
|
||||
S11,10.103,11,9z M6,51c-2.206,0-4-1.794-4-4s1.794-4,4-4s4,1.794,4,4S8.206,51,6,51z M33,49c0,2.206-1.794,4-4,4s-4-1.794-4-4
|
||||
s1.794-4,4-4S33,46.794,33,49z M29,31c-3.309,0-6-2.691-6-6s2.691-6,6-6s6,2.691,6,6S32.309,31,29,31z M47,41c0,1.103-0.897,2-2,2
|
||||
s-2-0.897-2-2s0.897-2,2-2S47,39.897,47,41z M49,10c-2.206,0-4-1.794-4-4s1.794-4,4-4s4,1.794,4,4S51.206,10,49,10z"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
<div id="global-graph-outer">
|
||||
<div id="global-graph-container" data-cfg={JSON.stringify(globalGraph)}></div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
Graph.css = style
|
||||
Graph.afterDOMLoaded = script
|
||||
|
||||
return Graph
|
||||
}) satisfies QuartzComponentConstructor
|
|
@ -1,44 +0,0 @@
|
|||
import { FullSlug, _stripSlashes, joinSegments, pathToRoot } from "../util/path"
|
||||
import { JSResourceToScriptElement } from "../util/resources"
|
||||
import { QuartzComponentConstructor, QuartzComponentProps } from "./types"
|
||||
|
||||
export default (() => {
|
||||
function Head({ cfg, fileData, externalResources }: QuartzComponentProps) {
|
||||
const title = fileData.frontmatter?.title ?? "Untitled"
|
||||
const description = fileData.description?.trim() ?? "No description provided"
|
||||
const { css, js } = externalResources
|
||||
|
||||
const url = new URL(`https://${cfg.baseUrl ?? "example.com"}`)
|
||||
const path = url.pathname as FullSlug
|
||||
const baseDir = fileData.slug === "404" ? path : pathToRoot(fileData.slug!)
|
||||
|
||||
const iconPath = joinSegments(baseDir, "static/icon.png")
|
||||
const ogImagePath = `https://${cfg.baseUrl}/static/og-image.png`
|
||||
|
||||
return (
|
||||
<head>
|
||||
<title>{title}</title>
|
||||
<meta charSet="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<meta property="og:title" content={title} />
|
||||
<meta property="og:description" content={description} />
|
||||
{cfg.baseUrl && <meta property="og:image" content={ogImagePath} />}
|
||||
<meta property="og:width" content="1200" />
|
||||
<meta property="og:height" content="675" />
|
||||
<link rel="icon" href={iconPath} />
|
||||
<meta name="description" content={description} />
|
||||
<meta name="generator" content="Quartz" />
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" />
|
||||
{css.map((href) => (
|
||||
<link key={href} href={href} rel="stylesheet" type="text/css" spa-preserve />
|
||||
))}
|
||||
{js
|
||||
.filter((resource) => resource.loadTime === "beforeDOMReady")
|
||||
.map((res) => JSResourceToScriptElement(res, true))}
|
||||
</head>
|
||||
)
|
||||
}
|
||||
|
||||
return Head
|
||||
}) satisfies QuartzComponentConstructor
|
|
@ -1,22 +0,0 @@
|
|||
import { QuartzComponentConstructor, QuartzComponentProps } from "./types"
|
||||
|
||||
function Header({ children }: QuartzComponentProps) {
|
||||
return children.length > 0 ? <header>{children}</header> : null
|
||||
}
|
||||
|
||||
Header.css = `
|
||||
header {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
margin: 2rem 0;
|
||||
gap: 1.5rem;
|
||||
}
|
||||
|
||||
header h1 {
|
||||
margin: 0;
|
||||
flex: auto;
|
||||
}
|
||||
`
|
||||
|
||||
export default (() => Header) satisfies QuartzComponentConstructor
|
|
@ -1,18 +0,0 @@
|
|||
import { QuartzComponent, QuartzComponentConstructor, QuartzComponentProps } from "./types"
|
||||
|
||||
export default ((component?: QuartzComponent) => {
|
||||
if (component) {
|
||||
const Component = component
|
||||
function MobileOnly(props: QuartzComponentProps) {
|
||||
return <Component displayClass="mobile-only" {...props} />
|
||||
}
|
||||
|
||||
MobileOnly.displayName = component.displayName
|
||||
MobileOnly.afterDOMLoaded = component?.afterDOMLoaded
|
||||
MobileOnly.beforeDOMLoaded = component?.beforeDOMLoaded
|
||||
MobileOnly.css = component?.css
|
||||
return MobileOnly
|
||||
} else {
|
||||
return () => <></>
|
||||
}
|
||||
}) satisfies QuartzComponentConstructor
|
|
@ -1,87 +0,0 @@
|
|||
import { FullSlug, resolveRelative } from "../util/path"
|
||||
import { QuartzPluginData } from "../plugins/vfile"
|
||||
import { Date, getDate } from "./Date"
|
||||
import { QuartzComponentProps } from "./types"
|
||||
import { GlobalConfiguration } from "../cfg"
|
||||
|
||||
export function byDateAndAlphabetical(
|
||||
cfg: GlobalConfiguration,
|
||||
): (f1: QuartzPluginData, f2: QuartzPluginData) => number {
|
||||
return (f1, f2) => {
|
||||
if (f1.dates && f2.dates) {
|
||||
// sort descending
|
||||
return getDate(cfg, f2)!.getTime() - getDate(cfg, f1)!.getTime()
|
||||
} else if (f1.dates && !f2.dates) {
|
||||
// prioritize files with dates
|
||||
return -1
|
||||
} else if (!f1.dates && f2.dates) {
|
||||
return 1
|
||||
}
|
||||
|
||||
// otherwise, sort lexographically by title
|
||||
const f1Title = f1.frontmatter?.title.toLowerCase() ?? ""
|
||||
const f2Title = f2.frontmatter?.title.toLowerCase() ?? ""
|
||||
return f1Title.localeCompare(f2Title)
|
||||
}
|
||||
}
|
||||
|
||||
type Props = {
|
||||
limit?: number
|
||||
} & QuartzComponentProps
|
||||
|
||||
export function PageList({ cfg, fileData, allFiles, limit }: Props) {
|
||||
let list = allFiles.sort(byDateAndAlphabetical(cfg))
|
||||
if (limit) {
|
||||
list = list.slice(0, limit)
|
||||
}
|
||||
|
||||
return (
|
||||
<ul class="section-ul">
|
||||
{list.map((page) => {
|
||||
const title = page.frontmatter?.title
|
||||
const tags = page.frontmatter?.tags ?? []
|
||||
|
||||
return (
|
||||
<li class="section-li">
|
||||
<div class="section">
|
||||
{page.dates && (
|
||||
<p class="meta">
|
||||
<Date date={getDate(cfg, page)!} />
|
||||
</p>
|
||||
)}
|
||||
<div class="desc">
|
||||
<h3>
|
||||
<a href={resolveRelative(fileData.slug!, page.slug!)} class="internal">
|
||||
{title}
|
||||
</a>
|
||||
</h3>
|
||||
</div>
|
||||
<ul class="tags">
|
||||
{tags.map((tag) => (
|
||||
<li>
|
||||
<a
|
||||
class="internal tag-link"
|
||||
href={resolveRelative(fileData.slug!, `tags/${tag}` as FullSlug)}
|
||||
>
|
||||
#{tag}
|
||||
</a>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
)
|
||||
}
|
||||
|
||||
PageList.css = `
|
||||
.section h3 {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.section > .tags {
|
||||
margin: 0;
|
||||
}
|
||||
`
|
|
@ -1,20 +0,0 @@
|
|||
import { pathToRoot } from "../util/path"
|
||||
import { QuartzComponentConstructor, QuartzComponentProps } from "./types"
|
||||
|
||||
function PageTitle({ fileData, cfg }: QuartzComponentProps) {
|
||||
const title = cfg?.pageTitle ?? "Untitled Quartz"
|
||||
const baseDir = pathToRoot(fileData.slug!)
|
||||
return (
|
||||
<h1 class="page-title">
|
||||
<a href={baseDir}>{title}</a>
|
||||
</h1>
|
||||
)
|
||||
}
|
||||
|
||||
PageTitle.css = `
|
||||
.page-title {
|
||||
margin: 0;
|
||||
}
|
||||
`
|
||||
|
||||
export default (() => PageTitle) satisfies QuartzComponentConstructor
|
|
@ -1,82 +0,0 @@
|
|||
import { QuartzComponentConstructor, QuartzComponentProps } from "./types"
|
||||
import { FullSlug, SimpleSlug, resolveRelative } from "../util/path"
|
||||
import { QuartzPluginData } from "../plugins/vfile"
|
||||
import { byDateAndAlphabetical } from "./PageList"
|
||||
import style from "./styles/recentNotes.scss"
|
||||
import { Date, getDate } from "./Date"
|
||||
import { GlobalConfiguration } from "../cfg"
|
||||
|
||||
interface Options {
|
||||
title: string
|
||||
limit: number
|
||||
linkToMore: SimpleSlug | false
|
||||
filter: (f: QuartzPluginData) => boolean
|
||||
sort: (f1: QuartzPluginData, f2: QuartzPluginData) => number
|
||||
}
|
||||
|
||||
const defaultOptions = (cfg: GlobalConfiguration): Options => ({
|
||||
title: "Recent Notes",
|
||||
limit: 3,
|
||||
linkToMore: false,
|
||||
filter: () => true,
|
||||
sort: byDateAndAlphabetical(cfg),
|
||||
})
|
||||
|
||||
export default ((userOpts?: Partial<Options>) => {
|
||||
function RecentNotes(props: QuartzComponentProps) {
|
||||
const { allFiles, fileData, displayClass, cfg } = props
|
||||
const opts = { ...defaultOptions(cfg), ...userOpts }
|
||||
const pages = allFiles.filter(opts.filter).sort(opts.sort)
|
||||
const remaining = Math.max(0, pages.length - opts.limit)
|
||||
return (
|
||||
<div class={`recent-notes ${displayClass}`}>
|
||||
<h3>{opts.title}</h3>
|
||||
<ul class="recent-ul">
|
||||
{pages.slice(0, opts.limit).map((page) => {
|
||||
const title = page.frontmatter?.title
|
||||
const tags = page.frontmatter?.tags ?? []
|
||||
|
||||
return (
|
||||
<li class="recent-li">
|
||||
<div class="section">
|
||||
<div class="desc">
|
||||
<h3>
|
||||
<a href={resolveRelative(fileData.slug!, page.slug!)} class="internal">
|
||||
{title}
|
||||
</a>
|
||||
</h3>
|
||||
</div>
|
||||
{page.dates && (
|
||||
<p class="meta">
|
||||
<Date date={getDate(cfg, page)!} />
|
||||
</p>
|
||||
)}
|
||||
<ul class="tags">
|
||||
{tags.map((tag) => (
|
||||
<li>
|
||||
<a
|
||||
class="internal tag-link"
|
||||
href={resolveRelative(fileData.slug!, `tags/${tag}` as FullSlug)}
|
||||
>
|
||||
#{tag}
|
||||
</a>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
{opts.linkToMore && remaining > 0 && (
|
||||
<p>
|
||||
<a href={resolveRelative(fileData.slug!, opts.linkToMore)}>See {remaining} more →</a>
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
RecentNotes.css = style
|
||||
return RecentNotes
|
||||
}) satisfies QuartzComponentConstructor
|
|
@ -1,49 +0,0 @@
|
|||
import { QuartzComponentConstructor } from "./types"
|
||||
import style from "./styles/search.scss"
|
||||
// @ts-ignore
|
||||
import script from "./scripts/search.inline"
|
||||
|
||||
export default (() => {
|
||||
function Search() {
|
||||
return (
|
||||
<div class="search">
|
||||
<div id="search-icon">
|
||||
<p>Search</p>
|
||||
<div></div>
|
||||
<svg
|
||||
tabIndex={0}
|
||||
aria-labelledby="title desc"
|
||||
role="img"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 19.9 19.7"
|
||||
>
|
||||
<title id="title">Search</title>
|
||||
<desc id="desc">Search</desc>
|
||||
<g class="search-path" fill="none">
|
||||
<path stroke-linecap="square" d="M18.5 18.3l-5.4-5.4" />
|
||||
<circle cx="8" cy="8" r="7" />
|
||||
</g>
|
||||
</svg>
|
||||
</div>
|
||||
<div id="search-container">
|
||||
<div id="search-space">
|
||||
<input
|
||||
autocomplete="off"
|
||||
id="search-bar"
|
||||
name="search"
|
||||
type="text"
|
||||
aria-label="Search for something"
|
||||
placeholder="Search for something"
|
||||
/>
|
||||
<div id="results-container"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
Search.afterDOMLoaded = script
|
||||
Search.css = style
|
||||
|
||||
return Search
|
||||
}) satisfies QuartzComponentConstructor
|
|
@ -1,8 +0,0 @@
|
|||
import { QuartzComponentConstructor, QuartzComponentProps } from "./types"
|
||||
|
||||
function Spacer({ displayClass }: QuartzComponentProps) {
|
||||
const className = displayClass ? `spacer ${displayClass}` : "spacer"
|
||||
return <div class={className}></div>
|
||||
}
|
||||
|
||||
export default (() => Spacer) satisfies QuartzComponentConstructor
|
|
@ -1,84 +0,0 @@
|
|||
import { QuartzComponentConstructor, QuartzComponentProps } from "./types"
|
||||
import legacyStyle from "./styles/legacyToc.scss"
|
||||
import modernStyle from "./styles/toc.scss"
|
||||
|
||||
// @ts-ignore
|
||||
import script from "./scripts/toc.inline"
|
||||
|
||||
interface Options {
|
||||
layout: "modern" | "legacy"
|
||||
}
|
||||
|
||||
const defaultOptions: Options = {
|
||||
layout: "modern",
|
||||
}
|
||||
|
||||
function TableOfContents({ fileData, displayClass }: QuartzComponentProps) {
|
||||
if (!fileData.toc) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<div class={`toc ${displayClass}`}>
|
||||
<button type="button" id="toc">
|
||||
<h3>Table of Contents</h3>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
class="fold"
|
||||
>
|
||||
<polyline points="6 9 12 15 18 9"></polyline>
|
||||
</svg>
|
||||
</button>
|
||||
<div id="toc-content">
|
||||
<ul class="overflow">
|
||||
{fileData.toc.map((tocEntry) => (
|
||||
<li key={tocEntry.slug} class={`depth-${tocEntry.depth}`}>
|
||||
<a href={`#${tocEntry.slug}`} data-for={tocEntry.slug}>
|
||||
{tocEntry.text}
|
||||
</a>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
TableOfContents.css = modernStyle
|
||||
TableOfContents.afterDOMLoaded = script
|
||||
|
||||
function LegacyTableOfContents({ fileData }: QuartzComponentProps) {
|
||||
if (!fileData.toc) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<details id="toc" open>
|
||||
<summary>
|
||||
<h3>Table of Contents</h3>
|
||||
</summary>
|
||||
<ul>
|
||||
{fileData.toc.map((tocEntry) => (
|
||||
<li key={tocEntry.slug} class={`depth-${tocEntry.depth}`}>
|
||||
<a href={`#${tocEntry.slug}`} data-for={tocEntry.slug}>
|
||||
{tocEntry.text}
|
||||
</a>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</details>
|
||||
)
|
||||
}
|
||||
LegacyTableOfContents.css = legacyStyle
|
||||
|
||||
export default ((opts?: Partial<Options>) => {
|
||||
const layout = opts?.layout ?? defaultOptions.layout
|
||||
return layout === "modern" ? TableOfContents : LegacyTableOfContents
|
||||
}) satisfies QuartzComponentConstructor
|
|
@ -1,52 +0,0 @@
|
|||
import { pathToRoot, slugTag } from "../util/path"
|
||||
import { QuartzComponentConstructor, QuartzComponentProps } from "./types"
|
||||
|
||||
function TagList({ fileData }: QuartzComponentProps) {
|
||||
const tags = fileData.frontmatter?.tags
|
||||
const baseDir = pathToRoot(fileData.slug!)
|
||||
if (tags && tags.length > 0) {
|
||||
return (
|
||||
<ul class="tags">
|
||||
{tags.map((tag) => {
|
||||
const display = `#${tag}`
|
||||
const linkDest = baseDir + `/tags/${slugTag(tag)}`
|
||||
return (
|
||||
<li>
|
||||
<a href={linkDest} class="internal tag-link">
|
||||
{display}
|
||||
</a>
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
)
|
||||
} else {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
TagList.css = `
|
||||
.tags {
|
||||
list-style: none;
|
||||
display: flex;
|
||||
padding-left: 0;
|
||||
gap: 0.4rem;
|
||||
margin: 1rem 0;
|
||||
}
|
||||
|
||||
.tags > li {
|
||||
display: inline-block;
|
||||
white-space: nowrap;
|
||||
margin: 0;
|
||||
overflow-wrap: normal;
|
||||
}
|
||||
|
||||
a.tag-link {
|
||||
border-radius: 8px;
|
||||
background-color: var(--highlight);
|
||||
padding: 0.2rem 0.4rem;
|
||||
margin: 0 0.1rem;
|
||||
}
|
||||
`
|
||||
|
||||
export default (() => TagList) satisfies QuartzComponentConstructor
|
|
@ -1,43 +0,0 @@
|
|||
import Content from "./pages/Content"
|
||||
import TagContent from "./pages/TagContent"
|
||||
import FolderContent from "./pages/FolderContent"
|
||||
import NotFound from "./pages/404"
|
||||
import ArticleTitle from "./ArticleTitle"
|
||||
import Darkmode from "./Darkmode"
|
||||
import Head from "./Head"
|
||||
import PageTitle from "./PageTitle"
|
||||
import ContentMeta from "./ContentMeta"
|
||||
import Spacer from "./Spacer"
|
||||
import TableOfContents from "./TableOfContents"
|
||||
import Explorer from "./Explorer"
|
||||
import TagList from "./TagList"
|
||||
import Graph from "./Graph"
|
||||
import Backlinks from "./Backlinks"
|
||||
import Search from "./Search"
|
||||
import Footer from "./Footer"
|
||||
import DesktopOnly from "./DesktopOnly"
|
||||
import MobileOnly from "./MobileOnly"
|
||||
import RecentNotes from "./RecentNotes"
|
||||
|
||||
export {
|
||||
ArticleTitle,
|
||||
Content,
|
||||
TagContent,
|
||||
FolderContent,
|
||||
Darkmode,
|
||||
Head,
|
||||
PageTitle,
|
||||
ContentMeta,
|
||||
Spacer,
|
||||
TableOfContents,
|
||||
Explorer,
|
||||
TagList,
|
||||
Graph,
|
||||
Backlinks,
|
||||
Search,
|
||||
Footer,
|
||||
DesktopOnly,
|
||||
MobileOnly,
|
||||
RecentNotes,
|
||||
NotFound,
|
||||
}
|
|
@ -1,12 +0,0 @@
|
|||
import { QuartzComponentConstructor } from "../types"
|
||||
|
||||
function NotFound() {
|
||||
return (
|
||||
<article class="popover-hint">
|
||||
<h1>404</h1>
|
||||
<p>Either this page is private or doesn't exist.</p>
|
||||
</article>
|
||||
)
|
||||
}
|
||||
|
||||
export default (() => NotFound) satisfies QuartzComponentConstructor
|
|
@ -1,11 +0,0 @@
|
|||
import { QuartzComponentConstructor, QuartzComponentProps } from "../types"
|
||||
import { Fragment, jsx, jsxs } from "preact/jsx-runtime"
|
||||
import { toJsxRuntime } from "hast-util-to-jsx-runtime"
|
||||
|
||||
function Content({ tree }: QuartzComponentProps) {
|
||||
// @ts-ignore (preact makes it angry)
|
||||
const content = toJsxRuntime(tree, { Fragment, jsx, jsxs, elementAttributeNameCase: "html" })
|
||||
return <article class="popover-hint">{content}</article>
|
||||
}
|
||||
|
||||
export default (() => Content) satisfies QuartzComponentConstructor
|
|
@ -1,49 +0,0 @@
|
|||
import { QuartzComponentConstructor, QuartzComponentProps } from "../types"
|
||||
import { Fragment, jsx, jsxs } from "preact/jsx-runtime"
|
||||
import { toJsxRuntime } from "hast-util-to-jsx-runtime"
|
||||
import path from "path"
|
||||
|
||||
import style from "../styles/listPage.scss"
|
||||
import { PageList } from "../PageList"
|
||||
import { _stripSlashes, simplifySlug } from "../../util/path"
|
||||
import { Root } from "hast"
|
||||
import { pluralize } from "../../util/lang"
|
||||
|
||||
function FolderContent(props: QuartzComponentProps) {
|
||||
const { tree, fileData, allFiles } = props
|
||||
const folderSlug = _stripSlashes(simplifySlug(fileData.slug!))
|
||||
const allPagesInFolder = allFiles.filter((file) => {
|
||||
const fileSlug = _stripSlashes(simplifySlug(file.slug!))
|
||||
const prefixed = fileSlug.startsWith(folderSlug) && fileSlug !== folderSlug
|
||||
const folderParts = folderSlug.split(path.posix.sep)
|
||||
const fileParts = fileSlug.split(path.posix.sep)
|
||||
const isDirectChild = fileParts.length === folderParts.length + 1
|
||||
return prefixed && isDirectChild
|
||||
})
|
||||
|
||||
const listProps = {
|
||||
...props,
|
||||
allFiles: allPagesInFolder,
|
||||
}
|
||||
|
||||
const content =
|
||||
(tree as Root).children.length === 0
|
||||
? fileData.description
|
||||
: // @ts-ignore
|
||||
toJsxRuntime(tree, { Fragment, jsx, jsxs, elementAttributeNameCase: "html" })
|
||||
|
||||
return (
|
||||
<div class="popover-hint">
|
||||
<article>
|
||||
<p>{content}</p>
|
||||
</article>
|
||||
<p>{pluralize(allPagesInFolder.length, "item")} under this folder.</p>
|
||||
<div>
|
||||
<PageList {...listProps} />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
FolderContent.css = style + PageList.css
|
||||
export default (() => FolderContent) satisfies QuartzComponentConstructor
|
|
@ -1,94 +0,0 @@
|
|||
import { QuartzComponentConstructor, QuartzComponentProps } from "../types"
|
||||
import { Fragment, jsx, jsxs } from "preact/jsx-runtime"
|
||||
import { toJsxRuntime } from "hast-util-to-jsx-runtime"
|
||||
import style from "../styles/listPage.scss"
|
||||
import { PageList } from "../PageList"
|
||||
import { FullSlug, getAllSegmentPrefixes, simplifySlug } from "../../util/path"
|
||||
import { QuartzPluginData } from "../../plugins/vfile"
|
||||
import { Root } from "hast"
|
||||
import { pluralize } from "../../util/lang"
|
||||
|
||||
const numPages = 10
|
||||
function TagContent(props: QuartzComponentProps) {
|
||||
const { tree, fileData, allFiles } = props
|
||||
const slug = fileData.slug
|
||||
|
||||
if (!(slug?.startsWith("tags/") || slug === "tags")) {
|
||||
throw new Error(`Component "TagContent" tried to render a non-tag page: ${slug}`)
|
||||
}
|
||||
|
||||
const tag = simplifySlug(slug.slice("tags/".length) as FullSlug)
|
||||
const allPagesWithTag = (tag: string) =>
|
||||
allFiles.filter((file) =>
|
||||
(file.frontmatter?.tags ?? []).flatMap(getAllSegmentPrefixes).includes(tag),
|
||||
)
|
||||
|
||||
const content =
|
||||
(tree as Root).children.length === 0
|
||||
? fileData.description
|
||||
: // @ts-ignore
|
||||
toJsxRuntime(tree, { Fragment, jsx, jsxs, elementAttributeNameCase: "html" })
|
||||
|
||||
if (tag === "") {
|
||||
const tags = [...new Set(allFiles.flatMap((data) => data.frontmatter?.tags ?? []))]
|
||||
const tagItemMap: Map<string, QuartzPluginData[]> = new Map()
|
||||
for (const tag of tags) {
|
||||
tagItemMap.set(tag, allPagesWithTag(tag))
|
||||
}
|
||||
|
||||
return (
|
||||
<div class="popover-hint">
|
||||
<article>
|
||||
<p>{content}</p>
|
||||
</article>
|
||||
<p>Found {tags.length} total tags.</p>
|
||||
<div>
|
||||
{tags.map((tag) => {
|
||||
const pages = tagItemMap.get(tag)!
|
||||
const listProps = {
|
||||
...props,
|
||||
allFiles: pages,
|
||||
}
|
||||
|
||||
const contentPage = allFiles.filter((file) => file.slug === `tags/${tag}`)[0]
|
||||
const content = contentPage?.description
|
||||
return (
|
||||
<div>
|
||||
<h2>
|
||||
<a class="internal tag-link" href={`./${tag}`}>
|
||||
#{tag}
|
||||
</a>
|
||||
</h2>
|
||||
{content && <p>{content}</p>}
|
||||
<p>
|
||||
{pluralize(pages.length, "item")} with this tag.{" "}
|
||||
{pages.length > numPages && `Showing first ${numPages}.`}
|
||||
</p>
|
||||
<PageList limit={numPages} {...listProps} />
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
} else {
|
||||
const pages = allPagesWithTag(tag)
|
||||
const listProps = {
|
||||
...props,
|
||||
allFiles: pages,
|
||||
}
|
||||
|
||||
return (
|
||||
<div class="popover-hint">
|
||||
<article>{content}</article>
|
||||
<p>{pluralize(pages.length, "item")} with this tag.</p>
|
||||
<div>
|
||||
<PageList {...listProps} />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
TagContent.css = style + PageList.css
|
||||
export default (() => TagContent) satisfies QuartzComponentConstructor
|
|
@ -1,154 +0,0 @@
|
|||
import { render } from "preact-render-to-string"
|
||||
import { QuartzComponent, QuartzComponentProps } from "./types"
|
||||
import HeaderConstructor from "./Header"
|
||||
import BodyConstructor from "./Body"
|
||||
import { JSResourceToScriptElement, StaticResources } from "../util/resources"
|
||||
import { FullSlug, RelativeURL, joinSegments } from "../util/path"
|
||||
import { visit } from "unist-util-visit"
|
||||
import { Root, Element } from "hast"
|
||||
|
||||
interface RenderComponents {
|
||||
head: QuartzComponent
|
||||
header: QuartzComponent[]
|
||||
beforeBody: QuartzComponent[]
|
||||
pageBody: QuartzComponent
|
||||
left: QuartzComponent[]
|
||||
right: QuartzComponent[]
|
||||
footer: QuartzComponent
|
||||
}
|
||||
|
||||
export function pageResources(
|
||||
baseDir: FullSlug | RelativeURL,
|
||||
staticResources: StaticResources,
|
||||
): StaticResources {
|
||||
const contentIndexPath = joinSegments(baseDir, "static/contentIndex.json")
|
||||
const contentIndexScript = `const fetchData = fetch(\`${contentIndexPath}\`).then(data => data.json())`
|
||||
|
||||
return {
|
||||
css: [joinSegments(baseDir, "index.css"), ...staticResources.css],
|
||||
js: [
|
||||
{
|
||||
src: joinSegments(baseDir, "prescript.js"),
|
||||
loadTime: "beforeDOMReady",
|
||||
contentType: "external",
|
||||
},
|
||||
{
|
||||
loadTime: "beforeDOMReady",
|
||||
contentType: "inline",
|
||||
spaPreserve: true,
|
||||
script: contentIndexScript,
|
||||
},
|
||||
...staticResources.js,
|
||||
{
|
||||
src: joinSegments(baseDir, "postscript.js"),
|
||||
loadTime: "afterDOMReady",
|
||||
moduleType: "module",
|
||||
contentType: "external",
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
export function renderPage(
|
||||
slug: FullSlug,
|
||||
componentData: QuartzComponentProps,
|
||||
components: RenderComponents,
|
||||
pageResources: StaticResources,
|
||||
): string {
|
||||
// process transcludes in componentData
|
||||
visit(componentData.tree as Root, "element", (node, _index, _parent) => {
|
||||
if (node.tagName === "blockquote") {
|
||||
const classNames = (node.properties?.className ?? []) as string[]
|
||||
if (classNames.includes("transclude")) {
|
||||
const inner = node.children[0] as Element
|
||||
const blockSlug = inner.properties?.["data-slug"] as FullSlug
|
||||
const blockRef = node.properties!.dataBlock as string
|
||||
|
||||
// TODO: avoid this expensive find operation and construct an index ahead of time
|
||||
let blockNode = componentData.allFiles.find((f) => f.slug === blockSlug)?.blocks?.[blockRef]
|
||||
if (blockNode) {
|
||||
if (blockNode.tagName === "li") {
|
||||
blockNode = {
|
||||
type: "element",
|
||||
tagName: "ul",
|
||||
children: [blockNode],
|
||||
}
|
||||
}
|
||||
|
||||
node.children = [
|
||||
blockNode,
|
||||
{
|
||||
type: "element",
|
||||
tagName: "a",
|
||||
properties: { href: inner.properties?.href, class: ["internal"] },
|
||||
children: [{ type: "text", value: `Link to original` }],
|
||||
},
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
const {
|
||||
head: Head,
|
||||
header,
|
||||
beforeBody,
|
||||
pageBody: Content,
|
||||
left,
|
||||
right,
|
||||
footer: Footer,
|
||||
} = components
|
||||
const Header = HeaderConstructor()
|
||||
const Body = BodyConstructor()
|
||||
|
||||
const LeftComponent = (
|
||||
<div class="left sidebar">
|
||||
{left.map((BodyComponent) => (
|
||||
<BodyComponent {...componentData} />
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
|
||||
const RightComponent = (
|
||||
<div class="right sidebar">
|
||||
{right.map((BodyComponent) => (
|
||||
<BodyComponent {...componentData} />
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
|
||||
const doc = (
|
||||
<html>
|
||||
<Head {...componentData} />
|
||||
<body data-slug={slug}>
|
||||
<div id="quartz-root" class="page">
|
||||
<Body {...componentData}>
|
||||
{LeftComponent}
|
||||
<div class="center">
|
||||
<div class="page-header">
|
||||
<Header {...componentData}>
|
||||
{header.map((HeaderComponent) => (
|
||||
<HeaderComponent {...componentData} />
|
||||
))}
|
||||
</Header>
|
||||
<div class="popover-hint">
|
||||
{beforeBody.map((BodyComponent) => (
|
||||
<BodyComponent {...componentData} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<Content {...componentData} />
|
||||
</div>
|
||||
{RightComponent}
|
||||
</Body>
|
||||
<Footer {...componentData} />
|
||||
</div>
|
||||
</body>
|
||||
{pageResources.js
|
||||
.filter((resource) => resource.loadTime === "afterDOMReady")
|
||||
.map((res) => JSResourceToScriptElement(res))}
|
||||
</html>
|
||||
)
|
||||
|
||||
return "<!DOCTYPE html>\n" + render(doc)
|
||||
}
|
|
@ -1,44 +0,0 @@
|
|||
function toggleCallout(this: HTMLElement) {
|
||||
const outerBlock = this.parentElement!
|
||||
outerBlock.classList.toggle(`is-collapsed`)
|
||||
const collapsed = outerBlock.classList.contains(`is-collapsed`)
|
||||
const height = collapsed ? this.scrollHeight : outerBlock.scrollHeight
|
||||
outerBlock.style.maxHeight = height + `px`
|
||||
|
||||
// walk and adjust height of all parents
|
||||
let current = outerBlock
|
||||
let parent = outerBlock.parentElement
|
||||
while (parent) {
|
||||
if (!parent.classList.contains(`callout`)) {
|
||||
return
|
||||
}
|
||||
|
||||
const collapsed = parent.classList.contains(`is-collapsed`)
|
||||
const height = collapsed ? parent.scrollHeight : parent.scrollHeight + current.scrollHeight
|
||||
parent.style.maxHeight = height + `px`
|
||||
|
||||
current = parent
|
||||
parent = parent.parentElement
|
||||
}
|
||||
}
|
||||
|
||||
function setupCallout() {
|
||||
const collapsible = document.getElementsByClassName(
|
||||
`callout is-collapsible`,
|
||||
) as HTMLCollectionOf<HTMLElement>
|
||||
for (const div of collapsible) {
|
||||
const title = div.firstElementChild
|
||||
|
||||
if (title) {
|
||||
title.removeEventListener(`click`, toggleCallout)
|
||||
title.addEventListener(`click`, toggleCallout)
|
||||
|
||||
const collapsed = div.classList.contains(`is-collapsed`)
|
||||
const height = collapsed ? title.scrollHeight : div.scrollHeight
|
||||
div.style.maxHeight = height + `px`
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener(`nav`, setupCallout)
|
||||
window.addEventListener(`resize`, setupCallout)
|
|
@ -1,33 +0,0 @@
|
|||
const svgCopy =
|
||||
'<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true"><path fill-rule="evenodd" d="M0 6.75C0 5.784.784 5 1.75 5h1.5a.75.75 0 010 1.5h-1.5a.25.25 0 00-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 00.25-.25v-1.5a.75.75 0 011.5 0v1.5A1.75 1.75 0 019.25 16h-7.5A1.75 1.75 0 010 14.25v-7.5z"></path><path fill-rule="evenodd" d="M5 1.75C5 .784 5.784 0 6.75 0h7.5C15.216 0 16 .784 16 1.75v7.5A1.75 1.75 0 0114.25 11h-7.5A1.75 1.75 0 015 9.25v-7.5zm1.75-.25a.25.25 0 00-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 00.25-.25v-7.5a.25.25 0 00-.25-.25h-7.5z"></path></svg>'
|
||||
const svgCheck =
|
||||
'<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true"><path fill-rule="evenodd" fill="rgb(63, 185, 80)" d="M13.78 4.22a.75.75 0 010 1.06l-7.25 7.25a.75.75 0 01-1.06 0L2.22 9.28a.75.75 0 011.06-1.06L6 10.94l6.72-6.72a.75.75 0 011.06 0z"></path></svg>'
|
||||
|
||||
document.addEventListener("nav", () => {
|
||||
const els = document.getElementsByTagName("pre")
|
||||
for (let i = 0; i < els.length; i++) {
|
||||
const codeBlock = els[i].getElementsByTagName("code")[0]
|
||||
if (codeBlock) {
|
||||
const source = codeBlock.innerText.replace(/\n\n/g, "\n")
|
||||
const button = document.createElement("button")
|
||||
button.className = "clipboard-button"
|
||||
button.type = "button"
|
||||
button.innerHTML = svgCopy
|
||||
button.ariaLabel = "Copy source"
|
||||
button.addEventListener("click", () => {
|
||||
navigator.clipboard.writeText(source).then(
|
||||
() => {
|
||||
button.blur()
|
||||
button.innerHTML = svgCheck
|
||||
setTimeout(() => {
|
||||
button.innerHTML = svgCopy
|
||||
button.style.borderColor = ""
|
||||
}, 2000)
|
||||
},
|
||||
(error) => console.error(error),
|
||||
)
|
||||
})
|
||||
els[i].prepend(button)
|
||||
}
|
||||
}
|
||||
})
|
|
@ -1,32 +0,0 @@
|
|||
const userPref = window.matchMedia("(prefers-color-scheme: light)").matches ? "light" : "dark"
|
||||
const currentTheme = localStorage.getItem("theme") ?? userPref
|
||||
document.documentElement.setAttribute("saved-theme", currentTheme)
|
||||
|
||||
document.addEventListener("nav", () => {
|
||||
const switchTheme = (e: any) => {
|
||||
if (e.target.checked) {
|
||||
document.documentElement.setAttribute("saved-theme", "dark")
|
||||
localStorage.setItem("theme", "dark")
|
||||
} else {
|
||||
document.documentElement.setAttribute("saved-theme", "light")
|
||||
localStorage.setItem("theme", "light")
|
||||
}
|
||||
}
|
||||
|
||||
// Darkmode toggle
|
||||
const toggleSwitch = document.querySelector("#darkmode-toggle") as HTMLInputElement
|
||||
toggleSwitch.removeEventListener("change", switchTheme)
|
||||
toggleSwitch.addEventListener("change", switchTheme)
|
||||
if (currentTheme === "dark") {
|
||||
toggleSwitch.checked = true
|
||||
}
|
||||
|
||||
// Listen for changes in prefers-color-scheme
|
||||
const colorSchemeMediaQuery = window.matchMedia("(prefers-color-scheme: dark)")
|
||||
colorSchemeMediaQuery.addEventListener("change", (e) => {
|
||||
const newTheme = e.matches ? "dark" : "light"
|
||||
document.documentElement.setAttribute("saved-theme", newTheme)
|
||||
localStorage.setItem("theme", newTheme)
|
||||
toggleSwitch.checked = e.matches
|
||||
})
|
||||
})
|
|
@ -1,162 +0,0 @@
|
|||
import { FolderState } from "../ExplorerNode"
|
||||
|
||||
// Current state of folders
|
||||
let explorerState: FolderState[]
|
||||
|
||||
const observer = new IntersectionObserver((entries) => {
|
||||
// If last element is observed, remove gradient of "overflow" class so element is visible
|
||||
const explorer = document.getElementById("explorer-ul")
|
||||
for (const entry of entries) {
|
||||
if (entry.isIntersecting) {
|
||||
explorer?.classList.add("no-background")
|
||||
} else {
|
||||
explorer?.classList.remove("no-background")
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
function toggleExplorer(this: HTMLElement) {
|
||||
// Toggle collapsed state of entire explorer
|
||||
this.classList.toggle("collapsed")
|
||||
const content = this.nextElementSibling as HTMLElement
|
||||
content.classList.toggle("collapsed")
|
||||
content.style.maxHeight = content.style.maxHeight === "0px" ? content.scrollHeight + "px" : "0px"
|
||||
}
|
||||
|
||||
function toggleFolder(evt: MouseEvent) {
|
||||
evt.stopPropagation()
|
||||
|
||||
// Element that was clicked
|
||||
const target = evt.target as HTMLElement
|
||||
|
||||
// Check if target was svg icon or button
|
||||
const isSvg = target.nodeName === "svg"
|
||||
|
||||
// corresponding <ul> element relative to clicked button/folder
|
||||
let childFolderContainer: HTMLElement
|
||||
|
||||
// <li> element of folder (stores folder-path dataset)
|
||||
let currentFolderParent: HTMLElement
|
||||
|
||||
// Get correct relative container and toggle collapsed class
|
||||
if (isSvg) {
|
||||
childFolderContainer = target.parentElement?.nextSibling as HTMLElement
|
||||
currentFolderParent = target.nextElementSibling as HTMLElement
|
||||
|
||||
childFolderContainer.classList.toggle("open")
|
||||
} else {
|
||||
childFolderContainer = target.parentElement?.parentElement?.nextElementSibling as HTMLElement
|
||||
currentFolderParent = target.parentElement as HTMLElement
|
||||
|
||||
childFolderContainer.classList.toggle("open")
|
||||
}
|
||||
if (!childFolderContainer) return
|
||||
|
||||
// Collapse folder container
|
||||
const isCollapsed = childFolderContainer.classList.contains("open")
|
||||
setFolderState(childFolderContainer, !isCollapsed)
|
||||
|
||||
// Save folder state to localStorage
|
||||
const clickFolderPath = currentFolderParent.dataset.folderpath as string
|
||||
|
||||
// Remove leading "/"
|
||||
const fullFolderPath = clickFolderPath.substring(1)
|
||||
toggleCollapsedByPath(explorerState, fullFolderPath)
|
||||
|
||||
const stringifiedFileTree = JSON.stringify(explorerState)
|
||||
localStorage.setItem("fileTree", stringifiedFileTree)
|
||||
}
|
||||
|
||||
function setupExplorer() {
|
||||
// Set click handler for collapsing entire explorer
|
||||
const explorer = document.getElementById("explorer")
|
||||
|
||||
// Get folder state from local storage
|
||||
const storageTree = localStorage.getItem("fileTree")
|
||||
|
||||
// Convert to bool
|
||||
const useSavedFolderState = explorer?.dataset.savestate === "true"
|
||||
|
||||
if (explorer) {
|
||||
// Get config
|
||||
const collapseBehavior = explorer.dataset.behavior
|
||||
|
||||
// Add click handlers for all folders (click handler on folder "label")
|
||||
if (collapseBehavior === "collapse") {
|
||||
Array.prototype.forEach.call(
|
||||
document.getElementsByClassName("folder-button"),
|
||||
function (item) {
|
||||
item.removeEventListener("click", toggleFolder)
|
||||
item.addEventListener("click", toggleFolder)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// Add click handler to main explorer
|
||||
explorer.removeEventListener("click", toggleExplorer)
|
||||
explorer.addEventListener("click", toggleExplorer)
|
||||
}
|
||||
|
||||
// Set up click handlers for each folder (click handler on folder "icon")
|
||||
Array.prototype.forEach.call(document.getElementsByClassName("folder-icon"), function (item) {
|
||||
item.removeEventListener("click", toggleFolder)
|
||||
item.addEventListener("click", toggleFolder)
|
||||
})
|
||||
|
||||
if (storageTree && useSavedFolderState) {
|
||||
// Get state from localStorage and set folder state
|
||||
explorerState = JSON.parse(storageTree)
|
||||
explorerState.map((folderUl) => {
|
||||
// grab <li> element for matching folder path
|
||||
const folderLi = document.querySelector(
|
||||
`[data-folderpath='/${folderUl.path}']`,
|
||||
) as HTMLElement
|
||||
|
||||
// Get corresponding content <ul> tag and set state
|
||||
const folderUL = folderLi.parentElement?.nextElementSibling
|
||||
if (folderUL) {
|
||||
setFolderState(folderUL as HTMLElement, folderUl.collapsed)
|
||||
}
|
||||
})
|
||||
} else {
|
||||
// If tree is not in localStorage or config is disabled, use tree passed from Explorer as dataset
|
||||
explorerState = JSON.parse(explorer?.dataset.tree as string)
|
||||
}
|
||||
}
|
||||
|
||||
window.addEventListener("resize", setupExplorer)
|
||||
document.addEventListener("nav", () => {
|
||||
setupExplorer()
|
||||
|
||||
const explorerContent = document.getElementById("explorer-ul")
|
||||
// select pseudo element at end of list
|
||||
const lastItem = document.getElementById("explorer-end")
|
||||
|
||||
observer.disconnect()
|
||||
observer.observe(lastItem as Element)
|
||||
})
|
||||
|
||||
/**
|
||||
* Toggles the state of a given folder
|
||||
* @param folderElement <div class="folder-outer"> Element of folder (parent)
|
||||
* @param collapsed if folder should be set to collapsed or not
|
||||
*/
|
||||
function setFolderState(folderElement: HTMLElement, collapsed: boolean) {
|
||||
if (collapsed) {
|
||||
folderElement?.classList.remove("open")
|
||||
} else {
|
||||
folderElement?.classList.add("open")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Toggles visibility of a folder
|
||||
* @param array array of FolderState (`fileTree`, either get from local storage or data attribute)
|
||||
* @param path path to folder (e.g. 'advanced/more/more2')
|
||||
*/
|
||||
function toggleCollapsedByPath(array: FolderState[], path: string) {
|
||||
const entry = array.find((item) => item.path === path)
|
||||
if (entry) {
|
||||
entry.collapsed = !entry.collapsed
|
||||
}
|
||||
}
|
|
@ -1,328 +0,0 @@
|
|||
import type { ContentDetails } from "../../plugins/emitters/contentIndex"
|
||||
import * as d3 from "d3"
|
||||
import { registerEscapeHandler, removeAllChildren } from "./util"
|
||||
import { FullSlug, SimpleSlug, getFullSlug, resolveRelative, simplifySlug } from "../../util/path"
|
||||
|
||||
type NodeData = {
|
||||
id: SimpleSlug
|
||||
text: string
|
||||
tags: string[]
|
||||
} & d3.SimulationNodeDatum
|
||||
|
||||
type LinkData = {
|
||||
source: SimpleSlug
|
||||
target: SimpleSlug
|
||||
}
|
||||
|
||||
const localStorageKey = "graph-visited"
|
||||
function getVisited(): Set<SimpleSlug> {
|
||||
return new Set(JSON.parse(localStorage.getItem(localStorageKey) ?? "[]"))
|
||||
}
|
||||
|
||||
function addToVisited(slug: SimpleSlug) {
|
||||
const visited = getVisited()
|
||||
visited.add(slug)
|
||||
localStorage.setItem(localStorageKey, JSON.stringify([...visited]))
|
||||
}
|
||||
|
||||
async function renderGraph(container: string, fullSlug: FullSlug) {
|
||||
const slug = simplifySlug(fullSlug)
|
||||
const visited = getVisited()
|
||||
const graph = document.getElementById(container)
|
||||
if (!graph) return
|
||||
removeAllChildren(graph)
|
||||
|
||||
let {
|
||||
drag: enableDrag,
|
||||
zoom: enableZoom,
|
||||
depth,
|
||||
scale,
|
||||
repelForce,
|
||||
centerForce,
|
||||
linkDistance,
|
||||
fontSize,
|
||||
opacityScale,
|
||||
removeTags,
|
||||
showTags,
|
||||
} = JSON.parse(graph.dataset["cfg"]!)
|
||||
|
||||
const data = await fetchData
|
||||
|
||||
const links: LinkData[] = []
|
||||
const tags: SimpleSlug[] = []
|
||||
|
||||
const validLinks = new Set(Object.keys(data).map((slug) => simplifySlug(slug as FullSlug)))
|
||||
|
||||
for (const [src, details] of Object.entries<ContentDetails>(data)) {
|
||||
const source = simplifySlug(src as FullSlug)
|
||||
const outgoing = details.links ?? []
|
||||
|
||||
for (const dest of outgoing) {
|
||||
if (validLinks.has(dest)) {
|
||||
links.push({ source, target: dest })
|
||||
}
|
||||
}
|
||||
|
||||
if (showTags) {
|
||||
const localTags = details.tags
|
||||
.filter((tag) => !removeTags.includes(tag))
|
||||
.map((tag) => simplifySlug(("tags/" + tag) as FullSlug))
|
||||
|
||||
tags.push(...localTags.filter((tag) => !tags.includes(tag)))
|
||||
|
||||
for (const tag of localTags) {
|
||||
links.push({ source, target: tag })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const neighbourhood = new Set<SimpleSlug>()
|
||||
const wl: (SimpleSlug | "__SENTINEL")[] = [slug, "__SENTINEL"]
|
||||
if (depth >= 0) {
|
||||
while (depth >= 0 && wl.length > 0) {
|
||||
// compute neighbours
|
||||
const cur = wl.shift()!
|
||||
if (cur === "__SENTINEL") {
|
||||
depth--
|
||||
wl.push("__SENTINEL")
|
||||
} else {
|
||||
neighbourhood.add(cur)
|
||||
const outgoing = links.filter((l) => l.source === cur)
|
||||
const incoming = links.filter((l) => l.target === cur)
|
||||
wl.push(...outgoing.map((l) => l.target), ...incoming.map((l) => l.source))
|
||||
}
|
||||
}
|
||||
} else {
|
||||
Object.keys(data).forEach((id) => neighbourhood.add(simplifySlug(id as FullSlug)))
|
||||
if (showTags) tags.forEach((tag) => neighbourhood.add(tag))
|
||||
}
|
||||
|
||||
const graphData: { nodes: NodeData[]; links: LinkData[] } = {
|
||||
nodes: [...neighbourhood].map((url) => {
|
||||
const text = url.startsWith("tags/") ? "#" + url.substring(5) : data[url]?.title ?? url
|
||||
return {
|
||||
id: url,
|
||||
text: text,
|
||||
tags: data[url]?.tags ?? [],
|
||||
}
|
||||
}),
|
||||
links: links.filter((l) => neighbourhood.has(l.source) && neighbourhood.has(l.target)),
|
||||
}
|
||||
|
||||
const simulation: d3.Simulation<NodeData, LinkData> = d3
|
||||
.forceSimulation(graphData.nodes)
|
||||
.force("charge", d3.forceManyBody().strength(-100 * repelForce))
|
||||
.force(
|
||||
"link",
|
||||
d3
|
||||
.forceLink(graphData.links)
|
||||
.id((d: any) => d.id)
|
||||
.distance(linkDistance),
|
||||
)
|
||||
.force("center", d3.forceCenter().strength(centerForce))
|
||||
|
||||
const height = Math.max(graph.offsetHeight, 250)
|
||||
const width = graph.offsetWidth
|
||||
|
||||
const svg = d3
|
||||
.select<HTMLElement, NodeData>("#" + container)
|
||||
.append("svg")
|
||||
.attr("width", width)
|
||||
.attr("height", height)
|
||||
.attr("viewBox", [-width / 2 / scale, -height / 2 / scale, width / scale, height / scale])
|
||||
|
||||
// draw links between nodes
|
||||
const link = svg
|
||||
.append("g")
|
||||
.selectAll("line")
|
||||
.data(graphData.links)
|
||||
.join("line")
|
||||
.attr("class", "link")
|
||||
.attr("stroke", "var(--lightgray)")
|
||||
.attr("stroke-width", 1)
|
||||
|
||||
// svg groups
|
||||
const graphNode = svg.append("g").selectAll("g").data(graphData.nodes).enter().append("g")
|
||||
|
||||
// calculate color
|
||||
const color = (d: NodeData) => {
|
||||
const isCurrent = d.id === slug
|
||||
if (isCurrent) {
|
||||
return "var(--secondary)"
|
||||
} else if (visited.has(d.id) || d.id.startsWith("tags/")) {
|
||||
return "var(--tertiary)"
|
||||
} else {
|
||||
return "var(--gray)"
|
||||
}
|
||||
}
|
||||
|
||||
const drag = (simulation: d3.Simulation<NodeData, LinkData>) => {
|
||||
function dragstarted(event: any, d: NodeData) {
|
||||
if (!event.active) simulation.alphaTarget(1).restart()
|
||||
d.fx = d.x
|
||||
d.fy = d.y
|
||||
}
|
||||
|
||||
function dragged(event: any, d: NodeData) {
|
||||
d.fx = event.x
|
||||
d.fy = event.y
|
||||
}
|
||||
|
||||
function dragended(event: any, d: NodeData) {
|
||||
if (!event.active) simulation.alphaTarget(0)
|
||||
d.fx = null
|
||||
d.fy = null
|
||||
}
|
||||
|
||||
const noop = () => {}
|
||||
return d3
|
||||
.drag<Element, NodeData>()
|
||||
.on("start", enableDrag ? dragstarted : noop)
|
||||
.on("drag", enableDrag ? dragged : noop)
|
||||
.on("end", enableDrag ? dragended : noop)
|
||||
}
|
||||
|
||||
function nodeRadius(d: NodeData) {
|
||||
const numLinks = links.filter((l: any) => l.source.id === d.id || l.target.id === d.id).length
|
||||
return 2 + Math.sqrt(numLinks)
|
||||
}
|
||||
|
||||
// draw individual nodes
|
||||
const node = graphNode
|
||||
.append("circle")
|
||||
.attr("class", "node")
|
||||
.attr("id", (d) => d.id)
|
||||
.attr("r", nodeRadius)
|
||||
.attr("fill", color)
|
||||
.style("cursor", "pointer")
|
||||
.on("click", (_, d) => {
|
||||
const targ = resolveRelative(fullSlug, d.id)
|
||||
window.spaNavigate(new URL(targ, window.location.toString()))
|
||||
})
|
||||
.on("mouseover", function (_, d) {
|
||||
const neighbours: SimpleSlug[] = data[fullSlug].links ?? []
|
||||
const neighbourNodes = d3
|
||||
.selectAll<HTMLElement, NodeData>(".node")
|
||||
.filter((d) => neighbours.includes(d.id))
|
||||
const currentId = d.id
|
||||
const linkNodes = d3
|
||||
.selectAll(".link")
|
||||
.filter((d: any) => d.source.id === currentId || d.target.id === currentId)
|
||||
|
||||
// highlight neighbour nodes
|
||||
neighbourNodes.transition().duration(200).attr("fill", color)
|
||||
|
||||
// highlight links
|
||||
linkNodes.transition().duration(200).attr("stroke", "var(--gray)").attr("stroke-width", 1)
|
||||
|
||||
const bigFont = fontSize * 1.5
|
||||
|
||||
// show text for self
|
||||
const parent = this.parentNode as HTMLElement
|
||||
d3.select<HTMLElement, NodeData>(parent)
|
||||
.raise()
|
||||
.select("text")
|
||||
.transition()
|
||||
.duration(200)
|
||||
.attr("opacityOld", d3.select(parent).select("text").style("opacity"))
|
||||
.style("opacity", 1)
|
||||
.style("font-size", bigFont + "em")
|
||||
})
|
||||
.on("mouseleave", function (_, d) {
|
||||
const currentId = d.id
|
||||
const linkNodes = d3
|
||||
.selectAll(".link")
|
||||
.filter((d: any) => d.source.id === currentId || d.target.id === currentId)
|
||||
|
||||
linkNodes.transition().duration(200).attr("stroke", "var(--lightgray)")
|
||||
|
||||
const parent = this.parentNode as HTMLElement
|
||||
d3.select<HTMLElement, NodeData>(parent)
|
||||
.select("text")
|
||||
.transition()
|
||||
.duration(200)
|
||||
.style("opacity", d3.select(parent).select("text").attr("opacityOld"))
|
||||
.style("font-size", fontSize + "em")
|
||||
})
|
||||
// @ts-ignore
|
||||
.call(drag(simulation))
|
||||
|
||||
// draw labels
|
||||
const labels = graphNode
|
||||
.append("text")
|
||||
.attr("dx", 0)
|
||||
.attr("dy", (d) => -nodeRadius(d) + "px")
|
||||
.attr("text-anchor", "middle")
|
||||
.text((d) => d.text)
|
||||
.style("opacity", (opacityScale - 1) / 3.75)
|
||||
.style("pointer-events", "none")
|
||||
.style("font-size", fontSize + "em")
|
||||
.raise()
|
||||
// @ts-ignore
|
||||
.call(drag(simulation))
|
||||
|
||||
// set panning
|
||||
if (enableZoom) {
|
||||
svg.call(
|
||||
d3
|
||||
.zoom<SVGSVGElement, NodeData>()
|
||||
.extent([
|
||||
[0, 0],
|
||||
[width, height],
|
||||
])
|
||||
.scaleExtent([0.25, 4])
|
||||
.on("zoom", ({ transform }) => {
|
||||
link.attr("transform", transform)
|
||||
node.attr("transform", transform)
|
||||
const scale = transform.k * opacityScale
|
||||
const scaledOpacity = Math.max((scale - 1) / 3.75, 0)
|
||||
labels.attr("transform", transform).style("opacity", scaledOpacity)
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
// progress the simulation
|
||||
simulation.on("tick", () => {
|
||||
link
|
||||
.attr("x1", (d: any) => d.source.x)
|
||||
.attr("y1", (d: any) => d.source.y)
|
||||
.attr("x2", (d: any) => d.target.x)
|
||||
.attr("y2", (d: any) => d.target.y)
|
||||
node.attr("cx", (d: any) => d.x).attr("cy", (d: any) => d.y)
|
||||
labels.attr("x", (d: any) => d.x).attr("y", (d: any) => d.y)
|
||||
})
|
||||
}
|
||||
|
||||
function renderGlobalGraph() {
|
||||
const slug = getFullSlug(window)
|
||||
const container = document.getElementById("global-graph-outer")
|
||||
const sidebar = container?.closest(".sidebar") as HTMLElement
|
||||
container?.classList.add("active")
|
||||
if (sidebar) {
|
||||
sidebar.style.zIndex = "1"
|
||||
}
|
||||
|
||||
renderGraph("global-graph-container", slug)
|
||||
|
||||
function hideGlobalGraph() {
|
||||
container?.classList.remove("active")
|
||||
const graph = document.getElementById("global-graph-container")
|
||||
if (sidebar) {
|
||||
sidebar.style.zIndex = "unset"
|
||||
}
|
||||
if (!graph) return
|
||||
removeAllChildren(graph)
|
||||
}
|
||||
|
||||
registerEscapeHandler(container, hideGlobalGraph)
|
||||
}
|
||||
|
||||
document.addEventListener("nav", async (e: unknown) => {
|
||||
const slug = (e as CustomEventMap["nav"]).detail.url
|
||||
addToVisited(slug)
|
||||
await renderGraph("graph-container", slug)
|
||||
|
||||
const containerIcon = document.getElementById("global-graph-icon")
|
||||
containerIcon?.removeEventListener("click", renderGlobalGraph)
|
||||
containerIcon?.addEventListener("click", renderGlobalGraph)
|
||||
})
|
|
@ -1,3 +0,0 @@
|
|||
import Plausible from "plausible-tracker"
|
||||
const { trackPageview } = Plausible()
|
||||
document.addEventListener("nav", () => trackPageview())
|
|
@ -1,83 +0,0 @@
|
|||
import { computePosition, flip, inline, shift } from "@floating-ui/dom"
|
||||
|
||||
// from micromorph/src/utils.ts
|
||||
// https://github.com/natemoo-re/micromorph/blob/main/src/utils.ts#L5
|
||||
export function normalizeRelativeURLs(el: Element | Document, base: string | URL) {
|
||||
const update = (el: Element, attr: string, base: string | URL) => {
|
||||
el.setAttribute(attr, new URL(el.getAttribute(attr)!, base).pathname)
|
||||
}
|
||||
|
||||
el.querySelectorAll('[href^="./"], [href^="../"]').forEach((item) => update(item, "href", base))
|
||||
|
||||
el.querySelectorAll('[src^="./"], [src^="../"]').forEach((item) => update(item, "src", base))
|
||||
}
|
||||
|
||||
const p = new DOMParser()
|
||||
async function mouseEnterHandler(
|
||||
this: HTMLLinkElement,
|
||||
{ clientX, clientY }: { clientX: number; clientY: number },
|
||||
) {
|
||||
const link = this
|
||||
async function setPosition(popoverElement: HTMLElement) {
|
||||
const { x, y } = await computePosition(link, popoverElement, {
|
||||
middleware: [inline({ x: clientX, y: clientY }), shift(), flip()],
|
||||
})
|
||||
Object.assign(popoverElement.style, {
|
||||
left: `${x}px`,
|
||||
top: `${y}px`,
|
||||
})
|
||||
}
|
||||
|
||||
// dont refetch if there's already a popover
|
||||
if ([...link.children].some((child) => child.classList.contains("popover"))) {
|
||||
return setPosition(link.lastChild as HTMLElement)
|
||||
}
|
||||
|
||||
const thisUrl = new URL(document.location.href)
|
||||
thisUrl.hash = ""
|
||||
thisUrl.search = ""
|
||||
const targetUrl = new URL(link.href)
|
||||
const hash = targetUrl.hash
|
||||
targetUrl.hash = ""
|
||||
targetUrl.search = ""
|
||||
// prevent hover of the same page
|
||||
if (thisUrl.toString() === targetUrl.toString()) return
|
||||
|
||||
const contents = await fetch(`${targetUrl}`)
|
||||
.then((res) => res.text())
|
||||
.catch((err) => {
|
||||
console.error(err)
|
||||
})
|
||||
|
||||
if (!contents) return
|
||||
const html = p.parseFromString(contents, "text/html")
|
||||
normalizeRelativeURLs(html, targetUrl)
|
||||
const elts = [...html.getElementsByClassName("popover-hint")]
|
||||
if (elts.length === 0) return
|
||||
|
||||
const popoverElement = document.createElement("div")
|
||||
popoverElement.classList.add("popover")
|
||||
const popoverInner = document.createElement("div")
|
||||
popoverInner.classList.add("popover-inner")
|
||||
popoverElement.appendChild(popoverInner)
|
||||
elts.forEach((elt) => popoverInner.appendChild(elt))
|
||||
|
||||
setPosition(popoverElement)
|
||||
link.appendChild(popoverElement)
|
||||
|
||||
if (hash !== "") {
|
||||
const heading = popoverInner.querySelector(hash) as HTMLElement | null
|
||||
if (heading) {
|
||||
// leave ~12px of buffer when scrolling to a heading
|
||||
popoverInner.scroll({ top: heading.offsetTop - 12, behavior: "instant" })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener("nav", () => {
|
||||
const links = [...document.getElementsByClassName("internal")] as HTMLLinkElement[]
|
||||
for (const link of links) {
|
||||
link.removeEventListener("mouseenter", mouseEnterHandler)
|
||||
link.addEventListener("mouseenter", mouseEnterHandler)
|
||||
}
|
||||
})
|
|
@ -1,353 +0,0 @@
|
|||
import { Document, SimpleDocumentSearchResultSetUnit } from "flexsearch"
|
||||
import { ContentDetails } from "../../plugins/emitters/contentIndex"
|
||||
import { registerEscapeHandler, removeAllChildren } from "./util"
|
||||
import { FullSlug, resolveRelative } from "../../util/path"
|
||||
|
||||
interface Item {
|
||||
id: number
|
||||
slug: FullSlug
|
||||
title: string
|
||||
content: string
|
||||
tags: string[]
|
||||
}
|
||||
|
||||
let index: Document<Item> | undefined = undefined
|
||||
|
||||
// Can be expanded with things like "term" in the future
|
||||
type SearchType = "basic" | "tags"
|
||||
|
||||
// Current searchType
|
||||
let searchType: SearchType = "basic"
|
||||
|
||||
const contextWindowWords = 30
|
||||
const numSearchResults = 5
|
||||
const numTagResults = 3
|
||||
function highlight(searchTerm: string, text: string, trim?: boolean) {
|
||||
// try to highlight longest tokens first
|
||||
const tokenizedTerms = searchTerm
|
||||
.split(/\s+/)
|
||||
.filter((t) => t !== "")
|
||||
.sort((a, b) => b.length - a.length)
|
||||
let tokenizedText = text.split(/\s+/).filter((t) => t !== "")
|
||||
|
||||
let startIndex = 0
|
||||
let endIndex = tokenizedText.length - 1
|
||||
if (trim) {
|
||||
const includesCheck = (tok: string) =>
|
||||
tokenizedTerms.some((term) => tok.toLowerCase().startsWith(term.toLowerCase()))
|
||||
const occurencesIndices = tokenizedText.map(includesCheck)
|
||||
|
||||
let bestSum = 0
|
||||
let bestIndex = 0
|
||||
for (let i = 0; i < Math.max(tokenizedText.length - contextWindowWords, 0); i++) {
|
||||
const window = occurencesIndices.slice(i, i + contextWindowWords)
|
||||
const windowSum = window.reduce((total, cur) => total + (cur ? 1 : 0), 0)
|
||||
if (windowSum >= bestSum) {
|
||||
bestSum = windowSum
|
||||
bestIndex = i
|
||||
}
|
||||
}
|
||||
|
||||
startIndex = Math.max(bestIndex - contextWindowWords, 0)
|
||||
endIndex = Math.min(startIndex + 2 * contextWindowWords, tokenizedText.length - 1)
|
||||
tokenizedText = tokenizedText.slice(startIndex, endIndex)
|
||||
}
|
||||
|
||||
const slice = tokenizedText
|
||||
.map((tok) => {
|
||||
// see if this tok is prefixed by any search terms
|
||||
for (const searchTok of tokenizedTerms) {
|
||||
if (tok.toLowerCase().includes(searchTok.toLowerCase())) {
|
||||
const regex = new RegExp(searchTok.toLowerCase(), "gi")
|
||||
return tok.replace(regex, `<span class="highlight">$&</span>`)
|
||||
}
|
||||
}
|
||||
return tok
|
||||
})
|
||||
.join(" ")
|
||||
|
||||
return `${startIndex === 0 ? "" : "..."}${slice}${
|
||||
endIndex === tokenizedText.length - 1 ? "" : "..."
|
||||
}`
|
||||
}
|
||||
|
||||
const encoder = (str: string) => str.toLowerCase().split(/([^a-z]|[^\x00-\x7F])/)
|
||||
let prevShortcutHandler: ((e: HTMLElementEventMap["keydown"]) => void) | undefined = undefined
|
||||
document.addEventListener("nav", async (e: unknown) => {
|
||||
const currentSlug = (e as CustomEventMap["nav"]).detail.url
|
||||
|
||||
const data = await fetchData
|
||||
const container = document.getElementById("search-container")
|
||||
const sidebar = container?.closest(".sidebar") as HTMLElement
|
||||
const searchIcon = document.getElementById("search-icon")
|
||||
const searchBar = document.getElementById("search-bar") as HTMLInputElement | null
|
||||
const results = document.getElementById("results-container")
|
||||
const resultCards = document.getElementsByClassName("result-card")
|
||||
const idDataMap = Object.keys(data) as FullSlug[]
|
||||
|
||||
function hideSearch() {
|
||||
container?.classList.remove("active")
|
||||
if (searchBar) {
|
||||
searchBar.value = "" // clear the input when we dismiss the search
|
||||
}
|
||||
if (sidebar) {
|
||||
sidebar.style.zIndex = "unset"
|
||||
}
|
||||
if (results) {
|
||||
removeAllChildren(results)
|
||||
}
|
||||
|
||||
searchType = "basic" // reset search type after closing
|
||||
}
|
||||
|
||||
function showSearch(searchTypeNew: SearchType) {
|
||||
searchType = searchTypeNew
|
||||
if (sidebar) {
|
||||
sidebar.style.zIndex = "1"
|
||||
}
|
||||
container?.classList.add("active")
|
||||
searchBar?.focus()
|
||||
}
|
||||
|
||||
function shortcutHandler(e: HTMLElementEventMap["keydown"]) {
|
||||
if (e.key === "k" && (e.ctrlKey || e.metaKey) && !e.shiftKey) {
|
||||
e.preventDefault()
|
||||
const searchBarOpen = container?.classList.contains("active")
|
||||
searchBarOpen ? hideSearch() : showSearch("basic")
|
||||
} else if (e.shiftKey && (e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "k") {
|
||||
// Hotkey to open tag search
|
||||
e.preventDefault()
|
||||
const searchBarOpen = container?.classList.contains("active")
|
||||
searchBarOpen ? hideSearch() : showSearch("tags")
|
||||
|
||||
// add "#" prefix for tag search
|
||||
if (searchBar) searchBar.value = "#"
|
||||
} else if (e.key === "Enter") {
|
||||
// If result has focus, navigate to that one, otherwise pick first result
|
||||
if (results?.contains(document.activeElement)) {
|
||||
const active = document.activeElement as HTMLInputElement
|
||||
active.click()
|
||||
} else {
|
||||
const anchor = document.getElementsByClassName("result-card")[0] as HTMLInputElement | null
|
||||
anchor?.click()
|
||||
}
|
||||
} else if (e.key === "ArrowDown") {
|
||||
e.preventDefault()
|
||||
// When first pressing ArrowDown, results wont contain the active element, so focus first element
|
||||
if (!results?.contains(document.activeElement)) {
|
||||
const firstResult = resultCards[0] as HTMLInputElement | null
|
||||
firstResult?.focus()
|
||||
} else {
|
||||
// If an element in results-container already has focus, focus next one
|
||||
const nextResult = document.activeElement?.nextElementSibling as HTMLInputElement | null
|
||||
nextResult?.focus()
|
||||
}
|
||||
} else if (e.key === "ArrowUp") {
|
||||
e.preventDefault()
|
||||
if (results?.contains(document.activeElement)) {
|
||||
// If an element in results-container already has focus, focus previous one
|
||||
const prevResult = document.activeElement?.previousElementSibling as HTMLInputElement | null
|
||||
prevResult?.focus()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function trimContent(content: string) {
|
||||
// works without escaping html like in `description.ts`
|
||||
const sentences = content.replace(/\s+/g, " ").split(".")
|
||||
let finalDesc = ""
|
||||
let sentenceIdx = 0
|
||||
|
||||
// Roughly estimate characters by (words * 5). Matches description length in `description.ts`.
|
||||
const len = contextWindowWords * 5
|
||||
while (finalDesc.length < len) {
|
||||
const sentence = sentences[sentenceIdx]
|
||||
if (!sentence) break
|
||||
finalDesc += sentence + "."
|
||||
sentenceIdx++
|
||||
}
|
||||
|
||||
// If more content would be available, indicate it by finishing with "..."
|
||||
if (finalDesc.length < content.length) {
|
||||
finalDesc += ".."
|
||||
}
|
||||
|
||||
return finalDesc
|
||||
}
|
||||
|
||||
const formatForDisplay = (term: string, id: number) => {
|
||||
const slug = idDataMap[id]
|
||||
return {
|
||||
id,
|
||||
slug,
|
||||
title: searchType === "tags" ? data[slug].title : highlight(term, data[slug].title ?? ""),
|
||||
// if searchType is tag, display context from start of file and trim, otherwise use regular highlight
|
||||
content:
|
||||
searchType === "tags"
|
||||
? trimContent(data[slug].content)
|
||||
: highlight(term, data[slug].content ?? "", true),
|
||||
tags: highlightTags(term, data[slug].tags),
|
||||
}
|
||||
}
|
||||
|
||||
function highlightTags(term: string, tags: string[]) {
|
||||
if (tags && searchType === "tags") {
|
||||
// Find matching tags
|
||||
const termLower = term.toLowerCase()
|
||||
let matching = tags.filter((str) => str.includes(termLower))
|
||||
|
||||
// Substract matching from original tags, then push difference
|
||||
if (matching.length > 0) {
|
||||
let difference = tags.filter((x) => !matching.includes(x))
|
||||
|
||||
// Convert to html (cant be done later as matches/term dont get passed to `resultToHTML`)
|
||||
matching = matching.map((tag) => `<li><p class="match-tag">#${tag}</p></li>`)
|
||||
difference = difference.map((tag) => `<li><p>#${tag}</p></li>`)
|
||||
matching.push(...difference)
|
||||
}
|
||||
|
||||
// Only allow max of `numTagResults` in preview
|
||||
if (tags.length > numTagResults) {
|
||||
matching.splice(numTagResults)
|
||||
}
|
||||
|
||||
return matching
|
||||
} else {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
const resultToHTML = ({ slug, title, content, tags }: Item) => {
|
||||
const htmlTags = tags.length > 0 ? `<ul>${tags.join("")}</ul>` : ``
|
||||
const button = document.createElement("button")
|
||||
button.classList.add("result-card")
|
||||
button.id = slug
|
||||
button.innerHTML = `<h3>${title}</h3>${htmlTags}<p>${content}</p>`
|
||||
button.addEventListener("click", () => {
|
||||
const targ = resolveRelative(currentSlug, slug)
|
||||
window.spaNavigate(new URL(targ, window.location.toString()))
|
||||
hideSearch()
|
||||
})
|
||||
return button
|
||||
}
|
||||
|
||||
function displayResults(finalResults: Item[]) {
|
||||
if (!results) return
|
||||
|
||||
removeAllChildren(results)
|
||||
if (finalResults.length === 0) {
|
||||
results.innerHTML = `<button class="result-card">
|
||||
<h3>No results.</h3>
|
||||
<p>Try another search term?</p>
|
||||
</button>`
|
||||
} else {
|
||||
results.append(...finalResults.map(resultToHTML))
|
||||
}
|
||||
}
|
||||
|
||||
async function onType(e: HTMLElementEventMap["input"]) {
|
||||
let term = (e.target as HTMLInputElement).value
|
||||
let searchResults: SimpleDocumentSearchResultSetUnit[]
|
||||
|
||||
if (term.toLowerCase().startsWith("#")) {
|
||||
searchType = "tags"
|
||||
} else {
|
||||
searchType = "basic"
|
||||
}
|
||||
|
||||
switch (searchType) {
|
||||
case "tags": {
|
||||
term = term.substring(1)
|
||||
searchResults =
|
||||
(await index?.searchAsync({ query: term, limit: numSearchResults, index: ["tags"] })) ??
|
||||
[]
|
||||
break
|
||||
}
|
||||
case "basic":
|
||||
default: {
|
||||
searchResults =
|
||||
(await index?.searchAsync({
|
||||
query: term,
|
||||
limit: numSearchResults,
|
||||
index: ["title", "content"],
|
||||
})) ?? []
|
||||
}
|
||||
}
|
||||
|
||||
const getByField = (field: string): number[] => {
|
||||
const results = searchResults.filter((x) => x.field === field)
|
||||
return results.length === 0 ? [] : ([...results[0].result] as number[])
|
||||
}
|
||||
|
||||
// order titles ahead of content
|
||||
const allIds: Set<number> = new Set([
|
||||
...getByField("title"),
|
||||
...getByField("content"),
|
||||
...getByField("tags"),
|
||||
])
|
||||
const finalResults = [...allIds].map((id) => formatForDisplay(term, id))
|
||||
displayResults(finalResults)
|
||||
}
|
||||
|
||||
if (prevShortcutHandler) {
|
||||
document.removeEventListener("keydown", prevShortcutHandler)
|
||||
}
|
||||
|
||||
document.addEventListener("keydown", shortcutHandler)
|
||||
prevShortcutHandler = shortcutHandler
|
||||
searchIcon?.removeEventListener("click", () => showSearch("basic"))
|
||||
searchIcon?.addEventListener("click", () => showSearch("basic"))
|
||||
searchBar?.removeEventListener("input", onType)
|
||||
searchBar?.addEventListener("input", onType)
|
||||
|
||||
// setup index if it hasn't been already
|
||||
if (!index) {
|
||||
index = new Document({
|
||||
cache: true,
|
||||
charset: "latin:extra",
|
||||
optimize: true,
|
||||
encode: encoder,
|
||||
document: {
|
||||
id: "id",
|
||||
index: [
|
||||
{
|
||||
field: "title",
|
||||
tokenize: "reverse",
|
||||
},
|
||||
{
|
||||
field: "content",
|
||||
tokenize: "reverse",
|
||||
},
|
||||
{
|
||||
field: "tags",
|
||||
tokenize: "reverse",
|
||||
},
|
||||
],
|
||||
},
|
||||
})
|
||||
|
||||
fillDocument(index, data)
|
||||
}
|
||||
|
||||
// register handlers
|
||||
registerEscapeHandler(container, hideSearch)
|
||||
})
|
||||
|
||||
/**
|
||||
* Fills flexsearch document with data
|
||||
* @param index index to fill
|
||||
* @param data data to fill index with
|
||||
*/
|
||||
async function fillDocument(index: Document<Item, false>, data: any) {
|
||||
let id = 0
|
||||
for (const [slug, fileData] of Object.entries<ContentDetails>(data)) {
|
||||
await index.addAsync(id, {
|
||||
id,
|
||||
slug: slug as FullSlug,
|
||||
title: fileData.title,
|
||||
content: fileData.content,
|
||||
tags: fileData.tags,
|
||||
})
|
||||
id++
|
||||
}
|
||||
}
|
|
@ -1,155 +0,0 @@
|
|||
import micromorph from "micromorph"
|
||||
import { FullSlug, RelativeURL, getFullSlug } from "../../util/path"
|
||||
|
||||
// adapted from `micromorph`
|
||||
// https://github.com/natemoo-re/micromorph
|
||||
|
||||
const NODE_TYPE_ELEMENT = 1
|
||||
let announcer = document.createElement("route-announcer")
|
||||
const isElement = (target: EventTarget | null): target is Element =>
|
||||
(target as Node)?.nodeType === NODE_TYPE_ELEMENT
|
||||
const isLocalUrl = (href: string) => {
|
||||
try {
|
||||
const url = new URL(href)
|
||||
if (window.location.origin === url.origin) {
|
||||
return true
|
||||
}
|
||||
} catch (e) {}
|
||||
return false
|
||||
}
|
||||
|
||||
const getOpts = ({ target }: Event): { url: URL; scroll?: boolean } | undefined => {
|
||||
if (!isElement(target)) return
|
||||
const a = target.closest("a")
|
||||
if (!a) return
|
||||
if ("routerIgnore" in a.dataset) return
|
||||
const { href } = a
|
||||
if (!isLocalUrl(href)) return
|
||||
return { url: new URL(href), scroll: "routerNoscroll" in a.dataset ? false : undefined }
|
||||
}
|
||||
|
||||
function notifyNav(url: FullSlug) {
|
||||
const event: CustomEventMap["nav"] = new CustomEvent("nav", { detail: { url } })
|
||||
document.dispatchEvent(event)
|
||||
}
|
||||
|
||||
let p: DOMParser
|
||||
async function navigate(url: URL, isBack: boolean = false) {
|
||||
p = p || new DOMParser()
|
||||
const contents = await fetch(`${url}`)
|
||||
.then((res) => res.text())
|
||||
.catch(() => {
|
||||
window.location.assign(url)
|
||||
})
|
||||
|
||||
if (!contents) return
|
||||
|
||||
const html = p.parseFromString(contents, "text/html")
|
||||
let title = html.querySelector("title")?.textContent
|
||||
if (title) {
|
||||
document.title = title
|
||||
} else {
|
||||
const h1 = document.querySelector("h1")
|
||||
title = h1?.innerText ?? h1?.textContent ?? url.pathname
|
||||
}
|
||||
if (announcer.textContent !== title) {
|
||||
announcer.textContent = title
|
||||
}
|
||||
announcer.dataset.persist = ""
|
||||
html.body.appendChild(announcer)
|
||||
|
||||
// morph body
|
||||
micromorph(document.body, html.body)
|
||||
|
||||
// scroll into place and add history
|
||||
if (!isBack) {
|
||||
if (url.hash) {
|
||||
const el = document.getElementById(decodeURIComponent(url.hash.substring(1)))
|
||||
el?.scrollIntoView()
|
||||
} else {
|
||||
window.scrollTo({ top: 0 })
|
||||
}
|
||||
}
|
||||
|
||||
// now, patch head
|
||||
const elementsToRemove = document.head.querySelectorAll(":not([spa-preserve])")
|
||||
elementsToRemove.forEach((el) => el.remove())
|
||||
const elementsToAdd = html.head.querySelectorAll(":not([spa-preserve])")
|
||||
elementsToAdd.forEach((el) => document.head.appendChild(el))
|
||||
|
||||
// delay setting the url until now
|
||||
// at this point everything is loaded so changing the url should resolve to the correct addresses
|
||||
if (!isBack) {
|
||||
history.pushState({}, "", url)
|
||||
}
|
||||
notifyNav(getFullSlug(window))
|
||||
delete announcer.dataset.persist
|
||||
}
|
||||
|
||||
window.spaNavigate = navigate
|
||||
|
||||
function createRouter() {
|
||||
if (typeof window !== "undefined") {
|
||||
window.addEventListener("click", async (event) => {
|
||||
const { url } = getOpts(event) ?? {}
|
||||
if (!url) return
|
||||
event.preventDefault()
|
||||
try {
|
||||
navigate(url, false)
|
||||
} catch (e) {
|
||||
window.location.assign(url)
|
||||
}
|
||||
})
|
||||
|
||||
window.addEventListener("popstate", (event) => {
|
||||
const { url } = getOpts(event) ?? {}
|
||||
if (window.location.hash && window.location.pathname === url?.pathname) return
|
||||
try {
|
||||
navigate(new URL(window.location.toString()), true)
|
||||
} catch (e) {
|
||||
window.location.reload()
|
||||
}
|
||||
return
|
||||
})
|
||||
}
|
||||
|
||||
return new (class Router {
|
||||
go(pathname: RelativeURL) {
|
||||
const url = new URL(pathname, window.location.toString())
|
||||
return navigate(url, false)
|
||||
}
|
||||
|
||||
back() {
|
||||
return window.history.back()
|
||||
}
|
||||
|
||||
forward() {
|
||||
return window.history.forward()
|
||||
}
|
||||
})()
|
||||
}
|
||||
|
||||
createRouter()
|
||||
notifyNav(getFullSlug(window))
|
||||
|
||||
if (!customElements.get("route-announcer")) {
|
||||
const attrs = {
|
||||
"aria-live": "assertive",
|
||||
"aria-atomic": "true",
|
||||
style:
|
||||
"position: absolute; left: 0; top: 0; clip: rect(0 0 0 0); clip-path: inset(50%); overflow: hidden; white-space: nowrap; width: 1px; height: 1px",
|
||||
}
|
||||
customElements.define(
|
||||
"route-announcer",
|
||||
class RouteAnnouncer extends HTMLElement {
|
||||
constructor() {
|
||||
super()
|
||||
}
|
||||
connectedCallback() {
|
||||
for (const [key, value] of Object.entries(attrs)) {
|
||||
this.setAttribute(key, value)
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
|
@ -1,42 +0,0 @@
|
|||
const bufferPx = 150
|
||||
const observer = new IntersectionObserver((entries) => {
|
||||
for (const entry of entries) {
|
||||
const slug = entry.target.id
|
||||
const tocEntryElement = document.querySelector(`a[data-for="${slug}"]`)
|
||||
const windowHeight = entry.rootBounds?.height
|
||||
if (windowHeight && tocEntryElement) {
|
||||
if (entry.boundingClientRect.y < windowHeight) {
|
||||
tocEntryElement.classList.add("in-view")
|
||||
} else {
|
||||
tocEntryElement.classList.remove("in-view")
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
function toggleToc(this: HTMLElement) {
|
||||
this.classList.toggle("collapsed")
|
||||
const content = this.nextElementSibling as HTMLElement
|
||||
content.classList.toggle("collapsed")
|
||||
content.style.maxHeight = content.style.maxHeight === "0px" ? content.scrollHeight + "px" : "0px"
|
||||
}
|
||||
|
||||
function setupToc() {
|
||||
const toc = document.getElementById("toc")
|
||||
if (toc) {
|
||||
const content = toc.nextElementSibling as HTMLElement
|
||||
content.style.maxHeight = content.scrollHeight + "px"
|
||||
toc.removeEventListener("click", toggleToc)
|
||||
toc.addEventListener("click", toggleToc)
|
||||
}
|
||||
}
|
||||
|
||||
window.addEventListener("resize", setupToc)
|
||||
document.addEventListener("nav", () => {
|
||||
setupToc()
|
||||
|
||||
// update toc entry highlighting
|
||||
observer.disconnect()
|
||||
const headers = document.querySelectorAll("h1[id], h2[id], h3[id], h4[id], h5[id], h6[id]")
|
||||
headers.forEach((header) => observer.observe(header))
|
||||
})
|
|
@ -1,25 +0,0 @@
|
|||
export function registerEscapeHandler(outsideContainer: HTMLElement | null, cb: () => void) {
|
||||
if (!outsideContainer) return
|
||||
function click(this: HTMLElement, e: HTMLElementEventMap["click"]) {
|
||||
if (e.target !== this) return
|
||||
e.preventDefault()
|
||||
cb()
|
||||
}
|
||||
|
||||
function esc(e: HTMLElementEventMap["keydown"]) {
|
||||
if (!e.key.startsWith("Esc")) return
|
||||
e.preventDefault()
|
||||
cb()
|
||||
}
|
||||
|
||||
outsideContainer?.removeEventListener("click", click)
|
||||
outsideContainer?.addEventListener("click", click)
|
||||
document.removeEventListener("keydown", esc)
|
||||
document.addEventListener("keydown", esc)
|
||||
}
|
||||
|
||||
export function removeAllChildren(node: HTMLElement) {
|
||||
while (node.firstChild) {
|
||||
node.removeChild(node.firstChild)
|
||||
}
|
||||
}
|
|
@ -1,20 +0,0 @@
|
|||
.backlinks {
|
||||
position: relative;
|
||||
|
||||
& > h3 {
|
||||
font-size: 1rem;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
& > ul {
|
||||
list-style: none;
|
||||
padding: 0;
|
||||
margin: 0.5rem 0;
|
||||
|
||||
& > li {
|
||||
& > a {
|
||||
background-color: transparent;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,36 +0,0 @@
|
|||
.clipboard-button {
|
||||
position: absolute;
|
||||
display: flex;
|
||||
float: right;
|
||||
right: 0;
|
||||
padding: 0.4rem;
|
||||
margin: -0.2rem 0.3rem;
|
||||
color: var(--gray);
|
||||
border-color: var(--dark);
|
||||
background-color: var(--light);
|
||||
border: 1px solid;
|
||||
border-radius: 5px;
|
||||
opacity: 0;
|
||||
transition: 0.2s;
|
||||
|
||||
& > svg {
|
||||
fill: var(--light);
|
||||
filter: contrast(0.3);
|
||||
}
|
||||
|
||||
&:hover {
|
||||
cursor: pointer;
|
||||
border-color: var(--secondary);
|
||||
}
|
||||
|
||||
&:focus {
|
||||
outline: 0;
|
||||
}
|
||||
}
|
||||
|
||||
pre {
|
||||
&:hover > .clipboard-button {
|
||||
opacity: 1;
|
||||
transition: 0.2s;
|
||||
}
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue