Files

78 lines
2.5 KiB
TypeScript

import { resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { PFiles } from "../publication/file.ts";
import { md } from "../mdit/md.ts";
import { renderTemplate, type TemplateVariables } from "../template/engine.ts";
import type { DocumentConfig, DocumentInput, HtmlDocument } from "./types.ts";
export function publicationToHtml(
files: PFiles,
config: DocumentConfig,
variables: TemplateVariables = {},
): HtmlDocument {
const render = (source: string) => renderTemplate(source, variables);
let id = 0;
return {
kind: "html",
metadata: {
title: config.journal.title ?? "未命名出版物",
author: config.journal.author ?? "未知作者",
language: config.journal.language ?? "zh-CN",
identifier: config.journal.identifier,
},
baseDirectory: resolve(config.journal.from_directory),
assetBase: /^file:\/\//i.test(config.asset_base ?? "")
? fileURLToPath(config.asset_base!)
: resolve(config.asset_base ?? "../../assets"),
chapters: files.pcolumes.flatMap((column) =>
column.pfiles.map((file) => ({
id: `article-${++id}`,
title: file.meta.title,
sourcePath: resolve(file.full_name),
index: file.meta.index,
column: { name: column.name, index: column.index },
html: md.render(renderTemplate(file.content, {
...variables,
document: {
title: file.meta.title,
index: file.meta.index,
file: file.full_name,
},
column: { name: column.name, index: column.index },
})),
}))
),
layout: {
cover: render(files.cover_html ?? ""),
styles: render(files.style_html ?? ""),
before: render(files.other_htmls.join("\n")),
after: render(files.end_html ?? ""),
},
};
}
export class PublicationInput implements DocumentInput {
constructor(
private readonly config: DocumentConfig,
private readonly variables: TemplateVariables = {},
) {}
async read(): Promise<HtmlDocument> {
const files = new PFiles(
this.config.journal.build_mode ?? "flat",
this.config.journal.from_directory,
this.config,
);
return publicationToHtml(files, this.config, this.variables);
}
}
/** Allows callers and future parsers to supply HTML without publication files. */
export class HtmlInput implements DocumentInput {
constructor(private readonly document: HtmlDocument) {}
async read(): Promise<HtmlDocument> {
return this.document;
}
}