Compare commits

...

10 Commits

Author SHA1 Message Date
Jacky Zhao
3173d185ed make og images look nice 2025-03-13 10:17:19 -07:00
Jacky Zhao
de727b4686 use readline instead 2025-03-13 08:46:55 -07:00
Jacky Zhao
07ffc8681e replace spinner, use disk cache for fonts 2025-03-13 08:38:16 -07:00
Jacky Zhao
f301eca9a7 custom font spec 2025-03-12 22:56:59 -07:00
Jacky Zhao
1fb7756c49 fix 2025-03-12 22:26:39 -07:00
Jacky Zhao
c5a8b199ae make emitters async generators 2025-03-12 13:31:43 -07:00
Jacky Zhao
5d50282124 checkpoint 2025-03-12 10:08:18 -07:00
Jacky Zhao
2718ab9019 feat: flex component, document higher-order layout components
Some checks are pending
Build and Test / build-and-test (macos-latest) (push) Waiting to run
Build and Test / build-and-test (windows-latest) (push) Waiting to run
Build and Test / build-and-test (ubuntu-latest) (push) Has been skipped
Build and Test / publish-tag (push) Has been skipped
2025-03-11 14:56:43 -07:00
Jacky Zhao
87b803790c fix(mermaid): themechange detector + expand simplification 2025-03-11 11:45:45 -07:00
Jacky Zhao
e59181c3aa docs(explorer): update to account for new client side explorer) 2025-03-11 10:20:15 -07:00
41 changed files with 1254 additions and 1165 deletions

View File

@@ -25,10 +25,11 @@ The following sections will go into detail for what methods can be implemented f
- `BuildCtx` is defined in `quartz/ctx.ts`. It consists of - `BuildCtx` is defined in `quartz/ctx.ts`. It consists of
- `argv`: The command line arguments passed to the Quartz [[build]] command - `argv`: The command line arguments passed to the Quartz [[build]] command
- `cfg`: The full Quartz [[configuration]] - `cfg`: The full Quartz [[configuration]]
- `allSlugs`: a list of all the valid content slugs (see [[paths]] for more information on what a `ServerSlug` is) - `allSlugs`: a list of all the valid content slugs (see [[paths]] for more information on what a slug is)
- `StaticResources` is defined in `quartz/resources.tsx`. It consists of - `StaticResources` is defined in `quartz/resources.tsx`. It consists of
- `css`: a list of CSS style definitions that should be loaded. A CSS style is described with the `CSSResource` type which is also defined in `quartz/resources.tsx`. It accepts either a source URL or the inline content of the stylesheet. - `css`: a list of CSS style definitions that should be loaded. A CSS style is described with the `CSSResource` type which is also defined in `quartz/resources.tsx`. It accepts either a source URL or the inline content of the stylesheet.
- `js`: a list of scripts that should be loaded. A script is described with the `JSResource` type which is also defined in `quartz/resources.tsx`. It allows you to define a load time (either before or after the DOM has been loaded), whether it should be a module, and either the source URL or the inline content of the script. - `js`: a list of scripts that should be loaded. A script is described with the `JSResource` type which is also defined in `quartz/resources.tsx`. It allows you to define a load time (either before or after the DOM has been loaded), whether it should be a module, and either the source URL or the inline content of the script.
- `additionalHead`: a list of JSX elements or functions that return JSX elements to be added to the `<head>` tag of the page. Functions receive the page's data as an argument and can conditionally render elements.
## Transformers ## Transformers
@@ -234,7 +235,7 @@ export type WriteOptions = (data: {
// the build context // the build context
ctx: BuildCtx ctx: BuildCtx
// the name of the file to emit (not including the file extension) // the name of the file to emit (not including the file extension)
slug: ServerSlug slug: FullSlug
// the file extension // the file extension
ext: `.${string}` | "" ext: `.${string}` | ""
// the file content to add // the file content to add

View File

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

View File

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

62
docs/layout-components.md Normal file
View File

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

View File

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

View File

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

10
package-lock.json generated
View File

@@ -75,7 +75,6 @@
"quartz": "quartz/bootstrap-cli.mjs" "quartz": "quartz/bootstrap-cli.mjs"
}, },
"devDependencies": { "devDependencies": {
"@types/cli-spinner": "^0.2.3",
"@types/d3": "^7.4.3", "@types/d3": "^7.4.3",
"@types/hast": "^3.0.4", "@types/hast": "^3.0.4",
"@types/js-yaml": "^4.0.9", "@types/js-yaml": "^4.0.9",
@@ -1585,15 +1584,6 @@
"integrity": "sha512-XKLA6syeBUaPzx4j3qwMqzzq+V4uo72BnlbOjmuljLrRqdsd3qnzvZZoxvMHZ23ndsRS4aufU6JOZYpCbU6T1A==", "integrity": "sha512-XKLA6syeBUaPzx4j3qwMqzzq+V4uo72BnlbOjmuljLrRqdsd3qnzvZZoxvMHZ23ndsRS4aufU6JOZYpCbU6T1A==",
"license": "MIT" "license": "MIT"
}, },
"node_modules/@types/cli-spinner": {
"version": "0.2.3",
"resolved": "https://registry.npmjs.org/@types/cli-spinner/-/cli-spinner-0.2.3.tgz",
"integrity": "sha512-TMO6mWltW0lCu1de8DMRq9+59OP/tEjghS+rs8ZEQ2EgYP5yV3bGw0tS14TMyJGqFaoVChNvhkVzv9RC1UgX+w==",
"dev": true,
"dependencies": {
"@types/node": "*"
}
},
"node_modules/@types/css-font-loading-module": { "node_modules/@types/css-font-loading-module": {
"version": "0.0.12", "version": "0.0.12",
"resolved": "https://registry.npmjs.org/@types/css-font-loading-module/-/css-font-loading-module-0.0.12.tgz", "resolved": "https://registry.npmjs.org/@types/css-font-loading-module/-/css-font-loading-module-0.0.12.tgz",

View File

@@ -98,7 +98,6 @@
"yargs": "^17.7.2" "yargs": "^17.7.2"
}, },
"devDependencies": { "devDependencies": {
"@types/cli-spinner": "^0.2.3",
"@types/d3": "^7.4.3", "@types/d3": "^7.4.3",
"@types/hast": "^3.0.4", "@types/hast": "^3.0.4",
"@types/js-yaml": "^4.0.9", "@types/js-yaml": "^4.0.9",

View File

@@ -19,7 +19,6 @@ const config: QuartzConfig = {
baseUrl: "quartz.jzhao.xyz", baseUrl: "quartz.jzhao.xyz",
ignorePatterns: ["private", "templates", ".obsidian"], ignorePatterns: ["private", "templates", ".obsidian"],
defaultDateType: "created", defaultDateType: "created",
generateSocialImages: true,
theme: { theme: {
fontOrigin: "googleFonts", fontOrigin: "googleFonts",
cdnCaching: true, cdnCaching: true,
@@ -88,6 +87,7 @@ const config: QuartzConfig = {
Plugin.Assets(), Plugin.Assets(),
Plugin.Static(), Plugin.Static(),
Plugin.NotFoundPage(), Plugin.NotFoundPage(),
Plugin.CustomOgImages(),
], ],
}, },
} }

View File

@@ -25,8 +25,15 @@ export const defaultContentPageLayout: PageLayout = {
left: [ left: [
Component.PageTitle(), Component.PageTitle(),
Component.MobileOnly(Component.Spacer()), Component.MobileOnly(Component.Spacer()),
Component.Search(), Component.Flex({
Component.Darkmode(), components: [
{
Component: Component.Search(),
grow: true,
},
{ Component: Component.Darkmode() },
],
}),
Component.Explorer(), Component.Explorer(),
], ],
right: [ right: [

View File

@@ -250,15 +250,25 @@ async function partialRebuildFromEntrypoint(
([_node, vfile]) => !toRemove.has(vfile.data.filePath!), ([_node, vfile]) => !toRemove.has(vfile.data.filePath!),
) )
const emittedFps = await emitter.emit(ctx, files, staticResources) const emitted = await emitter.emit(ctx, files, staticResources)
if (Symbol.asyncIterator in emitted) {
if (ctx.argv.verbose) { // Async generator case
for (const file of emittedFps) { for await (const file of emitted) {
console.log(`[emit:${emitter.name}] ${file}`) emittedFiles++
if (ctx.argv.verbose) {
console.log(`[emit:${emitter.name}] ${file}`)
}
}
} else {
// Array case
emittedFiles += emitted.length
if (ctx.argv.verbose) {
for (const file of emitted) {
console.log(`[emit:${emitter.name}] ${file}`)
}
} }
} }
emittedFiles += emittedFps.length
continue continue
} }
@@ -280,15 +290,24 @@ async function partialRebuildFromEntrypoint(
.filter((file) => !toRemove.has(file)) .filter((file) => !toRemove.has(file))
.map((file) => contentMap.get(file)!) .map((file) => contentMap.get(file)!)
const emittedFps = await emitter.emit(ctx, upstreamContent, staticResources) const emitted = await emitter.emit(ctx, upstreamContent, staticResources)
if (Symbol.asyncIterator in emitted) {
if (ctx.argv.verbose) { // Async generator case
for (const file of emittedFps) { for await (const file of emitted) {
console.log(`[emit:${emitter.name}] ${file}`) emittedFiles++
if (ctx.argv.verbose) {
console.log(`[emit:${emitter.name}] ${file}`)
}
}
} else {
// Array case
emittedFiles += emitted.length
if (ctx.argv.verbose) {
for (const file of emitted) {
console.log(`[emit:${emitter.name}] ${file}`)
}
} }
} }
emittedFiles += emittedFps.length
} }
} }

View File

@@ -61,10 +61,6 @@ export interface GlobalConfiguration {
* Quartz will avoid using this as much as possible and use relative URLs most of the time * Quartz will avoid using this as much as possible and use relative URLs most of the time
*/ */
baseUrl?: string baseUrl?: string
/**
* Whether to generate social images (Open Graph and Twitter standard) for link previews
*/
generateSocialImages: boolean | Partial<SocialImageOptions>
theme: Theme theme: Theme
/** /**
* Allow to translate the date in the language of your choice. * Allow to translate the date in the language of your choice.

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -31,7 +31,7 @@ export const NotFoundPage: QuartzEmitterPlugin = () => {
async getDependencyGraph(_ctx, _content, _resources) { async getDependencyGraph(_ctx, _content, _resources) {
return new DepGraph<FilePath>() return new DepGraph<FilePath>()
}, },
async emit(ctx, _content, resources): Promise<FilePath[]> { async *emit(ctx, _content, resources) {
const cfg = ctx.cfg.configuration const cfg = ctx.cfg.configuration
const slug = "404" as FullSlug const slug = "404" as FullSlug
@@ -55,14 +55,12 @@ export const NotFoundPage: QuartzEmitterPlugin = () => {
allFiles: [], allFiles: [],
} }
return [ yield write({
await write({ ctx,
ctx, content: renderPage(cfg, slug, componentData, opts, externalResources),
content: renderPage(cfg, slug, componentData, opts, externalResources), slug,
slug, ext: ".html",
ext: ".html", })
}),
]
}, },
} }
} }

View File

@@ -18,15 +18,13 @@ export const AliasRedirects: QuartzEmitterPlugin = () => ({
return graph return graph
}, },
async emit(ctx, content, _resources): Promise<FilePath[]> { async *emit(ctx, content, _resources) {
const fps: FilePath[] = []
for (const [_tree, file] of content) { for (const [_tree, file] of content) {
const ogSlug = simplifySlug(file.data.slug!) const ogSlug = simplifySlug(file.data.slug!)
for (const slug of file.data.aliases ?? []) { for (const slug of file.data.aliases ?? []) {
const redirUrl = resolveRelative(slug, file.data.slug!) const redirUrl = resolveRelative(slug, file.data.slug!)
const fp = await write({ yield write({
ctx, ctx,
content: ` content: `
<!DOCTYPE html> <!DOCTYPE html>
@@ -43,10 +41,7 @@ export const AliasRedirects: QuartzEmitterPlugin = () => ({
slug, slug,
ext: ".html", ext: ".html",
}) })
fps.push(fp)
} }
} }
return fps
}, },
}) })

View File

@@ -33,10 +33,9 @@ export const Assets: QuartzEmitterPlugin = () => {
return graph return graph
}, },
async emit({ argv, cfg }, _content, _resources): Promise<FilePath[]> { async *emit({ argv, cfg }, _content, _resources) {
const assetsPath = argv.output const assetsPath = argv.output
const fps = await filesToCopy(argv, cfg) const fps = await filesToCopy(argv, cfg)
const res: FilePath[] = []
for (const fp of fps) { for (const fp of fps) {
const ext = path.extname(fp) const ext = path.extname(fp)
const src = joinSegments(argv.directory, fp) as FilePath const src = joinSegments(argv.directory, fp) as FilePath
@@ -46,10 +45,8 @@ export const Assets: QuartzEmitterPlugin = () => {
const dir = path.dirname(dest) as FilePath const dir = path.dirname(dest) as FilePath
await fs.promises.mkdir(dir, { recursive: true }) // ensure dir exists await fs.promises.mkdir(dir, { recursive: true }) // ensure dir exists
await fs.promises.copyFile(src, dest) await fs.promises.copyFile(src, dest)
res.push(dest) yield dest
} }
return res
}, },
} }
} }

View File

@@ -14,7 +14,7 @@ export const CNAME: QuartzEmitterPlugin = () => ({
async getDependencyGraph(_ctx, _content, _resources) { async getDependencyGraph(_ctx, _content, _resources) {
return new DepGraph<FilePath>() return new DepGraph<FilePath>()
}, },
async emit({ argv, cfg }, _content, _resources): Promise<FilePath[]> { async emit({ argv, cfg }, _content, _resources) {
if (!cfg.configuration.baseUrl) { if (!cfg.configuration.baseUrl) {
console.warn(chalk.yellow("CNAME emitter requires `baseUrl` to be set in your configuration")) console.warn(chalk.yellow("CNAME emitter requires `baseUrl` to be set in your configuration"))
return [] return []
@@ -24,7 +24,7 @@ export const CNAME: QuartzEmitterPlugin = () => ({
if (!content) { if (!content) {
return [] return []
} }
fs.writeFileSync(path, content) await fs.promises.writeFile(path, content)
return [path] as FilePath[] return [path] as FilePath[]
}, },
}) })

View File

@@ -9,7 +9,7 @@ import styles from "../../styles/custom.scss"
import popoverStyle from "../../components/styles/popover.scss" import popoverStyle from "../../components/styles/popover.scss"
import { BuildCtx } from "../../util/ctx" import { BuildCtx } from "../../util/ctx"
import { QuartzComponent } from "../../components/types" import { QuartzComponent } from "../../components/types"
import { googleFontHref, joinStyles } from "../../util/theme" import { googleFontHref, joinStyles, processGoogleFonts } from "../../util/theme"
import { Features, transform } from "lightningcss" import { Features, transform } from "lightningcss"
import { transform as transpile } from "esbuild" import { transform as transpile } from "esbuild"
import { write } from "./helpers" import { write } from "./helpers"
@@ -207,8 +207,7 @@ export const ComponentResources: QuartzEmitterPlugin = () => {
async getDependencyGraph(_ctx, _content, _resources) { async getDependencyGraph(_ctx, _content, _resources) {
return new DepGraph<FilePath>() return new DepGraph<FilePath>()
}, },
async emit(ctx, _content, _resources): Promise<FilePath[]> { async *emit(ctx, _content, _resources) {
const promises: Promise<FilePath>[] = []
const cfg = ctx.cfg.configuration const cfg = ctx.cfg.configuration
// component specific scripts and styles // component specific scripts and styles
const componentResources = getComponentResources(ctx) const componentResources = getComponentResources(ctx)
@@ -217,42 +216,35 @@ export const ComponentResources: QuartzEmitterPlugin = () => {
// let the user do it themselves in css // let the user do it themselves in css
} else if (cfg.theme.fontOrigin === "googleFonts" && !cfg.theme.cdnCaching) { } else if (cfg.theme.fontOrigin === "googleFonts" && !cfg.theme.cdnCaching) {
// when cdnCaching is true, we link to google fonts in Head.tsx // when cdnCaching is true, we link to google fonts in Head.tsx
let match const response = await fetch(googleFontHref(ctx.cfg.configuration.theme))
googleFontsStyleSheet = await response.text()
const fontSourceRegex = /url\((https:\/\/fonts.gstatic.com\/s\/[^)]+\.(woff2|ttf))\)/g if (!cfg.baseUrl) {
throw new Error(
googleFontsStyleSheet = await ( "baseUrl must be defined when using Google Fonts without cfg.theme.cdnCaching",
await fetch(googleFontHref(ctx.cfg.configuration.theme))
).text()
while ((match = fontSourceRegex.exec(googleFontsStyleSheet)) !== null) {
// match[0] is the `url(path)`, match[1] is the `path`
const url = match[1]
// the static name of this file.
const [filename, ext] = url.split("/").pop()!.split(".")
googleFontsStyleSheet = googleFontsStyleSheet.replace(
url,
`https://${cfg.baseUrl}/static/fonts/${filename}.ttf`,
) )
}
promises.push( const { processedStylesheet, fontFiles } = await processGoogleFonts(
fetch(url) googleFontsStyleSheet,
.then((res) => { cfg.baseUrl,
if (!res.ok) { )
throw new Error(`Failed to fetch font`) googleFontsStyleSheet = processedStylesheet
}
return res.arrayBuffer() // Download and save font files
}) for (const fontFile of fontFiles) {
.then((buf) => const res = await fetch(fontFile.url)
write({ if (!res.ok) {
ctx, throw new Error(`failed to fetch font ${fontFile.filename}`)
slug: joinSegments("static", "fonts", filename) as FullSlug, }
ext: `.${ext}`,
content: Buffer.from(buf), const buf = await res.arrayBuffer()
}), yield write({
), ctx,
) slug: joinSegments("static", "fonts", fontFile.filename) as FullSlug,
ext: `.${fontFile.extension}`,
content: Buffer.from(buf),
})
} }
} }
@@ -267,45 +259,42 @@ export const ComponentResources: QuartzEmitterPlugin = () => {
...componentResources.css, ...componentResources.css,
styles, styles,
) )
const [prescript, postscript] = await Promise.all([ const [prescript, postscript] = await Promise.all([
joinScripts(componentResources.beforeDOMLoaded), joinScripts(componentResources.beforeDOMLoaded),
joinScripts(componentResources.afterDOMLoaded), joinScripts(componentResources.afterDOMLoaded),
]) ])
promises.push( yield write({
write({ ctx,
ctx, slug: "index" as FullSlug,
slug: "index" as FullSlug, ext: ".css",
ext: ".css", content: transform({
content: transform({ filename: "index.css",
filename: "index.css", code: Buffer.from(stylesheet),
code: Buffer.from(stylesheet), minify: true,
minify: true, targets: {
targets: { safari: (15 << 16) | (6 << 8), // 15.6
safari: (15 << 16) | (6 << 8), // 15.6 ios_saf: (15 << 16) | (6 << 8), // 15.6
ios_saf: (15 << 16) | (6 << 8), // 15.6 edge: 115 << 16,
edge: 115 << 16, firefox: 102 << 16,
firefox: 102 << 16, chrome: 109 << 16,
chrome: 109 << 16, },
}, include: Features.MediaQueries,
include: Features.MediaQueries, }).code.toString(),
}).code.toString(), }),
}), yield write({
write({
ctx, ctx,
slug: "prescript" as FullSlug, slug: "prescript" as FullSlug,
ext: ".js", ext: ".js",
content: prescript, content: prescript,
}), }),
write({ yield write({
ctx, ctx,
slug: "postscript" as FullSlug, slug: "postscript" as FullSlug,
ext: ".js", ext: ".js",
content: postscript, content: postscript,
}), })
)
return await Promise.all(promises)
}, },
} }
} }

View File

@@ -116,9 +116,8 @@ export const ContentIndex: QuartzEmitterPlugin<Partial<Options>> = (opts) => {
return graph return graph
}, },
async emit(ctx, content, _resources) { async *emit(ctx, content, _resources) {
const cfg = ctx.cfg.configuration const cfg = ctx.cfg.configuration
const emitted: FilePath[] = []
const linkIndex: ContentIndexMap = new Map() const linkIndex: ContentIndexMap = new Map()
for (const [tree, file] of content) { for (const [tree, file] of content) {
const slug = file.data.slug! const slug = file.data.slug!
@@ -140,25 +139,21 @@ export const ContentIndex: QuartzEmitterPlugin<Partial<Options>> = (opts) => {
} }
if (opts?.enableSiteMap) { if (opts?.enableSiteMap) {
emitted.push( yield write({
await write({ ctx,
ctx, content: generateSiteMap(cfg, linkIndex),
content: generateSiteMap(cfg, linkIndex), slug: "sitemap" as FullSlug,
slug: "sitemap" as FullSlug, ext: ".xml",
ext: ".xml", })
}),
)
} }
if (opts?.enableRSS) { if (opts?.enableRSS) {
emitted.push( yield write({
await write({ ctx,
ctx, content: generateRSSFeed(cfg, linkIndex, opts.rssLimit),
content: generateRSSFeed(cfg, linkIndex, opts.rssLimit), slug: (opts?.rssSlug ?? "index") as FullSlug,
slug: (opts?.rssSlug ?? "index") as FullSlug, ext: ".xml",
ext: ".xml", })
}),
)
} }
const fp = joinSegments("static", "contentIndex") as FullSlug const fp = joinSegments("static", "contentIndex") as FullSlug
@@ -173,16 +168,12 @@ export const ContentIndex: QuartzEmitterPlugin<Partial<Options>> = (opts) => {
}), }),
) )
emitted.push( yield write({
await write({ ctx,
ctx, content: JSON.stringify(simplifiedIndex),
content: JSON.stringify(simplifiedIndex), slug: fp,
slug: fp, ext: ".json",
ext: ".json", })
}),
)
return emitted
}, },
externalResources: (ctx) => { externalResources: (ctx) => {
if (opts?.enableRSS) { if (opts?.enableRSS) {

View File

@@ -94,9 +94,8 @@ export const ContentPage: QuartzEmitterPlugin<Partial<FullPageLayout>> = (userOp
return graph return graph
}, },
async emit(ctx, content, resources): Promise<FilePath[]> { async *emit(ctx, content, resources) {
const cfg = ctx.cfg.configuration const cfg = ctx.cfg.configuration
const fps: FilePath[] = []
const allFiles = content.map((c) => c[1].data) const allFiles = content.map((c) => c[1].data)
let containsIndex = false let containsIndex = false
@@ -118,14 +117,12 @@ export const ContentPage: QuartzEmitterPlugin<Partial<FullPageLayout>> = (userOp
} }
const content = renderPage(cfg, slug, componentData, opts, externalResources) const content = renderPage(cfg, slug, componentData, opts, externalResources)
const fp = await write({ yield write({
ctx, ctx,
content, content,
slug, slug,
ext: ".html", ext: ".html",
}) })
fps.push(fp)
} }
if (!containsIndex && !ctx.argv.fastRebuild) { if (!containsIndex && !ctx.argv.fastRebuild) {
@@ -135,8 +132,6 @@ export const ContentPage: QuartzEmitterPlugin<Partial<FullPageLayout>> = (userOp
), ),
) )
} }
return fps
}, },
} }
} }

View File

@@ -69,8 +69,7 @@ export const FolderPage: QuartzEmitterPlugin<Partial<FolderPageOptions>> = (user
return graph return graph
}, },
async emit(ctx, content, resources): Promise<FilePath[]> { async *emit(ctx, content, resources) {
const fps: FilePath[] = []
const allFiles = content.map((c) => c[1].data) const allFiles = content.map((c) => c[1].data)
const cfg = ctx.cfg.configuration const cfg = ctx.cfg.configuration
@@ -119,16 +118,13 @@ export const FolderPage: QuartzEmitterPlugin<Partial<FolderPageOptions>> = (user
} }
const content = renderPage(cfg, slug, componentData, opts, externalResources) const content = renderPage(cfg, slug, componentData, opts, externalResources)
const fp = await write({ yield write({
ctx, ctx,
content, content,
slug, slug,
ext: ".html", ext: ".html",
}) })
fps.push(fp)
} }
return fps
}, },
} }
} }

View File

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

View File

@@ -8,3 +8,4 @@ export { Static } from "./static"
export { ComponentResources } from "./componentResources" export { ComponentResources } from "./componentResources"
export { NotFoundPage } from "./404" export { NotFoundPage } from "./404"
export { CNAME } from "./cname" export { CNAME } from "./cname"
export { CustomOgImages } from "./ogImage"

View File

@@ -0,0 +1,134 @@
import { QuartzEmitterPlugin } from "../types"
import { i18n } from "../../i18n"
import { unescapeHTML } from "../../util/escape"
import { FullSlug, getFileExtension } from "../../util/path"
import { ImageOptions, SocialImageOptions, defaultImage, getSatoriFonts } from "../../util/og"
import sharp from "sharp"
import satori from "satori"
import { loadEmoji, getIconCode } from "../../util/emoji"
import { Readable } from "stream"
import { write } from "./helpers"
const defaultOptions: SocialImageOptions = {
colorScheme: "lightMode",
width: 1200,
height: 630,
imageStructure: defaultImage,
excludeRoot: false,
}
/**
* Generates social image (OG/twitter standard) and saves it as `.webp` inside the public folder
* @param opts options for generating image
*/
async function generateSocialImage(
{ cfg, description, fonts, title, fileData }: ImageOptions,
userOpts: SocialImageOptions,
): Promise<Readable> {
const { width, height } = userOpts
const imageComponent = userOpts.imageStructure(cfg, userOpts, title, description, fonts, fileData)
const svg = await satori(imageComponent, {
width,
height,
fonts,
loadAdditionalAsset: async (languageCode: string, segment: string) => {
if (languageCode === "emoji") {
return `data:image/svg+xml;base64,${btoa(await loadEmoji(getIconCode(segment)))}`
}
return languageCode
},
})
return sharp(Buffer.from(svg)).webp({ quality: 40 })
}
export const CustomOgImagesEmitterName = "CustomOgImages"
export const CustomOgImages: QuartzEmitterPlugin<Partial<SocialImageOptions>> = (userOpts) => {
const fullOptions = { ...defaultOptions, ...userOpts }
return {
name: CustomOgImagesEmitterName,
getQuartzComponents() {
return []
},
async *emit(ctx, content, _resources) {
const cfg = ctx.cfg.configuration
const headerFont = cfg.theme.typography.header
const bodyFont = cfg.theme.typography.body
const fonts = await getSatoriFonts(headerFont, bodyFont)
for (const [_tree, vfile] of content) {
// if this file defines socialImage, we can skip
if (vfile.data.frontmatter?.socialImage !== undefined) {
continue
}
const slug = vfile.data.slug!
const titleSuffix = cfg.pageTitleSuffix ?? ""
const title =
(vfile.data.frontmatter?.title ?? i18n(cfg.locale).propertyDefaults.title) + titleSuffix
const description =
vfile.data.frontmatter?.socialDescription ??
vfile.data.frontmatter?.description ??
unescapeHTML(
vfile.data.description?.trim() ?? i18n(cfg.locale).propertyDefaults.description,
)
const stream = await generateSocialImage(
{
title,
description,
fonts,
cfg,
fileData: vfile.data,
},
fullOptions,
)
yield write({
ctx,
content: stream,
slug: `${slug}-og-image` as FullSlug,
ext: ".webp",
})
}
},
externalResources: (ctx) => {
if (!ctx.cfg.configuration.baseUrl) {
return {}
}
const baseUrl = ctx.cfg.configuration.baseUrl
return {
additionalHead: [
(pageData) => {
const isRealFile = pageData.filePath !== undefined
const userDefinedOgImagePath = pageData.frontmatter?.socialImage
const generatedOgImagePath = isRealFile
? `https://${baseUrl}/${pageData.slug!}-og-image.webp`
: undefined
const defaultOgImagePath = `https://${baseUrl}/static/og-image.png`
const ogImagePath = userDefinedOgImagePath ?? generatedOgImagePath ?? defaultOgImagePath
const ogImageMimeType = `image/${getFileExtension(ogImagePath) ?? "png"}`
return (
<>
{!userDefinedOgImagePath && (
<>
<meta property="og:image:width" content={fullOptions.width.toString()} />
<meta property="og:image:height" content={fullOptions.height.toString()} />
</>
)}
<meta property="og:image" content={ogImagePath} />
<meta property="og:image:url" content={ogImagePath} />
<meta name="twitter:image" content={ogImagePath} />
<meta property="og:image:type" content={ogImageMimeType} />
</>
)
},
],
}
},
}
}

View File

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

View File

@@ -71,8 +71,7 @@ export const TagPage: QuartzEmitterPlugin<Partial<TagPageOptions>> = (userOpts)
return graph return graph
}, },
async emit(ctx, content, resources): Promise<FilePath[]> { async *emit(ctx, content, resources) {
const fps: FilePath[] = []
const allFiles = content.map((c) => c[1].data) const allFiles = content.map((c) => c[1].data)
const cfg = ctx.cfg.configuration const cfg = ctx.cfg.configuration
@@ -127,16 +126,13 @@ export const TagPage: QuartzEmitterPlugin<Partial<TagPageOptions>> = (userOpts)
} }
const content = renderPage(cfg, slug, componentData, opts, externalResources) const content = renderPage(cfg, slug, componentData, opts, externalResources)
const fp = await write({ yield write({
ctx, ctx,
content, content,
slug: file.data.slug!, slug: file.data.slug!,
ext: ".html", ext: ".html",
}) })
fps.push(fp)
} }
return fps
}, },
} }
} }

View File

@@ -131,6 +131,7 @@ declare module "vfile" {
created: string created: string
published: string published: string
description: string description: string
socialDescription: string
publish: boolean | string publish: boolean | string
draft: boolean | string draft: boolean | string
lang: string lang: string

View File

@@ -675,7 +675,6 @@ export const ObsidianFlavoredMarkdown: QuartzTransformerPlugin<Partial<Options>>
properties: { properties: {
className: ["expand-button"], className: ["expand-button"],
"aria-label": "Expand mermaid diagram", "aria-label": "Expand mermaid diagram",
"aria-hidden": "true",
"data-view-component": true, "data-view-component": true,
}, },
children: [ children: [
@@ -706,70 +705,13 @@ export const ObsidianFlavoredMarkdown: QuartzTransformerPlugin<Partial<Options>>
{ {
type: "element", type: "element",
tagName: "div", tagName: "div",
properties: { id: "mermaid-container" }, properties: { id: "mermaid-container", role: "dialog" },
children: [ children: [
{ {
type: "element", type: "element",
tagName: "div", tagName: "div",
properties: { id: "mermaid-space" }, properties: { id: "mermaid-space" },
children: [ children: [
{
type: "element",
tagName: "div",
properties: { className: ["mermaid-header"] },
children: [
{
type: "element",
tagName: "button",
properties: {
className: ["close-button"],
"aria-label": "close button",
},
children: [
{
type: "element",
tagName: "svg",
properties: {
"aria-hidden": "true",
xmlns: "http://www.w3.org/2000/svg",
width: 24,
height: 24,
viewBox: "0 0 24 24",
fill: "none",
stroke: "currentColor",
"stroke-width": "2",
"stroke-linecap": "round",
"stroke-linejoin": "round",
},
children: [
{
type: "element",
tagName: "line",
properties: {
x1: 18,
y1: 6,
x2: 6,
y2: 18,
},
children: [],
},
{
type: "element",
tagName: "line",
properties: {
x1: 6,
y1: 6,
x2: 18,
y2: 18,
},
children: [],
},
],
},
],
},
],
},
{ {
type: "element", type: "element",
tagName: "div", tagName: "div",

View File

@@ -38,7 +38,11 @@ export type QuartzEmitterPlugin<Options extends OptionType = undefined> = (
) => QuartzEmitterPluginInstance ) => QuartzEmitterPluginInstance
export type QuartzEmitterPluginInstance = { export type QuartzEmitterPluginInstance = {
name: string name: string
emit(ctx: BuildCtx, content: ProcessedContent[], resources: StaticResources): Promise<FilePath[]> emit(
ctx: BuildCtx,
content: ProcessedContent[],
resources: StaticResources,
): Promise<FilePath[]> | AsyncGenerator<FilePath>
/** /**
* Returns the components (if any) that are used in rendering the page. * Returns the components (if any) that are used in rendering the page.
* This helps Quartz optimize the page by only including necessary resources * This helps Quartz optimize the page by only including necessary resources

View File

@@ -4,6 +4,7 @@ import { ProcessedContent } from "../plugins/vfile"
import { QuartzLogger } from "../util/log" import { QuartzLogger } from "../util/log"
import { trace } from "../util/trace" import { trace } from "../util/trace"
import { BuildCtx } from "../util/ctx" import { BuildCtx } from "../util/ctx"
import chalk from "chalk"
export async function emitContent(ctx: BuildCtx, content: ProcessedContent[]) { export async function emitContent(ctx: BuildCtx, content: ProcessedContent[]) {
const { argv, cfg } = ctx const { argv, cfg } = ctx
@@ -14,20 +15,36 @@ export async function emitContent(ctx: BuildCtx, content: ProcessedContent[]) {
let emittedFiles = 0 let emittedFiles = 0
const staticResources = getStaticResourcesFromPlugins(ctx) const staticResources = getStaticResourcesFromPlugins(ctx)
for (const emitter of cfg.plugins.emitters) { await Promise.all(
try { cfg.plugins.emitters.map(async (emitter) => {
const emitted = await emitter.emit(ctx, content, staticResources) try {
emittedFiles += emitted.length const emitted = await emitter.emit(ctx, content, staticResources)
if (Symbol.asyncIterator in emitted) {
if (ctx.argv.verbose) { // Async generator case
for (const file of emitted) { for await (const file of emitted) {
console.log(`[emit:${emitter.name}] ${file}`) emittedFiles++
if (ctx.argv.verbose) {
console.log(`[emit:${emitter.name}] ${file}`)
} else {
log.updateText(`Emitting output files: ${chalk.gray(file)}`)
}
}
} else {
// Array case
emittedFiles += emitted.length
for (const file of emitted) {
if (ctx.argv.verbose) {
console.log(`[emit:${emitter.name}] ${file}`)
} else {
log.updateText(`Emitting output files: ${chalk.gray(file)}`)
}
}
} }
} catch (err) {
trace(`Failed to emit from plugin \`${emitter.name}\``, err as Error)
} }
} catch (err) { }),
trace(`Failed to emit from plugin \`${emitter.name}\``, err as Error) )
}
}
log.end(`Emitted ${emittedFiles} files to \`${argv.output}\` in ${perf.timeSince()}`) log.end(`Emitted ${emittedFiles} files to \`${argv.output}\` in ${perf.timeSince()}`)
} }

View File

@@ -1,26 +1,43 @@
import { Spinner } from "cli-spinner" import readline from "readline"
export class QuartzLogger { export class QuartzLogger {
verbose: boolean verbose: boolean
spinner: Spinner | undefined private spinnerInterval: NodeJS.Timeout | undefined
private spinnerText: string = ""
private spinnerIndex: number = 0
private readonly spinnerChars = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]
constructor(verbose: boolean) { constructor(verbose: boolean) {
this.verbose = verbose this.verbose = verbose
} }
start(text: string) { start(text: string) {
this.spinnerText = text
if (this.verbose) { if (this.verbose) {
console.log(text) console.log(text)
} else { } else {
this.spinner = new Spinner(`%s ${text}`) this.spinnerIndex = 0
this.spinner.setSpinnerString(18) this.spinnerInterval = setInterval(() => {
this.spinner.start() readline.clearLine(process.stdout, 0)
readline.cursorTo(process.stdout, 0)
process.stdout.write(`${this.spinnerChars[this.spinnerIndex]} ${this.spinnerText}`)
this.spinnerIndex = (this.spinnerIndex + 1) % this.spinnerChars.length
}, 100)
} }
} }
updateText(text: string) {
this.spinnerText = text
}
end(text?: string) { end(text?: string) {
if (!this.verbose) { if (!this.verbose && this.spinnerInterval) {
this.spinner!.stop(true) clearInterval(this.spinnerInterval)
this.spinnerInterval = undefined
readline.clearLine(process.stdout, 0)
readline.cursorTo(process.stdout, 0)
} }
if (text) { if (text) {
console.log(text) console.log(text)
} }

View File

@@ -1,28 +1,55 @@
import { promises as fs } from "fs"
import { FontWeight, SatoriOptions } from "satori/wasm" import { FontWeight, SatoriOptions } from "satori/wasm"
import { GlobalConfiguration } from "../cfg" import { GlobalConfiguration } from "../cfg"
import { QuartzPluginData } from "../plugins/vfile" import { QuartzPluginData } from "../plugins/vfile"
import { JSXInternal } from "preact/src/jsx" import { JSXInternal } from "preact/src/jsx"
import { ThemeKey } from "./theme" import { FontSpecification, ThemeKey } from "./theme"
import path from "path"
import { QUARTZ } from "./path"
import { formatDate } from "../components/Date"
import { getDate } from "../components/Date"
/** const defaultHeaderWeight = [700]
* Get an array of `FontOptions` (for satori) given google font names const defaultBodyWeight = [400]
* @param headerFontName name of google font used for header export async function getSatoriFonts(headerFont: FontSpecification, bodyFont: FontSpecification) {
* @param bodyFontName name of google font used for body // Get all weights for header and body fonts
* @returns FontOptions for header and body const headerWeights: FontWeight[] = (
*/ typeof headerFont === "string"
export async function getSatoriFont(headerFontName: string, bodyFontName: string) { ? defaultHeaderWeight
const headerWeight = 700 as FontWeight : (headerFont.weights ?? defaultHeaderWeight)
const bodyWeight = 400 as FontWeight ) as FontWeight[]
const bodyWeights: FontWeight[] = (
typeof bodyFont === "string" ? defaultBodyWeight : (bodyFont.weights ?? defaultBodyWeight)
) as FontWeight[]
// Fetch fonts const headerFontName = typeof headerFont === "string" ? headerFont : headerFont.name
const headerFont = await fetchTtf(headerFontName, headerWeight) const bodyFontName = typeof bodyFont === "string" ? bodyFont : bodyFont.name
const bodyFont = await fetchTtf(bodyFontName, bodyWeight)
// Fetch fonts for all weights
const headerFontPromises = headerWeights.map((weight) => fetchTtf(headerFontName, weight))
const bodyFontPromises = bodyWeights.map((weight) => fetchTtf(bodyFontName, weight))
const [headerFontData, bodyFontData] = await Promise.all([
Promise.all(headerFontPromises),
Promise.all(bodyFontPromises),
])
// Convert fonts to satori font format and return // Convert fonts to satori font format and return
const fonts: SatoriOptions["fonts"] = [ const fonts: SatoriOptions["fonts"] = [
{ name: headerFontName, data: headerFont, weight: headerWeight, style: "normal" }, ...headerFontData.map((data, idx) => ({
{ name: bodyFontName, data: bodyFont, weight: bodyWeight, style: "normal" }, name: headerFontName,
data,
weight: headerWeights[idx],
style: "normal" as const,
})),
...bodyFontData.map((data, idx) => ({
name: bodyFontName,
data,
weight: bodyWeights[idx],
style: "normal" as const,
})),
] ]
return fonts return fonts
} }
@@ -32,32 +59,49 @@ export async function getSatoriFont(headerFontName: string, bodyFontName: string
* @param weight what font weight to fetch font * @param weight what font weight to fetch font
* @returns `.ttf` file of google font * @returns `.ttf` file of google font
*/ */
async function fetchTtf(fontName: string, weight: FontWeight): Promise<ArrayBuffer> { export async function fetchTtf(
fontName: string,
weight: FontWeight,
): Promise<Buffer<ArrayBufferLike>> {
const cacheKey = `${fontName.replaceAll(" ", "-")}-${weight}`
const cacheDir = path.join(QUARTZ, ".quartz-cache", "fonts")
const cachePath = path.join(cacheDir, cacheKey)
// Check if font exists in cache
try { try {
// Get css file from google fonts await fs.access(cachePath)
const cssResponse = await fetch( return fs.readFile(cachePath)
`https://fonts.googleapis.com/css2?family=${fontName}:wght@${weight}`,
)
const css = await cssResponse.text()
// Extract .ttf url from css file
const urlRegex = /url\((https:\/\/fonts.gstatic.com\/s\/.*?.ttf)\)/g
const match = urlRegex.exec(css)
if (!match) {
throw new Error("Could not fetch font")
}
// Retrieve font data as ArrayBuffer
const fontResponse = await fetch(match[1])
// fontData is an ArrayBuffer containing the .ttf file data (get match[1] due to google fonts response format, always contains link twice, but second entry is the "raw" link)
const fontData = await fontResponse.arrayBuffer()
return fontData
} catch (error) { } catch (error) {
throw new Error(`Error fetching font: ${error}`) // ignore errors and fetch font
} }
// Get css file from google fonts
const cssResponse = await fetch(
`https://fonts.googleapis.com/css2?family=${fontName}:wght@${weight}`,
)
const css = await cssResponse.text()
// Extract .ttf url from css file
const urlRegex = /url\((https:\/\/fonts.gstatic.com\/s\/.*?.ttf)\)/g
const match = urlRegex.exec(css)
if (!match) {
throw new Error("Could not fetch font")
}
// fontData is an ArrayBuffer containing the .ttf file data
const fontResponse = await fetch(match[1])
const fontData = Buffer.from(await fontResponse.arrayBuffer())
try {
await fs.mkdir(cacheDir, { recursive: true })
await fs.writeFile(cachePath, fontData)
} catch (error) {
console.warn(`Failed to cache font: ${error}`)
// Continue even if caching fails
}
return fontData
} }
export type SocialImageOptions = { export type SocialImageOptions = {
@@ -108,22 +152,10 @@ export type ImageOptions = {
* what description to use as body in image * what description to use as body in image
*/ */
description: string description: string
/**
* what fileName to use when writing to disk
*/
fileName: string
/**
* what directory to store image in
*/
fileDir: string
/**
* what file extension to use (should be `webp` unless you also change sharp conversion)
*/
fileExt: string
/** /**
* header + body font to be used when generating satori image (as promise to work around sync in component) * header + body font to be used when generating satori image (as promise to work around sync in component)
*/ */
fontsPromise: Promise<SatoriOptions["fonts"]> fonts: SatoriOptions["fonts"]
/** /**
* `GlobalConfiguration` of quartz (used for theme/typography) * `GlobalConfiguration` of quartz (used for theme/typography)
*/ */
@@ -141,68 +173,94 @@ export const defaultImage: SocialImageOptions["imageStructure"] = (
title: string, title: string,
description: string, description: string,
fonts: SatoriOptions["fonts"], fonts: SatoriOptions["fonts"],
_fileData: QuartzPluginData, fileData: QuartzPluginData,
) => { ) => {
const fontBreakPoint = 22 const fontBreakPoint = 32
const useSmallerFont = title.length > fontBreakPoint const useSmallerFont = title.length > fontBreakPoint
const iconPath = `https://${cfg.baseUrl}/static/icon.png` const iconPath = `https://${cfg.baseUrl}/static/icon.png`
// Format date if available
const rawDate = getDate(cfg, fileData)
const date = rawDate ? formatDate(rawDate, cfg.locale) : null
// Get tags if available
const tags = fileData.frontmatter?.tags ?? []
return ( return (
<div <div
style={{ style={{
display: "flex", display: "flex",
flexDirection: "column", flexDirection: "column",
justifyContent: "center",
alignItems: "center",
height: "100%", height: "100%",
width: "100%", width: "100%",
backgroundColor: cfg.theme.colors[colorScheme].light, backgroundColor: cfg.theme.colors[colorScheme].light,
gap: "2rem", padding: "2.5rem",
padding: "1.5rem 5rem", fontFamily: fonts[1].name,
}} }}
> >
{/* Header Section */}
<div <div
style={{ style={{
display: "flex", display: "flex",
alignItems: "center", alignItems: "center",
width: "100%", gap: "1rem",
flexDirection: "row", marginBottom: "0.5rem",
gap: "2.5rem",
}} }}
> >
<img src={iconPath} width={135} height={135} /> <img
src={iconPath}
width={56}
height={56}
style={{
borderRadius: "50%",
}}
/>
<div <div
style={{ style={{
display: "flex", display: "flex",
color: cfg.theme.colors[colorScheme].dark, fontSize: 32,
fontSize: useSmallerFont ? 70 : 82, color: cfg.theme.colors[colorScheme].gray,
fontFamily: fonts[0].name, fontFamily: fonts[1].name,
maxWidth: "70%",
overflow: "hidden",
textOverflow: "ellipsis",
}} }}
> >
<p {cfg.baseUrl}
style={{
margin: 0,
overflow: "hidden",
textOverflow: "ellipsis",
whiteSpace: "nowrap",
}}
>
{title}
</p>
</div> </div>
</div> </div>
{/* Title Section */}
<div <div
style={{ style={{
display: "flex", display: "flex",
color: cfg.theme.colors[colorScheme].dark, marginTop: "1rem",
fontSize: 44, marginBottom: "1.5rem",
fontFamily: fonts[1].name, }}
maxWidth: "100%", >
maxHeight: "40%", <h1
overflow: "hidden", style={{
margin: 0,
fontSize: useSmallerFont ? 64 : 72,
fontFamily: fonts[0].name,
fontWeight: 700,
color: cfg.theme.colors[colorScheme].dark,
lineHeight: 1.2,
display: "-webkit-box",
WebkitBoxOrient: "vertical",
WebkitLineClamp: 2,
overflow: "hidden",
}}
>
{title}
</h1>
</div>
{/* Description Section */}
<div
style={{
display: "flex",
flex: 1,
fontSize: 36,
color: cfg.theme.colors[colorScheme].darkgray,
lineHeight: 1.4,
}} }}
> >
<p <p
@@ -210,14 +268,80 @@ export const defaultImage: SocialImageOptions["imageStructure"] = (
margin: 0, margin: 0,
display: "-webkit-box", display: "-webkit-box",
WebkitBoxOrient: "vertical", WebkitBoxOrient: "vertical",
WebkitLineClamp: 3, WebkitLineClamp: 4,
overflow: "hidden", overflow: "hidden",
textOverflow: "ellipsis",
}} }}
> >
{description} {description}
</p> </p>
</div> </div>
{/* Footer with Metadata */}
<div
style={{
display: "flex",
alignItems: "center",
justifyContent: "space-between",
marginTop: "2rem",
paddingTop: "2rem",
borderTop: `1px solid ${cfg.theme.colors[colorScheme].lightgray}`,
}}
>
{/* Left side - Date */}
<div
style={{
display: "flex",
alignItems: "center",
color: cfg.theme.colors[colorScheme].gray,
fontSize: 28,
}}
>
{date && (
<div style={{ display: "flex", alignItems: "center" }}>
<svg
style={{ marginRight: "0.5rem" }}
width="28"
height="28"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
>
<rect x="3" y="4" width="18" height="18" rx="2" ry="2"></rect>
<line x1="16" y1="2" x2="16" y2="6"></line>
<line x1="8" y1="2" x2="8" y2="6"></line>
<line x1="3" y1="10" x2="21" y2="10"></line>
</svg>
{date}
</div>
)}
</div>
{/* Right side - Tags */}
<div
style={{
display: "flex",
gap: "0.5rem",
flexWrap: "wrap",
justifyContent: "flex-end",
maxWidth: "60%",
}}
>
{tags.slice(0, 3).map((tag: string) => (
<div
style={{
display: "flex",
padding: "0.5rem 1rem",
backgroundColor: cfg.theme.colors[colorScheme].highlight,
color: cfg.theme.colors[colorScheme].secondary,
borderRadius: "10px",
fontSize: 24,
}}
>
#{tag}
</div>
))}
</div>
</div>
</div> </div>
) )
} }

View File

@@ -36,7 +36,7 @@ export type RelativeURL = SlugLike<"relative">
export function isRelativeURL(s: string): s is RelativeURL { export function isRelativeURL(s: string): s is RelativeURL {
const validStart = /^\.{1,2}/.test(s) const validStart = /^\.{1,2}/.test(s)
const validEnding = !endsWith(s, "index") const validEnding = !endsWith(s, "index")
return validStart && validEnding && ![".md", ".html"].includes(_getFileExtension(s) ?? "") return validStart && validEnding && ![".md", ".html"].includes(getFileExtension(s) ?? "")
} }
export function getFullSlug(window: Window): FullSlug { export function getFullSlug(window: Window): FullSlug {
@@ -61,7 +61,7 @@ function sluggify(s: string): string {
export function slugifyFilePath(fp: FilePath, excludeExt?: boolean): FullSlug { export function slugifyFilePath(fp: FilePath, excludeExt?: boolean): FullSlug {
fp = stripSlashes(fp) as FilePath fp = stripSlashes(fp) as FilePath
let ext = _getFileExtension(fp) let ext = getFileExtension(fp)
const withoutFileExt = fp.replace(new RegExp(ext + "$"), "") const withoutFileExt = fp.replace(new RegExp(ext + "$"), "")
if (excludeExt || [".md", ".html", undefined].includes(ext)) { if (excludeExt || [".md", ".html", undefined].includes(ext)) {
ext = "" ext = ""
@@ -272,10 +272,10 @@ function containsForbiddenCharacters(s: string): boolean {
} }
function _hasFileExtension(s: string): boolean { function _hasFileExtension(s: string): boolean {
return _getFileExtension(s) !== undefined return getFileExtension(s) !== undefined
} }
function _getFileExtension(s: string): string | undefined { export function getFileExtension(s: string): string | undefined {
return s.match(/\.[A-Za-z0-9]+$/)?.[0] return s.match(/\.[A-Za-z0-9]+$/)?.[0]
} }

View File

@@ -15,7 +15,7 @@ interface Colors {
darkMode: ColorScheme darkMode: ColorScheme
} }
type FontSpecification = export type FontSpecification =
| string | string
| { | {
name: string name: string
@@ -90,6 +90,36 @@ export function googleFontHref(theme: Theme) {
return `https://fonts.googleapis.com/css2?family=${bodyFont}&family=${headerFont}&family=${codeFont}&display=swap` return `https://fonts.googleapis.com/css2?family=${bodyFont}&family=${headerFont}&family=${codeFont}&display=swap`
} }
export interface GoogleFontFile {
url: string
filename: string
extension: string
}
export async function processGoogleFonts(
stylesheet: string,
baseUrl: string,
): Promise<{
processedStylesheet: string
fontFiles: GoogleFontFile[]
}> {
const fontSourceRegex = /url\((https:\/\/fonts.gstatic.com\/s\/[^)]+\.(woff2|ttf))\)/g
const fontFiles: GoogleFontFile[] = []
let processedStylesheet = stylesheet
let match
while ((match = fontSourceRegex.exec(stylesheet)) !== null) {
const url = match[1]
const [filename, extension] = url.split("/").pop()!.split(".")
const staticUrl = `https://${baseUrl}/static/fonts/${filename}.${extension}`
processedStylesheet = processedStylesheet.replace(url, staticUrl)
fontFiles.push({ url, filename, extension })
}
return { processedStylesheet, fontFiles }
}
export function joinStyles(theme: Theme, ...stylesheet: string[]) { export function joinStyles(theme: Theme, ...stylesheet: string[]) {
return ` return `
${stylesheet.join("\n\n")} ${stylesheet.join("\n\n")}