| | |
| | | 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 toml from "toml" |
| | | import { slugTag } from "../../util/path" |
| | | import { QuartzPluginData } from "../vfile" |
| | | |
| | | export interface Options { |
| | | language: 'yaml' | 'toml', |
| | | delims: string | string[] |
| | | language: "yaml" | "toml" |
| | | oneLineTagDelim: string |
| | | } |
| | | |
| | | const defaultOptions: Options = { |
| | | language: 'yaml', |
| | | delims: '---' |
| | | delims: "---", |
| | | language: "yaml", |
| | | oneLineTagDelim: ",", |
| | | } |
| | | |
| | | export const FrontMatter: QuartzTransformerPlugin<Partial<Options> | undefined> = (userOpts) => { |
| | |
| | | return { |
| | | name: "FrontMatter", |
| | | markdownPlugins() { |
| | | const { oneLineTagDelim } = opts |
| | | |
| | | return [ |
| | | remarkFrontmatter, |
| | | [remarkFrontmatter, ["yaml", "toml"]], |
| | | () => { |
| | | return (_, file) => { |
| | | const { data } = matter(file.value, opts) |
| | | const { data } = matter(Buffer.from(file.value), { |
| | | ...opts, |
| | | engines: { |
| | | yaml: (s) => yaml.load(s, { schema: yaml.JSON_SCHEMA }) as object, |
| | | toml: (s) => toml.parse(s) as object, |
| | | }, |
| | | }) |
| | | |
| | | if (typeof data.tags === 'string') { |
| | | data.tags = data.tags.split(" ") |
| | | // tag is an alias for tags |
| | | if (data.tag) { |
| | | data.tags = data.tag |
| | | } |
| | | |
| | | // coerce title to string |
| | | if (data.title) { |
| | | data.title = data.title.toString() |
| | | } else if (data.title === null || data.title === undefined) { |
| | | data.title = file.stem ?? "Untitled" |
| | | } |
| | | |
| | | if (data.tags) { |
| | | // coerce to array |
| | | if (!Array.isArray(data.tags)) { |
| | | data.tags = data.tags |
| | | .toString() |
| | | .split(oneLineTagDelim) |
| | | .map((tag: string) => tag.trim()) |
| | | } |
| | | |
| | | // remove all non-string tags |
| | | data.tags = data.tags |
| | | .filter((tag: unknown) => typeof tag === "string" || typeof tag === "number") |
| | | .map((tag: string | number) => tag.toString()) |
| | | } |
| | | |
| | | // 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 |
| | | } |
| | | file.data.frontmatter = data as QuartzPluginData["frontmatter"] |
| | | } |
| | | } |
| | | }, |
| | | ] |
| | | }, |
| | | } |
| | | } |
| | | |
| | | declare module 'vfile' { |
| | | declare module "vfile" { |
| | | interface DataMap { |
| | | frontmatter: { [key: string]: any } & { |
| | | title: string |