64 lines
1.5 KiB
JavaScript
64 lines
1.5 KiB
JavaScript
import knownNodes from './nodes/index.js'
|
|
import { useDocument } from '@terrace-lang/js'
|
|
import { createFileReader } from '@terrace-lang/js/readers/node-readline'
|
|
|
|
import process from 'node:process'
|
|
import path from 'node:path'
|
|
|
|
export default async function(filePath) {
|
|
filePath = path.resolve(filePath)
|
|
const doc = useDocument(createFileReader(filePath))
|
|
const { next, line, match, tail, level, head } = doc
|
|
|
|
const page = {
|
|
type: `Page`,
|
|
title: '',
|
|
description: [],
|
|
layout: '',
|
|
headings: [],
|
|
children: []
|
|
}
|
|
|
|
const context = {
|
|
page,
|
|
filePath
|
|
}
|
|
|
|
const originalCWD = process.cwd()
|
|
while(await next()) {
|
|
if (!line()) continue
|
|
if (match('title')) page.title = tail()
|
|
else if (match('layout')) page.layout = tail()
|
|
else if (match('description')) {
|
|
const l = level()
|
|
while(await next(l)) {
|
|
page.description.push(line(l))
|
|
}
|
|
}
|
|
else if (match('Section')) {
|
|
page.children.push(await knownNodes.Section(doc, level(), context))
|
|
}
|
|
else if (match('Include')) {
|
|
page.children.push(await knownNodes.Include(doc, level(), context))
|
|
}
|
|
}
|
|
process.chdir(originalCWD)
|
|
|
|
// Structure headings into tree.
|
|
page.headings.forEach((heading, index) => {
|
|
let parent = null
|
|
for (let i = index; i > 0; --i) {
|
|
if (page.headings[i].level === heading.level - 1) {
|
|
parent = page.headings[i]
|
|
break
|
|
}
|
|
}
|
|
|
|
if (parent) parent.children.push(heading)
|
|
})
|
|
|
|
page.headings = page.headings.filter(h => h.level === 2)
|
|
|
|
return page
|
|
}
|