run prettier

This commit is contained in:
Jacky Zhao 2023-07-22 17:27:41 -07:00
parent 2034b970b6
commit 7db2eda76c
101 changed files with 1810 additions and 1405 deletions

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[]
}
}