run prettier

This commit is contained in:
Jacky Zhao
2023-07-22 17:27:41 -07:00
parent 3079d003cc
commit adec32227f
101 changed files with 1810 additions and 1405 deletions

View File

@ -1,6 +1,12 @@
import { CanonicalSlug, FilePath, ServerSlug, canonicalizeServer, resolveRelative } from "../../path"
import {
CanonicalSlug,
FilePath,
ServerSlug,
canonicalizeServer,
resolveRelative,
} from "../../path"
import { QuartzEmitterPlugin } from "../types"
import path from 'path'
import path from "path"
export const AliasRedirects: QuartzEmitterPlugin = () => ({
name: "AliasRedirects",
@ -24,7 +30,7 @@ export const AliasRedirects: QuartzEmitterPlugin = () => ({
for (const alias of aliases) {
const slug = path.posix.join(dir, alias) as ServerSlug
const fp = slug + ".html" as FilePath
const fp = (slug + ".html") as FilePath
const redirUrl = resolveRelative(canonicalizeServer(slug), ogSlug)
await emit({
content: `
@ -47,5 +53,5 @@ export const AliasRedirects: QuartzEmitterPlugin = () => ({
}
}
return fps
}
},
})

View File

@ -5,12 +5,12 @@ import path from "path"
export type ContentIndex = Map<CanonicalSlug, ContentDetails>
export type ContentDetails = {
title: string,
links: CanonicalSlug[],
tags: string[],
content: string,
date?: Date,
description?: string,
title: string
links: CanonicalSlug[]
tags: string[]
content: string
date?: Date
description?: string
}
interface Options {
@ -31,7 +31,9 @@ function generateSiteMap(cfg: GlobalConfiguration, idx: ContentIndex): string {
<loc>https://${base}/${slug}</loc>
<lastmod>${content.date?.toISOString()}</lastmod>
</url>`
const urls = Array.from(idx).map(([slug, content]) => createURLEntry(slug, content)).join("")
const urls = Array.from(idx)
.map(([slug, content]) => createURLEntry(slug, content))
.join("")
return `<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">${urls}</urlset>`
}
@ -47,7 +49,9 @@ function generateRSSFeed(cfg: GlobalConfiguration, idx: ContentIndex): string {
<pubDate>${content.date?.toUTCString()}</pubDate>
</items>`
const items = Array.from(idx).map(([slug, content]) => createURLEntry(slug, content)).join("")
const items = Array.from(idx)
.map(([slug, content]) => createURLEntry(slug, content))
.join("")
return `<rss xmlns:atom="http://www.w3.org/2005/atom" version="2.0">
<channel>
<title>${cfg.pageTitle}</title>
@ -71,14 +75,14 @@ export const ContentIndex: QuartzEmitterPlugin<Partial<Options>> = (opts) => {
const slug = canonicalizeServer(file.data.slug!)
const date = file.data.dates?.modified ?? new Date()
if (opts?.includeEmptyFiles || (file.data.text && file.data.text !== "")) {
linkIndex.set(slug, {
title: file.data.frontmatter?.title!,
links: file.data.links ?? [],
tags: file.data.frontmatter?.tags ?? [],
content: file.data.text ?? "",
date: date,
description: file.data.description ?? ""
})
linkIndex.set(slug, {
title: file.data.frontmatter?.title!,
links: file.data.links ?? [],
tags: file.data.frontmatter?.tags ?? [],
content: file.data.text ?? "",
date: date,
description: file.data.description ?? "",
})
}
}
@ -86,7 +90,7 @@ export const ContentIndex: QuartzEmitterPlugin<Partial<Options>> = (opts) => {
await emit({
content: generateSiteMap(cfg, linkIndex),
slug: "sitemap" as ServerSlug,
ext: ".xml"
ext: ".xml",
})
emitted.push("sitemap.xml" as FilePath)
}
@ -95,7 +99,7 @@ export const ContentIndex: QuartzEmitterPlugin<Partial<Options>> = (opts) => {
await emit({
content: generateRSSFeed(cfg, linkIndex),
slug: "index" as ServerSlug,
ext: ".xml"
ext: ".xml",
})
emitted.push("index.xml" as FilePath)
}
@ -109,7 +113,7 @@ export const ContentIndex: QuartzEmitterPlugin<Partial<Options>> = (opts) => {
delete content.description
delete content.date
return [slug, content]
})
}),
)
await emit({

View File

@ -8,7 +8,9 @@ import { FilePath, canonicalizeServer } from "../../path"
export const ContentPage: QuartzEmitterPlugin<FullPageLayout> = (opts) => {
if (!opts) {
throw new Error("ContentPage must be initialized with options specifiying the components to use")
throw new Error(
"ContentPage must be initialized with options specifiying the components to use",
)
}
const { head: Head, header, beforeBody, pageBody: Content, left, right, footer: Footer } = opts
@ -22,7 +24,7 @@ export const ContentPage: QuartzEmitterPlugin<FullPageLayout> = (opts) => {
},
async emit(_contentDir, cfg, content, resources, emit): Promise<FilePath[]> {
const fps: FilePath[] = []
const allFiles = content.map(c => c[1].data)
const allFiles = content.map((c) => c[1].data)
for (const [tree, file] of content) {
const slug = canonicalizeServer(file.data.slug!)
const externalResources = pageResources(slug, resources)
@ -32,17 +34,12 @@ export const ContentPage: QuartzEmitterPlugin<FullPageLayout> = (opts) => {
cfg,
children: [],
tree,
allFiles
allFiles,
}
const content = renderPage(
slug,
componentData,
opts,
externalResources
)
const content = renderPage(slug, componentData, opts, externalResources)
const fp = file.data.slug + ".html" as FilePath
const fp = (file.data.slug + ".html") as FilePath
await emit({
content,
slug: file.data.slug!,
@ -52,6 +49,6 @@ export const ContentPage: QuartzEmitterPlugin<FullPageLayout> = (opts) => {
fps.push(fp)
}
return fps
}
},
}
}

View File

@ -24,20 +24,28 @@ export const FolderPage: QuartzEmitterPlugin<FullPageLayout> = (opts) => {
},
async emit(_contentDir, cfg, content, resources, emit): Promise<FilePath[]> {
const fps: FilePath[] = []
const allFiles = content.map(c => c[1].data)
const allFiles = content.map((c) => c[1].data)
const folders: Set<CanonicalSlug> = new Set(allFiles.flatMap(data => {
const slug = data.slug
const folderName = path.dirname(slug ?? "") as CanonicalSlug
if (slug && folderName !== "." && folderName !== "tags") {
return [folderName]
}
return []
}))
const folders: Set<CanonicalSlug> = new Set(
allFiles.flatMap((data) => {
const slug = data.slug
const folderName = path.dirname(slug ?? "") as CanonicalSlug
if (slug && folderName !== "." && folderName !== "tags") {
return [folderName]
}
return []
}),
)
const folderDescriptions: Record<string, ProcessedContent> = Object.fromEntries([...folders].map(folder => ([
folder, defaultProcessedContent({ slug: joinSegments(folder, "index") as ServerSlug, frontmatter: { title: `Folder: ${folder}`, tags: [] } })
])))
const folderDescriptions: Record<string, ProcessedContent> = Object.fromEntries(
[...folders].map((folder) => [
folder,
defaultProcessedContent({
slug: joinSegments(folder, "index") as ServerSlug,
frontmatter: { title: `Folder: ${folder}`, tags: [] },
}),
]),
)
for (const [tree, file] of content) {
const slug = canonicalizeServer(file.data.slug!)
@ -56,17 +64,12 @@ export const FolderPage: QuartzEmitterPlugin<FullPageLayout> = (opts) => {
cfg,
children: [],
tree,
allFiles
allFiles,
}
const content = renderPage(
slug,
componentData,
opts,
externalResources
)
const content = renderPage(slug, componentData, opts, externalResources)
const fp = file.data.slug! + ".html" as FilePath
const fp = (file.data.slug! + ".html") as FilePath
await emit({
content,
slug: file.data.slug!,
@ -76,6 +79,6 @@ export const FolderPage: QuartzEmitterPlugin<FullPageLayout> = (opts) => {
fps.push(fp)
}
return fps
}
},
}
}

View File

@ -1,5 +1,5 @@
export { ContentPage } from './contentPage'
export { TagPage } from './tagPage'
export { FolderPage } from './folderPage'
export { ContentIndex } from './contentIndex'
export { AliasRedirects } from './aliases'
export { ContentPage } from "./contentPage"
export { TagPage } from "./tagPage"
export { FolderPage } from "./folderPage"
export { ContentIndex } from "./contentIndex"
export { AliasRedirects } from "./aliases"

View File

@ -23,12 +23,18 @@ export const TagPage: QuartzEmitterPlugin<FullPageLayout> = (opts) => {
},
async emit(_contentDir, cfg, content, resources, emit): Promise<FilePath[]> {
const fps: FilePath[] = []
const allFiles = content.map(c => c[1].data)
const allFiles = content.map((c) => c[1].data)
const tags: Set<string> = new Set(allFiles.flatMap(data => data.frontmatter?.tags ?? []))
const tagDescriptions: Record<string, ProcessedContent> = Object.fromEntries([...tags].map(tag => ([
tag, defaultProcessedContent({ slug: `tags/${tag}/index` as ServerSlug, frontmatter: { title: `Tag: ${tag}`, tags: [] } })
])))
const tags: Set<string> = new Set(allFiles.flatMap((data) => data.frontmatter?.tags ?? []))
const tagDescriptions: Record<string, ProcessedContent> = Object.fromEntries(
[...tags].map((tag) => [
tag,
defaultProcessedContent({
slug: `tags/${tag}/index` as ServerSlug,
frontmatter: { title: `Tag: ${tag}`, tags: [] },
}),
]),
)
for (const [tree, file] of content) {
const slug = file.data.slug!
@ -50,17 +56,12 @@ export const TagPage: QuartzEmitterPlugin<FullPageLayout> = (opts) => {
cfg,
children: [],
tree,
allFiles
allFiles,
}
const content = renderPage(
slug,
componentData,
opts,
externalResources
)
const content = renderPage(slug, componentData, opts, externalResources)
const fp = file.data.slug + ".html" as FilePath
const fp = (file.data.slug + ".html") as FilePath
await emit({
content,
slug: file.data.slug!,
@ -70,6 +71,6 @@ export const TagPage: QuartzEmitterPlugin<FullPageLayout> = (opts) => {
fps.push(fp)
}
return fps
}
},
}
}

View File

@ -5,5 +5,5 @@ export const RemoveDrafts: QuartzFilterPlugin<{}> = () => ({
shouldPublish([_tree, vfile]) {
const draftFlag: boolean = vfile.data?.frontmatter?.draft ?? false
return !draftFlag
}
},
})

View File

@ -5,5 +5,5 @@ export const ExplicitPublish: QuartzFilterPlugin = () => ({
shouldPublish([_tree, vfile]) {
const publishFlag: boolean = vfile.data?.frontmatter?.publish ?? false
return publishFlag
}
},
})

View File

@ -1,2 +1,2 @@
export { RemoveDrafts } from './draft'
export { ExplicitPublish } from './explicit'
export { RemoveDrafts } from "./draft"
export { ExplicitPublish } from "./explicit"

View File

@ -1,14 +1,14 @@
import { GlobalConfiguration } from '../cfg'
import { QuartzComponent } from '../components/types'
import { StaticResources } from '../resources'
import { joinStyles } from '../theme'
import { EmitCallback, PluginTypes } from './types'
import styles from '../styles/base.scss'
import { FilePath, ServerSlug } from '../path'
import { GlobalConfiguration } from "../cfg"
import { QuartzComponent } from "../components/types"
import { StaticResources } from "../resources"
import { joinStyles } from "../theme"
import { EmitCallback, PluginTypes } from "./types"
import styles from "../styles/base.scss"
import { FilePath, ServerSlug } from "../path"
export type ComponentResources = {
css: string[],
beforeDOMLoaded: string[],
css: string[]
beforeDOMLoaded: string[]
afterDOMLoaded: string[]
}
@ -24,7 +24,7 @@ export function getComponentResources(plugins: PluginTypes): ComponentResources
const componentResources = {
css: new Set<string>(),
beforeDOMLoaded: new Set<string>(),
afterDOMLoaded: new Set<string>()
afterDOMLoaded: new Set<string>(),
}
for (const component of allComponents) {
@ -39,39 +39,42 @@ export function getComponentResources(plugins: PluginTypes): ComponentResources
componentResources.afterDOMLoaded.add(afterDOMLoaded)
}
}
return {
css: [...componentResources.css],
beforeDOMLoaded: [...componentResources.beforeDOMLoaded],
afterDOMLoaded: [...componentResources.afterDOMLoaded]
afterDOMLoaded: [...componentResources.afterDOMLoaded],
}
}
function joinScripts(scripts: string[]): string {
// wrap with iife to prevent scope collision
return scripts.map(script => `(function () {${script}})();`).join("\n")
return scripts.map((script) => `(function () {${script}})();`).join("\n")
}
export async function emitComponentResources(cfg: GlobalConfiguration, res: ComponentResources, emit: EmitCallback): Promise<FilePath[]> {
export async function emitComponentResources(
cfg: GlobalConfiguration,
res: ComponentResources,
emit: EmitCallback,
): Promise<FilePath[]> {
const fps = await Promise.all([
emit({
slug: "index" as ServerSlug,
ext: ".css",
content: joinStyles(cfg.theme, styles, ...res.css)
content: joinStyles(cfg.theme, styles, ...res.css),
}),
emit({
slug: "prescript" as ServerSlug,
ext: ".js",
content: joinScripts(res.beforeDOMLoaded)
content: joinScripts(res.beforeDOMLoaded),
}),
emit({
slug: "postscript" as ServerSlug,
ext: ".js",
content: joinScripts(res.afterDOMLoaded)
})
content: joinScripts(res.afterDOMLoaded),
}),
])
return fps
}
export function getStaticResourcesFromPlugins(plugins: PluginTypes) {
@ -93,11 +96,11 @@ export function getStaticResourcesFromPlugins(plugins: PluginTypes) {
return staticResources
}
export * from './transformers'
export * from './filters'
export * from './emitters'
export * from "./transformers"
export * from "./filters"
export * from "./emitters"
declare module 'vfile' {
declare module "vfile" {
// inserted in processors.ts
interface DataMap {
slug: ServerSlug

View File

@ -1,4 +1,4 @@
import { Root as HTMLRoot } from 'hast'
import { Root as HTMLRoot } from "hast"
import { toString } from "hast-util-to-string"
import { QuartzTransformerPlugin } from "../types"
@ -7,11 +7,16 @@ export interface Options {
}
const defaultOptions: Options = {
descriptionLength: 150
descriptionLength: 150,
}
const escapeHTML = (unsafe: string) => {
return unsafe.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;').replaceAll('"', '&quot;').replaceAll("'", '&#039;');
return unsafe
.replaceAll("&", "&amp;")
.replaceAll("<", "&lt;")
.replaceAll(">", "&gt;")
.replaceAll('"', "&quot;")
.replaceAll("'", "&#039;")
}
export const Description: QuartzTransformerPlugin<Partial<Options> | undefined> = (userOpts) => {
@ -26,30 +31,29 @@ export const Description: QuartzTransformerPlugin<Partial<Options> | undefined>
const text = escapeHTML(toString(tree))
const desc = frontMatterDescription ?? text
const sentences = desc.replace(/\s+/g, ' ').split('.')
const sentences = desc.replace(/\s+/g, " ").split(".")
let finalDesc = ""
let sentenceIdx = 0
const len = opts.descriptionLength
while (finalDesc.length < len) {
const sentence = sentences[sentenceIdx]
if (!sentence) break
finalDesc += sentence + '.'
finalDesc += sentence + "."
sentenceIdx++
}
file.data.description = finalDesc
file.data.text = text
}
}
},
]
}
},
}
}
declare module 'vfile' {
declare module "vfile" {
interface DataMap {
description: string
text: string
}
}

View File

@ -1,17 +1,17 @@
import matter from "gray-matter"
import remarkFrontmatter from 'remark-frontmatter'
import remarkFrontmatter from "remark-frontmatter"
import { QuartzTransformerPlugin } from "../types"
import yaml from 'js-yaml'
import { slug as slugAnchor } from 'github-slugger'
import yaml from "js-yaml"
import { slug as slugAnchor } from "github-slugger"
export interface Options {
language: 'yaml' | 'toml',
language: "yaml" | "toml"
delims: string | string[]
}
const defaultOptions: Options = {
language: 'yaml',
delims: '---'
language: "yaml",
delims: "---",
}
export const FrontMatter: QuartzTransformerPlugin<Partial<Options> | undefined> = (userOpts) => {
@ -26,8 +26,8 @@ export const FrontMatter: QuartzTransformerPlugin<Partial<Options> | undefined>
const { data } = matter(file.value, {
...opts,
engines: {
yaml: s => yaml.load(s, { schema: yaml.JSON_SCHEMA }) as object
}
yaml: (s) => yaml.load(s, { schema: yaml.JSON_SCHEMA }) as object,
},
})
// tag is an alias for tags
@ -36,7 +36,10 @@ export const FrontMatter: QuartzTransformerPlugin<Partial<Options> | undefined>
}
if (data.tags && !Array.isArray(data.tags)) {
data.tags = data.tags.toString().split(",").map((tag: string) => tag.trim())
data.tags = data.tags
.toString()
.split(",")
.map((tag: string) => tag.trim())
}
// slug them all!!
@ -46,16 +49,16 @@ export const FrontMatter: QuartzTransformerPlugin<Partial<Options> | undefined>
file.data.frontmatter = {
title: file.stem ?? "Untitled",
tags: [],
...data
...data,
}
}
}
},
]
},
}
}
declare module 'vfile' {
declare module "vfile" {
interface DataMap {
frontmatter: { [key: string]: any } & {
title: string

View File

@ -1,5 +1,5 @@
import remarkGfm from "remark-gfm"
import smartypants from 'remark-smartypants'
import smartypants from "remark-smartypants"
import { QuartzTransformerPlugin } from "../types"
import rehypeSlug from "rehype-slug"
import rehypeAutolinkHeadings from "rehype-autolink-headings"
@ -11,10 +11,12 @@ export interface Options {
const defaultOptions: Options = {
enableSmartyPants: true,
linkHeadings: true
linkHeadings: true,
}
export const GitHubFlavoredMarkdown: QuartzTransformerPlugin<Partial<Options> | undefined> = (userOpts) => {
export const GitHubFlavoredMarkdown: QuartzTransformerPlugin<Partial<Options> | undefined> = (
userOpts,
) => {
const opts = { ...defaultOptions, ...userOpts }
return {
name: "GitHubFlavoredMarkdown",
@ -23,15 +25,22 @@ export const GitHubFlavoredMarkdown: QuartzTransformerPlugin<Partial<Options> |
},
htmlPlugins() {
if (opts.linkHeadings) {
return [rehypeSlug, [rehypeAutolinkHeadings, {
behavior: 'append', content: {
type: 'text',
value: ' §',
}
}]]
return [
rehypeSlug,
[
rehypeAutolinkHeadings,
{
behavior: "append",
content: {
type: "text",
value: " §",
},
},
],
]
} else {
return []
}
}
},
}
}

View File

@ -1,9 +1,9 @@
export { FrontMatter } from './frontmatter'
export { GitHubFlavoredMarkdown } from './gfm'
export { CreatedModifiedDate } from './lastmod'
export { Latex } from './latex'
export { Description } from './description'
export { CrawlLinks } from './links'
export { ObsidianFlavoredMarkdown } from './ofm'
export { SyntaxHighlighting } from './syntax'
export { TableOfContents } from './toc'
export { FrontMatter } from "./frontmatter"
export { GitHubFlavoredMarkdown } from "./gfm"
export { CreatedModifiedDate } from "./lastmod"
export { Latex } from "./latex"
export { Description } from "./description"
export { CrawlLinks } from "./links"
export { ObsidianFlavoredMarkdown } from "./ofm"
export { SyntaxHighlighting } from "./syntax"
export { TableOfContents } from "./toc"

View File

@ -1,18 +1,20 @@
import fs from "fs"
import path from 'path'
import path from "path"
import { Repository } from "@napi-rs/simple-git"
import { QuartzTransformerPlugin } from "../types"
export interface Options {
priority: ('frontmatter' | 'git' | 'filesystem')[],
priority: ("frontmatter" | "git" | "filesystem")[]
}
const defaultOptions: Options = {
priority: ['frontmatter', 'git', 'filesystem']
priority: ["frontmatter", "git", "filesystem"],
}
type MaybeDate = undefined | string | number
export const CreatedModifiedDate: QuartzTransformerPlugin<Partial<Options> | undefined> = (userOpts) => {
export const CreatedModifiedDate: QuartzTransformerPlugin<Partial<Options> | undefined> = (
userOpts,
) => {
const opts = { ...defaultOptions, ...userOpts }
return {
name: "CreatedModifiedDate",
@ -51,13 +53,13 @@ export const CreatedModifiedDate: QuartzTransformerPlugin<Partial<Options> | und
published: published ? new Date(published) : new Date(),
}
}
}
},
]
},
}
}
declare module 'vfile' {
declare module "vfile" {
interface DataMap {
dates: {
created: Date

View File

@ -1,43 +1,39 @@
import remarkMath from "remark-math"
import rehypeKatex from 'rehype-katex'
import rehypeMathjax from 'rehype-mathjax/svg.js'
import rehypeKatex from "rehype-katex"
import rehypeMathjax from "rehype-mathjax/svg.js"
import { QuartzTransformerPlugin } from "../types"
interface Options {
renderEngine: 'katex' | 'mathjax'
renderEngine: "katex" | "mathjax"
}
export const Latex: QuartzTransformerPlugin<Options> = (opts?: Options) => {
const engine = opts?.renderEngine ?? 'katex'
const engine = opts?.renderEngine ?? "katex"
return {
name: "Latex",
markdownPlugins() {
return [remarkMath]
},
htmlPlugins() {
return [
engine === 'katex'
? [rehypeKatex, { output: 'html' }]
: [rehypeMathjax]
]
return [engine === "katex" ? [rehypeKatex, { output: "html" }] : [rehypeMathjax]]
},
externalResources() {
return engine === 'katex'
return engine === "katex"
? {
css: [
// base css
"https://cdn.jsdelivr.net/npm/katex@0.16.0/dist/katex.min.css",
],
js: [
{
// fix copy behaviour: https://github.com/KaTeX/KaTeX/blob/main/contrib/copy-tex/README.md
src: "https://cdn.jsdelivr.net/npm/katex@0.16.7/dist/contrib/copy-tex.min.js",
loadTime: "afterDOMReady",
contentType: 'external'
}
]
}
css: [
// base css
"https://cdn.jsdelivr.net/npm/katex@0.16.0/dist/katex.min.css",
],
js: [
{
// fix copy behaviour: https://github.com/KaTeX/KaTeX/blob/main/contrib/copy-tex/README.md
src: "https://cdn.jsdelivr.net/npm/katex@0.16.7/dist/contrib/copy-tex.min.js",
loadTime: "afterDOMReady",
contentType: "external",
},
],
}
: {}
}
},
}
}

View File

@ -1,18 +1,27 @@
import { QuartzTransformerPlugin } from "../types"
import { CanonicalSlug, RelativeURL, canonicalizeServer, joinSegments, pathToRoot, resolveRelative, splitAnchor, transformInternalLink } from "../../path"
import {
CanonicalSlug,
RelativeURL,
canonicalizeServer,
joinSegments,
pathToRoot,
resolveRelative,
splitAnchor,
transformInternalLink,
} from "../../path"
import path from "path"
import { visit } from 'unist-util-visit'
import { visit } from "unist-util-visit"
import isAbsoluteUrl from "is-absolute-url"
interface Options {
/** How to resolve Markdown paths */
markdownLinkResolution: 'absolute' | 'relative' | 'shortest'
markdownLinkResolution: "absolute" | "relative" | "shortest"
/** Strips folders from a link so that it looks nice */
prettyLinks: boolean
}
const defaultOptions: Options = {
markdownLinkResolution: 'absolute',
markdownLinkResolution: "absolute",
prettyLinks: true,
}
@ -21,84 +30,91 @@ export const CrawlLinks: QuartzTransformerPlugin<Partial<Options> | undefined> =
return {
name: "LinkProcessing",
htmlPlugins() {
return [() => {
return (tree, file) => {
const curSlug = canonicalizeServer(file.data.slug!)
const transformLink = (target: string): RelativeURL => {
const targetSlug = transformInternalLink(target).slice("./".length)
let [targetCanonical, targetAnchor] = splitAnchor(targetSlug)
if (opts.markdownLinkResolution === 'relative') {
return targetSlug as RelativeURL
} else if (opts.markdownLinkResolution === 'shortest') {
// https://forum.obsidian.md/t/settings-new-link-format-what-is-shortest-path-when-possible/6748/5
const allSlugs = file.data.allSlugs!
return [
() => {
return (tree, file) => {
const curSlug = canonicalizeServer(file.data.slug!)
const transformLink = (target: string): RelativeURL => {
const targetSlug = transformInternalLink(target).slice("./".length)
let [targetCanonical, targetAnchor] = splitAnchor(targetSlug)
if (opts.markdownLinkResolution === "relative") {
return targetSlug as RelativeURL
} else if (opts.markdownLinkResolution === "shortest") {
// https://forum.obsidian.md/t/settings-new-link-format-what-is-shortest-path-when-possible/6748/5
const allSlugs = file.data.allSlugs!
// if the file name is unique, then it's just the filename
const matchingFileNames = allSlugs.filter(slug => {
const parts = slug.split(path.posix.sep)
const fileName = parts.at(-1)
return targetCanonical === fileName
})
// if the file name is unique, then it's just the filename
const matchingFileNames = allSlugs.filter((slug) => {
const parts = slug.split(path.posix.sep)
const fileName = parts.at(-1)
return targetCanonical === fileName
})
if (matchingFileNames.length === 1) {
const targetSlug = canonicalizeServer(matchingFileNames[0])
return resolveRelative(curSlug, targetSlug) + targetAnchor as RelativeURL
if (matchingFileNames.length === 1) {
const targetSlug = canonicalizeServer(matchingFileNames[0])
return (resolveRelative(curSlug, targetSlug) + targetAnchor) as RelativeURL
}
// if it's not unique, then it's the absolute path from the vault root
// (fall-through case)
}
// if it's not unique, then it's the absolute path from the vault root
// (fall-through case)
// treat as absolute
return joinSegments(pathToRoot(curSlug), targetSlug) as RelativeURL
}
// treat as absolute
return joinSegments(pathToRoot(curSlug), targetSlug) as RelativeURL
const outgoing: Set<CanonicalSlug> = new Set()
visit(tree, "element", (node, _index, _parent) => {
// rewrite all links
if (
node.tagName === "a" &&
node.properties &&
typeof node.properties.href === "string"
) {
let dest = node.properties.href as RelativeURL
node.properties.className = isAbsoluteUrl(dest) ? "external" : "internal"
// don't process external links or intra-document anchors
if (!(isAbsoluteUrl(dest) || dest.startsWith("#"))) {
dest = node.properties.href = transformLink(dest)
const canonicalDest = path.normalize(joinSegments(curSlug, dest))
const [destCanonical, _destAnchor] = splitAnchor(canonicalDest)
outgoing.add(destCanonical as CanonicalSlug)
}
// rewrite link internals if prettylinks is on
if (
opts.prettyLinks &&
node.children.length === 1 &&
node.children[0].type === "text"
) {
node.children[0].value = path.basename(node.children[0].value)
}
}
// transform all other resources that may use links
if (
["img", "video", "audio", "iframe"].includes(node.tagName) &&
node.properties &&
typeof node.properties.src === "string"
) {
if (!isAbsoluteUrl(node.properties.src)) {
const ext = path.extname(node.properties.src)
node.properties.src =
transformLink(path.join("assets", node.properties.src)) + ext
}
}
})
file.data.links = [...outgoing]
}
const outgoing: Set<CanonicalSlug> = new Set()
visit(tree, 'element', (node, _index, _parent) => {
// rewrite all links
if (
node.tagName === 'a' &&
node.properties &&
typeof node.properties.href === 'string'
) {
let dest = node.properties.href as RelativeURL
node.properties.className = isAbsoluteUrl(dest) ? "external" : "internal"
// don't process external links or intra-document anchors
if (!(isAbsoluteUrl(dest) || dest.startsWith("#"))) {
dest = node.properties.href = transformLink(dest)
const canonicalDest = path.normalize(joinSegments(curSlug, dest))
const [destCanonical, _destAnchor] = splitAnchor(canonicalDest)
outgoing.add(destCanonical as CanonicalSlug)
}
// rewrite link internals if prettylinks is on
if (opts.prettyLinks && node.children.length === 1 && node.children[0].type === 'text') {
node.children[0].value = path.basename(node.children[0].value)
}
}
// transform all other resources that may use links
if (
["img", "video", "audio", "iframe"].includes(node.tagName) &&
node.properties &&
typeof node.properties.src === 'string'
) {
if (!isAbsoluteUrl(node.properties.src)) {
const ext = path.extname(node.properties.src)
node.properties.src = transformLink(path.join("assets", node.properties.src)) + ext
}
}
})
file.data.links = [...outgoing]
}
}]
}
},
]
},
}
}
declare module 'vfile' {
declare module "vfile" {
interface DataMap {
links: CanonicalSlug[]
}

View File

@ -1,8 +1,8 @@
import { PluggableList } from "unified"
import { QuartzTransformerPlugin } from "../types"
import { Root, HTML, BlockContent, DefinitionContent, Code } from 'mdast'
import { Root, HTML, BlockContent, DefinitionContent, Code } from "mdast"
import { findAndReplace } from "mdast-util-find-and-replace"
import { slug as slugAnchor } from 'github-slugger'
import { slug as slugAnchor } from "github-slugger"
import rehypeRaw from "rehype-raw"
import { visit } from "unist-util-visit"
import path from "path"
@ -71,7 +71,7 @@ function canonicalizeCallout(calloutName: string): keyof typeof callouts {
bug: "bug",
example: "example",
quote: "quote",
cite: "quote"
cite: "quote",
}
return calloutMapping[callout]
@ -94,10 +94,10 @@ const callouts = {
}
const capitalize = (s: string): string => {
return s.substring(0, 1).toUpperCase() + s.substring(1);
return s.substring(0, 1).toUpperCase() + s.substring(1)
}
// Match wikilinks
// Match wikilinks
// !? -> optional embedding
// \[\[ -> open brace
// ([^\[\]\|\#]+) -> one or more non-special characters ([,],|, or #) (name)
@ -105,16 +105,18 @@ const capitalize = (s: string): string => {
// (|[^\[\]\|\#]+)? -> | then one or more non-special characters (alias)
const wikilinkRegex = new RegExp(/!?\[\[([^\[\]\|\#]+)(#[^\[\]\|\#]+)?(\|[^\[\]\|\#]+)?\]\]/, "g")
// Match highlights
// Match highlights
const highlightRegex = new RegExp(/==(.+)==/, "g")
// Match comments
// Match comments
const commentRegex = new RegExp(/%%(.+)%%/, "g")
// from https://github.com/escwxyz/remark-obsidian-callout/blob/main/src/index.ts
const calloutRegex = new RegExp(/^\[\!(\w+)\]([+-]?)/)
export const ObsidianFlavoredMarkdown: QuartzTransformerPlugin<Partial<Options> | undefined> = (userOpts) => {
export const ObsidianFlavoredMarkdown: QuartzTransformerPlugin<Partial<Options> | undefined> = (
userOpts,
) => {
const opts = { ...defaultOptions, ...userOpts }
return {
name: "ObsidianFlavoredMarkdown",
@ -154,28 +156,31 @@ export const ObsidianFlavoredMarkdown: QuartzTransformerPlugin<Partial<Options>
width ||= "auto"
height ||= "auto"
return {
type: 'image',
type: "image",
url,
data: {
hProperties: {
width, height
}
}
width,
height,
},
},
}
} else if ([".mp4", ".webm", ".ogv", ".mov", ".mkv"].includes(ext)) {
return {
type: 'html',
value: `<video src="${url}" controls></video>`
type: "html",
value: `<video src="${url}" controls></video>`,
}
} else if ([".mp3", ".webm", ".wav", ".m4a", ".ogg", ".3gp", ".flac"].includes(ext)) {
} else if (
[".mp3", ".webm", ".wav", ".m4a", ".ogg", ".3gp", ".flac"].includes(ext)
) {
return {
type: 'html',
value: `<audio src="${url}" controls></audio>`
type: "html",
value: `<audio src="${url}" controls></audio>`,
}
} else if ([".pdf"].includes(ext)) {
return {
type: 'html',
value: `<iframe src="${url}"></iframe>`
type: "html",
value: `<iframe src="${url}"></iframe>`,
}
} else {
// TODO: this is the node embed case
@ -187,17 +192,18 @@ export const ObsidianFlavoredMarkdown: QuartzTransformerPlugin<Partial<Options>
// const url = transformInternalLink(fp + anchor)
const url = fp + anchor
return {
type: 'link',
type: "link",
url,
children: [{
type: 'text',
value: alias ?? fp
}]
children: [
{
type: "text",
value: alias ?? fp,
},
],
}
})
}
}
)
})
}
if (opts.highlight) {
@ -206,21 +212,21 @@ export const ObsidianFlavoredMarkdown: QuartzTransformerPlugin<Partial<Options>
findAndReplace(tree, highlightRegex, (_value: string, ...capture: string[]) => {
const [inner] = capture
return {
type: 'html',
value: `<span class="text-highlight">${inner}</span>`
type: "html",
value: `<span class="text-highlight">${inner}</span>`,
}
})
}
})
}
if (opts.comments) {
plugins.push(() => {
return (tree: Root, _file) => {
findAndReplace(tree, commentRegex, (_value: string, ..._capture: string[]) => {
return {
type: 'text',
value: ''
type: "text",
value: "",
}
})
}
@ -252,7 +258,8 @@ export const ObsidianFlavoredMarkdown: QuartzTransformerPlugin<Partial<Options>
const calloutType = typeString.toLowerCase() as keyof typeof callouts
const collapse = collapseChar === "+" || collapseChar === "-"
const defaultState = collapseChar === "-" ? "collapsed" : "expanded"
const title = match.input.slice(calloutDirective.length).trim() || capitalize(calloutType)
const title =
match.input.slice(calloutDirective.length).trim() || capitalize(calloutType)
const toggleIcon = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="fold">
<polyline points="6 9 12 15 18 9"></polyline>
@ -266,17 +273,20 @@ export const ObsidianFlavoredMarkdown: QuartzTransformerPlugin<Partial<Options>
<div class="callout-icon">${callouts[canonicalizeCallout(calloutType)]}</div>
<div class="callout-title-inner">${title}</div>
${collapse ? toggleIcon : ""}
</div>`
</div>`,
}
const blockquoteContent: (BlockContent | DefinitionContent)[] = [titleNode]
if (remainingText.length > 0) {
blockquoteContent.push({
type: 'paragraph',
children: [{
type: 'text',
value: remainingText,
}, ...restChildren]
type: "paragraph",
children: [
{
type: "text",
value: remainingText,
},
...restChildren,
],
})
}
@ -287,10 +297,12 @@ export const ObsidianFlavoredMarkdown: QuartzTransformerPlugin<Partial<Options>
node.data = {
hProperties: {
...(node.data?.hProperties ?? {}),
className: `callout ${collapse ? "is-collapsible" : ""} ${defaultState === "collapsed" ? "is-collapsed" : ""}`,
className: `callout ${collapse ? "is-collapsible" : ""} ${
defaultState === "collapsed" ? "is-collapsed" : ""
}`,
"data-callout": calloutType,
"data-callout-fold": collapse,
}
},
}
}
})
@ -301,12 +313,12 @@ export const ObsidianFlavoredMarkdown: QuartzTransformerPlugin<Partial<Options>
if (opts.mermaid) {
plugins.push(() => {
return (tree: Root, _file) => {
visit(tree, 'code', (node: Code) => {
if (node.lang === 'mermaid') {
visit(tree, "code", (node: Code) => {
if (node.lang === "mermaid") {
node.data = {
hProperties: {
className: 'mermaid'
}
className: "mermaid",
},
}
}
})
@ -325,8 +337,8 @@ export const ObsidianFlavoredMarkdown: QuartzTransformerPlugin<Partial<Options>
if (opts.callouts) {
js.push({
script: calloutScript,
loadTime: 'afterDOMReady',
contentType: 'inline'
loadTime: "afterDOMReady",
contentType: "inline",
})
}
@ -336,13 +348,13 @@ export const ObsidianFlavoredMarkdown: QuartzTransformerPlugin<Partial<Options>
import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.esm.min.mjs';
mermaid.initialize({ startOnLoad: true });
`,
loadTime: 'afterDOMReady',
moduleType: 'module',
contentType: 'inline'
loadTime: "afterDOMReady",
moduleType: "module",
contentType: "inline",
})
}
return { js }
}
},
}
}

View File

@ -4,8 +4,13 @@ import rehypePrettyCode, { Options as CodeOptions } from "rehype-pretty-code"
export const SyntaxHighlighting: QuartzTransformerPlugin = () => ({
name: "SyntaxHighlighting",
htmlPlugins() {
return [[rehypePrettyCode, {
theme: 'css-variables',
} satisfies Partial<CodeOptions>]]
}
return [
[
rehypePrettyCode,
{
theme: "css-variables",
} satisfies Partial<CodeOptions>,
],
]
},
})

View File

@ -2,11 +2,11 @@ import { QuartzTransformerPlugin } from "../types"
import { Root } from "mdast"
import { visit } from "unist-util-visit"
import { toString } from "mdast-util-to-string"
import { slug as slugAnchor } from 'github-slugger'
import { slug as slugAnchor } from "github-slugger"
export interface Options {
maxDepth: 1 | 2 | 3 | 4 | 5 | 6,
minEntries: 1,
maxDepth: 1 | 2 | 3 | 4 | 5 | 6
minEntries: 1
showByDefault: boolean
}
@ -17,47 +17,53 @@ const defaultOptions: Options = {
}
interface TocEntry {
depth: number,
text: string,
depth: number
text: string
slug: string // this is just the anchor (#some-slug), not the canonical slug
}
export const TableOfContents: QuartzTransformerPlugin<Partial<Options> | undefined> = (userOpts) => {
export const TableOfContents: QuartzTransformerPlugin<Partial<Options> | undefined> = (
userOpts,
) => {
const opts = { ...defaultOptions, ...userOpts }
return {
name: "TableOfContents",
markdownPlugins() {
return [() => {
return async (tree: Root, file) => {
const display = file.data.frontmatter?.enableToc ?? opts.showByDefault
if (display) {
const toc: TocEntry[] = []
let highestDepth: number = opts.maxDepth
visit(tree, 'heading', (node) => {
if (node.depth <= opts.maxDepth) {
const text = toString(node)
highestDepth = Math.min(highestDepth, node.depth)
toc.push({
depth: node.depth,
text,
slug: slugAnchor(text)
})
}
})
return [
() => {
return async (tree: Root, file) => {
const display = file.data.frontmatter?.enableToc ?? opts.showByDefault
if (display) {
const toc: TocEntry[] = []
let highestDepth: number = opts.maxDepth
visit(tree, "heading", (node) => {
if (node.depth <= opts.maxDepth) {
const text = toString(node)
highestDepth = Math.min(highestDepth, node.depth)
toc.push({
depth: node.depth,
text,
slug: slugAnchor(text),
})
}
})
if (toc.length > opts.minEntries) {
file.data.toc = toc.map(entry => ({ ...entry, depth: entry.depth - highestDepth }))
if (toc.length > opts.minEntries) {
file.data.toc = toc.map((entry) => ({
...entry,
depth: entry.depth - highestDepth,
}))
}
}
}
}
}]
},
]
},
}
}
declare module 'vfile' {
declare module "vfile" {
interface DataMap {
toc: TocEntry[]
}
}

View File

@ -6,13 +6,15 @@ import { QuartzComponent } from "../components/types"
import { FilePath, ServerSlug } from "../path"
export interface PluginTypes {
transformers: QuartzTransformerPluginInstance[],
filters: QuartzFilterPluginInstance[],
emitters: QuartzEmitterPluginInstance[],
transformers: QuartzTransformerPluginInstance[]
filters: QuartzFilterPluginInstance[]
emitters: QuartzEmitterPluginInstance[]
}
type OptionType = object | undefined
export type QuartzTransformerPlugin<Options extends OptionType = undefined> = (opts?: Options) => QuartzTransformerPluginInstance
export type QuartzTransformerPlugin<Options extends OptionType = undefined> = (
opts?: Options,
) => QuartzTransformerPluginInstance
export type QuartzTransformerPluginInstance = {
name: string
textTransform?: (src: string | Buffer) => string | Buffer
@ -21,16 +23,26 @@ export type QuartzTransformerPluginInstance = {
externalResources?: () => Partial<StaticResources>
}
export type QuartzFilterPlugin<Options extends OptionType = undefined> = (opts?: Options) => QuartzFilterPluginInstance
export type QuartzFilterPlugin<Options extends OptionType = undefined> = (
opts?: Options,
) => QuartzFilterPluginInstance
export type QuartzFilterPluginInstance = {
name: string
shouldPublish(content: ProcessedContent): boolean
}
export type QuartzEmitterPlugin<Options extends OptionType = undefined> = (opts?: Options) => QuartzEmitterPluginInstance
export type QuartzEmitterPlugin<Options extends OptionType = undefined> = (
opts?: Options,
) => QuartzEmitterPluginInstance
export type QuartzEmitterPluginInstance = {
name: string
emit(contentDir: string, cfg: GlobalConfiguration, content: ProcessedContent[], resources: StaticResources, emitCallback: EmitCallback): Promise<FilePath[]>
emit(
contentDir: string,
cfg: GlobalConfiguration,
content: ProcessedContent[],
resources: StaticResources,
emitCallback: EmitCallback,
): Promise<FilePath[]>
getQuartzComponents(): QuartzComponent[]
}

View File

@ -1,11 +1,11 @@
import { Node, Parent } from 'hast'
import { Data, VFile } from 'vfile'
import { Node, Parent } from "hast"
import { Data, VFile } from "vfile"
export type QuartzPluginData = Data
export type ProcessedContent = [Node<QuartzPluginData>, VFile]
export function defaultProcessedContent(vfileData: Partial<QuartzPluginData>): ProcessedContent {
const root: Parent = { type: 'root', children: [] }
const root: Parent = { type: "root", children: [] }
const vfile = new VFile("")
vfile.data = vfileData
return [root, vfile]