diff --git a/apps/server/src/scient/pandoc/PandocWordConverter.integration.test.ts b/apps/server/src/scient/pandoc/PandocWordConverter.integration.test.ts index 625f0446da..117f1bce5f 100644 --- a/apps/server/src/scient/pandoc/PandocWordConverter.integration.test.ts +++ b/apps/server/src/scient/pandoc/PandocWordConverter.integration.test.ts @@ -633,4 +633,228 @@ describe.skipIf(binary === null)("Word export with the real Pandoc (local integr }), ), ); + describe("local font size and family", () => { + const exportMarkdown = (name: string, markdown: string) => + withConverter(({ converter, directory }) => + Effect.gen(function* () { + const { docx, result } = yield* convertTo(converter, directory, name, { + bundle: makeBundle({ markdown }), + }); + return { + document: docx.text("word/document.xml"), + styles: docx.text("word/styles.xml"), + warnings: result.warnings.map((warning) => warning.message).join("\n"), + }; + }), + ); + + it.live("applies a size in points as a Word character style", () => + Effect.gen(function* () { + const { document, styles, warnings } = yield* exportMarkdown( + "font-size-span", + 'Some big words.', + ); + expect(document).toMatch( + /[\s\S]*?]*>big<\/w:t>/u, + ); + expect(styles).toMatch(/w:styleId="Scient13_5pt"[\s\S]*?/u); + expect(warnings).not.toContain("Raw HTML"); + expect(document).not.toContain("<span"); + }), + ); + + it.live("applies a named font as a Word character style", () => + Effect.gen(function* () { + const { document, styles } = yield* exportMarkdown( + "font-family-span", + "Some code words.", + ); + expect(document).toMatch(/[\s\S]*?code/u); + expect(styles).toMatch(/w:styleId="ScientCourierNew"[\s\S]*?w:ascii="Courier New"/u); + }), + ); + + it.live("keeps both when a size span and a font span are nested", () => + Effect.gen(function* () { + const { document } = yield* exportMarkdown( + "font-nested", + 'Some big words here.', + ); + const sizeRun = /(?:(?!<\/w:r>)[\s\S])*?big/u.exec(document)?.[0] ?? ""; + const wordsRun = /(?:(?!<\/w:r>)[\s\S])*?words/u.exec(document)?.[0] ?? ""; + expect(sizeRun).toContain("Scient14pt"); + expect(wordsRun).toContain("ScientArial14pt"); + }), + ); + + it.live("keeps an absolute size inside a heading and a footnote", () => + Effect.gen(function* () { + const { document, styles } = yield* exportMarkdown( + "font-heading", + '# Title with big word\n\nText[^1]\n\n[^1]: Note big.\n', + ); + expect(document).toMatch(/[\s\S]*?]*>big<\/w:t>/u); + expect(styles).toMatch(/w:styleId="Scient20pt"[\s\S]*?/u); + }), + ); + + it.live("keeps the link look on a sized run inside a link", () => + Effect.gen(function* () { + const { document, styles } = yield* exportMarkdown( + "font-link", + 'See [a big link](https://example.com).', + ); + expect(document).toMatch(/[\s\S]*?big/u); + expect(styles).toMatch( + /w:styleId="Scient14ptlink"[\s\S]*?[\s\S]*? + Effect.gen(function* () { + const { document, warnings } = yield* exportMarkdown( + "font-other-span", + 'Some plain words.', + ); + expect(document).toContain("plain"); + expect(document).not.toContain("ScientSize"); + expect(document).not.toContain("color"); + expect(warnings).toContain("Raw HTML was left out"); + }), + ); + + it.live("sets the base font and size from the front matter", () => + Effect.gen(function* () { + const { styles } = yield* exportMarkdown( + "font-front-matter", + "---\nfontsize: 12pt\nmainfont: Times New Roman\n---\n\nText.\n", + ); + expect(styles).toMatch( + /[\s\S]*?w:ascii="Times New Roman"[\s\S]*?/u, + ); + }), + ); + const exportLatex = (name: string, tex: string) => + withConverter(({ converter, directory }) => + Effect.gen(function* () { + const paper = NodePath.join(directory, "paper"); + NodeFS.mkdirSync(paper, { recursive: true }); + NodeFS.writeFileSync(NodePath.join(paper, "main.tex"), tex); + const latex = yield* prepareLatexProject(NodePath.join(paper, "main.tex"), directory); + const { docx } = yield* convertTo(converter, directory, name, { + bundle: makeBundle({ markdown: "" }), + latex, + files: { baseDirectory: paper, allowRoots: [paper] }, + }); + return { document: docx.text("word/document.xml"), styles: docx.text("word/styles.xml") }; + }), + ); + + it.live("keeps LaTeX size groups and family commands as Word character styles", () => + Effect.gen(function* () { + const { document } = yield* exportLatex( + "latex-font", + [ + "\\documentclass{article}", + "\\begin{document}", + "A {\\fontsize{14.4}{17.3}\\selectfont big \\textsf{both}} and \\textrm{roman} and {\\small tiny}.", + "\\end{document}", + ].join("\n"), + ); + const run = (text: string) => + new RegExp(`(?:(?!)[\\s\\S])*?${text}`, "u").exec(document)?.[0] ?? ""; + expect(run("big")).toContain("Scient14_4pt"); + expect(run("both")).toContain("ScientArial14_4pt"); + expect(run("roman")).toContain("ScientTimesNewRoman"); + expect(run("tiny")).toContain("Scient9pt"); + expect(document).not.toContain("scient-size"); + }), + ); + + it.live("exports size groups next to commands and inside arguments", () => + Effect.gen(function* () { + const { document } = yield* exportLatex( + "latex-brace-forms", + [ + "\\documentclass{article}", + "\\begin{document}", + "\\section {\\large Intro}", + "Body\\footnote {\\small note}. a{\\Large b}c and \\textbf{x}{\\large y}.", + "\\end{document}", + ].join("\n"), + ); + const run = (text: string) => + new RegExp(`(?:(?!)[\\s\\S])*?${text}`, "u").exec(document)?.[0] ?? ""; + expect(run("Intro")).toContain("Scient12pt"); + expect(run(">b<")).toContain("Scient14_4pt"); + expect(run(">y<")).toContain("Scient12pt"); + expect(document).not.toContain("scient-size"); + }), + ); + + it.live("keeps a LaTeX font family group as a Word character style", () => + Effect.gen(function* () { + const { document } = yield* exportLatex( + "latex-font-family", + [ + "\\documentclass{article}", + "\\begin{document}", + "A {\\fontfamily{qtm}\\selectfont serif} text.", + "\\end{document}", + ].join("\n"), + ); + const run = /(?:(?!<\/w:r>)[\s\S])*?serif/u.exec(document)?.[0] ?? ""; + expect(run).toContain("ScientTimesNewRoman"); + }), + ); + + it.live("takes the base font from the LaTeX class option and \\familydefault", () => + Effect.gen(function* () { + const { styles } = yield* exportLatex( + "latex-base-font", + [ + "\\documentclass[12pt]{article}", + "\\renewcommand{\\familydefault}{\\rmdefault}", + "\\begin{document}", + "Text.", + "\\end{document}", + ].join("\n"), + ); + expect(styles).toMatch( + /[\s\S]*?Times New Roman[\s\S]*?/u, + ); + }), + ); + + it.live("takes the named font the document settings card writes, at LaTeX's 10 pt", () => + Effect.gen(function* () { + const pdftex = yield* exportLatex( + "latex-card-font-pdftex", + [ + "\\documentclass{article}", + "\\renewcommand{\\familydefault}{qtm}", + "\\begin{document}", + "Text.", + "\\end{document}", + ].join("\n"), + ); + expect(pdftex.styles).toMatch( + /[\s\S]*?Times New Roman[\s\S]*?/u, + ); + const fontspec = yield* exportLatex( + "latex-card-font-fontspec", + [ + "\\documentclass{article}", + "\\usepackage{fontspec}", + "\\setmainfont{Calibri}", + "\\begin{document}", + "Text.", + "\\end{document}", + ].join("\n"), + ); + expect(fontspec.styles).toMatch(/[\s\S]*?Calibri/u); + }), + ); + }); }); diff --git a/apps/server/src/scient/pandoc/PandocWordConverter.ts b/apps/server/src/scient/pandoc/PandocWordConverter.ts index 09bfb17086..6cf0dd64cd 100644 --- a/apps/server/src/scient/pandoc/PandocWordConverter.ts +++ b/apps/server/src/scient/pandoc/PandocWordConverter.ts @@ -34,9 +34,16 @@ import { type PandocLimits, type PandocRunError, } from "./pandocProcess.ts"; +import { + applyFontSpans, + applyLatexFontSpans, + latexBaseFontOf, + rewriteLatexSizeGroups, + wordBaseFontOf, +} from "./pandocFont.ts"; import { securePandocDocument } from "./pandocResources.ts"; import { spaceTextAroundTables } from "./pandocTableSpacing.ts"; -import { scientReferenceDocument } from "./scientReferenceDocument.ts"; +import { scientReferenceDocumentFor, type WordLocalFont } from "./scientReferenceDocument.ts"; import type { PreparedLatexProject } from "./latexProjectPreparation.ts"; import type { CapturedWorkspaceImage } from "./wordImageSnapshot.ts"; @@ -323,7 +330,7 @@ const make = Effect.gen(function* () { input.latex ? ["--sandbox", "-f", "latex", "-t", "json"] : ["--sandbox", "--preserve-tabs", "-f", SCIENT_PANDOC_READER, "-t", "json"], - new TextEncoder().encode(source), + new TextEncoder().encode(input.latex ? rewriteLatexSizeGroups(source) : source), readLimits, ); const decoded = yield* decodePandocDocument(new TextDecoder().decode(read.stdout)).pipe( @@ -368,6 +375,11 @@ const make = Effect.gen(function* () { } } const citations = applyCitations(document.blocks, bibliography); + // Read before the security pass, which clears the document's metadata. + const baseFont = input.latex ? latexBaseFontOf(source) : wordBaseFontOf(document.meta); + const fontPass = { base: baseFont, used: new Map() }; + if (input.latex) applyLatexFontSpans(document.blocks, fontPass); + else applyFontSpans(document.blocks, fontPass); const security = yield* securePandocDocument(document, { assets: input.bundle.assets, files: input.imageSnapshot === undefined ? (input.files ?? null) : null, @@ -407,7 +419,7 @@ const make = Effect.gen(function* () { const args = ["--sandbox", "-f", "json", "-t", "docx", "--reference-doc=reference.docx"]; yield* fileSystem.writeFile( path.join(scratch.work, "reference.docx"), - yield* scientReferenceDocument, + yield* scientReferenceDocumentFor(baseFont, [...fontPass.used.values()]), ); const cited = [...citations.citedKeys].flatMap((key) => { const item = bibliography.get(key); diff --git a/apps/server/src/scient/pandoc/pandocFont.test.ts b/apps/server/src/scient/pandoc/pandocFont.test.ts new file mode 100644 index 0000000000..0d16798c1d --- /dev/null +++ b/apps/server/src/scient/pandoc/pandocFont.test.ts @@ -0,0 +1,254 @@ +/** + * Word font handling that needs no Pandoc: the LaTeX size-group rewrite and the base font reads. + */ +import { FONT_CATALOGUE } from "@scientfactory/scient-markdown"; +import { describe, expect, it } from "vite-plus/test"; + +import { + applyFontSpans, + type FontPass, + latexBaseFontOf, + rewriteLatexSizeGroups, +} from "./pandocFont.ts"; +import { scientReferenceDocumentParts, type WordLocalFont } from "./scientReferenceDocument.ts"; + +const carrier = (name: string, body: string) => `{\\ScientSize{scient-size-${name}}{${body}}}`; + +describe("rewriteLatexSizeGroups", () => { + it("rewrites a size group and leaves the rest of the source unchanged", () => { + const rewritten = rewriteLatexSizeGroups("A {\\Large big} B"); + expect(rewritten).toContain(`A ${carrier("14p4", "big")} B`); + expect(rewritten.startsWith("\\newcommand{\\ScientSize}")).toBe(true); + }); + + it("keeps nested groups and family commands inside the body", () => { + expect(rewriteLatexSizeGroups("{\\large a {\\small b} \\textsf{c}}")).toContain( + carrier("12", `a ${carrier("9", "b")} \\textsf{c}`), + ); + }); + + it("returns the source untouched when it has no size group", () => { + const source = "Plain {grouped} text with \\textbf{bold}."; + expect(rewriteLatexSizeGroups(source)).toBe(source); + }); + + it("does not touch escaped braces, comments, math or an unbalanced group", () => { + for (const source of [ + "\\{\\Large not a group\\}", + "% {\\Large in a comment}\nText", + "Math $a {\\large b}$ here", + "Open {\\Large never closed", + ]) { + expect(rewriteLatexSizeGroups(source)).toBe(source); + } + }); + + it("keeps the braces of a group, so an argument or a spaced group stays valid", () => { + expect(rewriteLatexSizeGroups("\\section {\\large Intro}")).toContain( + `\\section ${carrier("12", "Intro")}`, + ); + expect(rewriteLatexSizeGroups("a{\\Large b}c")).toContain(`a${carrier("14p4", "b")}c`); + expect(rewriteLatexSizeGroups("\\textbf{x}{\\large y}")).toContain( + `\\textbf{x}${carrier("12", "y")}`, + ); + }); + + it("leaves other braces alone", () => { + const source = "\\begin{tabular}{l}\\\\[2pt]\\end{tabular}"; + expect(rewriteLatexSizeGroups(source)).toBe(source); + }); + + it("does not touch verbatim environments or bracket math", () => { + for (const source of [ + "\\begin{verbatim}{\\large x}\\end{verbatim}", + "\\begin{lstlisting}\n{\\large x}\n\\end{lstlisting}", + "\\[ a {\\large b} \\]", + "\\( a {\\large b} \\)", + ]) { + expect(rewriteLatexSizeGroups(source)).toBe(source); + } + }); + + it("still rewrites a group after bracket math", () => { + expect(rewriteLatexSizeGroups("\\[ a \\] {\\large x}")).toContain(carrier("12", "x")); + }); + + it("does not match a longer command that starts with a size name", () => { + const source = "{\\largesse text}"; + expect(rewriteLatexSizeGroups(source)).toBe(source); + }); +}); + +describe("latexBaseFontOf", () => { + it("reads the class option and the default family", () => { + expect( + latexBaseFontOf( + "\\documentclass[a4paper,12pt]{article}\n\\renewcommand{\\familydefault}{\\ttdefault}", + ), + ).toEqual({ sizePoints: 12, family: "Courier New" }); + }); + + it("uses LaTeX's 10 pt and Word's default font when nothing is set", () => { + expect(latexBaseFontOf("\\documentclass{article}")).toEqual({ + sizePoints: 10, + family: null, + }); + }); +}); + +describe("local fonts become Word character styles", () => { + const raw = (html: string) => ({ t: "RawInline", c: ["html", html] }); + const close = raw(""); + const word = { t: "Str", c: "word" }; + const pass = (): FontPass => ({ + base: { sizePoints: 11, family: null }, + used: new Map(), + }); + const stylesOf = (inlines: unknown) => + JSON.stringify(inlines).match(/custom-style","([^"]*)/gu) ?? []; + + it("names an absolute size in points", () => { + const text = [{ t: "Para", c: [raw(''), word, close] }]; + const used = pass(); + applyFontSpans(text, used); + expect(stylesOf(text)).toEqual(['custom-style","13.5 pt']); + expect([...used.used.keys()]).toEqual(["13.5 pt"]); + }); + + it("names a font and combines a nested size and font in one style", () => { + const text = [ + { + t: "Para", + c: [ + raw(''), + raw(""), + word, + close, + close, + ], + }, + ]; + const used = pass(); + applyFontSpans(text, used); + expect(stylesOf(text).at(-1)).toBe('custom-style","Times New Roman 14 pt'); + expect(used.used.has("Times New Roman 14 pt")).toBe(true); + }); + + it("leaves a name outside the catalogue as plain source", () => { + const text = [ + { t: "Para", c: [raw(""), word, close] }, + ]; + applyFontSpans(text, pass()); + expect(stylesOf(text)).toEqual([]); + }); + + it("defines each used style with half-point sizes and the right fonts", () => { + const styles = scientReferenceDocumentParts({ sizePoints: 11, family: null }, [ + { size: 13.3, family: "Arial" }, + { family: "Times New Roman" }, + ]).find(([name]) => name === "word/styles.xml")?.[1]; + // 13.3 pt rounds to 26.5 pt, written as 27 half points. + expect(styles).toMatch(/w:styleId="ScientArial13_3pt"[\s\S]*? { + it("reads a fontsize group in points", () => { + expect(rewriteLatexSizeGroups("A {\\fontsize{13}{15.6}\\selectfont big} B")).toContain( + `A ${carrier("13", "big")} B`, + ); + }); + + it("keeps a decimal size and a leading space after selectfont{}", () => { + expect(rewriteLatexSizeGroups("{\\fontsize{13.5}{16}\\selectfont{} x}")).toContain( + carrier("13p5", " x"), + ); + }); + + it("maps a named size through the class option", () => { + const source = "\\documentclass[12pt]{article}\n{\\large x}"; + expect(rewriteLatexSizeGroups(source)).toContain(carrier("14p4", "x")); + expect(rewriteLatexSizeGroups("{\\large x}")).toContain(carrier("12", "x")); + }); + + it("ignores a commented class option and a commented family default", () => { + const source = + "%\\documentclass[12pt]{article}\n% \\renewcommand{\\familydefault}{\\ttdefault}"; + expect(latexBaseFontOf(source)).toEqual({ sizePoints: 10, family: null }); + }); + + it("reads the named font the document settings card writes, under each engine", () => { + expect( + latexBaseFontOf("\\documentclass{article}\n\\renewcommand{\\familydefault}{qtm}"), + ).toEqual({ sizePoints: 10, family: "Times New Roman" }); + expect( + latexBaseFontOf( + "\\documentclass[11pt]{article}\n\\usepackage{fontspec}\n\\setmainfont{Calibri}\n\\begin{document}\nx\n\\end{document}", + ), + ).toEqual({ sizePoints: 11, family: "Calibri" }); + }); + + it("lets the declaration that sets the text win, and reads \\setmainfont options", () => { + const preamble = (...lines: string[]) => ["\\documentclass{article}", ...lines].join("\n"); + expect( + latexBaseFontOf(preamble("\\renewcommand{\\familydefault}{qtm}", "\\setmainfont{Calibri}")) + .family, + ).toBe("Calibri"); + expect( + latexBaseFontOf( + preamble("\\setmainfont{Georgia}", "\\renewcommand{\\familydefault}{\\rmdefault}"), + ).family, + ).toBe("Georgia"); + expect( + latexBaseFontOf( + preamble("\\setmainfont{Georgia}", "\\renewcommand{\\familydefault}{\\sfdefault}"), + ).family, + ).toBe("Arial"); + expect(latexBaseFontOf(preamble("\\setmainfont[Ligatures=TeX]{Calibri}")).family).toBe( + "Calibri", + ); + }); + + it("ignores a font outside the catalogue and a \\setmainfont after the preamble", () => { + expect(latexBaseFontOf("\\setmainfont{Comic Sans MS}")).toEqual({ + sizePoints: 10, + family: null, + }); + expect(latexBaseFontOf("\\begin{document}\n\\setmainfont{Calibri}\n\\end{document}")).toEqual({ + sizePoints: 10, + family: null, + }); + }); + + it("reads the fontsize forms the editor reads", () => { + for (const source of [ + "{\\fontsize{12pt}{15pt}\\selectfont x}", + "{\\fontsize { 12 }{ 15 }\\selectfont x}", + ]) { + expect(rewriteLatexSizeGroups(source)).toContain(carrier("12", "x")); + } + }); + + it("does not rewrite inside \\verb or \\lstinline", () => { + for (const source of [ + "\\verb|{\\large x}| and more", + "\\lstinline{{\\large x}} and more", + "\\lstinline[language=C]|{\\large x}|", + ]) { + expect(rewriteLatexSizeGroups(source)).toBe(source); + } + expect(rewriteLatexSizeGroups("\\verb|x| {\\large y}")).toContain(carrier("12", "y")); + }); + + it("rewrites a font family group in both written forms", () => { + const index = FONT_CATALOGUE.findIndex((font) => font.name === "Times New Roman"); + const code = rewriteLatexSizeGroups("{\\fontfamily{qtm}\\selectfont serif}"); + expect(code).toContain(`{\\ScientSize{scient-font-${index}}{serif}}`); + const named = rewriteLatexSizeGroups( + "{\\IfFontExistsTF{Times New Roman}{\\fontspec{Times New Roman}}{\\fontspec{Latin Modern Roman}} serif}", + ); + expect(named).toContain(`{\\ScientSize{scient-font-${index}}{serif}}`); + }); +}); diff --git a/apps/server/src/scient/pandoc/pandocFont.ts b/apps/server/src/scient/pandoc/pandocFont.ts new file mode 100644 index 0000000000..e375a670bc --- /dev/null +++ b/apps/server/src/scient/pandoc/pandocFont.ts @@ -0,0 +1,357 @@ +/** + * Word export of local font size and family. Scient's recognised `` forms are turned + * into Word character styles before raw HTML is stripped; the `fontsize` and `mainfont` front + * matter keys set the base font of the reference document. + */ +import { + DOCUMENT_FONT_SIZES, + MARKDOWN_FONT_SPAN_CLOSE, + type MarkdownFontSpan, + FONT_CATALOGUE, + catalogueFont, + normalizeFontSize, + parseMarkdownFontSpanOpen, +} from "@scientfactory/scient-markdown"; +import * as Predicate from "effect/Predicate"; + +import { attr, customStyleSpan, inlineText, isPandocNode, type PandocNode } from "./pandocAst.ts"; +import { + DEFAULT_WORD_BASE_FONT, + type WordBaseFont, + type WordLocalFont, + wordFontStyleName, +} from "./scientReferenceDocument.ts"; + +const SPAN_OPEN = /^; +} + +/** The Word style name for a font, noting it so the reference document defines it. */ +function styleNameOf(font: WordLocalFont, pass: FontPass): string { + const name = wordFontStyleName(font); + pass.used.set(name, font); + return name; +} + +/** The font of a span laid over the font already in force around it. */ +function layered(outer: WordLocalFont, span: MarkdownFontSpan): WordLocalFont { + return "family" in span ? { ...outer, family: span.family } : { ...outer, size: span.size }; +} + +/** The raw HTML text of an inline, or null when it is not a raw HTML inline. */ +function rawHtml(node: unknown): string | null { + if (!isPandocNode(node) || node.t !== "RawInline" || !Array.isArray(node.c)) return null; + const [format, text] = node.c; + return format === "html" && Predicate.isString(text) ? text.trim() : null; +} + +/** Index of the `` that closes the span opened at `open`, counting nested spans. */ +function closingIndex(inlines: Array, open: number): number { + let depth = 0; + for (let index = open; index < inlines.length; index += 1) { + const html = rawHtml(inlines[index]); + if (html === null) continue; + if (SPAN_OPEN.test(html)) depth += 1; + else if (html.toLowerCase() === MARKDOWN_FONT_SPAN_CLOSE) depth -= 1; + if (depth === 0) return index; + } + return -1; +} + +function wrapFontSpans(inlines: Array, outer: WordLocalFont, pass: FontPass): void { + for (let index = 0; index < inlines.length; index += 1) { + const html = rawHtml(inlines[index]); + const span = html === null ? null : parseMarkdownFontSpanOpen(html); + if (span === null) continue; + const close = closingIndex(inlines, index); + if (close < 0) continue; + const font = layered(outer, span); + const inner = inlines.slice(index + 1, close) as Array; + // A Word run carries one character style, so a nested span names the combined font. + applyFontSpans(inner, pass, font); + inlines.splice(index, close - index + 1, customStyleSpan(styleNameOf(font, pass), inner)); + } +} + +/** + * Replace each recognised size or family span with a Word character style span. Other HTML is + * left for the raw-HTML strip. + */ +export function applyFontSpans(value: unknown, pass: FontPass, outer: WordLocalFont = {}): void { + if (Array.isArray(value)) { + wrapFontSpans(value, outer, pass); + for (const item of value) applyFontSpans(item, pass, outer); + return; + } + if (!Predicate.isObject(value)) return; + // Runs in a link keep the link's look, which a character style would otherwise replace. + const within = isPandocNode(value) && value.t === "Link" ? { ...outer, link: true } : outer; + for (const child of Object.values(value)) applyFontSpans(child, pass, within); +} + +/** The base font named by the document's metadata; anything unrecognised keeps the default. */ +export function wordBaseFontOf(meta: Record): WordBaseFont { + const size = inlineText(meta["fontsize"]).trim(); + const family = inlineText(meta["mainfont"]).trim(); + return { + sizePoints: BASE_SIZE.test(size) + ? Number.parseInt(size, 10) + : DEFAULT_WORD_BASE_FONT.sizePoints, + family: catalogueFont(family) === null ? DEFAULT_WORD_BASE_FONT.family : family, + }; +} + +// LaTeX source. Pandoc keeps `\textsf` and `\textrm` as classed spans but drops `{\large …}`, so a +// size group is rewritten to a `\textcolor` carrier Pandoc keeps, then turned into the same Word +// style as a Markdown span. + +// Sizes of the standard class commands, in points, for the 10, 11 and 12 pt class options +// (the same table as the Visual editor's layout). +const LATEX_NAMED_SIZES: Readonly> = { + tiny: [5, 6, 6], + scriptsize: [7, 8, 8], + footnotesize: [8, 9, 10], + small: [9, 10, 10.95], + normalsize: [10, 10.95, 12], + large: [12, 12, 14.4], + Large: [14.4, 14.4, 17.28], + LARGE: [17.28, 17.28, 20.74], + huge: [20.74, 20.74, 24.88], + Huge: [24.88, 24.88, 24.88], +}; +const LATEX_SIZE_COMMAND = new RegExp( + String.raw`^\\(?:(${Object.keys(LATEX_NAMED_SIZES).join("|")})|fontsize\s*\{\s*(\d+(?:\.\d+)?)\s*(?:pt)?\s*\}\s*\{[^{}]*\}\s*\\selectfont)(?:\{\}|(?![A-Za-z@])\s?)`, + "u", +); +const LATEX_SIZE_CARRIER = "scient-size-"; +const LATEX_SIZE_MACRO = String.raw`\newcommand{\ScientSize}[2]{\textcolor{#1}{#2}}`; +const LATEX_CLASS_SIZE = new RegExp( + String.raw`\\documentclass\[[^\]]*?\b(${DOCUMENT_FONT_SIZES.join("|")})\b[^\]]*\]`, + "u", +); +const LATEX_FAMILY_DEFAULT = /\\renewcommand\s*\{\\familydefault\}\s*\{\\?([A-Za-z0-9]+)\}/gu; +const LATEX_MAIN_FONT = /\\setmainfont\s*(?:\[[^\]]*\]\s*)?\{([^{}]+)\}/gu; +const LATEX_FAMILIES: Readonly> = { + rm: "Times New Roman", + sf: "Arial", + tt: "Courier New", +}; + +/** The source without its comments, so commented lines are never read as settings. */ +const withoutComments = (source: string): string => source.replaceAll(/(? + code === null ? font.latex.fontspec === named?.[1] : font.latex.pdftex === code[1], + ); + const match = code ?? named; + return match === null || index < 0 + ? null + : { carrier: `${LATEX_FONT_CARRIER}${index}`, length: match[0].length }; +} + +const isEscaped = (text: string, index: number): boolean => { + let backslashes = 0; + while (index - 1 - backslashes >= 0 && text[index - 1 - backslashes] === "\\") backslashes += 1; + return backslashes % 2 === 1; +}; + +/** Index of the `}` closing the `{` at `open`, or -1. Comments and escaped braces are skipped. */ +function braceEnd(text: string, open: number): number { + let depth = 0; + for (let index = open; index < text.length; index += 1) { + const char = text[index]; + if (char === "%" && !isEscaped(text, index)) { + const newline = text.indexOf("\n", index); + if (newline < 0) return -1; + index = newline; + } else if (char === "{" && !isEscaped(text, index)) depth += 1; + else if (char === "}" && !isEscaped(text, index)) { + depth -= 1; + if (depth === 0) return index; + } + } + return -1; +} + +// Environments whose content is copied as is. +const LATEX_VERBATIM_START = /^\\begin\{(verbatim\*?|lstlisting|minted)\}/u; +// `\verb|…|` and `\lstinline|…|` (or with braces): the delimiter closes the copied text. +const LATEX_INLINE_VERBATIM = /^\\(?:verb\*?|lstinline(?:\[[^\]]*\])?)([^\sA-Za-z*])/u; + +function rewriteSizeGroups( + text: string, + counter: { found: boolean }, + classSize: 10 | 11 | 12, +): string { + let out = ""; + let inMath = false; + for (let index = 0; index < text.length; index += 1) { + const char = text[index] ?? ""; + if (char === "%" && !isEscaped(text, index)) { + const newline = text.indexOf("\n", index); + const end = newline < 0 ? text.length : newline; + out += text.slice(index, end); + index = end - 1; + continue; + } + if (char === "\\" && !isEscaped(text, index)) { + const verbatim = LATEX_VERBATIM_START.exec(text.slice(index)); + if (verbatim !== null) { + const close = `\\end{${verbatim[1]}}`; + const end = text.indexOf(close, index); + const stop = end < 0 ? text.length : end + close.length; + out += text.slice(index, stop); + index = stop - 1; + continue; + } + const inline = LATEX_INLINE_VERBATIM.exec(text.slice(index)); + if (inline !== null) { + const opener = inline[1] ?? ""; + const from = index + inline[0].length; + const stop = opener === "{" ? braceEnd(text, from - 1) : text.indexOf(opener, from); + const end = stop < 0 ? text.length : stop + 1; + out += text.slice(index, end); + index = end - 1; + continue; + } + const next = text[index + 1]; + if (next === "(" || next === "[") inMath = true; + else if (next === ")" || next === "]") inMath = false; + } + if (char === "$" && !isEscaped(text, index)) inMath = !inMath; + if (char === "{" && !inMath && !isEscaped(text, index)) { + const declaration = latexDeclaration(text.slice(index + 1), classSize); + const end = declaration === null ? -1 : braceEnd(text, index); + if (declaration !== null && end >= 0) { + counter.found = true; + const body = text.slice(index + 1 + declaration.length, end); + // The group's own braces stay, so it is still a group (or an argument) to Pandoc. + out += `{\\ScientSize{${declaration.carrier}}{${rewriteSizeGroups(body, counter, classSize)}}}`; + index = end; + continue; + } + } + out += char; + } + return out; +} + +/** The LaTeX source with each `{\large …}` size group made readable by Pandoc. */ +export function rewriteLatexSizeGroups(source: string): string { + const counter = { found: false }; + const rewritten = rewriteSizeGroups(source, counter, latexClassSize(source)); + return counter.found ? `${LATEX_SIZE_MACRO}\n${rewritten}` : source; +} + +/** The value of the last match of `pattern` in `text`. */ +const lastValue = (text: string, pattern: RegExp): string | undefined => + [...text.matchAll(pattern)].at(-1)?.[1]?.trim(); + +/** + * The base font set by the preamble, as the Visual card writes it: the class option size (10 pt + * when absent), and the font the text is set in. A sans-serif or monospace `\familydefault` + * wins; otherwise a catalogue font in `\setmainfont` (it defines the roman family), then a + * catalogue font code in `\familydefault`, then the generic roman family. + */ +export function latexBaseFontOf(source: string): WordBaseFont { + const active = withoutComments(source); + const bodyStart = active.indexOf("\\begin{document}"); + const preamble = bodyStart < 0 ? active : active.slice(0, bodyStart); + const familyDefault = lastValue(preamble, LATEX_FAMILY_DEFAULT); + const mainFont = lastValue(preamble, LATEX_MAIN_FONT); + const generic = familyDefault?.match(/^(rm|sf|tt)default$/u)?.[1]; + const family = + (generic === "sf" || generic === "tt" ? LATEX_FAMILIES[generic] : undefined) ?? + FONT_CATALOGUE.find((font) => font.latex.fontspec === mainFont)?.name ?? + FONT_CATALOGUE.find((font) => font.latex.pdftex === familyDefault)?.name ?? + (generic === "rm" ? LATEX_FAMILIES["rm"] : undefined); + return { + sizePoints: latexClassSize(source), + family: family ?? DEFAULT_WORD_BASE_FONT.family, + }; +} + +/** The font a Pandoc-read LaTeX span stands for, or null for any other span. */ +function latexSpanFont(attributes: unknown): WordLocalFont | null { + if (!Array.isArray(attributes)) return null; + const [, classes, pairs] = attributes as [unknown, unknown, unknown]; + if (Array.isArray(classes)) { + if (classes.includes("sans-serif")) return { family: LATEX_FAMILIES["sf"] ?? "Arial" }; + if (classes.includes("roman")) return { family: LATEX_FAMILIES["rm"] ?? "Times New Roman" }; + } + if (!Array.isArray(pairs)) return null; + for (const pair of pairs) { + const style = Array.isArray(pair) && pair[0] === "style" ? pair[1] : null; + const carried = Predicate.isString(style) + ? new RegExp(`^color:\\s*${LATEX_SIZE_CARRIER}(\\d+(?:p\\d+)?)$`, "u").exec(style)?.[1] + : undefined; + if (carried !== undefined) return { size: Number(carried.replace("p", ".")) }; + const font = Predicate.isString(style) + ? new RegExp(`^color:\\s*${LATEX_FONT_CARRIER}(\\d+)$`, "u").exec(style)?.[1] + : undefined; + const family = font === undefined ? undefined : FONT_CATALOGUE[Number(font)]?.name; + if (family !== undefined) return { family }; + } + return null; +} + +/** Turn the spans Pandoc made from LaTeX font commands into Word character style spans. */ +export function applyLatexFontSpans( + value: unknown, + pass: FontPass, + outer: WordLocalFont = {}, +): void { + if (Array.isArray(value)) { + for (const item of value) applyLatexFontSpans(item, pass, outer); + return; + } + if (!Predicate.isObject(value)) return; + if (isPandocNode(value) && value.t === "Span" && Array.isArray(value.c)) { + const own = latexSpanFont(value.c[0]); + if (own !== null) { + const font = { ...outer, ...own }; + applyLatexFontSpans(value.c[1], pass, font); + value.c[0] = attr([], [["custom-style", styleNameOf(font, pass)]]); + return; + } + } + const within = isPandocNode(value) && value.t === "Link" ? { ...outer, link: true } : outer; + for (const child of Object.values(value)) applyLatexFontSpans(child, pass, within); +} diff --git a/apps/server/src/scient/pandoc/scientReferenceDocument.ts b/apps/server/src/scient/pandoc/scientReferenceDocument.ts index 9b65fb905f..6ef5aa7516 100644 --- a/apps/server/src/scient/pandoc/scientReferenceDocument.ts +++ b/apps/server/src/scient/pandoc/scientReferenceDocument.ts @@ -7,10 +7,12 @@ import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as yazl from "yazl"; +import { catalogueFont } from "@scientfactory/scient-markdown"; const W = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"; const BODY_FONT = ``; const CODE_FONT = ``; +const HYPERLINK_LOOK = ``; const HEADING_COLOR = "1F3864"; interface StyleSpec { @@ -44,11 +46,19 @@ function style(spec: StyleSpec): string { ].join(""); } -const size = (points: number) => ``; +// Word sizes are whole half points. +const size = (points: number) => { + const halfPoints = Math.round(points * 2); + return ``; +}; + +/** Heading sizes in points, level 1 first. */ +const HEADING_POINTS = [18, 15, 13, 12, 11, 11, 11, 11, 11] as const; +/** Footnote text size in points. */ +const FOOTNOTE_POINTS = 9; function headingStyles(): Array { - const sizes = [18, 15, 13, 12, 11, 11, 11, 11, 11]; - return sizes.map((points, index) => ({ + return HEADING_POINTS.map((points, index) => ({ type: "paragraph", id: `Heading${index + 1}`, name: `heading ${index + 1}`, @@ -188,7 +198,7 @@ export const SCIENT_REFERENCE_STYLES: ReadonlyArray = [ name: "footnote text", basedOn: "Normal", pPr: ``, - rPr: size(9), + rPr: size(FOOTNOTE_POINTS), }, { type: "paragraph", @@ -270,7 +280,7 @@ export const SCIENT_REFERENCE_STYLES: ReadonlyArray = [ type: "character", id: "Hyperlink", name: "Hyperlink", - rPr: ``, + rPr: HYPERLINK_LOOK, }, { type: "table", @@ -343,13 +353,65 @@ export const SCIENT_REFERENCE_STYLES: ReadonlyArray = [ }, ]; -function scientReferenceStylesXml(): string { +/** The document's base text size and font name (null for the default font), from its settings. */ +export interface WordBaseFont { + readonly sizePoints: number; + readonly family: string | null; +} + +export const DEFAULT_WORD_BASE_FONT: WordBaseFont = { sizePoints: 11, family: null }; + +/** A local size in points and/or a font name; a Word run carries only one style. */ +export interface WordLocalFont { + readonly size?: number | undefined; + readonly family?: string | undefined; + /** Inside a link: the run keeps the link's look, since a run carries only one style. */ + readonly link?: boolean | undefined; +} + +const escapeXml = (text: string): string => + text + .replaceAll("&", "&") + .replaceAll("<", "<") + .replaceAll(">", ">") + .replaceAll('"', """); + +/** Word font attributes; the complex-script font (Hebrew) is the same font only when it has Hebrew. */ +const familyFonts = (family: string | null): string => { + if (family === null) return BODY_FONT; + const name = escapeXml(family); + const complex = catalogueFont(family)?.hebrew === true ? name : "Arial"; + return ``; +}; + +/** Word style name for a local font: "12 pt", "Times New Roman" or "Times New Roman 12 pt". */ +export const wordFontStyleName = (font: WordLocalFont): string => + [font.family, font.size === undefined ? null : `${font.size} pt`, font.link ? "link" : null] + .filter((part) => part !== undefined && part !== null) + .join(" "); + +function fontStyle(font: WordLocalFont): StyleSpec { + const name = wordFontStyleName(font); + return { + type: "character", + id: `Scient${name.replaceAll(".", "_").replaceAll(/[^A-Za-z0-9_]/gu, "")}`, + name, + custom: true, + rPr: [ + font.family === undefined ? "" : familyFonts(font.family), + font.size === undefined ? "" : size(font.size), + font.link ? HYPERLINK_LOOK : "", + ].join(""), + }; +} + +function scientReferenceStylesXml(base: WordBaseFont, used: ReadonlyArray): string { return [ ``, ``, - `${BODY_FONT}${size(11)}`, + `${familyFonts(base.family)}${size(base.sizePoints)}`, ``, - ...SCIENT_REFERENCE_STYLES.map(style), + ...[...SCIENT_REFERENCE_STYLES, ...used.map(fontStyle)].map(style), ``, ].join(""); } @@ -421,34 +483,53 @@ const DOCUMENT_RELATIONSHIPS = [ /** Fixed entry time, so the reference document is byte-for-byte reproducible. */ const ENTRY_TIME = DateTime.toDateUtc(DateTime.makeUnsafe("2026-01-01T00:00:00Z")); -export function scientReferenceDocumentParts(): ReadonlyArray { +export function scientReferenceDocumentParts( + base: WordBaseFont = DEFAULT_WORD_BASE_FONT, + used: ReadonlyArray = [], +): ReadonlyArray { return [ ["[Content_Types].xml", CONTENT_TYPES], ["_rels/.rels", PACKAGE_RELATIONSHIPS], ["word/document.xml", DOCUMENT_XML], ["word/_rels/document.xml.rels", DOCUMENT_RELATIONSHIPS], - ["word/styles.xml", scientReferenceStylesXml()], + ["word/styles.xml", scientReferenceStylesXml(base, used)], ]; } -let cached: Promise | null = null; +const cached = new Map>(); -function packReferenceDocument(): Promise { +function packReferenceDocument( + base: WordBaseFont, + used: ReadonlyArray, +): Promise { return new Promise((resolve, reject) => { const zip = new yazl.ZipFile(); const chunks: Array = []; zip.outputStream.on("data", (chunk: Buffer) => chunks.push(chunk)); zip.outputStream.on("error", reject); zip.outputStream.on("end", () => resolve(new Uint8Array(Buffer.concat(chunks)))); - for (const [name, contents] of scientReferenceDocumentParts()) { + for (const [name, contents] of scientReferenceDocumentParts(base, used)) { zip.addBuffer(Buffer.from(contents, "utf8"), name, { mtime: ENTRY_TIME, mode: 0o100644 }); } zip.end(); }); } -/** The packed reference document; built once per process. */ -export const scientReferenceDocument = Effect.promise(() => { - cached ??= packReferenceDocument(); - return cached; -}); +/** The packed reference document for a base font and the local fonts used; built once per combination. */ +export const scientReferenceDocumentFor = ( + base: WordBaseFont, + used: ReadonlyArray = [], +) => + Effect.promise(() => { + const key = [ + `${base.sizePoints}/${base.family ?? ""}`, + ...used.map(wordFontStyleName).toSorted(), + ].join("|"); + const existing = cached.get(key); + if (existing !== undefined) return existing; + const packed = packReferenceDocument(base, used); + cached.set(key, packed); + return packed; + }); + +export const scientReferenceDocument = scientReferenceDocumentFor(DEFAULT_WORD_BASE_FONT); diff --git a/apps/web/src/components/ui/number-field.tsx b/apps/web/src/components/ui/number-field.tsx index 37aceaef9d..ca20da8dcf 100644 --- a/apps/web/src/components/ui/number-field.tsx +++ b/apps/web/src/components/ui/number-field.tsx @@ -7,16 +7,23 @@ export function NumberField({ id, className, size = "default", + variant = "default", ...props }: NumberFieldPrimitive.Root.Props & { size?: "sm" | "default" | "lg"; + /** `compact`: a narrow boxed number between two borderless minus and plus buttons, in one row. */ + variant?: "default" | "compact"; }): React.ReactElement { const generatedId = React.useId(); const fieldId = id ?? generatedId; return ( [asset.id, asset])), assetBaseUrl: props.inputUrl, @@ -509,7 +520,9 @@ export function ScientDocumentPage(props: ScientDocumentPageProps) { const rehypePlugins: NonNullable = [ rehypeRaw, [rehypeReportUnsupportedHtml, { tracker }], + rehypeMarkFontSpans, [rehypeSanitize, DOCUMENT_SANITIZE_SCHEMA], + rehypeApplyFontSpans, [rehypeEnsureTitle, { title: input.title }], [rehypeScientBidi, { direction, requestedDirection: input.direction }], ]; @@ -526,6 +539,13 @@ export function ScientDocumentPage(props: ScientDocumentPageProps) { dir={direction} lang={input.language ?? undefined} data-scient-document={input.documentKind} + data-scient-font-size={documentFont.fontSize ?? undefined} + data-scient-font-family={documentFont.fontFamily ?? undefined} + style={ + documentFontCss === null + ? undefined + : ({ "--scient-document-font-family": documentFontCss } as CSSProperties) + } > { + const processor = unified() + .use(remarkParse) + .use(remarkRehype, { allowDangerousHtml: true }) + .use(rehypeRaw) + .use(rehypeMarkFontSpans) + .use(rehypeSanitize, schema) + .use(rehypeApplyFontSpans); + const tree = await processor.run(processor.parse(markdown)); + return toHtml(tree); +} + +describe("export of local font styles", () => { + it("keeps the exact size and family styles through the sanitizer", async () => { + expect(await exported('a big b')).toContain( + 'big', + ); + expect(await exported(`x`)).toContain( + "font-family:'Times New Roman',", + ); + }); + + it.each([ + 'x', + 'x', + 'x', + 'x', + `x`, + ])("removes any other style: %s", async (markdown) => { + const html = await exported(markdown); + expect(html).not.toContain("color"); + expect(html).not.toContain("Arial"); + expect(html).not.toContain("300pt"); + expect(html).not.toContain("Comic"); + expect(html).toContain(">x"); + }); + + it("ignores a font data attribute written directly in the document", async () => { + const html = await exported('x'); + expect(html).not.toContain("style="); + expect(html).not.toContain("data-scient-font-size"); + }); + + it("reads the whole-document keys of a leading front matter only", () => { + expect( + documentFontOfMarkdown("---\ntitle: T\nfontsize: 12pt\nmainfont: Courier New\n---\n\ntext"), + ).toEqual({ fontFamily: "Courier New", fontSize: "12pt" }); + expect(documentFontOfMarkdown("text\n\n---\nfontsize: 12pt\n---\n")).toEqual({ + fontFamily: null, + fontSize: null, + }); + }); +}); diff --git a/apps/web/src/scient/documentPage/documentFont.ts b/apps/web/src/scient/documentPage/documentFont.ts new file mode 100644 index 0000000000..f00e1282b3 --- /dev/null +++ b/apps/web/src/scient/documentPage/documentFont.ts @@ -0,0 +1,76 @@ +import { + catalogueFont, + markdownFontSpanStyle, + normalizeFontSize, + parseMarkdownFontSpanStyle, +} from "@scientfactory/scient-markdown"; +import { LEADING_FRONT_MATTER, readMarkdownDocumentFont } from "../markdownEditor/documentFont"; + +/** + * Font styles of an exported Markdown document: the local `` forms + * Scient writes, and the whole-document front matter keys. Only the exact + * listed values get through the sanitizer; any other CSS is still removed. + */ + +interface HastNode { + type?: string; + tagName?: string; + properties?: Record; + children?: HastNode[]; +} + +export const DOCUMENT_FONT_SANITIZE_ATTRIBUTES = { + span: ["dataScientFontSize", "dataScientFontFamily"], +} as const; + +function visitSpans(node: HastNode, visit: (properties: Record) => void) { + if (node.type === "element" && node.tagName === "span") visit((node.properties ??= {})); + node.children?.forEach((child) => visitSpans(child, visit)); +} + +/** Before the sanitizer: move a recognised style into data attributes it allows. */ +export function rehypeMarkFontSpans() { + return (tree: HastNode) => + visitSpans(tree, (properties) => { + // Only the style may ask for a font; the document's own attributes are not trusted. + delete properties.dataScientFontSize; + delete properties.dataScientFontFamily; + const style = typeof properties.style === "string" ? properties.style.trim() : ""; + const span = parseMarkdownFontSpanStyle(style); + if (span === null) return; + if ("size" in span) properties.dataScientFontSize = span.size; + else properties.dataScientFontFamily = span.family; + }); +} + +/** After the sanitizer: turn the surviving data attributes back into the style they stand for. */ +export function rehypeApplyFontSpans() { + return (tree: HastNode) => + visitSpans(tree, (properties) => { + const sizeValue = properties.dataScientFontSize; + const family = properties.dataScientFontFamily; + delete properties.dataScientFontSize; + delete properties.dataScientFontFamily; + const size = sizeValue === undefined ? null : normalizeFontSize(Number(sizeValue)); + const font = typeof family === "string" ? catalogueFont(family) : null; + if (size !== null) { + properties.style = markdownFontSpanStyle({ size }); + } else if (font !== null) { + properties.style = `font-family:${documentFontFamilyCss(font.name)}`; + } + }); +} + +/** The leading `---` block of the document, if it starts with one. */ +export function documentFontOfMarkdown(markdown: string) { + const front = LEADING_FRONT_MATTER.exec(markdown); + return readMarkdownDocumentFont(front?.[0] ?? null); +} + +const HEBREW_FALLBACKS = '"Noto Sans Hebrew", "Arial Hebrew", "Noto Sans Arabic"'; + +/** The CSS font stack for a catalogue name, with fallbacks for Hebrew and Arabic text. */ +export function documentFontFamilyCss(name: string | null): string | null { + const font = name === null ? null : catalogueFont(name); + return font === null ? null : `${font.css}, ${HEBREW_FALLBACKS}`; +} diff --git a/apps/web/src/scient/documentPage/scient-document-page.css b/apps/web/src/scient/documentPage/scient-document-page.css index f857ef20e4..8ecd122423 100644 --- a/apps/web/src/scient/documentPage/scient-document-page.css +++ b/apps/web/src/scient/documentPage/scient-document-page.css @@ -92,6 +92,35 @@ body { font-size: 11pt; } +/* Whole-document font from the front matter (see documentFont.ts). */ +.scient-document[data-scient-font-size="10pt"] { + --scient-document-size-scale: calc(10 / 10.5); +} +.scient-document[data-scient-font-size="11pt"] { + --scient-document-size-scale: calc(11 / 10.5); +} +.scient-document[data-scient-font-size="12pt"] { + --scient-document-size-scale: calc(12 / 10.5); +} +.scient-document[data-scient-font-size] { + font-size: calc(10.5pt * var(--scient-document-size-scale)); +} +.scient-document[data-scient-font-size] h1 { + font-size: calc(20pt * var(--scient-document-size-scale)); +} +.scient-document[data-scient-font-size] h2 { + font-size: calc(15pt * var(--scient-document-size-scale)); +} +.scient-document[data-scient-font-size] h3 { + font-size: calc(12.5pt * var(--scient-document-size-scale)); +} +.scient-document[data-scient-font-size] :where(h4, h5, h6) { + font-size: calc(11pt * var(--scient-document-size-scale)); +} +.scient-document[data-scient-font-family] { + font-family: var(--scient-document-font-family); +} + .scient-document :where(p, ul, ol, blockquote, .scient-document-table, figure) { margin: 0 0 0.8em; } diff --git a/apps/web/src/scient/keyboard/catalog.ts b/apps/web/src/scient/keyboard/catalog.ts index b0ee24f700..e5c867dc35 100644 --- a/apps/web/src/scient/keyboard/catalog.ts +++ b/apps/web/src/scient/keyboard/catalog.ts @@ -28,6 +28,8 @@ const markdownActions = [ "bulletList", "taskList", "clearFormatting", + "fontSizeLarger", + "fontSizeSmaller", "moveBlockUp", "moveBlockDown", "duplicateBlock", diff --git a/apps/web/src/scient/keyboard/keyboard.browser.test.ts b/apps/web/src/scient/keyboard/keyboard.browser.test.ts index 44da55e8ce..5c62ebe06b 100644 --- a/apps/web/src/scient/keyboard/keyboard.browser.test.ts +++ b/apps/web/src/scient/keyboard/keyboard.browser.test.ts @@ -11,6 +11,7 @@ import { saveKeyboardPreferences, subscribeKeyboardPreferences, } from "./preferences"; +import { EVENT_CODE_SHORTCUT_KEYS } from "@t3tools/shared/keybindingMatching"; import { eventStroke, isMacKeyboard, normalizeKeys } from "./keys"; import { ShortcutSequence } from "./sequence"; import { attachShortcutHost } from "./host"; @@ -133,7 +134,13 @@ describe("sequence matching and ownership", () => { for (const [index, stroke] of strokes.entries()) { const parts = stroke.split("+"); const value = parts.pop()!; + // A real key always carries its physical position, which digit and punctuation + // shortcuts are matched by. + const code = + Object.entries(EVENT_CODE_SHORTCUT_KEYS).find(([, symbol]) => symbol === value)?.[0] ?? + ""; const event = key(value === "plus" ? "+" : value === "space" ? " " : value, { + code, ctrlKey: parts.includes("ctrl"), metaKey: parts.includes("meta"), altKey: parts.includes("alt"), diff --git a/apps/web/src/scient/keyboard/keys.ts b/apps/web/src/scient/keyboard/keys.ts index 092494648a..e2d509241e 100644 --- a/apps/web/src/scient/keyboard/keys.ts +++ b/apps/web/src/scient/keyboard/keys.ts @@ -1,3 +1,5 @@ +import { EVENT_CODE_SHORTCUT_KEYS } from "@t3tools/shared/keybindingMatching"; + /** Platform-independent persisted notation; resolve Mod only when matching. */ export function isMacKeyboard( platform = typeof navigator === "undefined" ? "" : navigator.platform, @@ -86,14 +88,18 @@ export function eventStroke( (inSequence || event.altKey || event.ctrlKey || event.metaKey) ) key = physical.toLowerCase(); - // Digit shortcuts retain their physical digit when Shift produces punctuation. - const digit = /^Digit([0-9])$/u.exec(event.code)?.[1]; - if (digit && (event.ctrlKey || event.metaKey || event.altKey)) key = digit; + // Digit and punctuation shortcuts name the physical key when Shift produces another character + // (macOS reports the unshifted one while Cmd and Shift are held), as app shortcuts do. + const modified = event.ctrlKey || event.metaKey || event.altKey; + const physicalSymbol = modified ? EVENT_CODE_SHORTCUT_KEYS[event.code] : undefined; + if (physicalSymbol) key = physicalSymbol; return [ ...(event.ctrlKey ? ["ctrl"] : []), ...(event.metaKey ? ["meta"] : []), ...(event.altKey ? ["alt"] : []), - ...(event.shiftKey && (/^[a-z0-9]$/u.test(key) || event.key.length > 1) ? ["shift"] : []), + ...(event.shiftKey && (/^[a-z0-9]$/u.test(key) || event.key.length > 1 || physicalSymbol) + ? ["shift"] + : []), key, ].join("+"); } diff --git a/apps/web/src/scient/keyboard/writingCommands.ts b/apps/web/src/scient/keyboard/writingCommands.ts index 0981991689..042e8949fa 100644 --- a/apps/web/src/scient/keyboard/writingCommands.ts +++ b/apps/web/src/scient/keyboard/writingCommands.ts @@ -4,6 +4,8 @@ export const WRITING_COMMANDS = [ ["italic", "Emphasis / italic", ["mod+i", "alt+c e"]], ["inlineCode", "Inline code", ["mod+e"]], ["link", "Link", ["mod+k"]], + ["fontSizeLarger", "Larger text size", ["mod+shift+."]], + ["fontSizeSmaller", "Smaller text size", ["mod+shift+,"]], ["paragraph", "Normal paragraph", ["mod+alt+0", "alt+p s"]], ["section", "Section", ["mod+alt+1", "alt+p 1"]], ["subsection", "Subsection", ["mod+alt+2", "alt+p 2"]], diff --git a/apps/web/src/scient/latex/LatexDocumentSettings.tsx b/apps/web/src/scient/latex/LatexDocumentSettings.tsx index 822e23387f..fac79db8cf 100644 --- a/apps/web/src/scient/latex/LatexDocumentSettings.tsx +++ b/apps/web/src/scient/latex/LatexDocumentSettings.tsx @@ -1,7 +1,9 @@ -import { useState, type ReactNode } from "react"; +import { FONT_CATALOGUE } from "@scientfactory/scient-markdown/fonts"; +import { useState } from "react"; import { XIcon } from "lucide-react"; import { Button } from "~/components/ui/button"; import { Input } from "~/components/ui/input"; +import { DocumentSettingsField } from "../writing/DocumentSettingsField"; import { LatexSelect } from "./LatexSelect"; import { latexVisualLayoutProfile, type LatexVisualLayoutUpdate } from "./latexVisualDocument"; import { LATEX_PAPER_SIZES } from "./latexVisualLayout"; @@ -53,16 +55,6 @@ function currentSettings(source: string) { }; } -/** A small label above its control. */ -function Field(props: { readonly label: string; readonly children: ReactNode }) { - return ( -
- {props.label} - {props.children} -
- ); -} - /** * Two or three choices side by side, drawn like the header's view switch: * white, with a grey pill under the chosen one that slides when it changes. @@ -135,6 +127,12 @@ function Choice(props: { * One card: every setting shows what the document uses now, and Apply writes * only what was changed. */ +const GENERIC_FAMILIES = [ + { value: "serif", label: "Serif" }, + { value: "sans-serif", label: "Sans serif" }, + { value: "monospace", label: "Code" }, +]; + export function LatexDocumentSettings(props: { onOpenChange: (open: boolean) => void; source: string; @@ -232,7 +230,7 @@ export function LatexDocumentSettings(props: { >
- + - - + + ({ value: String(size), label: `${size} pt` }))} /> - - + + - +
- + + { + const unavailable = + (changes.engine ?? extended.engine) === "pdflatex" && + font.latex.pdftex === null; + return { + value: font.name, + label: unavailable ? `${font.name} (needs XeLaTeX or LuaLaTeX)` : font.name, + disabled: unavailable, + }; + }), + ]} + onValueChange={(value) => setLayout("fontFamily", value)} + /> + + - - + + - - + + - - + + - + {marginChoice === "custom" ? (
{SIDES.map((side) => { const name = side[0]!.toUpperCase() + side.slice(1); return ( - + setSide(side, event.target.value)} /> - + ); })}
@@ -386,7 +407,7 @@ export function LatexDocumentSettings(props: {
Columns and spacing
- + setLayout("columns", Number(value) as 1 | 2)} /> - - + + setLayout("lineSpacing", Number(event.target.value))} /> - + {( [ ["columnGap", "Column gap"], @@ -419,16 +440,16 @@ export function LatexDocumentSettings(props: { ["paragraphGap", "Paragraph spacing"], ] as const ).map(([key, label]) => ( - + setLayout(key, event.target.value)} /> - + ))} - + setLayout("alignment", value as "justify" | "left")} /> - +
@@ -453,16 +474,16 @@ export function LatexDocumentSettings(props: { ["gutter", "Binding gutter"], ] as const ).map(([key, label]) => ( - + setLayout(key, event.target.value)} /> - + ))} - + setLayout("mirroredMargins", value === "yes")} /> - +
Fonts and compiler
- + - + {( [ ["mainFont", "Main font"], @@ -502,7 +523,7 @@ export function LatexDocumentSettings(props: { ["monoFont", "Monospace font"], ] as const ).map(([key, label]) => ( - + setLayout(key, event.target.value)} /> - + ))}
Headings
- + setLayout("titleSize", Number(event.target.value))} /> - - + + setLayout("headingSize", Number(event.target.value))} /> - - + + setLayout("numberingDepth", Number(event.target.value))} /> - + {( [ ["headingBefore", "Space before sections"], ["headingAfter", "Space after sections"], ] as const ).map(([key, label]) => ( - + setLayout(key, event.target.value)} /> - + ))}
@@ -600,7 +621,7 @@ export function LatexDocumentSettings(props: { .replaceAll("\\rightmark", ""), ); return ( - + - + ); })} - + - - + + - + {(changes.mirroredMargins ?? extended.mirroredMargins) && (
@@ -675,14 +696,14 @@ export function LatexDocumentSettings(props: { ["evenFooterRight", "Even-page right footer"], ] as const ).map(([key, label]) => ( - + setLayout(key, event.target.value)} /> - + ))}
)} diff --git a/apps/web/src/scient/latex/LatexVisualEditor.tsx b/apps/web/src/scient/latex/LatexVisualEditor.tsx index a866514924..cf286be1c6 100644 --- a/apps/web/src/scient/latex/LatexVisualEditor.tsx +++ b/apps/web/src/scient/latex/LatexVisualEditor.tsx @@ -1,7 +1,16 @@ import type { PagedTableLayout } from "./latexPagedGeometry"; import { resolvedLatexFontSize } from "./latexVisualLayout"; import { latexSelectionClipboard } from "./latexClipboard"; +import { catalogueFont } from "@scientfactory/scient-markdown/fonts"; +import { FontControls } from "../writing/FontControls"; import { TextMenu, TextMenuItems } from "../writing/TextMenu"; +import { + latexFontAvailable, + latexFontEngine, + setLatexFontFamily, + setLatexFontSize, + stepLatexFontSize, +} from "./latexFontCommands"; import { LatexDirectionMenuItems } from "./LatexDirectionMenuItems"; import { mathColorSource } from "./mathColorSyntax"; import { LatexStructuredSelection } from "./latexStructuredSelection"; @@ -5575,6 +5584,51 @@ const LatexTextMarks = LATEX_CANVAS_TEXT_MARKS.map(({ name, style }) => ), ); +/** A numeric size (`\fontsize{12}{14.4}\selectfont`): size and baseline in TeX points. */ +const LatexFontSize = Mark.create({ + name: "latexFontSize", + addAttributes() { + return { points: { default: 10 }, leading: { default: 12 } }; + }, + parseHTML() { + return [{ tag: "span[data-latex-font-size]" }]; + }, + renderHTML({ mark }) { + const pixels = (points: unknown) => + `${(Number(points) * CSS_PIXELS_PER_INCH) / TEX_POINTS_PER_INCH}px`; + return [ + "span", + { + "data-latex-font-size": String(mark.attrs.points), + style: `font-size:${pixels(mark.attrs.points)};line-height:${pixels(mark.attrs.leading)}`, + }, + 0, + ]; + }, +}); + +/** A named font from the catalogue; `engine` is the form it is written in (see latexTextFormatting). */ +const LatexFontFamily = Mark.create({ + name: "latexFontFamily", + addAttributes() { + return { family: { default: "" }, engine: { default: "pdftex" } }; + }, + parseHTML() { + return [{ tag: "span[data-latex-font-family]" }]; + }, + renderHTML({ mark }) { + const font = catalogueFont(String(mark.attrs.family)); + return [ + "span", + { + "data-latex-font-family": String(mark.attrs.family), + ...(font ? { style: `font-family:${font.css}` } : {}), + }, + 0, + ]; + }, +}); + const LatexColor = Mark.create({ name: "latexColor", priority: 1100, @@ -5624,6 +5678,8 @@ const LatexMonospace = Code.extend({ excludes: "" }); const inlineFieldExtensions = [ ...LatexTextMarks, + LatexFontSize, + LatexFontFamily, LatexColor, LatexColor.extend({ name: "latexBackground", @@ -5658,6 +5714,8 @@ const baseExtensions = [ trailingNode: false, }), ...LatexTextMarks, + LatexFontSize, + LatexFontFamily, LatexColor, LatexColor.extend({ name: "latexBackground", @@ -8584,6 +8642,15 @@ function LatexVisualEditorReady( return mathTarget.current ? mathTarget.current.toggleTextFormat("monospace") : toggleLatexProseMark(editor ? latexEditingTarget(editor) : null, "code"); + if (id === "latex.fontSizeLarger" || id === "latex.fontSizeSmaller") + return ( + !mathTarget.current && + stepLatexFontSize( + latexEditingTarget(editor), + id === "latex.fontSizeLarger" ? 1 : -1, + latexVisualLayoutProfile(mathSetupSource).baseFontPt, + ) + ); if (id === "latex.link") { const link = insertActions.find((action) => action.id === "link"); if (!link || link.disabled || link.disabledReason) return false; @@ -9244,7 +9311,10 @@ function LatexVisualEditorReady( // The same inline formatting, in the same order, as the Markdown bar; LaTeX // has no strikethrough. // Inline formatting acts on text; on an object (title, figure, equation) it is off. - const editingPresentation = useLatexEditingPresentation(editor); + const editingPresentation = useLatexEditingPresentation( + editor, + latexVisualLayoutProfile(mathSetupSource).baseFontPt, + ); const editingTarget = editingPresentation.editor; const formattingAvailable = editingPresentation.formattingAvailable; const formatActions = [ @@ -9650,9 +9720,30 @@ function LatexVisualEditorReady( ))} ); + const fontEngine = latexFontEngine(mathSetupSource); const writingTextContents = { paragraphStyle: writingStyleItems, formatting: writingFormattingItems, + font: ( + latexFontAvailable(fontEngine, name)} + unavailableNote="Needs XeLaTeX or LuaLaTeX" + onFamily={(family) => setLatexFontFamily(editingTarget, family, fontEngine)} + onSize={(size) => setLatexFontSize(editingTarget, size)} + onStep={(steps) => + stepLatexFontSize( + editingTarget, + steps, + latexVisualLayoutProfile(mathSetupSource).baseFontPt, + ) + } + /> + ), direction: ( node.text === "Title")!.text = "New title"; }); expect(result?.source).toBe(source.replace("Title", "New title")); + // A group around one paragraph reopens as a numeric size mark on its text. expect( - descendants(projectLatexVisualDocument(result!.source).content).some( - (node) => node.attrs?.layout?.points === 19, + descendants(projectLatexVisualDocument(result!.source).content).some((node) => + node.marks?.some((mark) => mark.type === "latexFontSize" && mark.attrs?.points === 19), ), ).toBe(true); }); diff --git a/apps/web/src/scient/latex/latexDocumentLayoutSettings.ts b/apps/web/src/scient/latex/latexDocumentLayoutSettings.ts index 8aae07a855..d07c7f577d 100644 --- a/apps/web/src/scient/latex/latexDocumentLayoutSettings.ts +++ b/apps/web/src/scient/latex/latexDocumentLayoutSettings.ts @@ -1,3 +1,4 @@ +import { FONT_CATALOGUE, catalogueFont } from "@scientfactory/scient-markdown/fonts"; import { latexPreambleEnd, latexSourceArgument, latexSourceCommands } from "./latexSourceSyntax"; import { latexLengthInches, latexVisualLayoutProfile } from "./latexVisualLayout"; import { latexRunningPageSourceFields, latexRunningPageStyle } from "./latexPageLayouts"; @@ -16,6 +17,8 @@ export interface DocumentLayoutSettings { gutter?: string; mirroredMargins?: boolean; engine?: "pdflatex" | "xelatex" | "lualatex"; + /** "default", a generic family, or the name of a catalogue font (written for the document's engine). */ + fontFamily?: string; mainFont?: string; sansFont?: string; monoFont?: string; @@ -38,10 +41,27 @@ export interface DocumentLayoutSettings { evenFooterRight?: string; } +/** The default-family declaration written for each generic family. */ +const FAMILY_DEFAULTS = { serif: "rmdefault", "sans-serif": "sfdefault", monospace: "ttdefault" }; +/** `\familydefault` holds a generic (`\rmdefault`) or a font family code (`qtm`) for a catalogue font. */ +const FAMILY_DEFAULT_PATTERN = /\\renewcommand\s*\{\\familydefault\}\s*\{\\?([A-Za-z0-9]+)\}/gu; +const MAIN_FONT_PATTERN = /\\setmainfont\s*\{([^{}]+)\}/gu; +const isGenericFamily = (value: string) => value === "default" || value in FAMILY_DEFAULTS; + const length = (value: string) => /^(?:\d+(?:\.\d*)?|\.\d+)\s*(?:in|cm|mm|pt|bp|em|ex)$/u.test(value.trim()); const plain = (value: string) => !/[\\{}%#$&_~^\r\n]/u.test(value); +/** What the Font select shows: a generic family, or the catalogue font the declarations name. */ +function documentFontChoice(familyDefault: string | undefined, mainFont: string | undefined) { + const generic = Object.entries(FAMILY_DEFAULTS).find(([, command]) => command === familyDefault); + if (generic) return generic[0]; + const named = FONT_CATALOGUE.find( + (font) => font.latex.fontspec === mainFont?.trim() || font.latex.pdftex === familyDefault, + ); + return named?.name ?? "default"; +} + /** Current literal settings, scoped to active preamble declarations rather than macro bodies. */ export function documentLayoutSettings(source: string) { const profile = latexVisualLayoutProfile(source); @@ -56,6 +76,7 @@ export function documentLayoutSettings(source: string) { const family = (name: string) => last(new RegExp(`\\\\set${name}font\\s*(?:\\[[^\\]]*\\])?\\s*\\{([^{}]+)\\}`, "gu"))?.[1] ?? ""; const classOptions = last(/\\documentclass\s*(?:\[([^\]]*)\])?\s*\{[^{}]+\}/gu)?.[1] ?? ""; + const familyDefault = last(FAMILY_DEFAULT_PATTERN)?.[1]; const running = latexRunningPageStyle(source); const odd = latexRunningPageSourceFields(running, 1); const even = latexRunningPageSourceFields(running, 2); @@ -84,6 +105,7 @@ export function documentLayoutSettings(source: string) { gutter: `${profile.bindingOffsetIn.toFixed(4)}in`, mirroredMargins: profile.twoSided, engine, + fontFamily: documentFontChoice(familyDefault, last(MAIN_FONT_PATTERN)?.[1]), mainFont: latexDocumentLanguage(source).mainFont ?? family("main"), sansFont: family("sans"), monoFont: family("mono"), @@ -145,20 +167,24 @@ export function updateDocumentLayoutSettings( ) return null; const eol = source.includes("\r\n") ? "\r\n" : "\n"; - const replace = (pattern: RegExp, declaration: string) => { + // Matches of a declaration that are active preamble commands, not comments or macro bodies. + const activeMatches = (pattern: RegExp) => { const end = latexPreambleEnd(result); const active = new Set( latexSourceCommands(result.slice(0, end)) .filter((command) => command.depth === 0) .map((command) => command.from), ); - const matches = [...result.slice(0, end).matchAll(pattern)].filter((match) => - active.has(match.index), - ); - const found = matches.at(-1); + return [...result.slice(0, end).matchAll(pattern)].filter((match) => active.has(match.index)); + }; + const replace = (pattern: RegExp, declaration: string) => { + const found = activeMatches(pattern).at(-1); result = found ? result.slice(0, found.index) + declaration + result.slice(found.index + found[0].length) - : result.slice(0, end) + declaration + eol + result.slice(end); + : result.slice(0, latexPreambleEnd(result)) + + declaration + + eol + + result.slice(latexPreambleEnd(result)); }; const requirePackage = (name: string) => { const preamble = result.slice(0, latexPreambleEnd(result)); @@ -254,6 +280,35 @@ export function updateDocumentLayoutSettings( update.alignment === "left" ? "\\RaggedRight" : "\\justifying", ); } + // Named fonts are written for the document's engine: a family code under pdfLaTeX, `\setmainfont` + // under XeLaTeX and LuaLaTeX. The select only ever touches what it can show, so a + // `\setmainfont` naming a catalogue font is cleared whenever the choice changes. + let mainFontFromChoice: string | undefined; + if (update.fontFamily !== undefined) { + for (const match of activeMatches(MAIN_FONT_PATTERN).reverse()) { + if (FONT_CATALOGUE.some((font) => font.latex.fontspec === match[1]?.trim())) + result = result.slice(0, match.index) + result.slice(match.index + match[0].length); + } + const named = isGenericFamily(update.fontFamily) ? null : catalogueFont(update.fontFamily); + if (named === null && !isGenericFamily(update.fontFamily)) return null; + const engine = update.engine ?? documentLayoutSettings(source).engine; + if (named !== null && engine !== "pdflatex") { + for (const match of activeMatches(FAMILY_DEFAULT_PATTERN).reverse()) + result = result.slice(0, match.index) + result.slice(match.index + match[0].length); + mainFontFromChoice = named.latex.fontspec; + } else if (named !== null) { + if (named.latex.pdftex === null) return null; + replace(FAMILY_DEFAULT_PATTERN, `\\renewcommand{\\familydefault}{${named.latex.pdftex}}`); + } else if (update.fontFamily === "default") { + for (const match of activeMatches(FAMILY_DEFAULT_PATTERN).reverse()) + result = result.slice(0, match.index) + result.slice(match.index + match[0].length); + } else { + replace( + FAMILY_DEFAULT_PATTERN, + `\\renewcommand{\\familydefault}{\\${FAMILY_DEFAULTS[update.fontFamily as keyof typeof FAMILY_DEFAULTS]}}`, + ); + } + } if (update.engine !== undefined) { if ( update.engine === "pdflatex" && @@ -273,7 +328,7 @@ export function updateDocumentLayoutSettings( ["sansFont", "setsansfont"], ["monoFont", "setmonofont"], ] as const) { - const value = update[key]; + const value = key === "mainFont" ? (update.mainFont ?? mainFontFromChoice) : update[key]; if (value === undefined) continue; if ( !value.trim() || diff --git a/apps/web/src/scient/latex/latexDocumentSettings.test.ts b/apps/web/src/scient/latex/latexDocumentSettings.test.ts index 73d37d33ca..34e47fc8e0 100644 --- a/apps/web/src/scient/latex/latexDocumentSettings.test.ts +++ b/apps/web/src/scient/latex/latexDocumentSettings.test.ts @@ -1,4 +1,5 @@ import { describe, expect, it } from "vite-plus/test"; +import { documentLayoutSettings } from "./latexDocumentLayoutSettings"; import { updateLatexDocumentSettingsSource } from "./latexDocumentSettingsSource"; import { latexDocumentLanguage, latexLanguageLabels } from "./latexLanguage"; import { DOCUMENT_TEMPLATES, createNewDocumentSource } from "../documents/documentTemplates"; @@ -116,3 +117,90 @@ describe("document settings language application", () => { expect(updateLatexDocumentSettingsSource(body, { language: "hebrew" })).toBeNull(); }); }); + +describe("document settings font family", () => { + it.each([ + ["serif", "rmdefault"], + ["sans-serif", "sfdefault"], + ["monospace", "ttdefault"], + ] as const)("writes and reads the %s default", (fontFamily, command) => { + const next = updateLatexDocumentSettingsSource(document(), { fontFamily })!; + expect(next).toContain(`\\renewcommand{\\familydefault}{\\${command}}`); + expect(documentLayoutSettings(next).fontFamily).toBe(fontFamily); + expect(documentBody(next)).toBe(documentBody(document())); + }); + + it("replaces a previous choice and removes it on Default", () => { + const sans = updateLatexDocumentSettingsSource(document(), { fontFamily: "sans-serif" })!; + const mono = updateLatexDocumentSettingsSource(sans, { fontFamily: "monospace" })!; + expect(mono.match(/familydefault/gu)).toHaveLength(1); + const none = updateLatexDocumentSettingsSource(mono, { fontFamily: "default" })!; + expect(none).not.toContain("familydefault"); + expect(documentLayoutSettings(none).fontFamily).toBe("default"); + }); + + it("removes only the active family declaration on Default", () => { + const commented = String.raw`% \renewcommand{\familydefault}{\sfdefault} +\newcommand{\mono}{\renewcommand{\familydefault}{\ttdefault}} +`; + const withActive = updateLatexDocumentSettingsSource( + document().replace("\\begin{document}", `${commented}\\begin{document}`), + { fontFamily: "serif" }, + )!; + const none = updateLatexDocumentSettingsSource(withActive, { fontFamily: "default" })!; + expect(none).toContain("% \\renewcommand{\\familydefault}{\\sfdefault}"); + expect(none).toContain("\\newcommand{\\mono}{\\renewcommand{\\familydefault}{\\ttdefault}}"); + expect(none).not.toContain("{\\rmdefault}"); + expect(documentLayoutSettings(none).fontFamily).toBe("default"); + }); +}); + +describe("document settings named fonts", () => { + const xelatex = (preamble = "") => document(`% !TEX program = xelatex\n${preamble}`); + + it("writes a pdfLaTeX family code for a font with a look-alike, and reads it back", () => { + const next = updateLatexDocumentSettingsSource(document(), { fontFamily: "Times New Roman" })!; + expect(next).toContain("\\renewcommand{\\familydefault}{qtm}"); + expect(documentLayoutSettings(next).fontFamily).toBe("Times New Roman"); + expect(documentBody(next)).toBe(documentBody(document())); + }); + + it("refuses a font pdfLaTeX has no look-alike for, and an unknown name", () => { + expect(updateLatexDocumentSettingsSource(document(), { fontFamily: "Garamond" })).toBeNull(); + expect(updateLatexDocumentSettingsSource(document(), { fontFamily: "Comic Sans" })).toBeNull(); + }); + + it("writes setmainfont under XeLaTeX and no familydefault", () => { + const sans = updateLatexDocumentSettingsSource(xelatex(), { fontFamily: "sans-serif" })!; + const next = updateLatexDocumentSettingsSource(sans, { fontFamily: "Garamond" })!; + expect(next).toContain("\\setmainfont{Garamond}"); + expect(next).toContain("\\usepackage{fontspec}"); + expect(next).not.toContain("familydefault"); + expect(documentLayoutSettings(next).fontFamily).toBe("Garamond"); + expect(documentBody(next)).toBe(documentBody(document())); + }); + + it("applies a font together with the engine change in one update", () => { + const next = updateLatexDocumentSettingsSource(document(), { + engine: "xelatex", + fontFamily: "Garamond", + })!; + expect(next).toContain("\\setmainfont{Garamond}"); + expect(documentLayoutSettings(next)).toMatchObject({ + engine: "xelatex", + fontFamily: "Garamond", + }); + }); + + it("clears a catalogue main font on a new choice or Default, and keeps the author's own", () => { + const named = updateLatexDocumentSettingsSource(xelatex(), { fontFamily: "Garamond" })!; + const serif = updateLatexDocumentSettingsSource(named, { fontFamily: "serif" })!; + expect(serif).not.toContain("\\setmainfont"); + expect(serif).toContain("\\renewcommand{\\familydefault}{\\rmdefault}"); + const none = updateLatexDocumentSettingsSource(named, { fontFamily: "default" })!; + expect(none).not.toContain("\\setmainfont"); + const own = xelatex("\\usepackage{fontspec}\n\\setmainfont{Charter}\n"); + const kept = updateLatexDocumentSettingsSource(own, { fontFamily: "default" })!; + expect(kept).toContain("\\setmainfont{Charter}"); + }); +}); diff --git a/apps/web/src/scient/latex/latexEditingTarget.ts b/apps/web/src/scient/latex/latexEditingTarget.ts index 0c3b8030dc..28eabd62a8 100644 --- a/apps/web/src/scient/latex/latexEditingTarget.ts +++ b/apps/web/src/scient/latex/latexEditingTarget.ts @@ -1,7 +1,9 @@ import type { Editor } from "@tiptap/core"; import { createContext, useState, useSyncExternalStore } from "react"; +import { useStableCallback } from "~/hooks/useStableCallback"; import { NodeSelection, type EditorState } from "@tiptap/pm/state"; import { countSelectedWords } from "../writing/caretStatus"; +import { latexFontState } from "./latexFontCommands"; export const LatexInlineOwnerContext = createContext(null); @@ -137,11 +139,16 @@ interface EditingPresentation { bold: boolean; italic: boolean; code: boolean; + fontFamily: string | null; + fontFamilyMixed: boolean; + fontSize: number | null; + fontSizeMixed: boolean; selectedWords: number | null; } -function editingPresentation(editor: Editor | null): EditingPresentation { +function editingPresentation(editor: Editor | null, baseFontPt: 10 | 11 | 12): EditingPresentation { const selection = editor?.state.selection; + const font = latexFontState(editor, baseFontPt); return { formattingAvailable: Boolean( editor?.isEditable && @@ -152,6 +159,10 @@ function editingPresentation(editor: Editor | null): EditingPresentation { bold: editor?.isActive("bold") ?? false, italic: editor?.isActive("italic") ?? false, code: editor?.isActive("code") ?? false, + fontFamily: font.family, + fontFamilyMixed: font.familyMixed, + fontSize: font.size, + fontSizeMixed: font.sizeMixed, selectedWords: editor ? countSelectedWords(editor.state) : null, }; } @@ -161,16 +172,19 @@ const sameEditingPresentation = (before: EditingPresentation, after: EditingPres before.bold === after.bold && before.italic === after.italic && before.code === after.code && + before.fontFamily === after.fontFamily && + before.fontFamilyMixed === after.fontFamilyMixed && + before.fontSize === after.fontSize && + before.fontSizeMixed === after.fontSizeMixed && before.selectedWords === after.selectedWords; /** Typing at a collapsed caret need not render unchanged controls. Selection, * formatting, ownership and editability changes still publish immediately. */ -export function useLatexEditingPresentation(owner: Editor | null) { - const { editor, value } = useLatexEditingSnapshot( - owner, - editingPresentation, - sameEditingPresentation, +export function useLatexEditingPresentation(owner: Editor | null, baseFontPt: 10 | 11 | 12 = 10) { + const select = useStableCallback((target: Editor | null) => + editingPresentation(target, baseFontPt), ); + const { editor, value } = useLatexEditingSnapshot(owner, select, sameEditingPresentation); return { editor, ...value }; } diff --git a/apps/web/src/scient/latex/latexFontCommands.browser.test.ts b/apps/web/src/scient/latex/latexFontCommands.browser.test.ts new file mode 100644 index 0000000000..12cf797604 --- /dev/null +++ b/apps/web/src/scient/latex/latexFontCommands.browser.test.ts @@ -0,0 +1,183 @@ +// Replays the reported font gestures on a real LaTeX Visual editor schema in a browser: words +// sized one by one, the word under the caret, and + and − over mixed sizes. +import { Editor, Mark } from "@tiptap/core"; +import StarterKit from "@tiptap/starter-kit"; +import { describe, expect, it } from "vite-plus/test"; +import { attachShortcutHost } from "../keyboard/host"; +import { isMacKeyboard } from "../keyboard/keys"; +import { drawnPointsAt } from "../writing/fontChoices"; +import { latexFontState, setLatexFontSize, stepLatexFontSize } from "./latexFontCommands"; +import { LATEX_CANVAS_TEXT_MARKS } from "./latexTextFormatting"; + +const marks = [ + Mark.create({ + name: "latexFontSize", + addAttributes: () => ({ points: { default: 10 }, leading: { default: 12 } }), + renderHTML: () => ["span", 0], + }), + Mark.create({ + name: "latexFontFamily", + addAttributes: () => ({ family: { default: "" }, engine: { default: "pdftex" } }), + renderHTML: () => ["span", 0], + }), + ...LATEX_CANVAS_TEXT_MARKS.map(({ name }) => + Mark.create({ + name, + // Small caps drawn smaller, so text without a size is drawn at two sizes. + renderHTML: () => ["span", name === "latexSmallCaps" ? { style: "font-size:8px" } : {}, 0], + }), + ), +]; + +/** An editor on a throwaway element; `using` destroys both when the test ends. */ +function open(text: string) { + const element = document.createElement("div"); + document.body.append(element); + const editor = new Editor({ + element, + extensions: [StarterKit, ...marks], + content: `

${text}

`, + }); + return { + editor, + [Symbol.dispose]() { + editor.destroy(); + element.remove(); + }, + }; +} + +/** Text offsets of the first paragraph (0 = start of its text). */ +const select = (editor: Editor, from: number, to = from) => + editor.commands.setTextSelection({ from: 1 + from, to: 1 + to }); + +/** Each word with its size, read from the document. */ +const sizes = (editor: Editor) => { + const runs: Array<[string, unknown]> = []; + editor.state.doc.descendants((node) => { + if (node.isText) + runs.push([ + node.text!, + node.marks.find((m) => m.type.name === "latexFontSize")?.attrs.points, + ]); + }); + return runs; +}; + +describe("LaTeX font commands in a real editor", () => { + it("shows the common size of words sized one by one", () => { + using fixture = open("alpha beta gamma"); + const { editor } = fixture; + select(editor, 2); + setLatexFontSize(editor, 14); + select(editor, 8); + setLatexFontSize(editor, 14); + select(editor, 0, 10); + expect(latexFontState(editor)).toMatchObject({ size: 14, sizeMixed: false }); + }); + + it("sizes a whole word with an apostrophe or a combining accent at the caret", () => { + using fixture = open("I don't know café now"); + const { editor } = fixture; + select(editor, 3); + setLatexFontSize(editor, 14); + select(editor, 14); + setLatexFontSize(editor, 16); + expect(sizes(editor)).toEqual([ + ["I ", undefined], + ["don't", 14], + [" know ", undefined], + ["café", 16], + [" now", undefined], + ]); + }); + + it("+ and − move each word of a mixed selection by one point and keep the field empty", () => { + using fixture = open("alpha beta gamma"); + const { editor } = fixture; + const drawn = drawnPointsAt(editor.view, 13)!; + select(editor, 2); + setLatexFontSize(editor, 11); + select(editor, 8); + setLatexFontSize(editor, 20); + select(editor, 0, 16); + stepLatexFontSize(editor, 1, 10); + expect(sizes(editor)).toEqual([ + ["alpha", 12], + [" ", undefined], + ["beta", 21], + [" ", undefined], + ["gamma", drawn + 1], + ]); + expect(latexFontState(editor)).toMatchObject({ size: null, sizeMixed: true }); + stepLatexFontSize(editor, -1, 10); + expect(sizes(editor).map(([, points]) => points)).toEqual([ + 11, + undefined, + 20, + undefined, + drawn, + ]); + }); + + it("+ at a caret moves the word under it, from a named size", () => { + using fixture = open("one two"); + const { editor } = fixture; + editor.commands.setTextSelection({ from: 1, to: 4 }); + editor.commands.setMark("latexSize_large"); + select(editor, 1); + stepLatexFontSize(editor, 1, 10); + expect(sizes(editor)).toEqual([ + ["one", 13], + [" two", undefined], + ]); + }); + + it("Mod+Shift+. and Mod+Shift+, reach the LaTeX size commands", () => { + using fixture = open("alpha beta"); + const { editor } = fixture; + const run: string[] = []; + const detach = attachShortcutHost(editor.view.dom, ["latex"], { + accepts: () => true, + execute: (id) => { + run.push(id); + return true; + }, + }); + editor.commands.focus(); + select(editor, 0, 5); + // macOS reports the unshifted character while Cmd and Shift are held. + const mac = isMacKeyboard(); + for (const [code, key] of [ + ["Period", "."], + ["Comma", ","], + ] as const) { + editor.view.dom.dispatchEvent( + new KeyboardEvent("keydown", { + key, + code, + metaKey: mac, + ctrlKey: !mac, + shiftKey: true, + bubbles: true, + cancelable: true, + }), + ); + } + detach(); + expect(run).toEqual(["latex.fontSizeLarger", "latex.fontSizeSmaller"]); + }); + + it("text without a size steps from the size it is drawn at, wherever the selection starts", () => { + using fixture = open("ab cd"); + const { editor } = fixture; + select(editor, 3, 5); + editor.commands.setMark("latexSmallCaps"); + const small = drawnPointsAt(editor.view, 1 + 4)!; + const body = drawnPointsAt(editor.view, 1 + 1)!; + expect(small).toBeLessThan(body); + select(editor, 0, 5); + stepLatexFontSize(editor, 1, 10); + expect(sizes(editor).map(([, points]) => points)).toEqual([body + 1, undefined, small + 1]); + }); +}); diff --git a/apps/web/src/scient/latex/latexFontCommands.ts b/apps/web/src/scient/latex/latexFontCommands.ts new file mode 100644 index 0000000000..2cf7770606 --- /dev/null +++ b/apps/web/src/scient/latex/latexFontCommands.ts @@ -0,0 +1,220 @@ +import type { ChainedCommands, Editor } from "@tiptap/core"; +import type { Mark } from "@tiptap/pm/model"; +import { latexVisualFontMetrics } from "./latexVisualLayout"; +import { drawnPointsAt, normalizeFontSize } from "../writing/fontChoices"; +import { + type FontRun, + holdsFont, + sharedValue, + steppedFontSize, + steppedRuns, + wordAround, +} from "../writing/fontTarget"; +import { declaredLatexCompiler } from "./latexCompiler"; +import { latexFontFamilyDeclaration, type LatexFontEngine } from "./latexTextFormatting"; + +const NAMED_SIZES = [ + "tiny", + "scriptsize", + "footnotesize", + "small", + "normalsize", + "large", + "Large", + "LARGE", + "huge", + "Huge", +] as const; + +/** Baseline written with a new size: 1.2 times the size, as the class sizes mostly are. */ +const LEADING_RATIO = 1.2; + +/** The size of a run in points: its numeric size, or its named size for the class size. */ +function latexRunSize(marks: ReadonlyArray, baseFontPt: 10 | 11 | 12): number | null { + const numeric = marks.find((mark) => mark.type.name === "latexFontSize")?.attrs.points; + if (typeof numeric === "number") return numeric; + const named = NAMED_SIZES.find((name) => + marks.some((mark) => mark.type.name === `latexSize_${name}`), + ); + return named === undefined ? null : latexVisualFontMetrics(baseFontPt)[named][0]; +} + +/** + * The size and font shared by the whole selection. A value is null when the text has none, and + * the matching `Mixed` flag is true when the selection holds several. A named size (`\large`) + * reports its number for the document's class size. Whitespace and code are ignored (`holdsFont`). + */ +export function latexFontState( + editor: Editor | null, + baseFontPt: 10 | 11 | 12 = 10, +): { + readonly size: number | null; + readonly family: string | null; + readonly sizeMixed: boolean; + readonly familyMixed: boolean; +} { + if (!editor) return { size: null, family: null, sizeMixed: false, familyMixed: false }; + const { selection, doc } = editor.state; + const sizes = new Set(); + const families = new Set(); + const read = (marks: ReadonlyArray) => { + sizes.add(latexRunSize(marks, baseFontPt)); + const family = marks.find((mark) => mark.type.name === "latexFontFamily")?.attrs.family; + families.add(typeof family === "string" && family !== "" ? family : null); + }; + if (selection.empty) read(editor.state.storedMarks ?? selection.$from.marks()); + else { + doc.nodesBetween(selection.from, selection.to, (node) => { + if (!node.isText) return; + if ( + holdsFont( + node.text ?? "", + node.marks.some((mark) => mark.type.name === "code"), + ) + ) + read(node.marks); + }); + } + const size = sharedValue(sizes); + const family = sharedValue(families); + return { + size: size.value, + family: family.value, + sizeMixed: size.mixed, + familyMixed: family.mixed, + }; +} + +/** The word around an empty selection, as document positions, or null. */ +function caretWord(editor: Editor): { from: number; to: number } | null { + const { selection } = editor.state; + const { $from } = selection; + if (!selection.empty || !$from.parent.isTextblock) return null; + const text = $from.parent.textBetween(0, $from.parent.content.size, undefined, "\ufffc"); + const word = wordAround(text, $from.parentOffset); + return word === null ? null : { from: $from.start() + word.start, to: $from.start() + word.end }; +} + +/** + * Runs a font change on the selection; at a caret it covers the word around it, as in Word, + * and the caret stays where it was. Between words the change stays with the typing marks. + */ +function runFontChange( + editor: Editor, + change: (chain: ChainedCommands) => ChainedCommands, +): boolean { + const { selection } = editor.state; + const word = caretWord(editor); + const chain = editor.chain().focus(); + if (word === null) return change(chain).run(); + return change(chain.setTextSelection(word)).setTextSelection(selection.from).run(); +} + +/** The size mark written for a size in points, with its baseline. */ +const sizeAttributes = (points: number) => ({ + points, + leading: Math.round(points * LEADING_RATIO * 100) / 100, +}); + +/** A size replaces the previous one, as in LaTeX; null returns to the document default. */ +export function setLatexFontSize(editor: Editor | null, points: number | null): boolean { + if (!editor) return false; + const size = points === null ? null : normalizeFontSize(points); + if (points !== null && size === null) return false; + return runFontChange(editor, (first) => { + let chain = first.unsetMark("latexFontSize"); + for (const name of NAMED_SIZES) chain = chain.unsetMark(`latexSize_${name}`); + return size === null ? chain : chain.setMark("latexFontSize", sizeAttributes(size)); + }); +} + +/** + * Moves the size of every run of the selection (or of the word at the caret) by `steps` steps; + * each run keeps its difference with the others. Text without a size starts from the size it is + * drawn at, so a heading word grows from the heading's size. + */ +export function stepLatexFontSize( + editor: Editor | null, + steps: number, + baseFontPt: 10 | 11 | 12, +): boolean { + if (!editor) return false; + const { state, view } = editor; + const word = caretWord(editor); + if (state.selection.empty && word === null) { + const current = + latexRunSize(state.storedMarks ?? state.selection.$from.marks(), baseFontPt) ?? + drawnPointsAt(view, state.selection.from); + return current !== null && setLatexFontSize(editor, steppedFontSize(current, steps)); + } + const ranges = word + ? [word] + : state.selection.ranges.map((range) => ({ from: range.$from.pos, to: range.$to.pos })); + const sizeMarks = ["latexFontSize", ...NAMED_SIZES.map((name) => `latexSize_${name}`)]; + return editor + .chain() + .focus() + .command(({ tr }) => { + for (const range of ranges) { + const runs: FontRun[] = []; + state.doc.nodesBetween(range.from, range.to, (node, position) => { + if (!node.isText) return; + const from = Math.max(range.from, position); + runs.push({ + text: (node.text ?? "").slice( + from - position, + Math.min(range.to, position + node.nodeSize) - position, + ), + from, + isCode: node.marks.some((mark) => mark.type.name === "code"), + size: latexRunSize(node.marks, baseFontPt), + }); + }); + for (const change of steppedRuns(runs, steps, (position) => + drawnPointsAt(view, position), + )) { + for (const name of sizeMarks) + tr.removeMark(change.from, change.to, state.schema.marks[name]); + tr.addMark( + change.from, + change.to, + state.schema.marks["latexFontSize"]!.create(sizeAttributes(change.size)), + ); + } + } + return true; + }) + .run(); +} + +/** + * The form named fonts are written in: guarded `\fontspec` names when the document is compiled + * with XeLaTeX, LuaLaTeX or Tectonic or loads `fontspec`, font family codes otherwise (pdfLaTeX). + */ +export function latexFontEngine(setupSource: string): LatexFontEngine { + const declared = declaredLatexCompiler(setupSource); + if (declared === "xelatex" || declared === "lualatex" || declared === "tectonic") + return "fontspec"; + return /^[^%\n]*\\usepackage(?:\[[^\]]*\])?\{[^}]*\bfontspec\b[^}]*\}/mu.test(setupSource) + ? "fontspec" + : "pdftex"; +} + +/** Whether the document's engine can write this font by name. */ +export function latexFontAvailable(engine: LatexFontEngine, family: string): boolean { + return latexFontFamilyDeclaration(engine, family) !== null; +} + +/** A font replaces the previous one, as in LaTeX; null returns to the document default. */ +export function setLatexFontFamily( + editor: Editor | null, + family: string | null, + engine: LatexFontEngine, +): boolean { + if (!editor) return false; + if (family !== null && !latexFontAvailable(engine, family)) return false; + return runFontChange(editor, (first) => { + const chain = first.unsetMark("latexFontFamily").unsetMark("latexRoman").unsetMark("latexSans"); + return family === null ? chain : chain.setMark("latexFontFamily", { family, engine }); + }); +} diff --git a/apps/web/src/scient/latex/latexFontSize.test.ts b/apps/web/src/scient/latex/latexFontSize.test.ts new file mode 100644 index 0000000000..a3efc74a94 --- /dev/null +++ b/apps/web/src/scient/latex/latexFontSize.test.ts @@ -0,0 +1,188 @@ +import { describe, expect, it } from "vite-plus/test"; +import { latexFontGroupSource, latexTextDeclarationAt } from "./latexTextFormatting"; +import { applyLatexVisualDocumentChange, projectLatexVisualDocument } from "./latexVisualDocument"; + +const document = (body: string) => + `\\documentclass{article}\n\n\\begin{document}\n${body}\n\\end{document}\n`; + +describe("numeric font size in LaTeX", () => { + it("reads a size declaration with or without units and rejects bad values", () => { + expect(latexTextDeclarationAt("\\fontsize{12}{14.4}\\selectfont text")?.mark).toBe( + "latexFontSize:12/14.4", + ); + expect(latexTextDeclarationAt("\\fontsize{12pt}{15pt}\\selectfont{} text")?.length).toBe( + "\\fontsize{12pt}{15pt}\\selectfont{}".length, + ); + expect(latexTextDeclarationAt("\\fontsize{300}{360}\\selectfont x")).toBeNull(); + expect(latexTextDeclarationAt("\\fontsize{12}{14.4} x")).toBeNull(); + expect(latexTextDeclarationAt("\\large text")?.mark).toBe("latexSize_large"); + }); + + it("writes one group per run and keeps a leading space", () => { + expect( + latexFontGroupSource({ type: "latexFontSize", attrs: { points: 13, leading: 15.6 } }, "word"), + ).toBe("{\\fontsize{13}{15.6}\\selectfont word}"); + expect( + latexFontGroupSource( + { type: "latexFontSize", attrs: { points: 13, leading: 15.6 } }, + " here", + ), + ).toBe("{\\fontsize{13}{15.6}\\selectfont{} here}"); + }); + + it("round-trips a size group inside a paragraph and keeps surrounding bytes", () => { + const source = document("Before {\\fontsize{14}{16.8}\\selectfont big} after."); + const projection = projectLatexVisualDocument(source); + const paragraph = projection.content.content![0]!; + const texts = paragraph.content!.map((node) => [node.text, node.marks?.[0]?.attrs?.points]); + expect(texts).toEqual([ + ["Before ", undefined], + ["big", 14], + [" after.", undefined], + ]); + const unchanged = applyLatexVisualDocumentChange(source, projection, projection.content, {}); + expect(unchanged === null || unchanged.source === source).toBe(true); + }); +}); + +describe("named fonts in LaTeX", () => { + const pdftex = "\\fontfamily{qtm}\\selectfont"; + const fontspec = + "\\IfFontExistsTF{Times New Roman}{\\fontspec{Times New Roman}}{\\fontspec{Latin Modern Roman}}"; + + it("reads both written forms as the same catalogue font", () => { + expect(latexTextDeclarationAt(`${pdftex} text`)?.mark).toBe( + "latexFontFamily:pdftex:Times New Roman", + ); + expect(latexTextDeclarationAt(`${fontspec} text`)?.mark).toBe( + "latexFontFamily:fontspec:Times New Roman", + ); + }); + + it("does not read a family code or font name the catalogue does not offer", () => { + expect(latexTextDeclarationAt("\\fontfamily{zzz}\\selectfont x")).toBeNull(); + expect( + latexTextDeclarationAt( + "\\IfFontExistsTF{Comic Sans}{\\fontspec{Comic Sans}}{\\fontspec{X}} x", + ), + ).toBeNull(); + expect( + latexTextDeclarationAt(`${fontspec.replace("Latin Modern Roman", "Evil")} x`), + ).toBeNull(); + }); + + it("writes only forms the engine offers", () => { + const mark = (engine: string, family: string) => ({ + type: "latexFontFamily", + attrs: { engine, family }, + }); + expect(latexFontGroupSource(mark("pdftex", "Times New Roman"), "word")).toBe( + `{${pdftex} word}`, + ); + expect(latexFontGroupSource(mark("fontspec", "Times New Roman"), " word")).toBe( + `{${fontspec}{} word}`, + ); + // Calibri has no pdfLaTeX package font: the text is written without a group. + expect(latexFontGroupSource(mark("pdftex", "Calibri"), "word")).toBe("word"); + }); + + it("round-trips a font group inside a paragraph", () => { + const source = document(`Before {${pdftex} serif} after.`); + const projection = projectLatexVisualDocument(source); + const texts = projection.content.content![0]!.content!.map((node) => [ + node.text, + node.marks?.[0]?.attrs?.family, + ]); + expect(texts).toEqual([ + ["Before ", undefined], + ["serif", "Times New Roman"], + [" after.", undefined], + ]); + const unchanged = applyLatexVisualDocumentChange(source, projection, projection.content, {}); + expect(unchanged === null || unchanged.source === source).toBe(true); + }); +}); + +describe("a size over math keeps every space", () => { + it("writes one group around text, math and text", () => { + const base = document("We see $x$ here"); + const projection = projectLatexVisualDocument(base); + const paragraph = projection.content.content![0]!; + const size = { type: "latexFontSize", attrs: { points: 14, leading: 16.8 } }; + const sized = { + ...projection.content, + content: [ + { + ...paragraph, + content: paragraph.content!.map((node) => ({ + ...node, + marks: [...(node.marks ?? []), size], + })), + }, + ], + }; + const result = applyLatexVisualDocumentChange(base, projection, sized, {}); + expect(result?.source).toContain("{\\fontsize{14}{16.8}\\selectfont We see $x$ here}"); + }); +}); + +describe("fontspec for named fonts under XeLaTeX", () => { + it("adds the fontspec package when a guarded font group is written", () => { + const base = "% !TEX program = xelatex\n" + document("Plain text."); + const projection = projectLatexVisualDocument(base); + const paragraph = projection.content.content![0]!; + const font = { + type: "latexFontFamily", + attrs: { engine: "fontspec", family: "Times New Roman" }, + }; + const changed = { + ...projection.content, + content: [ + { + ...paragraph, + content: [{ type: "text", text: "Plain text.", marks: [font] }], + }, + ], + }; + const result = applyLatexVisualDocumentChange(base, projection, changed, {}); + expect(result?.source).toContain("\\usepackage{fontspec}"); + }); +}); + +describe("fix-cm for exact sizes", () => { + it("adds fix-cm once when a size group is first written, and not when a scalable package is loaded", () => { + const base = document("Plain text."); + const projection = projectLatexVisualDocument(base); + const paragraph = projection.content.content![0]!; + const sized = { + ...projection.content, + content: [ + { + ...paragraph, + content: [ + { + type: "text", + text: "Plain text.", + marks: [{ type: "latexFontSize", attrs: { points: 13, leading: 15.6 } }], + }, + ], + }, + ], + }; + const result = applyLatexVisualDocumentChange(base, projection, sized, {}); + expect(result?.source).toContain("\\usepackage{fix-cm}"); + expect(result?.source).toContain("{\\fontsize{13}{15.6}\\selectfont Plain text.}"); + const withPackage = base.replace( + "\\begin{document}", + "\\usepackage{lmodern}\n\\begin{document}", + ); + const second = projectLatexVisualDocument(withPackage); + const again = applyLatexVisualDocumentChange( + withPackage, + second, + { ...sized, content: sized.content }, + {}, + ); + expect(again?.source).not.toContain("fix-cm"); + }); +}); diff --git a/apps/web/src/scient/latex/latexFontState.test.ts b/apps/web/src/scient/latex/latexFontState.test.ts new file mode 100644 index 0000000000..650769d9bc --- /dev/null +++ b/apps/web/src/scient/latex/latexFontState.test.ts @@ -0,0 +1,48 @@ +// Tests how the font size and family are read from a selection, including mixed selections. +import type { Editor } from "@tiptap/core"; +import { describe, expect, it } from "vite-plus/test"; +import { latexFontState } from "./latexFontCommands"; + +const mark = (name: string, attrs: Record) => ({ type: { name }, attrs }); + +/** A stub editor whose selection covers the given runs of text, each with its own marks. */ +function editorOver(runs: ReadonlyArray>>): Editor { + return { + state: { + selection: { empty: false, from: 0, to: 10 }, + storedMarks: null, + doc: { + nodesBetween: (_from: number, _to: number, visit: (node: unknown) => void) => + runs.forEach((marks) => visit({ isText: true, text: "word", marks })), + }, + }, + } as unknown as Editor; +} + +const size = (points: number) => mark("latexFontSize", { points }); +const family = (name: string) => mark("latexFontFamily", { family: name }); + +describe("latexFontState", () => { + it("reports the shared size even when the fonts differ", () => { + const state = latexFontState(editorOver([[size(14), family("Garamond")], [size(14)]])); + expect(state).toMatchObject({ size: 14, sizeMixed: false, familyMixed: true }); + }); + + it("reports mixed sizes as an empty value with the mixed flag", () => { + const state = latexFontState(editorOver([[size(14)], [size(18)]])); + expect(state).toMatchObject({ size: null, sizeMixed: true }); + }); + + it("treats text without a size next to sized text as mixed", () => { + expect(latexFontState(editorOver([[size(14)], []])).sizeMixed).toBe(true); + }); + + it("reports no size and no mix for text with no size at all", () => { + expect(latexFontState(editorOver([[], []]))).toMatchObject({ + size: null, + family: null, + sizeMixed: false, + familyMixed: false, + }); + }); +}); diff --git a/apps/web/src/scient/latex/latexPackages.ts b/apps/web/src/scient/latex/latexPackages.ts index 2183b38945..b8e915ae47 100644 --- a/apps/web/src/scient/latex/latexPackages.ts +++ b/apps/web/src/scient/latex/latexPackages.ts @@ -61,6 +61,10 @@ const commandPackages: Readonly> = { hypertarget: ["hyperref"], autoref: ["hyperref"], url: ["url"], + // Computer Modern has only fixed sizes; fix-cm makes any `\fontsize` exact. + fontsize: ["fix-cm"], + fontspec: ["fontspec"], + IfFontExistsTF: ["fontspec"], cref: ["cleveref"], Cref: ["cleveref"], }; @@ -74,6 +78,13 @@ const providedPackages: Readonly> = { xcolor: ["color"], hyperref: ["url"], algorithm: ["float"], + // Scalable font packages already give every size. + lmodern: ["fix-cm"], + fontspec: ["fix-cm"], + newtxtext: ["fix-cm"], + newpxtext: ["fix-cm"], + tgtermes: ["fix-cm"], + tgpagella: ["fix-cm"], }; /** Existing commands do not turn an unrelated prose edit into a package edit. */ diff --git a/apps/web/src/scient/latex/latexTextFormatting.ts b/apps/web/src/scient/latex/latexTextFormatting.ts index e81251ef8f..a5f4562eec 100644 --- a/apps/web/src/scient/latex/latexTextFormatting.ts +++ b/apps/web/src/scient/latex/latexTextFormatting.ts @@ -1,3 +1,8 @@ +import { + FONT_CATALOGUE, + catalogueFont, + normalizeFontSize, +} from "@scientfactory/scient-markdown/fonts"; import { LATEX_DIRECTION_MARKS, latexDirectionMark } from "./latexLanguage"; /** Text styles understood by both the source adapter and the editable canvas. */ @@ -29,7 +34,7 @@ export const LATEX_INLINE_MARKS: Readonly> = { ...Object.fromEntries(LATEX_DIRECTION_MARKS.map(({ command, name }) => [command, name])), }; -export const LATEX_TEXT_DECLARATIONS: Readonly> = { +const LATEX_TEXT_DECLARATIONS: Readonly> = { bfseries: "bold", mdseries: "latexMedium", itshape: "italic", @@ -42,6 +47,128 @@ export const LATEX_TEXT_DECLARATIONS: Readonly> = { ...Object.fromEntries(LATEX_TEXT_SIZES.map((size) => [size, `latexSize_${size}`])), }; +/** + * A numeric size is one mark whose key carries its values (`latexFontSize:12/14.4`: + * size and baseline in points), so the parser can keep working on plain string marks. + */ +const FONT_SIZE_MARK = "latexFontSize"; + +function latexFontSizeMark(points: number, leading?: number): string { + return `${FONT_SIZE_MARK}:${points}/${leading ?? Math.round(points * 1.2 * 100) / 100}`; +} + +/** + * A named font is one mark whose key carries the catalogue name and the form it is written in + * (`latexFontFamily:pdftex:Times New Roman`), so the same bytes are written back on save. + */ +const FONT_FAMILY_MARK = "latexFontFamily"; + +/** pdfLaTeX writes a font family code; XeLaTeX and LuaLaTeX write a guarded `\fontspec` name. */ +export type LatexFontEngine = "pdftex" | "fontspec"; + +function latexFontFamilyMark(engine: LatexFontEngine, family: string): string { + return `${FONT_FAMILY_MARK}:${engine}:${family}`; +} + +type LatexMarkNode = { type: string; attrs?: Record }; + +/** The ProseMirror mark a string mark stands for. */ +export function latexMarkNode(key: string): LatexMarkNode { + const size = new RegExp(`^${FONT_SIZE_MARK}:([\\d.]+)/([\\d.]+)$`, "u").exec(key); + if (size) + return { type: FONT_SIZE_MARK, attrs: { points: Number(size[1]), leading: Number(size[2]) } }; + const font = new RegExp(`^${FONT_FAMILY_MARK}:(pdftex|fontspec):(.+)$`, "u").exec(key); + return font + ? { type: FONT_FAMILY_MARK, attrs: { engine: font[1]!, family: font[2]! } } + : { type: key }; +} + +/** The string mark key of a ProseMirror mark: the inverse of `latexMarkNode`. */ +export function latexMarkKey(mark: { type: string; attrs?: Record }): string { + if (mark.type === FONT_FAMILY_MARK) + return latexFontFamilyMark( + mark.attrs?.engine === "fontspec" ? "fontspec" : "pdftex", + String(mark.attrs?.family), + ); + return mark.type === FONT_SIZE_MARK + ? latexFontSizeMark(Number(mark.attrs?.points), Number(mark.attrs?.leading)) + : mark.type; +} + +const SIMPLE_DECLARATION = /^\\([A-Za-z]+)(?![A-Za-z])(?:\{\}|[\t\r\n ]*)/u; +const FONT_SIZE_DECLARATION = + /^\\fontsize\s*\{\s*([\d.]+)\s*(?:pt)?\s*\}\s*\{\s*([\d.]+)\s*(?:pt)?\s*\}\s*\\selectfont(?![A-Za-z])(?:\{\}|[\t\r\n ]*)/u; +const FONT_FAMILY_CODE_DECLARATION = + /^\\fontfamily\{([a-z0-9]+)\}\\selectfont(?![A-Za-z])(?:\{\}|[\t\r\n ]*)/u; +const FONT_FAMILY_NAME_DECLARATION = + /^\\IfFontExistsTF\{([^{}]+)\}\{\\fontspec\{\1\}\}\{\\fontspec\{([^{}]+)\}\}(?:\{\}|[\t\r\n ]*)/u; + +/** The fonts used when a named font is missing under XeLaTeX or LuaLaTeX: Latin Modern, always installed. */ +const FALLBACK_FONT: Readonly> = { + serif: "Latin Modern Roman", + "sans-serif": "Latin Modern Sans", + monospace: "Latin Modern Mono", +}; + +/** The declaration that selects a catalogue font, or null when the form does not offer it. */ +export function latexFontFamilyDeclaration(engine: LatexFontEngine, family: string): string | null { + const font = catalogueFont(family); + if (!font) return null; + if (engine === "pdftex") + return font.latex.pdftex === null ? null : `\\fontfamily{${font.latex.pdftex}}\\selectfont`; + const fallback = FALLBACK_FONT[font.category]!; + return `\\IfFontExistsTF{${font.latex.fontspec}}{\\fontspec{${font.latex.fontspec}}}{\\fontspec{${fallback}}}`; +} + +/** A text style declaration at the start of `source`: `\large`, `\ttfamily`, `\fontsize{12}{14.4}\selectfont`. */ +export function latexTextDeclarationAt(source: string): { mark: string; length: number } | null { + const size = FONT_SIZE_DECLARATION.exec(source); + if (size) { + const points = normalizeFontSize(Number(size[1])); + const leading = Number(size[2]); + return points === null || !(leading > 0 && leading <= 150) + ? null + : { mark: latexFontSizeMark(points, leading), length: size[0].length }; + } + const code = FONT_FAMILY_CODE_DECLARATION.exec(source); + if (code) { + const font = FONT_CATALOGUE.find((entry) => entry.latex.pdftex === code[1]); + return font ? { mark: latexFontFamilyMark("pdftex", font.name), length: code[0].length } : null; + } + const named = FONT_FAMILY_NAME_DECLARATION.exec(source); + if (named) { + const font = FONT_CATALOGUE.find((entry) => entry.latex.fontspec === named[1]); + const written = font && latexFontFamilyDeclaration("fontspec", font.name); + return font && named[0].startsWith(written ?? "\0") + ? { mark: latexFontFamilyMark("fontspec", font.name), length: named[0].length } + : null; + } + const simple = SIMPLE_DECLARATION.exec(source); + const mark = simple ? LATEX_TEXT_DECLARATIONS[simple[1]!] : undefined; + return simple && mark !== undefined ? { mark, length: simple[0].length } : null; +} + +/** Source of a group around already serialised text; `{}` after the declaration keeps a leading space. */ +function declarationGroup(declaration: string, text: string): string { + return `{${declaration}${/^\s/u.test(text) ? "{}" : " "}${text}}`; +} + +/** Source of the group a size or font-family ProseMirror mark stands for. */ +export function latexFontGroupSource( + mark: { type: string; attrs?: Record }, + text: string, +): string { + if (mark.type === FONT_FAMILY_MARK) { + const engine = mark.attrs?.engine === "fontspec" ? "fontspec" : "pdftex"; + const declaration = latexFontFamilyDeclaration(engine, String(mark.attrs?.family)); + return declaration === null ? text : declarationGroup(declaration, text); + } + return declarationGroup( + `\\fontsize{${Number(mark.attrs?.points)}}{${Number(mark.attrs?.leading)}}\\selectfont`, + text, + ); +} + export const LATEX_CANVAS_TEXT_MARKS = [ { name: "latexSmallCaps", style: "small-caps" }, { name: "latexRoman", style: "roman" }, @@ -54,7 +181,8 @@ export const LATEX_CANVAS_TEXT_MARKS = [ function markGroup(mark: string): string { if (latexDirectionMark(mark)) return "direction"; - if (mark.startsWith("latexSize_")) return "size"; + if (mark.startsWith("latexSize_") || mark.startsWith(`${FONT_SIZE_MARK}:`)) return "size"; + if (mark.startsWith(`${FONT_FAMILY_MARK}:`)) return "family"; if (["code", "latexRoman", "latexSans"].includes(mark)) return "family"; if (["italic", "latexSlanted", "latexUpright", "latexSmallCaps"].includes(mark)) return "shape"; if (["bold", "latexMedium"].includes(mark)) return "weight"; diff --git a/apps/web/src/scient/latex/latexVisualDocument.ts b/apps/web/src/scient/latex/latexVisualDocument.ts index 54f9bb9fbe..99b06c3fb7 100644 --- a/apps/web/src/scient/latex/latexVisualDocument.ts +++ b/apps/web/src/scient/latex/latexVisualDocument.ts @@ -88,7 +88,10 @@ import { } from "./latexLiteral"; import { LATEX_INLINE_MARKS, - LATEX_TEXT_DECLARATIONS, + latexFontGroupSource, + latexMarkKey, + latexMarkNode, + latexTextDeclarationAt, latexTextMarkSource, withLatexTextMark, } from "./latexTextFormatting"; @@ -563,7 +566,7 @@ function textNode(text: string, marks: readonly string[]): JSONContent | null { return { type: "text", text, - ...(marks.length === 0 ? {} : { marks: marks.map((type) => ({ type })) }), + ...(marks.length === 0 ? {} : { marks: marks.map(latexMarkNode) }), }; } @@ -756,13 +759,10 @@ function inlineGroup(source: string, at: number, marks: readonly string[]): Inli ); // Declarations affect the rest of this group and stop at its closing brace. for (;;) { - const declaration = /^\\([A-Za-z]+)(?![A-Za-z])(?:\{\}|[\t\r\n ]*)/u.exec( - source.slice(from, close), - ); - const declaredMark = declaration ? LATEX_TEXT_DECLARATIONS[declaration[1]!] : undefined; - if (declaredMark === undefined) break; - nextMarks = withLatexTextMark(nextMarks, declaredMark); - from += declaration![0].length; + const declaration = latexTextDeclarationAt(source.slice(from, close)); + if (declaration === null) break; + nextMarks = withLatexTextMark(nextMarks, declaration.mark); + from += declaration.length; } return { from, to: close, end: close + 1, marks: nextMarks, prefix: source.slice(at, from) }; } @@ -907,13 +907,13 @@ function inlinePiece( const group = inlineGroup(source, at, marks); if (group) return { end: group.end, group }; if (scoped) { - const declaration = /^\\([A-Za-z]+)(?![A-Za-z])(?:\{\}|[\t\r\n ]*)/u.exec(rest); - const mark = declaration ? LATEX_TEXT_DECLARATIONS[declaration[1]!] : undefined; - if (mark !== undefined) return { end: at + declaration![0].length, declaration: mark }; + const declaration = latexTextDeclarationAt(rest); + if (declaration !== null) + return { end: at + declaration.length, declaration: declaration.mark }; } const marked = (node: JSONContent): JSONContent => ({ ...node, - ...(marks.length ? { marks: marks.map((type) => ({ type })) } : {}), + ...(marks.length ? { marks: marks.map(latexMarkNode) } : {}), }); const columnBreak = /^\\columnbreak\b(?:[\t ]*\[4\])?[\t ]*(?:\r?\n[\t ]*)?/u.exec(rest); if (columnBreak) { @@ -4845,6 +4845,31 @@ function serializeInline(nodes: readonly JSONContent[] | undefined): string { } return result; } + // One group covers a whole run of equal size (or font), with its math and other marks inside. + const groupType = ["latexFontSize", "latexFontFamily"].find((type) => + nodes?.some((node) => node.marks?.some((mark) => mark.type === type)), + ); + if (groupType && nodes) { + let result = ""; + for (let at = 0; at < nodes.length;) { + const group = nodes[at]!.marks?.find((mark) => mark.type === groupType); + const signature = JSON.stringify(group); + let end = at + 1; + while ( + end < nodes.length && + JSON.stringify(nodes[end]!.marks?.find((mark) => mark.type === groupType)) === signature + ) + end++; + const content = nodes.slice(at, end).map((node) => ({ + ...node, + marks: (node.marks ?? []).filter((mark) => mark.type !== groupType), + })); + const inner = serializeInline(content); + result += group ? latexFontGroupSource(group, inner) : inner; + at = end; + } + return result; + } const merged: JSONContent[] = []; for (const node of nodes ?? []) { const previous = merged.at(-1); @@ -7279,14 +7304,14 @@ function minimallyPatchedBlock( if ( start > end || changed.some((node) => - context.some((mark) => !node.marks?.some((item) => item.type === mark)), + context.some((mark) => !node.marks?.some((item) => latexMarkKey(item) === mark)), ) ) continue; const inserted = serializeInline( changed.map((node) => ({ ...node, - marks: (node.marks ?? []).filter((mark) => !context.includes(mark.type)), + marks: (node.marks ?? []).filter((mark) => !context.includes(latexMarkKey(mark))), })), ); const before = block.source.slice(0, start); diff --git a/apps/web/src/scient/latex/latexVisualLayout.ts b/apps/web/src/scient/latex/latexVisualLayout.ts index e72c2915e0..eb0e712281 100644 --- a/apps/web/src/scient/latex/latexVisualLayout.ts +++ b/apps/web/src/scient/latex/latexVisualLayout.ts @@ -443,7 +443,7 @@ export function resolvedLatexFontSize(points: number, source: string): number { source.indexOf("\\begin{document}") < 0 ? source.length : source.indexOf("\\begin{document}"), ); if ( - /\\(?:setmainfont|babelfont)\b|\\(?:usepackage|RequirePackage)(?:\[[^\]]*\])?\{[^{}]*\b(?:fontspec|lmodern|newtxtext|newpxtext|tgtermes|tgpagella)\b/u.test( + /\\(?:setmainfont|babelfont)\b|\\(?:usepackage|RequirePackage)(?:\[[^\]]*\])?\{[^{}]*\b(?:fontspec|fix-cm|lmodern|newtxtext|newpxtext|tgtermes|tgpagella)\b/u.test( preamble, ) ) diff --git a/apps/web/src/scient/markdownEditor/documentFont.test.ts b/apps/web/src/scient/markdownEditor/documentFont.test.ts new file mode 100644 index 0000000000..e8d9f0e4c6 --- /dev/null +++ b/apps/web/src/scient/markdownEditor/documentFont.test.ts @@ -0,0 +1,75 @@ +import { describe, expect, it } from "vite-plus/test"; +import { + canWriteMarkdownDocumentFont, + readMarkdownDocumentFont, + writeMarkdownDocumentFont, + type MarkdownDocumentFont, +} from "./documentFont"; + +const none: MarkdownDocumentFont = { fontFamily: null, fontSize: null }; + +describe("Markdown document font front matter", () => { + it("reads the two keys, quoted or not, with a trailing comment, and ignores unknown values", () => { + expect( + readMarkdownDocumentFont( + '---\ntitle: T\nfontsize: "11pt" # base\nmainfont: Times New Roman\n---', + ), + ).toEqual({ fontFamily: "Times New Roman", fontSize: "11pt" }); + expect(readMarkdownDocumentFont("---\nfontsize: 14pt\nmainfont: Comic Sans\n---")).toEqual( + none, + ); + expect(readMarkdownDocumentFont(null)).toEqual(none); + }); + + it("creates a block when there is none, and returns null when nothing is wanted", () => { + expect(writeMarkdownDocumentFont(null, { fontFamily: "Arial", fontSize: "12pt" })).toBe( + "---\nfontsize: 12pt\nmainfont: Arial\n---", + ); + expect(writeMarkdownDocumentFont(null, none)).toBeNull(); + }); + + it("keeps other keys, order and line endings, and only rewrites the changed key", () => { + const source = "---\r\ntitle: T\r\nfontsize: 10pt\r\ntags: [a]\r\n---"; + expect(writeMarkdownDocumentFont(source, { fontFamily: "Arial", fontSize: "10pt" })).toBe( + "---\r\ntitle: T\r\nfontsize: 10pt\r\ntags: [a]\r\nmainfont: Arial\r\n---", + ); + }); + + it("leaves a size the card does not know when only the font changes", () => { + const source = "---\nfontsize: 14pt # base size\ntitle: T\n---"; + expect(writeMarkdownDocumentFont(source, { fontFamily: "Arial", fontSize: null })).toBe( + "---\nfontsize: 14pt # base size\ntitle: T\nmainfont: Arial\n---", + ); + }); + + it("keeps the comment when a recognised value changes", () => { + expect( + writeMarkdownDocumentFont("---\nfontsize: 10pt # base\n---", { + fontFamily: null, + fontSize: "12pt", + }), + ).toBe("---\nfontsize: 12pt # base\n---"); + }); + + it("keeps the blank lines of the block", () => { + const source = "---\ntitle: T\n\n# notes\ntags: [a]\n\n---"; + expect(writeMarkdownDocumentFont(source, { fontFamily: null, fontSize: "12pt" })).toBe( + "---\ntitle: T\n\n# notes\ntags: [a]\nfontsize: 12pt\n\n---", + ); + }); + + it("removes the block when the last key goes, and refuses TOML", () => { + expect(writeMarkdownDocumentFont("---\nfontsize: 10pt\n---", none)).toBeNull(); + expect( + writeMarkdownDocumentFont("+++\ntitle = 'T'\n+++", { fontFamily: "Arial", fontSize: null }), + ).toBeUndefined(); + }); + + it("refuses a font key whose value spans several lines instead of corrupting the block", () => { + const source = "---\ntitle: Original\nmainfont: |\n Arial\n---"; + expect(canWriteMarkdownDocumentFont(source)).toBe(false); + expect( + writeMarkdownDocumentFont(source, { fontFamily: null, fontSize: "12pt" }), + ).toBeUndefined(); + }); +}); diff --git a/apps/web/src/scient/markdownEditor/documentFont.ts b/apps/web/src/scient/markdownEditor/documentFont.ts new file mode 100644 index 0000000000..a2b15a494f --- /dev/null +++ b/apps/web/src/scient/markdownEditor/documentFont.ts @@ -0,0 +1,117 @@ +import { + DOCUMENT_FONT_SIZES, + catalogueFont, + type DocumentFontSize, +} from "@scientfactory/scient-markdown"; + +/** + * Whole-document font settings of a Markdown file, kept as two keys of its + * leading YAML front matter: `fontsize: 11pt` and `mainfont: Times New Roman` + * (the names Pandoc and Quarto already read). Only a key whose setting the user + * changed is rewritten; every other line, value and comment stays as it is. + */ + +export interface MarkdownDocumentFont { + readonly fontFamily: string | null; + readonly fontSize: DocumentFontSize | null; +} + +// The leading `---` block of a whole document. +export const LEADING_FRONT_MATTER = /^---[ \t]*\r?\n[\s\S]*?\r?\n---[ \t]*(?:\r?\n|$)/u; +// Fence, body, closing fence, and whatever follows the block (kept untouched). +const YAML_FRONT_MATTER = /^(---[ \t]*)(\r?\n)([\s\S]*?)(?:\r?\n)?(---[ \t]*)(\s*)$/u; + +const SIZE_KEY = "fontsize"; +const FAMILY_KEY = "mainfont"; + +interface KeyLine { + readonly index: number; + /** The value without quotes and trailing comment; null when it spans several lines. */ + readonly value: string | null; + readonly comment: string; +} + +function findKey(lines: readonly string[], key: string): KeyLine | null { + const index = lines.findIndex((line) => new RegExp(`^${key}[ \\t]*:`, "u").test(line)); + if (index < 0) return null; + const line = lines[index]!; + const rest = line.slice(line.indexOf(":") + 1); + const comment = /\s+#.*$/u.exec(rest)?.[0] ?? ""; + const text = rest.slice(0, rest.length - comment.length).trim(); + const continues = /^\s+\S/u.test(lines[index + 1] ?? "") || /^[|>]/u.test(text) || text === ""; + return { + index, + value: continues ? null : text.replace(/^(["'])(.*)\1$/u, "$2"), + comment, + }; +} + +function bodyLines(frontMatter: string): string[] | null { + const body = YAML_FRONT_MATTER.exec(frontMatter)?.[3]; + return body === undefined ? null : body.split(/\r?\n/u); +} + +export function readMarkdownDocumentFont(frontMatter: string | null): MarkdownDocumentFont { + const lines = frontMatter === null ? [] : (bodyLines(frontMatter) ?? []); + const size = findKey(lines, SIZE_KEY)?.value ?? null; + const family = findKey(lines, FAMILY_KEY)?.value ?? null; + return { + fontSize: DOCUMENT_FONT_SIZES.find((candidate) => candidate === size) ?? null, + fontFamily: family !== null && catalogueFont(family) !== null ? family : null, + }; +} + +/** + * Whether the settings can be written: no front matter yet, or a YAML block whose + * font keys are single-line values. Otherwise the card stays off and the file is left alone. + */ +export function canWriteMarkdownDocumentFont(frontMatter: string | null): boolean { + if (frontMatter === null) return true; + const lines = bodyLines(frontMatter); + if (lines === null) return false; + return [SIZE_KEY, FAMILY_KEY].every((key) => { + const found = findKey(lines, key); + return found === null || found.value !== null; + }); +} + +/** + * The front matter block after applying `font`, or null when it would be empty + * (the block is then removed); undefined when the block cannot be written safely. + */ +export function writeMarkdownDocumentFont( + frontMatter: string | null, + font: MarkdownDocumentFont, +): string | null | undefined { + if (frontMatter === null) { + const wanted = [ + ...(font.fontSize ? [`${SIZE_KEY}: ${font.fontSize}`] : []), + ...(font.fontFamily ? [`${FAMILY_KEY}: ${font.fontFamily}`] : []), + ]; + return wanted.length ? `---\n${wanted.join("\n")}\n---` : null; + } + const match = YAML_FRONT_MATTER.exec(frontMatter); + if (!match || !canWriteMarkdownDocumentFont(frontMatter)) return undefined; + const [, open, eol, , close, after = ""] = match; + const newline = eol ?? "\n"; + const lines = [...(bodyLines(frontMatter) ?? [])]; + const current = readMarkdownDocumentFont(frontMatter); + const edits: ReadonlyArray = [ + [SIZE_KEY, current.fontSize, font.fontSize], + [FAMILY_KEY, current.fontFamily, font.fontFamily], + ]; + for (const [key, before, wanted] of edits) { + if (before === wanted) continue; + const found = findKey(lines, key); + if (wanted === null) { + if (found) lines.splice(found.index, 1); + } else if (found) { + lines[found.index] = `${key}: ${wanted}${found.comment}`; + } else { + // A new key goes after the last other key; blank lines inside the block are kept. + lines.splice(lines.findLastIndex((line) => line !== "") + 1, 0, `${key}: ${wanted}`); + } + } + if (lines.every((line) => line === "")) return null; + return `${open}${newline}${lines.join(newline)}${newline}${close}${after}`; +} diff --git a/apps/web/src/scient/markdownEditor/prosemirror/commands.ts b/apps/web/src/scient/markdownEditor/prosemirror/commands.ts index d39f61f004..95dcc934a1 100644 --- a/apps/web/src/scient/markdownEditor/prosemirror/commands.ts +++ b/apps/web/src/scient/markdownEditor/prosemirror/commands.ts @@ -33,6 +33,14 @@ import { scientMarkdownSchema } from "./schema"; import { selectMarkdownTable } from "./tables"; import { nextScientMarkdownFootnoteLabel } from "../footnotes"; import { WRITING_COMMAND_LABELS } from "../../writing/commandNames"; +import { type FontRun, steppedFontSize, steppedRuns, wordAround } from "../../writing/fontTarget"; +import { catalogueFont, normalizeFontSize } from "@scientfactory/scient-markdown"; +import { + canWriteMarkdownDocumentFont, + readMarkdownDocumentFont, + writeMarkdownDocumentFont, + type MarkdownDocumentFont, +} from "../documentFont"; export type ScientMarkdownCommand = | "add-column-after" @@ -55,6 +63,9 @@ export type ScientMarkdownCommand = | "direction-rtl" | "display-math" | "footnote" + | `font-family-${string}` + | `font-size-${number}` + | "font-size-default" | "clear-formatting" | "hard-break" | "heading-1" @@ -481,6 +492,208 @@ function clearMarkdownFormatting(): Command { }; } +/** The word around a caret inside its text block, or null (see `wordAround`). */ +function wordAroundCaret(state: EditorState): { from: number; to: number } | null { + const { $from } = state.selection; + if (!$from.parent.isTextblock) return null; + const text = $from.parent.textBetween(0, $from.parent.content.size, undefined, "\ufffc"); + const word = wordAround(text, $from.parentOffset); + return word === null ? null : { from: $from.start() + word.start, to: $from.start() + word.end }; +} + +/** A range without the whitespace at its ends: like toggleMark, a written span cannot keep it. */ +function trimmedRange(doc: ProseMirrorNode, from: number, to: number) { + const isSpace = (at: number) => /^\s$/u.test(doc.textBetween(at, at + 1)); + let start = from; + let end = to; + while (start < end && isSpace(start)) start += 1; + while (end > start && isSpace(end - 1)) end -= 1; + return { start, end }; +} + +/** + * Set one font mark on the selection; `null` removes it. At a caret it applies to the word + * around it (as Word does), or, between words, to the typing marks. Every selected range gets + * it, so a selection across table cells reaches all of them. Inline code is skipped: the file + * cannot hold a font span around code, so code keeps its own look. + */ +function setMarkdownFontMark(markName: string, attrs: Attrs | null): Command { + return (state, dispatch) => { + if (!dispatch) return true; + const type = requiredMarkType(markName); + const code = requiredMarkType("code"); + const { empty, $from } = state.selection; + const word = empty ? wordAroundCaret(state) : null; + if (empty && word === null) { + const kept = (state.storedMarks ?? $from.marks()).filter((mark) => mark.type !== type); + if (kept.some((mark) => mark.type === code)) return true; + dispatch(state.tr.setStoredMarks(attrs ? type.create(attrs).addToSet(kept) : kept)); + return true; + } + let transaction = state.tr; + const ranges = word + ? [word] + : state.selection.ranges.map((range) => ({ from: range.$from.pos, to: range.$to.pos })); + for (const { from, to } of ranges) { + transaction = transaction.removeMark(from, to, type); + if (!attrs) continue; + const { start, end } = trimmedRange(state.doc, from, to); + state.doc.nodesBetween(start, end, (node, position) => { + if (!node.isInline || node.marks.some((mark) => mark.type === code)) return; + transaction = transaction.addMark( + Math.max(start, position), + Math.min(end, position + node.nodeSize), + type.create(attrs), + ); + }); + } + dispatch(transaction); + return true; + }; +} + +/** + * Move the size of every run of the selection (or of the word at the caret) by `steps` steps; + * each run keeps its difference with the others. Text without a size starts from the size it is + * drawn at (`drawnPoints`), so a heading word grows from the heading's size. + */ +function stepMarkdownFontSize( + steps: number, + drawnPoints: (position: number) => number | null, +): Command { + return (state, dispatch) => { + const type = requiredMarkType("font_size"); + const code = requiredMarkType("code"); + const { empty, from } = state.selection; + const word = empty ? wordAroundCaret(state) : null; + if (empty && word === null) { + const typing = (state.storedMarks ?? state.selection.$from.marks()).find( + (mark) => mark.type === type, + ); + const current = typing?.attrs.size ?? drawnPoints(from); + return typeof current === "number" + ? setMarkdownFontMark("font_size", { size: steppedFontSize(current, steps) })( + state, + dispatch, + ) + : false; + } + if (!dispatch) return true; + const transaction = state.tr; + const ranges = word + ? [word] + : state.selection.ranges.map((range) => ({ from: range.$from.pos, to: range.$to.pos })); + for (const range of ranges) { + const runs: FontRun[] = []; + state.doc.nodesBetween(range.from, range.to, (node, position) => { + if (!node.isText) return; + const from = Math.max(range.from, position); + const own = type.isInSet(node.marks)?.attrs.size; + runs.push({ + text: (node.text ?? "").slice( + from - position, + Math.min(range.to, position + node.nodeSize) - position, + ), + from, + isCode: code.isInSet(node.marks) !== undefined, + size: typeof own === "number" ? own : null, + }); + }); + for (const change of steppedRuns(runs, steps, drawnPoints)) + transaction.addMark(change.from, change.to, type.create({ size: change.size })); + } + dispatch(transaction); + return true; + }; +} + +/** Turn inline code on or off. The file cannot hold a font span around code, so turning it on drops the fonts. */ +const toggleInlineCode: Command = (state, dispatch) => { + const code = requiredMarkType("code"); + const fonts = [requiredMarkType("font_size"), requiredMarkType("font_family")]; + return toggleMark(code)( + state, + dispatch && + ((transaction) => { + const ranges = state.selection.ranges.map((range) => [range.$from.pos, range.$to.pos]); + const turnedOn = + transaction.storedMarks?.some((mark) => mark.type === code) || + ranges.some(([from, to]) => transaction.doc.rangeHasMark(from!, to!, code)); + if (turnedOn) { + for (const font of fonts) { + for (const [from, to] of ranges) transaction.removeMark(from!, to!, font); + } + if (transaction.storedMarks) { + transaction.setStoredMarks( + transaction.storedMarks.filter((mark) => !fonts.includes(mark.type)), + ); + } + } + dispatch(transaction); + }), + ); +}; + +/** Parses `font-size-12`, `font-size-default`, `font-family-Arial`, `font-family-default`. */ +function fontCommand(command: string): Command { + const [, kind, value = ""] = /^font-(size|family)-(.+)$/u.exec(command) ?? []; + if (kind === undefined) return () => false; + const markName = kind === "size" ? "font_size" : "font_family"; + if (value === "default") return setMarkdownFontMark(markName, null); + if (kind === "size") { + const size = normalizeFontSize(Number(value)); + return size === null ? () => false : setMarkdownFontMark(markName, { size }); + } + return catalogueFont(value) === null + ? () => false + : setMarkdownFontMark(markName, { family: value }); +} + +/** The leading YAML or TOML front matter block, if the document starts with one. */ +function leadingFrontMatter(doc: ProseMirrorNode): ProseMirrorNode | null { + const first = doc.firstChild; + const kind = first?.attrs.sourceKind; + return first?.type.name === "raw_block" && (kind === "yaml" || kind === "toml") ? first : null; +} + +export function documentFontOf(doc: ProseMirrorNode): MarkdownDocumentFont { + return readMarkdownDocumentFont(leadingFrontMatter(doc)?.attrs.source ?? null); +} + +/** Whether the document's front matter can carry font keys (none yet, or YAML). */ +export function documentFontEditable(doc: ProseMirrorNode): boolean { + const front = leadingFrontMatter(doc); + if (front === null) return true; + return ( + front.attrs.sourceKind === "yaml" && canWriteMarkdownDocumentFont(String(front.attrs.source)) + ); +} + +/** Write the whole-document font keys into the front matter, creating or removing the block. */ +export function runScientMarkdownDocumentFont( + font: MarkdownDocumentFont, + state: EditorState, + dispatch?: (transaction: Transaction) => void, +): boolean { + const front = leadingFrontMatter(state.doc); + const next = writeMarkdownDocumentFont(front ? String(front.attrs.source) : null, font); + if (next === undefined) return false; + if (!dispatch) return true; + let transaction = state.tr; + if (next === null) { + if (front) transaction = transaction.delete(0, front.nodeSize); + } else if (front) { + transaction = transaction.setNodeMarkup(0, undefined, { ...front.attrs, source: next }); + } else { + transaction = transaction.insert( + 0, + requiredNodeType("raw_block").create({ source: next, sourceKind: "yaml" }), + ); + } + dispatch(closeHistory(transaction)); + return true; +} + /** Set block direction across the selection; a table is one directional block. */ function setMarkdownTextDirection(direction: "ltr" | "rtl" | null): Command { return (state, dispatch) => { @@ -515,7 +728,7 @@ function commandFor(command: ScientMarkdownCommand): Command { case "strike": return toggleMark(requiredMarkType("strike")); case "inline-code": - return toggleMark(requiredMarkType("code")); + return toggleInlineCode; case "undo": return undo; case "redo": @@ -593,6 +806,8 @@ function commandFor(command: ScientMarkdownCommand): Command { // GFM cannot encode spans or arbitrary header cells. Keep the command // boundary honest as well as the menu, including keyboard/API callers. return () => false; + default: + return fontCommand(command); } } @@ -626,6 +841,20 @@ export function runScientMarkdownCommand( ); } +/** Move the selection's sizes by `steps` steps through the same history path as dock commands. */ +export function runScientMarkdownFontStep( + steps: number, + drawnPoints: (position: number) => number | null, + state: EditorState, + dispatch?: (transaction: Transaction) => void, +): boolean { + return runExplicitScientMarkdownCommand( + stepMarkdownFontSize(steps, drawnPoints), + state, + dispatch, + ); +} + /** Insert one bounded GFM table through the same transaction/history path as dock commands. */ export function runScientMarkdownTableInsert( dimensions: ScientMarkdownTableDimensions, diff --git a/apps/web/src/scient/markdownEditor/prosemirror/documentFontPresentation.ts b/apps/web/src/scient/markdownEditor/prosemirror/documentFontPresentation.ts new file mode 100644 index 0000000000..89adfb2399 --- /dev/null +++ b/apps/web/src/scient/markdownEditor/prosemirror/documentFontPresentation.ts @@ -0,0 +1,26 @@ +import { catalogueFont } from "@scientfactory/scient-markdown"; +import { Plugin } from "prosemirror-state"; +import { documentFontOf } from "./commands"; + +/** + * Shows the whole-document font keys of the front matter on the editor root as + * data attributes and a CSS variable; the stylesheet turns them into size and family. + */ +export function scientMarkdownDocumentFontPlugin(): Plugin { + return new Plugin({ + props: { + attributes: (state) => { + const { fontFamily, fontSize } = documentFontOf(state.doc); + return { + ...(fontSize ? { "data-scient-font-size": fontSize } : {}), + ...(fontFamily + ? { + "data-scient-font-family": fontFamily, + style: `--scient-markdown-font-family:${catalogueFont(fontFamily)?.css ?? "inherit"}`, + } + : {}), + }; + }, + }, + }); +} diff --git a/apps/web/src/scient/markdownEditor/prosemirror/fontGestures.browser.test.ts b/apps/web/src/scient/markdownEditor/prosemirror/fontGestures.browser.test.ts new file mode 100644 index 0000000000..710bae0ebc --- /dev/null +++ b/apps/web/src/scient/markdownEditor/prosemirror/fontGestures.browser.test.ts @@ -0,0 +1,243 @@ +// Replays font size and bold gestures in a real browser with real keystrokes on a throwaway +// document, and checks that no edit is refused and the file text stays as expected. +import { TextSelection } from "prosemirror-state"; +import { describe, expect, it, vi } from "vite-plus/test"; +import { userEvent } from "vitest/browser"; +import { isMacKeyboard } from "../../keyboard/keys"; +import { drawnPointsAt } from "../../writing/fontChoices"; +import { selectionMarkValue } from "./selectionMarkValue"; +import { ScientMarkdownEditorView } from "./view"; + +/** Mounts an editor on a throwaway host; `using` destroys both when the test ends. */ +function open(source: string) { + const controller = new ScientMarkdownEditorView({ + source, + revision: "gesture-fixture", + mode: "write", + ariaLabel: "Gesture fixture", + }); + const host = document.createElement("div"); + document.body.append(host); + const view = controller.mount(host); + view.focus(); + return { + controller, + view, + [Symbol.dispose]() { + controller.destroy(); + host.remove(); + }, + }; +} + +/** Select text offsets of the first paragraph (0 = start of its text). */ +function select(view: ReturnType["view"], from: number, to = from) { + view.dispatch(view.state.tr.setSelection(TextSelection.create(view.state.doc, 1 + from, 1 + to))); + view.focus(); +} + +/** Mod+Shift on a physical key, as the browser reports it: on a Mac, `key` stays unshifted. */ +function pressSizeShortcut(target: HTMLElement, code: string, key: string) { + const mac = isMacKeyboard(); + target.dispatchEvent( + new KeyboardEvent("keydown", { + key, + code, + metaKey: mac, + ctrlKey: !mac, + shiftKey: true, + bubbles: true, + cancelable: true, + }), + ); +} + +const draft = (controller: ScientMarkdownEditorView) => controller.session.session.draftSource; +const refused = (controller: ScientMarkdownEditorView) => + controller.session.pendingWriteback !== null; + +describe("font gestures in a real browser", () => { + it("typing a space then a word at the end of a sized word is accepted and continues the size", async () => { + using editor = open("alpha beta\n"); + const { controller, view } = editor; + select(view, 0, 5); + controller.execute("font-size-14"); + select(view, 5); + await userEvent.keyboard(" gamma"); + expect(refused(controller)).toBe(false); + expect(draft(controller)).toBe(`alpha gamma beta\n`); + }); + + it("applying a size to a selection that ends with a space does not size the space", async () => { + using editor = open("alpha beta\n"); + const { controller, view } = editor; + select(view, 0, 6); + controller.execute("font-size-14"); + expect(refused(controller)).toBe(false); + expect(draft(controller)).toBe(`alpha beta\n`); + }); + + it("typing a space after a bold word is accepted", async () => { + using editor = open("**alpha**\n"); + const { controller, view } = editor; + select(view, 5); + await userEvent.keyboard(" more"); + expect(refused(controller)).toBe(false); + expect(draft(controller)).toBe("**alpha more**\n"); + }); + + it("holding Enter after a sized word never refuses and keeps the size on the first line only", async () => { + using editor = open("alpha\n"); + const { controller, view } = editor; + select(view, 0, 5); + controller.execute("font-size-14"); + select(view, 5); + await userEvent.keyboard("{Enter}".repeat(8)); + expect(refused(controller)).toBe(false); + expect(draft(controller).startsWith(`alpha`)).toBe(true); + expect(draft(controller).match(/font-size/gu)).toHaveLength(1); + }); + + it("removing the size from a sized word restores plain text", async () => { + using editor = open(`alpha beta\n`); + const { controller, view } = editor; + select(view, 0, 5); + controller.execute("font-size-default"); + expect(refused(controller)).toBe(false); + expect(draft(controller)).toBe("alpha beta\n"); + }); + + it("a lone space typed after a bold word is accepted", async () => { + using editor = open("alpha **beta**\n"); + const { controller, view } = editor; + select(view, 10); + await userEvent.keyboard(" "); + expect(refused(controller)).toBe(false); + }); + + it("a lone space typed after a sized word is accepted", async () => { + using editor = open(`alpha beta\n`); + const { controller, view } = editor; + select(view, 10); + await userEvent.keyboard(" "); + expect(refused(controller)).toBe(false); + }); + + it("removing bold from the last word of a paragraph is accepted", async () => { + using editor = open("alpha **beta**\n"); + const { controller, view } = editor; + select(view, 6, 10); + controller.execute("bold"); + expect(refused(controller)).toBe(false); + expect(draft(controller)).toBe("alpha beta\n"); + }); + + it("a size applied across a selection ending after a bold word is accepted", async () => { + using editor = open("alpha **beta** gamma\n"); + const { controller, view } = editor; + select(view, 0, 11); + controller.execute("font-size-18"); + expect(refused(controller)).toBe(false); + }); + + describe("with the selection made by real keys, in the conditions that failed before", () => { + /** Put the caret at `from`, then extend the selection to `to` with Shift+ArrowRight. */ + async function selectByKeys(view: ReturnType["view"], from: number, to: number) { + select(view, from); + await userEvent.keyboard(`{Shift>}${"{ArrowRight}".repeat(to - from)}{/Shift}`); + // The editor reads the browser selection asynchronously; wait until it has. + await vi.waitFor(() => { + expect([view.state.selection.from, view.state.selection.to]).toEqual([1 + from, 1 + to]); + }); + } + + it("a space typed between a sized word and the next word is accepted", async () => { + using editor = open("un bien mot\n"); + const { controller, view } = editor; + await selectByKeys(view, 3, 7); + controller.execute("font-size-14"); + await userEvent.keyboard("{ArrowRight}"); + await vi.waitFor(() => expect(view.state.selection.empty).toBe(true)); + await userEvent.keyboard(" "); + expect(refused(controller)).toBe(false); + // Chromium types a non-breaking space before an existing space; it is a space for this rule. + expect(draft(controller).replaceAll("\u00a0", " ")).toBe( + `un bien mot\n`, + ); + }); + + it("italic over two differently sized words is accepted", async () => { + using editor = open("aa bb cc\n"); + const { controller, view } = editor; + await selectByKeys(view, 0, 2); + controller.execute("font-size-14"); + await selectByKeys(view, 3, 5); + controller.execute("font-size-20"); + await selectByKeys(view, 1, 4); + controller.execute("italic"); + expect(refused(controller)).toBe(false); + }); + + it("removing bold from the last word of a bold phrase is accepted", async () => { + using editor = open("**one two**\n"); + const { controller, view } = editor; + await selectByKeys(view, 4, 7); + controller.execute("bold"); + expect(refused(controller)).toBe(false); + expect(draft(controller)).toBe("**one** two\n"); + }); + + it("a size on the text after a sized line break is accepted", async () => { + using editor = open("one \ntwo three\n"); + const { controller, view } = editor; + await selectByKeys(view, 0, 13); + controller.execute("font-size-14"); + await selectByKeys(view, 4, 9); + controller.execute("font-size-20"); + expect(refused(controller)).toBe(false); + }); + }); + + it("+ and − move each word of a mixed selection by one point and keep the field empty", () => { + using editor = open( + `alpha beta gamma\n`, + ); + const { controller, view } = editor; + const drawn = drawnPointsAt(view, 14)!; + select(view, 0, 16); + controller.stepFontSize(1); + expect(refused(controller)).toBe(false); + expect(draft(controller)).toBe( + `alpha beta gamma\n`, + ); + expect(selectionMarkValue(view.state, "font_size", "size", "number")).toEqual({ + value: null, + mixed: true, + }); + controller.stepFontSize(-1); + expect(draft(controller)).toContain(`alpha`); + }); + + it("+ on a heading word starts from the heading's drawn size", () => { + using editor = open("# Title\n"); + const { controller, view } = editor; + const drawn = drawnPointsAt(view, 2)!; + select(view, 2); + controller.stepFontSize(1); + expect(draft(controller)).toBe(`# Title\n`); + }); + + it("Mod+Shift+. and Mod+Shift+, step the size of the selection, by key position", () => { + using editor = open("alpha beta\n"); + const { controller, view } = editor; + select(view, 0, 5); + controller.execute("font-size-14"); + // macOS reports the unshifted character while Cmd and Shift are held; a French keyboard + // has ":" and ";" on those two keys. + pressSizeShortcut(view.dom, "Period", "."); + pressSizeShortcut(view.dom, "Period", ":"); + expect(draft(controller)).toBe(`alpha beta\n`); + pressSizeShortcut(view.dom, "Comma", ","); + expect(draft(controller)).toBe(`alpha beta\n`); + }); +}); diff --git a/apps/web/src/scient/markdownEditor/prosemirror/fontStyles.test.ts b/apps/web/src/scient/markdownEditor/prosemirror/fontStyles.test.ts new file mode 100644 index 0000000000..2b5bbe7f89 --- /dev/null +++ b/apps/web/src/scient/markdownEditor/prosemirror/fontStyles.test.ts @@ -0,0 +1,519 @@ +import { TextSelection } from "prosemirror-state"; +import { CellSelection } from "prosemirror-tables"; +import { describe, expect, it } from "vite-plus/test"; +import { + runScientMarkdownCommand, + runScientMarkdownDocumentFont, + type ScientMarkdownCommand, +} from "./commands"; +import { scientMarkdownSchema } from "./schema"; +import { selectionMarkValue } from "./selectionMarkValue"; +import { ScientProseMirrorSession } from "./session"; + +function open(source: string) { + return new ScientProseMirrorSession({ source, revision: "r0" }); +} + +/** Select the text of the first paragraph between two text offsets. */ +function select(session: ScientProseMirrorSession, from: number, to: number) { + session.applyTransaction( + session.state.tr.setSelection(TextSelection.create(session.state.doc, 1 + from, 1 + to)), + "user", + ); +} + +function run(session: ScientProseMirrorSession, command: ScientMarkdownCommand) { + runScientMarkdownCommand(command, session.state, (tr) => session.applyTransaction(tr, "user")); +} + +function markedText(session: ScientProseMirrorSession, markName: string) { + const found: string[] = []; + session.state.doc.descendants((node) => { + if (node.isText && node.marks.some((mark) => mark.type.name === markName)) { + found.push(node.text ?? ""); + } + }); + return found; +} + +describe("Markdown font size and family", () => { + it("reads the recognised span forms as marks", () => { + const session = open( + `a big and code\n`, + ); + expect(markedText(session, "font_size")).toEqual(["big"]); + expect(markedText(session, "font_family")).toEqual(["code"]); + const size = session.state.doc.firstChild!.child(1).marks[0]!; + expect(size.attrs.size).toBe(14); + }); + + it.each([ + 'x', + 'x', + 'x', + 'x', + `x`, + 'x', + 'unclosed', + "plain stray close", + ])("leaves other HTML as text: %s", (source) => { + const session = open(`${source}\n`); + expect(markedText(session, "font_size")).toEqual([]); + expect(markedText(session, "font_family")).toEqual([]); + expect(session.session.draftSource).toBe(`${source}\n`); + }); + + it("keeps the outer text size when a size span sits inside another size span", () => { + const source = + 'a x y z\n'; + const session = open(source); + // The outer span stays source, so " z" keeps its meaning and the bytes are unchanged. + expect(markedText(session, "font_size")).toEqual(["y"]); + expect(session.session.draftSource).toBe(source); + }); + + it.each(["x `
` y", "x y", "x a\\
b y"])( + "leaves a span as source when its text hides a closing tag: %s", + (inner) => { + const source = `${inner}\n`; + const session = open(source); + expect(markedText(session, "font_size")).toEqual([]); + expect(session.session.draftSource).toBe(source); + }, + ); + + it("lets a size span sit inside a font span", () => { + const session = open( + `a b c\n`, + ); + expect(markedText(session, "font_family")).toEqual(["a ", "b", " c"]); + expect(markedText(session, "font_size")).toEqual(["b"]); + }); + + it("writes new front matter at the first byte, even before leading blank lines", () => { + const session = open("\n\nHello\n"); + runScientMarkdownDocumentFont({ fontFamily: "Arial", fontSize: "12pt" }, session.state, (tr) => + session.applyTransaction(tr, "user"), + ); + expect(session.session.draftSource).toBe( + "---\nfontsize: 12pt\nmainfont: Arial\n---\n\nHello\n", + ); + }); + + it("applies, replaces and removes a size on a selection, writing the exact span", () => { + const session = open("one two three\n"); + select(session, 4, 7); + run(session, "font-size-14"); + expect(session.session.draftSource).toBe('one two three\n'); + run(session, "font-size-9.5"); + expect(session.session.draftSource).toBe( + 'one two three\n', + ); + run(session, "font-size-default"); + expect(session.session.draftSource).toBe("one two three\n"); + }); + + it("applies a size to the word around a caret, and removes it the same way", () => { + const session = open("one two three\n"); + select(session, 5, 5); + run(session, "font-size-14"); + expect(session.session.draftSource).toBe('one two three\n'); + run(session, "font-size-default"); + expect(session.session.draftSource).toBe("one two three\n"); + }); + + it("keeps a caret between words as typing marks and leaves the text unchanged", () => { + const session = open("one two\n"); + select(session, 4, 4); + run(session, "font-size-14"); + expect(session.session.draftSource).toBe("one two\n"); + expect(session.state.storedMarks?.map((mark) => mark.type.name)).toEqual(["font_size"]); + }); + + it("leaves whitespace at the ends of the selection outside the span", () => { + const session = open("one two three\n"); + select(session, 3, 8); + run(session, "font-size-18"); + expect(session.session.draftSource).toBe('one two three\n'); + }); + + it("never nests two sizes and keeps size and family as separate spans", () => { + const session = open("one two three\n"); + select(session, 4, 7); + run(session, "font-size-24"); + run(session, "font-family-Arial"); + const written = session.session.draftSource; + expect(written.match(/font-size/gu)).toHaveLength(1); + const reopened = open(written); + expect(markedText(reopened, "font_size")).toEqual(["two"]); + expect(markedText(reopened, "font_family")).toEqual(["two"]); + expect(reopened.session.draftSource).toBe(written); + }); + + it("keeps bytes outside the edited range unchanged", () => { + const session = open("# Title\n\nkeep __this__ exactly\n\nsecond paragraph\n"); + session.applyTransaction( + session.state.tr.setSelection(TextSelection.create(session.state.doc, 10, 14)), + "user", + ); + run(session, "font-size-16"); + const written = session.session.draftSource; + expect(written.startsWith("# Title\n\n")).toBe(true); + expect(written.endsWith("\n\nsecond paragraph\n")).toBe(true); + }); + + it("applies a size to every selected table cell", () => { + const session = open("| A | B |\n| --- | --- |\n| c | d |\n"); + const cells: number[] = []; + session.state.doc.descendants((node, position) => { + if (node.type.name === "table_header") cells.push(position); + return node.type.name === "table" || node.type.name === "table_row"; + }); + session.applyTransaction( + session.state.tr.setSelection(CellSelection.create(session.state.doc, cells[0]!, cells[1]!)), + "user", + ); + run(session, "font-size-14"); + expect(markedText(session, "font_size")).toEqual(["A", "B"]); + }); + + it("round-trips a span inside bold, a list item and a table cell", () => { + for (const source of [ + '**a b c**\n', + `- item x\n`, + '| A |\n| --- |\n| t |\n', + ]) { + const session = open(source); + expect( + markedText(session, source.includes("family") ? "font_family" : "font_size"), + ).toHaveLength(1); + const reopened = open(session.session.draftSource); + expect( + markedText(reopened, source.includes("family") ? "font_family" : "font_size"), + ).toHaveLength(1); + } + }); + + it.each([ + '- a x `` y
', + '- a x `` y', + '- [](https://example.com) y', + ])("keeps a block whose span text contains tags in code or links: %s", (block) => { + const source = `${block}\n\nsecond paragraph\n`; + const session = open(source); + // Edit the other paragraph: the block above must come back byte for byte. + session.applyTransaction( + session.state.tr.setSelection( + TextSelection.create(session.state.doc, session.state.doc.content.size - 8), + ), + "user", + ); + session.applyTransaction(session.state.tr.insertText("X"), "user"); + const written = session.session.draftSource; + expect(written).toContain("X"); + expect(written.startsWith(`${block}\n\n`)).toBe(true); + }); + + it("defines both marks in the schema", () => { + expect(scientMarkdownSchema.marks.font_size).toBeDefined(); + expect(scientMarkdownSchema.marks.font_family).toBeDefined(); + }); + + it("ignores pasted HTML whose size or family is not a known size or font", () => { + const parseRule = (markName: "font_size" | "font_family") => { + const rule = scientMarkdownSchema.marks[markName]?.spec.parseDOM?.[0]; + return rule?.getAttrs as (element: { getAttribute: (name: string) => string }) => unknown; + }; + const attribute = (value: string) => ({ getAttribute: () => value }); + expect(parseRule("font_size")(attribute("14"))).toEqual({ size: 14 }); + expect(parseRule("font_size")(attribute("1000"))).toBe(false); + expect(parseRule("font_size")(attribute("x;background:url(https://example.invalid)"))).toBe( + false, + ); + expect(parseRule("font_family")(attribute("Arial"))).toEqual({ family: "Arial" }); + expect(parseRule("font_family")(attribute("Comic Sans MS"))).toBe(false); + expect(parseRule("font_family")(attribute('Arial" onmouseover="alert(1)'))).toBe(false); + }); +}); + +/** Insert text at a text offset of the first paragraph, as typing does (it inherits the marks). */ +function type(session: ScientProseMirrorSession, offset: number, text: string) { + session.applyTransaction(session.state.tr.insertText(text, 1 + offset), "user"); +} + +describe("Whitespace is not styled content", () => { + it("accepts a space typed after a sized word and keeps typing unchanged", () => { + const session = open("un bien mot\n"); + select(session, 3, 7); + run(session, "font-size-14"); + type(session, 7, " "); + expect(session.pendingWriteback).toBeNull(); + expect(session.session.draftSource).toBe('un bien mot\n'); + // The editor still shows the typed space with the size, so typing on continues in it. + expect(markedText(session, "font_size")).toEqual(["bien "]); + }); + + it("accepts a space typed after a bold word", () => { + const session = open("a **b** c\n"); + type(session, 3, " "); + expect(session.pendingWriteback).toBeNull(); + expect(session.session.draftSource).toBe("a **b** c\n"); + }); + + it("accepts italic over two sizes", () => { + const session = open("aa bb cc\n"); + select(session, 0, 2); + run(session, "font-size-14"); + select(session, 3, 5); + run(session, "font-size-20"); + select(session, 1, 4); + run(session, "italic"); + expect(session.pendingWriteback).toBeNull(); + // The space carries no style, and size tags stay outside the italic delimiters. + expect(session.session.draftSource).toBe( + 'a*a* *b*b cc\n', + ); + }); + + it("accepts removing bold from the last word of a bold phrase", () => { + const session = open("**one two**\n"); + select(session, 4, 7); + run(session, "bold"); + expect(session.pendingWriteback).toBeNull(); + expect(session.session.draftSource).toBe("**one** two\n"); + }); + + it("accepts another size on the text after a sized line break", () => { + const session = open("one \ntwo three\n"); + select(session, 0, 13); + run(session, "font-size-14"); + select(session, 4, 9); + run(session, "font-size-20"); + expect(session.pendingWriteback).toBeNull(); + expect(session.session.draftSource).toBe( + 'one\\\ntwo three\n', + ); + }); + + it.each([ + [ + "two line breaks then sized text", + 'ab\\\n\\\ncd\n', + 0, + '\\\n\\\ncd\n', + ], + ["two line breaks then bold text", "**ab\\\n\\\ncd**\n", 0, "\\\n\\\n**cd**\n"], + [ + "two line breaks between two sizes", + 'xab\\\n\\\ncd\n', + 1, + 'x\\\n\\\ncd\n', + ], + ])( + "accepts deleting the text before %s: the whole run of whitespace leaves the tag", + (_name, source, start, expected) => { + const session = open(source); + session.applyTransaction(session.state.tr.delete(1 + start, 1 + start + 2), "user"); + expect(session.pendingWriteback).toBeNull(); + expect(session.session.draftSource).toBe(expected); + }, + ); + + it("accepts a size on two bold words separated by a plain space", () => { + const session = open("**a** **b**\n"); + select(session, 0, 3); + run(session, "font-size-14"); + expect(session.pendingWriteback).toBeNull(); + expect(session.session.draftSource).toBe( + '**a** **b**\n', + ); + expect(markedText(open(session.session.draftSource), "font_size")).toEqual(["a", "b"]); + }); + + it("moves an edge space out of a tag when the paragraph is edited", () => { + const session = open('a two b\n'); + select(session, 3, 6); + run(session, "font-size-20"); + expect(session.pendingWriteback).toBeNull(); + expect(session.session.draftSource).toBe('a two b\n'); + }); + + it("leaves the bytes of an untouched paragraph with edge spaces in its tag", () => { + const source = 'a two b\n\nsecond\n'; + const session = open(source); + session.applyTransaction( + session.state.tr.insertText("X", session.state.doc.content.size - 1), + "user", + ); + expect(session.session.draftSource).toBe(source.replace("second", "secondX")); + }); + + it("applies a size around inline code, never to the code itself", () => { + const session = open("aa `bb` cc\n"); + select(session, 0, 8); + run(session, "font-size-14"); + expect(session.pendingWriteback).toBeNull(); + // The spaces beside the code keep the size on screen; the file writes them outside the tag. + expect(markedText(session, "font_size")).toEqual(["aa ", " cc"]); + expect(session.session.draftSource).toContain("`bb`"); + expect(session.session.draftSource).not.toMatch(/]*>`/u); + }); + + it("does not set a typing size or font inside inline code", () => { + const session = open("aa `bb` cc\n"); + select(session, 4, 4); + run(session, "font-size-14"); + expect(session.state.storedMarks).toBeNull(); + }); +}); + +describe("Size and font shown for a selection", () => { + it("ignores the spaces between words sized one by one", () => { + const session = open("one two three\n"); + for (const [from, to] of [ + [0, 3], + [4, 7], + [8, 13], + ] as const) { + select(session, from, to); + run(session, "font-size-14"); + } + select(session, 0, 13); + expect(selectionMarkValue(session.state, "font_size", "size", "number")).toEqual({ + value: 14, + mixed: false, + }); + }); + + it("still reports a selection that mixes two sizes", () => { + const session = open("one two\n"); + select(session, 0, 3); + run(session, "font-size-14"); + select(session, 4, 7); + run(session, "font-size-20"); + select(session, 0, 7); + expect(selectionMarkValue(session.state, "font_size", "size", "number")).toEqual({ + value: null, + mixed: true, + }); + }); + + it("shows no size for a selection of spaces only", () => { + const session = open("a b\n"); + select(session, 1, 4); + expect(selectionMarkValue(session.state, "font_size", "size", "number")).toEqual({ + value: null, + mixed: false, + }); + }); +}); + +describe("Whitespace rule: other marks and characters", () => { + it("keeps a link whole across bold text when the paragraph is edited", () => { + const session = open("[one **two** three](old.md) end\n"); + type(session, 17, "X"); + expect(session.pendingWriteback).toBeNull(); + expect(session.session.draftSource).toBe("[one **two** three](old.md) endX\n"); + }); + + it("drops the size when inline code is turned on over sized text, and accepts it", () => { + const session = open("aa bb cc\n"); + select(session, 0, 8); + run(session, "font-size-14"); + select(session, 3, 5); + run(session, "inline-code"); + expect(session.pendingWriteback).toBeNull(); + expect(session.session.draftSource).toContain("`bb`"); + expect(markedText(session, "font_size")).not.toContain("bb"); + expect(markedText(session, "code")).toEqual(["bb"]); + }); + + it("does not carry a typing size into inline code turned on at a caret", () => { + const session = open("aa bb\n"); + select(session, 0, 2); + run(session, "font-size-14"); + select(session, 2, 2); + run(session, "inline-code"); + const stored = session.state.storedMarks ?? []; + expect(stored.map((mark) => mark.type.name)).toEqual(["code"]); + }); + + it("sizes a word whose accent is a combining character as a whole", () => { + const session = open("cafe\u0301 ok\n"); + select(session, 2, 2); + run(session, "font-size-14"); + expect(session.session.draftSource).toBe('cafe\u0301 ok\n'); + }); + + it("sizes a Hebrew word and leaves the space after it unsized", () => { + const session = open("שלום עולם\n"); + select(session, 0, 5); + run(session, "font-size-14"); + expect(session.pendingWriteback).toBeNull(); + expect(session.session.draftSource).toBe('שלום עולם\n'); + }); + + it("leaves a non-breaking space at the edge of a selection outside the span", () => { + const session = open("a\u00a0b c\n"); + select(session, 0, 2); + run(session, "font-size-14"); + expect(session.pendingWriteback).toBeNull(); + expect(session.session.draftSource).toBe('a\u00a0b c\n'); + }); + + it("shows the shared size when the selection also holds inline code", () => { + const session = open("aa `bb` cc\n"); + select(session, 0, 8); + run(session, "font-size-14"); + select(session, 0, 8); + expect(selectionMarkValue(session.state, "font_size", "size", "number")).toEqual({ + value: 14, + mixed: false, + }); + }); + + it("accepts deleting the first word of a line after a line break, as at the start of a paragraph", () => { + const session = open("aa bb \ncc dd ee\n"); + session.applyTransaction(session.state.tr.delete(1 + 6, 1 + 8), "user"); + expect(session.pendingWriteback).toBeNull(); + expect(session.session.draftSource).toBe("aa bb\\\n dd ee\n"); + }); + + it("sizes a word with an apostrophe between letters as a whole, but not a lone apostrophe", () => { + const session = open("don't 'x' l\u2019arbre\n"); + select(session, 2, 2); + run(session, "font-size-14"); + expect(markedText(session, "font_size")).toEqual(["don't"]); + select(session, 8, 8); + run(session, "font-size-20"); + expect(markedText(session, "font_size")).toEqual(["don't", "x"]); + select(session, 12, 12); + run(session, "font-size-18"); + expect(markedText(session, "font_size")).toEqual(["don't", "x", "l\u2019arbre"]); + }); +}); + +const SIZE = ''; + +describe("Size and font tags are written outside bold, italic and strike, inside links", () => { + it.each([ + ["un**believ**able", 4, 7, "font-size-14", `un**be**${SIZE}**lie****v**able`], + ["un~~believ~~able", 4, 7, "font-size-14", `un~~be~~${SIZE}~~lie~~
~~v~~able`], + ["un*believ*able", 4, 7, "font-size-14", `un*be*${SIZE}*lie**v*able`], + [`unbel${SIZE}ievable`, 2, 8, "bold", `un**bel**${SIZE}**iev**able`], + ["[abc](https://x.example)", 1, 2, "font-size-14", `[a${SIZE}bc](https://x.example)`], + [ + "**defg**", + 2, + 4, + "font-family-Arial", + `**de****fg**`, + ], + ] as const)("in %s", (source, from, to, command, expected) => { + const session = open(`${source}\n`); + select(session, from, to); + run(session, command); + expect(session.pendingWriteback).toBeNull(); + expect(session.session.draftSource).toBe(`${expected}\n`); + }); +}); diff --git a/apps/web/src/scient/markdownEditor/prosemirror/plugins.ts b/apps/web/src/scient/markdownEditor/prosemirror/plugins.ts index c73e5ad2c7..b3e86ff632 100644 --- a/apps/web/src/scient/markdownEditor/prosemirror/plugins.ts +++ b/apps/web/src/scient/markdownEditor/prosemirror/plugins.ts @@ -22,6 +22,7 @@ import { Plugin, PluginKey, type Command } from "prosemirror-state"; import { goToNextCell, tableEditing } from "prosemirror-tables"; import { scientMarkdownDirectionPresentationPlugin } from "./directionPresentation"; +import { scientMarkdownDocumentFontPlugin } from "./documentFontPresentation"; import { runScientMarkdownCommand } from "./commands"; import { scientMarkdownSchema } from "./schema"; import { imageUploadPlugin } from "./imageUploads"; @@ -128,6 +129,7 @@ export function buildScientMarkdownPlugins(): ReadonlyArray { return [ sourceIdentityPlugin(), scientMarkdownDirectionPresentationPlugin(), + scientMarkdownDocumentFontPlugin(), imageUploadPlugin(), scientMarkdownSearchPlugin(), scientMarkdownOutlinePlugin(), diff --git a/apps/web/src/scient/markdownEditor/prosemirror/projection.ts b/apps/web/src/scient/markdownEditor/prosemirror/projection.ts index f1dd75699f..c905d5e363 100644 --- a/apps/web/src/scient/markdownEditor/prosemirror/projection.ts +++ b/apps/web/src/scient/markdownEditor/prosemirror/projection.ts @@ -4,7 +4,7 @@ import { type MarkdownSourceBlock, type MarkdownSourceLedger, } from "@scientfactory/scient-markdown"; -import type { Node as ProseMirrorNode } from "prosemirror-model"; +import { Fragment, type Node as ProseMirrorNode } from "prosemirror-model"; import { findScientBackslashMathSpans } from "~/scient/math/scientMathText"; import { makeFaithfulMarkdownParse } from "./faithfulParse"; @@ -12,6 +12,7 @@ import { scientMarkdownParser, scientMarkdownSchema, scientMarkdownSerializer, + unstyleBoundaryWhitespace, withMarkdownSourceId, } from "./schema"; @@ -565,6 +566,8 @@ export function projectScientMarkdownSource( if (patched !== null) cache.verified.set(node, source); } cache.sources.set(node, { original, source }); + // A front matter block is valid only at the first byte: new, it replaces the blank prefix. + if (index === 0 && original === undefined && node.attrs.sourceKind === "yaml") output = ""; const from = output.length; output += source; blockRanges.push({ from, to: from + source.length }); @@ -578,6 +581,31 @@ export function projectScientMarkdownSource( return { source: output, blockRanges }; } +/** + * The inline content of a paragraph or heading as the file can state it: whitespace carries no + * style at a style boundary (`unstyleBoundaryWhitespace`), and spaces at the ends of the block + * and next to a line break are dropped (Markdown ignores them). + */ +function fileInlineContent(block: ProseMirrorNode): Fragment { + const joined: ProseMirrorNode[] = []; + unstyleBoundaryWhitespace(block).forEach((child) => joined.push(child)); + const trimmed: ProseMirrorNode[] = []; + joined.forEach((child, index) => { + if (!child.isText) { + trimmed.push(child); + return; + } + let text = child.text ?? ""; + if (index === 0 || joined[index - 1]?.type.name === "hard_break") + text = text.replace(/^[ \t]+/u, ""); + if (index === joined.length - 1 || joined[index + 1]?.type.name === "hard_break") + text = text.replace(/[ \t]+$/u, ""); + if (text !== "") + trimmed.push(text === child.text ? child : child.type.schema.text(text, child.marks)); + }); + return Fragment.fromArray(trimmed); +} + function hasSameWritebackContent(before: ProseMirrorNode, after: ProseMirrorNode): boolean { const metadata = new Set([ "sourceId", @@ -586,7 +614,13 @@ function hasSameWritebackContent(before: ProseMirrorNode, after: ProseMirrorNode "referenceHref", "referenceTitle", ]); - const canonical = (node: ProseMirrorNode, trimEnd = false, trimStart = false): unknown => { + const canonical = (original: ProseMirrorNode): unknown => { + // A table cell keeps its edge spaces in the file (` `), so only its styles are unified. + const node = ["paragraph", "heading"].includes(original.type.name) + ? original.copy(fileInlineContent(original)) + : ["table_cell", "table_header"].includes(original.type.name) + ? original.copy(unstyleBoundaryWhitespace(original)) + : original; const attrs = Object.fromEntries( Object.entries(node.attrs).filter( ([name]) => @@ -595,29 +629,17 @@ function hasSameWritebackContent(before: ProseMirrorNode, after: ProseMirrorNode ), ); if (node.type.name === "image") attrs.alt = attrs.alt ?? ""; - const children = Array.from({ length: node.childCount }, (_, i) => - canonical( - node.child(i), - ["paragraph", "heading"].includes(node.type.name) && i === node.childCount - 1, - ["paragraph", "heading"].includes(node.type.name) && i === 0, - ), - ); return { type: node.type.name, attrs, - text: node.isText - ? (trimStart ? node.text?.replace(/^ +/u, "") : node.text)?.replace( - trimEnd ? / +$/u : /$^/u, - "", - ) - : node.text, + text: node.text, marks: node.marks.map((mark) => ({ type: mark.type.name, attrs: Object.fromEntries( Object.entries(mark.attrs).filter(([name]) => !metadata.has(name)), ), })), - content: children, + content: Array.from({ length: node.childCount }, (_, i) => canonical(node.child(i))), }; }; return JSON.stringify(canonical(before)) === JSON.stringify(canonical(after)); diff --git a/apps/web/src/scient/markdownEditor/prosemirror/roundTripBattery.test.ts b/apps/web/src/scient/markdownEditor/prosemirror/roundTripBattery.test.ts new file mode 100644 index 0000000000..c12ff0469c --- /dev/null +++ b/apps/web/src/scient/markdownEditor/prosemirror/roundTripBattery.test.ts @@ -0,0 +1,141 @@ +// Seeded editing gestures over many paragraph kinds: an edit is refused only for the known family +// left refused on purpose (an emphasis delimiter between a letter and punctuation). Size and font +// tags are written outside other styles, so a delimiter never touches them inside a word. Strike, +// inline code and formulas are not exercised. +import { TextSelection } from "prosemirror-state"; +import { describe, expect, it } from "vite-plus/test"; +import { runScientMarkdownCommand, type ScientMarkdownCommand } from "./commands"; +import { ScientProseMirrorSession } from "./session"; + +const DOCUMENTS: Readonly> = { + plain: "aa bb cc dd ee\n", + twoParagraphs: "aa bb cc\n\ndd ee ff\n", + lineBreak: "aa bb \ncc dd ee\n", + boldItalic: "**aa bb** cc *dd ee* ff\n", + underscores: "__aa bb__ cc _dd ee_ ff\n", + link: "aa [bb cc](https://x.example) dd ee\n", + heading: "# aa bb cc dd ee\n", + bulletList: "- aa bb cc dd ee\n", + orderedList: "1. aa bb cc dd\n", + quote: "> aa bb cc dd ee\n", + table: "| aa bb cc | dd |\n| --- | --- |\n| ee | ff |\n", + footnote: "aa bb[^1] cc dd\n\n[^1]: note\n", + hebrew: "שלום עולם טוב מאוד\n", + punctuation: "aa, bb. cc! (dd) ee?\n", + sizeSpan: 'aa bb cc dd ee\n', + familySpan: "aa bb cc dd ee\n", +}; + +const COMMANDS: readonly ScientMarkdownCommand[] = [ + "font-size-14", + "font-size-20", + "font-size-default", + "font-family-Arial", + "font-family-Georgia", + "font-family-default", + "bold", + "italic", +]; + +const SEQUENCES_PER_DOCUMENT = 120; +const MAX_KNOWN_REFUSALS_PER_DOCUMENT = 5; + +/** + * The known family, tested only on sources the guard already refused: a delimiter between a + * letter and punctuation (CommonMark cannot open or close emphasis there, with or without sizes). + */ +const KNOWN_REFUSAL = /[\p{L}\p{N}](?:\*{1,3}|~~)\p{P}|\p{P}(?:\*{1,3}|~~)[\p{L}\p{N}]/u; + +function firstTextblock(session: ScientProseMirrorSession) { + let found: { start: number; size: number } | null = null; + session.state.doc.descendants((node, position) => { + if (found === null && node.isTextblock) + found = { start: position + 1, size: node.content.size }; + return found === null; + }); + if (found === null) throw new Error("The test document has no text block."); + return found as { start: number; size: number }; +} + +/** mulberry32: a small generator whose outputs are evenly spread, unlike a plain LCG in doubles. */ +function seededRandom(seed: number) { + let state = seed >>> 0; + return (limit: number) => { + state = (state + 0x6d2b79f5) >>> 0; + let t = state; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((((t ^ (t >>> 14)) >>> 0) / 4294967296) * limit) | 0; + }; +} + +describe("round trip of editing gestures", () => { + it.each(Object.entries(DOCUMENTS))( + "refuses nothing but the known family in: %s", + (name, source) => { + // A fixed seed per document keeps the sequences identical on every run. + const random = seededRandom(1000 + name.length * 7919); + const refused: string[] = []; + for (let sequence = 0; sequence < SEQUENCES_PER_DOCUMENT; sequence += 1) { + const session = new ScientProseMirrorSession({ source, revision: "r0" }); + for (let step = 0; step < 1 + random(5); step += 1) { + const { start, size } = firstTextblock(session); + const text = session.state.doc.textBetween(start, start + size, undefined, ""); + const words = [...text.matchAll(/[\p{L}\p{N}_]+/gu)].map( + (m) => [m.index, m.index + m[0].length] as const, + ); + const word = words[random(words.length)] ?? ([0, size] as const); + const gesture = random(100); + const select = (from: number, to: number) => + session.applyTransaction( + session.state.tr.setSelection( + TextSelection.create(session.state.doc, start + from, start + to), + ), + "user", + ); + const apply = () => { + const command = COMMANDS[random(COMMANDS.length)]!; + runScientMarkdownCommand(command, session.state, (tr) => + session.applyTransaction(tr, "user"), + ); + }; + if (gesture < 30) { + select(word[0], word[1]); + apply(); + } else if (gesture < 55) { + const next = + words[Math.min(words.length - 1, words.indexOf(word) + 1 + random(2))] ?? word; + select(word[0], Math.max(word[1], next[1])); + apply(); + } else if (gesture < 65) { + const a = random(size + 1); + const b = random(size + 1); + select(Math.min(a, b), Math.max(a, b)); + apply(); + } else if (gesture < 75) { + const caret = word[0] + random(word[1] - word[0] + 1); + select(caret, caret); + apply(); + } else if (gesture < 90) { + session.applyTransaction( + session.state.tr.insertText(random(2) === 0 ? " " : "xé", start + random(size + 1)), + "user", + ); + } else if (size > 4) { + const from = random(size); + session.applyTransaction( + session.state.tr.delete(start + from, start + Math.min(size, from + 1 + random(3))), + "user", + ); + } + if (session.pendingWriteback) { + refused.push(JSON.stringify(session.pendingWriteback.proposedSource)); + break; + } + } + } + expect(refused.filter((source) => !KNOWN_REFUSAL.test(source))).toEqual([]); + expect(refused.length).toBeLessThanOrEqual(MAX_KNOWN_REFUSALS_PER_DOCUMENT); + }, + ); +}); diff --git a/apps/web/src/scient/markdownEditor/prosemirror/schema.ts b/apps/web/src/scient/markdownEditor/prosemirror/schema.ts index 45f5d48933..c3576d44e1 100644 --- a/apps/web/src/scient/markdownEditor/prosemirror/schema.ts +++ b/apps/web/src/scient/markdownEditor/prosemirror/schema.ts @@ -14,9 +14,16 @@ import type { NodeSpec, SchemaSpec, } from "prosemirror-model"; -import { Schema } from "prosemirror-model"; +import { Fragment, Mark, Schema } from "prosemirror-model"; import { tableNodes } from "prosemirror-tables"; +import { + MARKDOWN_FONT_SPAN_CLOSE, + catalogueFont, + markdownFontSpanOpen, + normalizeFontSize, + parseMarkdownFontSpanOpen, +} from "@scientfactory/scient-markdown"; import { findScientBackslashMathSpans, type ScientBackslashMathSpan, @@ -61,6 +68,67 @@ type InternalMarkdownSerializerStateConstructor = new ( const InternalMarkdownSerializerState = MarkdownSerializerState as unknown as InternalMarkdownSerializerStateConstructor; +/** Marks that `**`, `*`, `~~` and `` cannot open or close on a space. */ +const WHITESPACE_NEUTRAL_MARKS = new Set(["em", "strong", "strike", "font_size", "font_family"]); + +function withoutNeutralMarks(marks: readonly Mark[]): readonly Mark[] { + return marks.filter((mark) => !WHITESPACE_NEUTRAL_MARKS.has(mark.type.name)); +} + +/** + * Whitespace where the styles change loses the `WHITESPACE_NEUTRAL_MARKS` (links and code keep + * it), as the file cannot hold them there; shared by the writer and the round-trip guard. + * Passes repeat until a whole run of spaces and line breaks is unstyled; marks only go, so it ends. + */ +export function unstyleBoundaryWhitespace(block: ProseMirrorNode): Fragment { + let content = block.content; + for (;;) { + const next = unstyleWhitespaceNextToChange(content); + if (next.eq(content)) return next; + content = next; + } +} + +function unstyleWhitespaceNextToChange(content: Fragment): Fragment { + const children: ProseMirrorNode[] = []; + content.forEach((child) => children.push(child)); + const unstyled: ProseMirrorNode[] = []; + children.forEach((child, index) => { + const sameBefore = Mark.sameSet(child.marks, children[index - 1]?.marks ?? Mark.none); + const sameAfter = Mark.sameSet(child.marks, children[index + 1]?.marks ?? Mark.none); + if (child.type.name === "hard_break") { + unstyled.push(sameBefore && sameAfter ? child : child.mark(withoutNeutralMarks(child.marks))); + return; + } + if (!child.isText || (sameBefore && sameAfter)) { + unstyled.push(child); + return; + } + const text = child.text ?? ""; + const lead = sameBefore ? 0 : (/^\s*/u.exec(text)?.[0].length ?? 0); + const tail = sameAfter ? 0 : (/\s*$/u.exec(text.slice(lead))?.[0].length ?? 0); + const edgeMarks = withoutNeutralMarks(child.marks); + for (const [from, to, marks] of [ + [0, lead, edgeMarks], + [lead, text.length - tail, child.marks], + [text.length - tail, text.length, edgeMarks], + ] as const) { + if (from < to) unstyled.push(child.cut(from, to).mark(marks)); + } + }); + return Fragment.fromArray(unstyled); +} + +/** The same document with `unstyleBoundaryWhitespace` applied to every paragraph and heading. */ +function withUnstyledBoundaryWhitespace(node: ProseMirrorNode): ProseMirrorNode { + if (["paragraph", "heading"].includes(node.type.name)) + return node.copy(unstyleBoundaryWhitespace(node)); + if (node.isLeaf || node.isTextblock) return node; + const children: ProseMirrorNode[] = []; + node.forEach((child) => children.push(withUnstyledBoundaryWhitespace(child))); + return node.copy(Fragment.fromArray(children)); +} + class ScientMarkdownSerializer extends MarkdownSerializer { override serialize( content: ProseMirrorNode, @@ -79,7 +147,7 @@ class ScientMarkdownSerializer extends MarkdownSerializer { escapeMarkdown(text, startOfLine) .replace(/(? ["s", 0], }; +const fontSizeSpec: MarkSpec = { + attrs: { size: { default: 12 } }, + parseDOM: [ + { + tag: "span[data-scient-font-size]", + // Pasted HTML is untrusted: only a size inside the allowed range becomes a mark. + getAttrs: (element) => { + const size = normalizeFontSize(Number(element.getAttribute("data-scient-font-size"))); + return size === null ? false : { size }; + }, + }, + ], + toDOM: (mark) => [ + "span", + { style: `font-size:${mark.attrs.size}pt`, "data-scient-font-size": String(mark.attrs.size) }, + 0, + ], +}; + +const fontFamilySpec: MarkSpec = { + attrs: { family: { default: "Times New Roman" } }, + parseDOM: [ + { + tag: "span[data-scient-font-family]", + // Only a name from the catalogue becomes a mark; the CSS never comes from the paste. + getAttrs: (element) => { + const family = element.getAttribute("data-scient-font-family"); + return family !== null && catalogueFont(family) !== null ? { family } : false; + }, + }, + ], + toDOM: (mark) => [ + "span", + { + style: `font-family:${catalogueFont(String(mark.attrs.family))?.css ?? "inherit"}`, + "data-scient-font-family": String(mark.attrs.family), + }, + 0, + ], +}; + const displayMathSpec: NodeSpec = { attrs: { tex: { default: "" }, @@ -451,8 +560,13 @@ if (!linkSpec) throw new Error("Missing ProseMirror mark spec 'link'."); export const scientMarkdownSchema: Schema = new Schema({ nodes, marks: defaultMarkdownParser.schema.spec.marks - .update("link", { ...linkSpec, attrs: { ...linkSpec.attrs, ...referenceAttributes } }) - .addBefore("code", "strike", strikeSpec), + .remove("link") + .addBefore("code", "strike", strikeSpec) + // Rank sets nesting: a link stays whole, and size and font tags go outside bold, italic and + // strike, so their delimiters never touch a span tag inside a word (CommonMark misreads it). + .addToStart("font_family", fontFamilySpec) + .addToStart("font_size", fontSizeSpec) + .addToStart("link", { ...linkSpec, attrs: { ...linkSpec.attrs, ...referenceAttributes } }), } satisfies SchemaSpec); function tableAlignment(token: { readonly attrGet: (name: string) => string | null }): { @@ -519,6 +633,66 @@ gfmTokenizer.inline.ruler.before("html_inline", "scient_hard_break", (state, sil return true; }); +// HTML is disabled, so only the exact font spans the package lists are read here. +// Tokenizing the content between the tags guarantees every open token its close. +const FONT_SPAN_OPEN_TAG = /^]*>/u; +const FONT_SPAN_TAG = /]*>|<\/span>/gu; + +function fontSpanEnd(src: string, from: number, max: number): number { + FONT_SPAN_TAG.lastIndex = from; + let depth = 1; + for (let tag = FONT_SPAN_TAG.exec(src); tag && tag.index < max; tag = FONT_SPAN_TAG.exec(src)) { + depth += tag[0] === "" ? -1 : 1; + if (depth === 0) return tag.index; + } + return -1; +} + +/** + * Whether a span of the same kind (size or family) sits inside `src[from, to)`. A mark of one + * kind cannot nest in itself, so the outer span would lose its font after the inner one closes; + * such text is left as source instead. + */ +function hasNestedSpanOfKind(src: string, from: number, to: number, kind: "size" | "family") { + FONT_SPAN_TAG.lastIndex = from; + for (let tag = FONT_SPAN_TAG.exec(src); tag && tag.index < to; tag = FONT_SPAN_TAG.exec(src)) { + const inner = parseMarkdownFontSpanOpen(tag[0]); + if (inner !== null && kind in inner) return true; + } + return false; +} + +gfmTokenizer.inline.ruler.before("html_inline", "scient_font_span", (state, silent) => { + const tag = FONT_SPAN_OPEN_TAG.exec(state.src.slice(state.pos, state.posMax))?.[0]; + const span = tag === undefined ? null : parseMarkdownFontSpanOpen(tag); + if (tag === undefined || span === null) return false; + const contentStart = state.pos + tag.length; + const contentEnd = fontSpanEnd(state.src, contentStart, state.posMax); + if (contentEnd < 0) return false; + // Code spans, comments and escapes hide tags from a raw scan: such text stays source. + if (/`|