cyberware/quartz/plugins/transformers/frontmatter.ts
Hrishikesh Barman 5c6d1e27ba
feat(plugins): add toml support for frontmatter (#418)
* feat(plugins): add toml support for frontmatter

Currently frontmatter is expected to be yaml, with delimiter set to
"---". This might not always be the case, for example ox-hugo(a hugo
exporter for org-mode files) exports in toml format with the delimiter
set to "+++" by default.

With this change, the users will be able use frontmatter plugin to
support this toml frontmatter format.

Example usage: `Plugin.FrontMatter({delims: "+++", language: 'toml'})`

- [0] https://ox-hugo.scripter.co/doc/org-meta-data-to-hugo-front-matter/

* fixup! feat(plugins): add toml support for frontmatter
2023-08-25 10:25:46 -07:00

70 lines
1.7 KiB
TypeScript

import matter from "gray-matter"
import remarkFrontmatter from "remark-frontmatter"
import { QuartzTransformerPlugin } from "../types"
import yaml from "js-yaml"
import toml from "toml"
import { slugTag } from "../../util/path"
export interface Options {
delims: string | string[]
language: "yaml" | "toml"
}
const defaultOptions: Options = {
delims: "---",
language: "yaml",
}
export const FrontMatter: QuartzTransformerPlugin<Partial<Options> | undefined> = (userOpts) => {
const opts = { ...defaultOptions, ...userOpts }
return {
name: "FrontMatter",
markdownPlugins() {
return [
remarkFrontmatter,
() => {
return (_, file) => {
const { data } = matter(file.value, {
...opts,
engines: {
yaml: (s) => yaml.load(s, { schema: yaml.JSON_SCHEMA }) as object,
toml: (s) => toml.parse(s) as object,
},
})
// tag is an alias for tags
if (data.tag) {
data.tags = data.tag
}
if (data.tags && !Array.isArray(data.tags)) {
data.tags = data.tags
.toString()
.split(",")
.map((tag: string) => tag.trim())
}
// slug them all!!
data.tags = [...new Set(data.tags?.map((tag: string) => slugTag(tag)))] ?? []
// fill in frontmatter
file.data.frontmatter = {
title: file.stem ?? "Untitled",
tags: [],
...data,
}
}
},
]
},
}
}
declare module "vfile" {
interface DataMap {
frontmatter: { [key: string]: any } & {
title: string
tags: string[]
}
}
}