import fs from 'node:fs'; import {u} from 'unist-builder'; import {h} from 'hastscript'; import {select} from 'hast-util-select'; import {toString as hastToString} from 'mdast-util-to-string'; import cssesc from 'cssesc'; import toml from '@ltd/j-toml'; import {toString, toMdRaw, mdToHtmlRaw} from './to-html.mjs'; import {getArticleYear} from './article.mjs'; import i18n from './i18n.mjs'; const loadMD = (listFile, suffix, lang) => { const listContent = []; for (const file of listFile) { console.log(`Working on ${file}`); const content = fs.readFileSync(`${suffix}/${file}`, 'utf8'); const mdRaw = toMdRaw(content); const tomlStringValue = mdRaw.children[0].value; const metaData = toml.parse(tomlStringValue); const newHTML = mdToHtmlRaw(mdRaw); const htmlContent = newHTML; const htmlRender = toString(htmlContent); const titleHtml = select('h1', htmlContent); const intro = select('p', htmlContent); intro.children = intro.children.filter(child => child.tagName !== 'br'); const logo = select('img', intro); if (logo && logo?.properties) { if (logo.properties.src[0] != '/') { logo.properties.src = `/${suffix}/${logo.properties.src}`; } logo.properties.height = '150'; logo.properties.width = '150'; } const logoP = select('source', intro); if (logoP !== null) { logoP.properties.srcSet = `/${suffix}/${logoP.properties.srcSet}`; } titleHtml.children[0].properties.href = `/${suffix}/${file.slice(0, -3)}`; const title = hastToString(titleHtml); const domTitle = cssesc(title.replace(/\s+/g, '-').replace(/['"#@]/, '').toLowerCase()); // Maybe encodeURI const readMore = h('a', i18n[lang]['read_more']); readMore.properties.href = `/${suffix}/${file.slice(0, -3)}`; const pubYear = getArticleYear({metaData}); if (metaData.pubDate) { try { metaData.pubDateISO = metaData.pubDate.toISOString(); } catch (error) { console.error(`Error on file ${file} with pubDate (${metaData.pubDate}): ${error}`); } } listContent.push({ name: file.slice(0, -3), content: htmlRender, intro: toString(u('root', [titleHtml, intro, readMore])), introDesc: hastToString(intro), imageUrl: logo?.properties?.src || '', metaData, pubYear, title, domTitle, url: `/${suffix}/${file.slice(0, -3)}`, }); } return listContent; }; export default loadMD;