From 953ad4d9c2f8688f34d798b8f650cf50acafd723 Mon Sep 17 00:00:00 2001 From: Asko Nõmm Date: Sat, 25 Jan 2025 22:07:57 +0200 Subject: Implement FrontMatter parsing. --- src/flatmatter.ts | 27 +++++++++++++++++++-------- 1 file changed, 19 insertions(+), 8 deletions(-) (limited to 'src/flatmatter.ts') diff --git a/src/flatmatter.ts b/src/flatmatter.ts index 3bf8704..8ffee6f 100644 --- a/src/flatmatter.ts +++ b/src/flatmatter.ts @@ -1,9 +1,6 @@ +import { EOL } from "node:os"; import {trimChar} from "./utils.ts"; -export type Matter = { - [key: string]: Matter | unknown; -}; - export type ParsedValue = { value: unknown; computeActions: ComputeAction[]; @@ -15,7 +12,7 @@ export type ComputeAction = { }; export interface Serializer { - serialize(parsedConfig: Matter): unknown; + serialize(parsedConfig: Record): unknown; } export interface FlatMatterFn { @@ -26,7 +23,7 @@ export interface FlatMatterFn { export default class FlatMatter { private content: string; - private parsedConfig: Matter = {}; + private parsedConfig: Record = {}; private functions: FlatMatterFn[]; constructor(content: string, functions: FlatMatterFn[] = []) { @@ -37,9 +34,23 @@ export default class FlatMatter { private parse(): void { const lines = this.content.split(/\r?\n/); + let frontMatterBreakCount = 0; for (let i = 0; i < lines.length; i++) { - this.parseLine(i, lines[i]); + if (lines[i].trim() === "---" && frontMatterBreakCount < 2) { + frontMatterBreakCount++; + continue; + } + + + // FlatMatter ends, Markdown begins + if (frontMatterBreakCount < 2) { + this.parseLine(i, lines[i]); + continue; + } + + this.parsedConfig.content = lines.slice(i).join(EOL).trim(); + break; } } @@ -60,7 +71,7 @@ export default class FlatMatter { const config = keys.reduceRight((acc, key) => { return {[key]: acc}; - }, this.computeValue(parsedValue)) as Matter; + }, this.computeValue(parsedValue)) as Record; this.parsedConfig = {...this.parsedConfig, ...config}; } -- cgit v1.2.3