Jacky Zhao
2023-11-16 a26eb59392c617bf567df23ee45d16b3fce69da3
feat: scrub link formatting from toc entries
2 files modified
18 ■■■■ changed files
quartz/plugins/transformers/ofm.ts 5 ●●●● patch | view | raw | blame | history
quartz/plugins/transformers/toc.ts 13 ●●●●● patch | view | raw | blame | history
quartz/plugins/transformers/ofm.ts
@@ -110,7 +110,10 @@
// ([^\[\]\|\#]+)   -> one or more non-special characters ([,],|, or #) (name)
// (#[^\[\]\|\#]+)? -> # then one or more non-special characters (heading link)
// (|[^\[\]\|\#]+)? -> | then one or more non-special characters (alias)
const wikilinkRegex = new RegExp(/!?\[\[([^\[\]\|\#]+)?(#+[^\[\]\|\#]+)?(\|[^\[\]\|\#]+)?\]\]/, "g")
export const wikilinkRegex = new RegExp(
  /!?\[\[([^\[\]\|\#]+)?(#+[^\[\]\|\#]+)?(\|[^\[\]\|\#]+)?\]\]/,
  "g",
)
const highlightRegex = new RegExp(/==([^=]+)==/, "g")
const commentRegex = new RegExp(/%%(.+)%%/, "g")
// from https://github.com/escwxyz/remark-obsidian-callout/blob/main/src/index.ts
quartz/plugins/transformers/toc.ts
@@ -3,6 +3,7 @@
import { visit } from "unist-util-visit"
import { toString } from "mdast-util-to-string"
import Slugger from "github-slugger"
import { wikilinkRegex } from "./ofm"
export interface Options {
  maxDepth: 1 | 2 | 3 | 4 | 5 | 6
@@ -24,6 +25,7 @@
  slug: string // this is just the anchor (#some-slug), not the canonical slug
}
const regexMdLinks = new RegExp(/\[([^\[]+)\](\(.*\))/, "g")
export const TableOfContents: QuartzTransformerPlugin<Partial<Options> | undefined> = (
  userOpts,
) => {
@@ -41,7 +43,16 @@
              let highestDepth: number = opts.maxDepth
              visit(tree, "heading", (node) => {
                if (node.depth <= opts.maxDepth) {
                  const text = toString(node)
                  let text = toString(node)
                  // strip link formatting from toc entries
                  text = text.replace(wikilinkRegex, (_, rawFp, __, rawAlias) => {
                    const fp = rawFp?.trim() ?? ""
                    const alias = rawAlias?.slice(1).trim()
                    return alias ?? fp
                  })
                  text = text.replace(regexMdLinks, "$1")
                  highestDepth = Math.min(highestDepth, node.depth)
                  toc.push({
                    depth: node.depth,