-
Remi PLANEL authoredRemi PLANEL authored
content.ts 3.42 KiB
import YAML from 'yaml'
import * as d3 from "d3";
export default defineNitroPlugin((nitroApp) => {
// nitroApp.hooks.hook('content:file:beforeParse',
// (file) => {
// if (file?._id?.startsWith('content:3.defense-systems:') && file?._id?.endsWith('.md')) {
// const frontMatterRegex = /(?<=---\n).*?(?=\n---)/sg;
// const fontMatterMatch = file.body.match(frontMatterRegex);
// if (fontMatterMatch?.length > 0) {
// const frontMatter = fontMatterMatch[0]
// const parsedFrontMatter = YAML.parse(frontMatter)
// if (parsedFrontMatter?.contributors?.length > 0) {
// // file.body = file.body.replace(/(^#[\s+]\w*[\s\S])/gm, "$1\n:contributors\n\n")
// }
// }
// }
// })
nitroApp.hooks.hook(
'content:file:afterParse',
(file) => {
if (file?._id?.startsWith('content') && file._id.endsWith('.md')) {
if (file?.body?.children?.length > 0) {
// has contributors
if (file?.contributors?.length > 0) {
const h1Index = file.body.children.findIndex(({ tag }) => tag === "h1")
if (h1Index >= 0) {
file.body.children.splice(h1Index + 1, 0, {
type: "element",
tag: 'contributors',
props: {},
children: []
})
}
}
const root = d3.hierarchy(file.body)
const refNodes = []
root.eachAfter(({ data }) => {
if (data?.tag === 'ref') refNodes.push(data)
})
const refTags = new Set(
refNodes
.flatMap(({ props }) => {
return props?.doi ? props.doi.split(',').map(d => d.trim()) : null
})
.filter(doi => doi !== null)
)
// console.log(refTags)
if (refTags.size > 0) file.references = Array.from(refTags).map(doi => ({ doi }))
// Update the TOC
// if relevant abstract available
if (file?.relevantAbstracts?.length > 0) {
// check if relevant Abstracts exists
file.body.toc.links.push({ id: "relevant-abstracts", depth: 2, text: 'Relevant abstracts' })
file.body.children.push({
type: "element",
tag: 'relevant-abstracts',
props: {},
children: []
})
}
if (file?.references?.length > 0) {
file.body.toc.links.push({ id: "references", depth: 2, text: 'References' })
file.body.children.push({
type: "element",
tag: 'references',
props: {},
children: []
})
}
}
}
})
})