From 1932d0482af2215c740400542532a2a5e01a6031 Mon Sep 17 00:00:00 2001 From: Bo-Y-G Date: Thu, 15 Aug 2024 19:30:51 +0000 Subject: [PATCH] Title Collecting and rendering titles to Pretext --- .../unified-latex-to-pretext/libs/title.ts | 28 +++++++++++++ .../tests/title.test.ts | 41 +++++++++++++++++++ 2 files changed, 69 insertions(+) create mode 100644 packages/unified-latex-to-pretext/libs/title.ts create mode 100644 packages/unified-latex-to-pretext/tests/title.test.ts diff --git a/packages/unified-latex-to-pretext/libs/title.ts b/packages/unified-latex-to-pretext/libs/title.ts new file mode 100644 index 00000000..16d9f5c5 --- /dev/null +++ b/packages/unified-latex-to-pretext/libs/title.ts @@ -0,0 +1,28 @@ +import * as Ast from "@unified-latex/unified-latex-types"; +import { visit } from "@unified-latex/unified-latex-util-visit"; +import { match } from "@unified-latex/unified-latex-util-match"; +import { htmlLike } from "@unified-latex/unified-latex-util-html-like"; + +export function gatherTitle(ast: Ast.Ast): Ast.Node[] { + const ti: Ast.Node[] = []; + + visit(ast, (node) => { + if (match.macro(node, "title") && node.args) { + const titleContent = Object.fromEntries( + node.args.map((x) => [x.content]) + ); + return titleContent; + } + }); + return ti; +} + +export function renderTitle(ast: Ast.Ast, title: Ast.Node): Ast.Macro { + + const renderedAuthorList = htmlLike({ + tag: "title", + content: title, + }); + + return renderedAuthorList; +} diff --git a/packages/unified-latex-to-pretext/tests/title.test.ts b/packages/unified-latex-to-pretext/tests/title.test.ts new file mode 100644 index 00000000..954b8bd5 --- /dev/null +++ b/packages/unified-latex-to-pretext/tests/title.test.ts @@ -0,0 +1,41 @@ +import { describe, it, expect } from "vitest"; +import Prettier from "prettier"; +import util from "util"; +import { getParser } from "@unified-latex/unified-latex-util-parse"; +import { toXml } from "xast-util-to-xml"; +import { xmlCompilePlugin } from "../libs/convert-to-pretext"; +import { unified } from "unified"; +import { gatherTitle, renderTitle } from "../libs/title"; +import { toPretextWithLoggerFactory } from "../libs/pretext-subs/to-pretext"; + +function normalizeHtml(str: string) { + try { + return Prettier.format(str, { parser: "html" }); + } catch { + console.warn("Could not format HTML string", str); + return str; + } +} + +// Make console.log pretty-print by default +const origLog = console.log; +console.log = (...args) => { + origLog(...args.map((x) => util.inspect(x, false, 10, true))); +}; + +describe("unified-latex-to-pretext:title", () => { + let sample: string; + let input: string; + const parser = getParser(); + + it("collects title content", () => { + sample = + "\\title{Title}"; + expect(gatherTitle(parser.parse(sample))).toEqual([]); + + sample = + "\\title{Title} \n \\maketitle"; + input = " Title" + expect(gatherTitle(parser.parse(sample))).toEqual(parser.parse(input).content); + }); +}); \ No newline at end of file