Improved markdown parser
This commit is contained in:
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ztimson/utils",
|
"name": "@ztimson/utils",
|
||||||
"version": "0.30.3",
|
"version": "0.30.4",
|
||||||
"description": "Utility library",
|
"description": "Utility library",
|
||||||
"author": "Zak Timson",
|
"author": "Zak Timson",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
|||||||
24
src/html.ts
24
src/html.ts
@@ -26,6 +26,9 @@ export function decodeHtml(html: string) {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Parse markdown headers
|
* Parse markdown headers
|
||||||
|
*
|
||||||
|
* **NOTE: frontmatter parsing only works 2 layers deep**
|
||||||
|
*
|
||||||
* @param {string} content
|
* @param {string} content
|
||||||
* @returns {{meta: any, content: string} | {meta: {}, content: string}}
|
* @returns {{meta: any, content: string} | {meta: {}, content: string}}
|
||||||
*/
|
*/
|
||||||
@@ -34,12 +37,29 @@ export function parseMarkdown(content: string) {
|
|||||||
if (!match) return {meta: {}, content};
|
if (!match) return {meta: {}, content};
|
||||||
|
|
||||||
const meta: any = {};
|
const meta: any = {};
|
||||||
for (const line of match[1].split('\n')) {
|
let currentParent: string | null = null;
|
||||||
|
|
||||||
|
for (const rawLine of match[1].split('\n')) {
|
||||||
|
if (!rawLine.trim()) continue;
|
||||||
|
const indented = /^\s+/.test(rawLine);
|
||||||
|
const line = rawLine.trim();
|
||||||
const colonIdx = line.indexOf(':');
|
const colonIdx = line.indexOf(':');
|
||||||
if (colonIdx === -1) continue;
|
if (colonIdx === -1) continue;
|
||||||
|
|
||||||
const key = line.slice(0, colonIdx).trim();
|
const key = line.slice(0, colonIdx).trim();
|
||||||
const value = line.slice(colonIdx + 1).trim();
|
const value = line.slice(colonIdx + 1).trim();
|
||||||
try { meta[key] = JSON.parse(value); } catch { meta[key] = value; }
|
|
||||||
|
let parsed: any = value;
|
||||||
|
try { parsed = JSON.parse(value); } catch {}
|
||||||
|
|
||||||
|
if (!indented) {
|
||||||
|
currentParent = value === '' ? key : null;
|
||||||
|
if (value === '') meta[key] = {};
|
||||||
|
else meta[key] = parsed;
|
||||||
|
} else if (currentParent) {
|
||||||
|
meta[currentParent][key] = parsed;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return {meta, content: match[2].trim()};
|
return {meta, content: match[2].trim()};
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user