import { promises as fs } from "fs"; import path from "path"; import hljs from "highlight.js"; import ejs from "ejs"; import formatDate from "date-fns/format"; import { Metadata } from "./metadata"; export async function write(filePath: string, data: any) { const dest = path.join("out", filePath); await fs.mkdir(path.dirname(dest), { recursive: true }); await fs.writeFile(dest, data); } export function getWordCount(text: string): number { return text.split(/\s+/).length; } export function getReadingTime(words: number): number { const avgWPM = 225; return Math.max(1, Math.round(words / avgWPM)) } export function highlight(source: string, language?: string): string { const res = language ? hljs.highlight(language, source) : hljs.highlightAuto(source); const highlighted = res.value; return `
${highlighted}
`; } interface Chunk { chunk: T[]; index: number; } export function chunk(array: T[], size: number): Chunk[] { const chunks: Chunk[] = []; for (let i = 0; i < array.length; i += size) { chunks.push({ chunk: array.slice(i, i + size), index: i / size }); } return chunks; } export function fancyLink(text: string, href: string, meta?: string): string { return `${text}`; } export function video(metadata: Metadata, name: string, attributes: object): string { if (!attributes["poster"]) { attributes["poster"] = `${metadata.permalink}/${name}.png`; } if (attributes["controls"] === undefined) { attributes["controls"] = true; } var attributesStr = ""; for (const k of Object.keys(attributes)) { const v = attributes[k]; if (typeof v == "boolean" && v) { attributesStr += `${k} `; } else if (typeof v == "string") { attributesStr += `${k}="${v}" `; } else { console.warn(`Unexpected attribute value for ${k}: ${v}`); } } return ` `; } export function render(template: string, data: any, filename?: string): string { data.fancyLink = fancyLink; data.formatDate = formatDate; data.video = video; return ejs.render(template, data, { filename }); }