From 3d50c332d2dd1ff80a0b79e8914d17020a4a5b4b Mon Sep 17 00:00:00 2001 From: Tova <291672564+Tova22@users.noreply.github.com> Date: Mon, 9 Nov 2026 09:05:52 +0200 Subject: [PATCH 01/42] Add font family and size to the Markdown and LaTeX Visual editors - Shared Text > Font / Size menu: three generic families, ten sizes. - Markdown: recognised marks on a selection; front matter keys and a Document settings card for the whole document. - LaTeX Visual: menu wired to the existing size and family marks; a Font field in Document settings (\familydefault). - PDF export keeps the recognised span styles before sanitising. Co-Authored-By: Claude Sonnet 5.5 --- .../documentPage/ScientDocumentPage.tsx | 12 ++ .../scient/documentPage/documentFont.test.ts | 73 ++++++++++ .../src/scient/documentPage/documentFont.ts | 67 +++++++++ .../documentPage/scient-document-page.css | 37 +++++ .../scient/latex/LatexDocumentSettings.tsx | 125 +++++++++-------- .../src/scient/latex/LatexVisualEditor.tsx | 11 ++ .../latex/latexDocumentLayoutSettings.ts | 19 +++ .../latex/latexDocumentSettings.test.ts | 23 ++++ .../src/scient/latex/latexEditingTarget.ts | 9 ++ .../web/src/scient/latex/latexFontCommands.ts | 46 +++++++ .../markdownEditor/documentFont.test.ts | 39 ++++++ .../src/scient/markdownEditor/documentFont.ts | 64 +++++++++ .../markdownEditor/prosemirror/commands.ts | 86 ++++++++++++ .../prosemirror/documentFontPresentation.ts | 20 +++ .../prosemirror/fontStyles.test.ts | 128 ++++++++++++++++++ .../markdownEditor/prosemirror/plugins.ts | 2 + .../markdownEditor/prosemirror/schema.ts | 103 +++++++++++++- .../scient/markdownEditor/prosemirror/view.ts | 35 +++++ .../markdownEditor/scient-markdown-editor.css | 35 +++++ .../ui/MarkdownDocumentSettings.tsx | 111 +++++++++++++++ .../ui/ScientMarkdownControls.tsx | 42 ++++++ .../scient/writing/DocumentSettingsField.tsx | 14 ++ apps/web/src/scient/writing/FontMenuItems.tsx | 67 +++++++++ apps/web/src/scient/writing/TextMenu.tsx | 2 + apps/web/src/scient/writing/fontChoices.ts | 45 ++++++ packages/scient-markdown/src/fontSpans.ts | 59 ++++++++ packages/scient-markdown/src/index.ts | 12 ++ .../scient-markdown/src/sourceLedger.test.ts | 12 ++ packages/scient-markdown/src/sourceLedger.ts | 39 +++++- 29 files changed, 1273 insertions(+), 64 deletions(-) create mode 100644 apps/web/src/scient/documentPage/documentFont.test.ts create mode 100644 apps/web/src/scient/documentPage/documentFont.ts create mode 100644 apps/web/src/scient/latex/latexFontCommands.ts create mode 100644 apps/web/src/scient/markdownEditor/documentFont.test.ts create mode 100644 apps/web/src/scient/markdownEditor/documentFont.ts create mode 100644 apps/web/src/scient/markdownEditor/prosemirror/documentFontPresentation.ts create mode 100644 apps/web/src/scient/markdownEditor/prosemirror/fontStyles.test.ts create mode 100644 apps/web/src/scient/markdownEditor/ui/MarkdownDocumentSettings.tsx create mode 100644 apps/web/src/scient/writing/DocumentSettingsField.tsx create mode 100644 apps/web/src/scient/writing/FontMenuItems.tsx create mode 100644 apps/web/src/scient/writing/fontChoices.ts create mode 100644 packages/scient-markdown/src/fontSpans.ts diff --git a/apps/web/src/scient/documentPage/ScientDocumentPage.tsx b/apps/web/src/scient/documentPage/ScientDocumentPage.tsx index 13944ada91..5d87691e3f 100644 --- a/apps/web/src/scient/documentPage/ScientDocumentPage.tsx +++ b/apps/web/src/scient/documentPage/ScientDocumentPage.tsx @@ -31,6 +31,12 @@ import { scientMathMarkdownText, scientMathRemarkPluginsForMessage } from "../ma import { resolveScientRichFenceKind } from "../presentation/scientRichFenceKind"; import { scientMarkdownRemarkPlugins } from "../markdown/scientMarkdownProfiles"; import type { DocumentPageTracker } from "./documentPageReadiness"; +import { + DOCUMENT_FONT_SANITIZE_ATTRIBUTES, + documentFontOfMarkdown, + rehypeApplyFontSpans, + rehypeMarkFontSpans, +} from "./documentFont"; import { remarkDocumentFrontMatter } from "./remarkDocumentFrontMatter"; import "../bidi/scient-bidi.css"; @@ -75,6 +81,7 @@ const DOCUMENT_SANITIZE_SCHEMA = { attributes: { ...defaultSchema.attributes, blockquote: [...(defaultSchema.attributes?.blockquote ?? []), "dataAlert"], + span: [...(defaultSchema.attributes?.span ?? []), ...DOCUMENT_FONT_SANITIZE_ATTRIBUTES.span], }, protocols: { ...defaultSchema.protocols, @@ -500,6 +507,7 @@ export function ScientDocumentPage(props: ScientDocumentPageProps) { input.markdown, ); const direction = resolveMarkdownDirection(input.markdown, input.direction); + const documentFont = documentFontOfMarkdown(input.markdown); const context = { assets: new Map(input.assets.map((asset) => [asset.id, asset])), assetBaseUrl: props.inputUrl, @@ -509,7 +517,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 +536,8 @@ 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} > { + 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( + 'style="font-family:serif,', + ); + }); + + it.each([ + '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("3em"); + 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\nfont-size: 12pt\nfont-family: monospace\n---\n\ntext"), + ).toEqual({ fontFamily: "monospace", fontSize: "12pt" }); + expect(documentFontOfMarkdown("text\n\n---\nfont-size: 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..e5cbf7c8ce --- /dev/null +++ b/apps/web/src/scient/documentPage/documentFont.ts @@ -0,0 +1,67 @@ +import { + MARKDOWN_FONT_SIZES, + markdownFontSpanStyle, + parseMarkdownFontSpanStyle, +} from "@scientfactory/scient-markdown"; +import { readMarkdownDocumentFont } from "../markdownEditor/documentFont"; +import { isFontFamilyName } from "../writing/fontChoices"; + +/** + * 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 size = properties.dataScientFontSize; + const family = properties.dataScientFontFamily; + delete properties.dataScientFontSize; + delete properties.dataScientFontFamily; + const sizeName = MARKDOWN_FONT_SIZES.find(({ name }) => name === size)?.name; + if (sizeName !== undefined) { + properties.style = markdownFontSpanStyle({ size: sizeName }); + } else if (typeof family === "string" && isFontFamilyName(family)) { + properties.style = `font-family:${family}, "Noto Sans Hebrew", "Arial Hebrew", "Noto Sans Arabic"`; + } + }); +} + +/** The leading `---` block of the document, if it starts with one. */ +export function documentFontOfMarkdown(markdown: string) { + const front = /^---[ \t]*\r?\n[\s\S]*?\r?\n---[ \t]*(?:\r?\n|$)/u.exec(markdown); + return readMarkdownDocumentFont(front?.[0] ?? null); +} diff --git a/apps/web/src/scient/documentPage/scient-document-page.css b/apps/web/src/scient/documentPage/scient-document-page.css index f857ef20e4..3943ed9b12 100644 --- a/apps/web/src/scient/documentPage/scient-document-page.css +++ b/apps/web/src/scient/documentPage/scient-document-page.css @@ -92,6 +92,43 @@ 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="serif"] { + font-family: serif, "Noto Sans Hebrew", "Arial Hebrew", "Noto Sans Arabic"; +} +.scient-document[data-scient-font-family="sans-serif"] { + font-family: sans-serif, "Noto Sans Hebrew", "Arial Hebrew", "Noto Sans Arabic"; +} +.scient-document[data-scient-font-family="monospace"] { + font-family: + ui-monospace, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace, "Noto Sans Hebrew", + "Arial Hebrew"; +} + .scient-document :where(p, ul, ol, blockquote, .scient-document-table, figure) { margin: 0 0 0.8em; } diff --git a/apps/web/src/scient/latex/LatexDocumentSettings.tsx b/apps/web/src/scient/latex/LatexDocumentSettings.tsx index 822e23387f..e19e991a3f 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 { 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 { FONT_FAMILIES } from "../writing/fontChoices"; 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. @@ -232,7 +224,7 @@ export function LatexDocumentSettings(props: { >
- + - - + + ({ value: String(size), label: `${size} pt` }))} /> - - + + - +
- + + ({ value: family.name, label: family.label })), + ]} + onValueChange={(value) => + setLayout("fontFamily", value as DocumentLayoutSettings["fontFamily"]) + } + /> + + - - + + - - + + - - + + - + {marginChoice === "custom" ? (
{SIDES.map((side) => { const name = side[0]!.toUpperCase() + side.slice(1); return ( - + setSide(side, event.target.value)} /> - + ); })}
@@ -386,7 +393,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 +426,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 +460,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 +509,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 +607,7 @@ export function LatexDocumentSettings(props: { .replaceAll("\\rightmark", ""), ); return ( - + - + ); })} - + - - + + - + {(changes.mirroredMargins ?? extended.mirroredMargins) && (
@@ -675,14 +682,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..ab247ea891 100644 --- a/apps/web/src/scient/latex/LatexVisualEditor.tsx +++ b/apps/web/src/scient/latex/LatexVisualEditor.tsx @@ -1,7 +1,9 @@ import type { PagedTableLayout } from "./latexPagedGeometry"; import { resolvedLatexFontSize } from "./latexVisualLayout"; import { latexSelectionClipboard } from "./latexClipboard"; +import { FontMenuItems } from "../writing/FontMenuItems"; import { TextMenu, TextMenuItems } from "../writing/TextMenu"; +import { setLatexFontFamily, setLatexFontSize } from "./latexFontCommands"; import { LatexDirectionMenuItems } from "./LatexDirectionMenuItems"; import { mathColorSource } from "./mathColorSyntax"; import { LatexStructuredSelection } from "./latexStructuredSelection"; @@ -9653,6 +9655,15 @@ function LatexVisualEditorReady( const writingTextContents = { paragraphStyle: writingStyleItems, formatting: writingFormattingItems, + font: ( + setLatexFontFamily(editingTarget, family)} + onSize={(size) => setLatexFontSize(editingTarget, size)} + /> + ), direction: ( /^(?:\d+(?:\.\d*)?|\.\d+)\s*(?:in|cm|mm|pt|bp|em|ex)$/u.test(value.trim()); const plain = (value: string) => !/[\\{}%#$&_~^\r\n]/u.test(value); @@ -56,6 +62,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 +91,9 @@ export function documentLayoutSettings(source: string) { gutter: `${profile.bindingOffsetIn.toFixed(4)}in`, mirroredMargins: profile.twoSided, engine, + fontFamily: (Object.entries(FAMILY_DEFAULTS).find( + ([, command]) => command === familyDefault, + )?.[0] ?? "default") as NonNullable, mainFont: latexDocumentLanguage(source).mainFont ?? family("main"), sansFont: family("sans"), monoFont: family("mono"), @@ -254,6 +264,15 @@ export function updateDocumentLayoutSettings( update.alignment === "left" ? "\\RaggedRight" : "\\justifying", ); } + if (update.fontFamily === "default") { + const end = latexPreambleEnd(result); + result = result.slice(0, end).replace(FAMILY_DEFAULT_PATTERN, "") + result.slice(end); + } else if (update.fontFamily !== undefined) { + replace( + FAMILY_DEFAULT_PATTERN, + `\\renewcommand{\\familydefault}{\\${FAMILY_DEFAULTS[update.fontFamily]}}`, + ); + } if (update.engine !== undefined) { if ( update.engine === "pdflatex" && diff --git a/apps/web/src/scient/latex/latexDocumentSettings.test.ts b/apps/web/src/scient/latex/latexDocumentSettings.test.ts index 73d37d33ca..1d94435cf1 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,25 @@ 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"); + }); +}); diff --git a/apps/web/src/scient/latex/latexEditingTarget.ts b/apps/web/src/scient/latex/latexEditingTarget.ts index 0c3b8030dc..2da15ab0ba 100644 --- a/apps/web/src/scient/latex/latexEditingTarget.ts +++ b/apps/web/src/scient/latex/latexEditingTarget.ts @@ -2,6 +2,8 @@ import type { Editor } from "@tiptap/core"; import { createContext, useState, useSyncExternalStore } from "react"; import { NodeSelection, type EditorState } from "@tiptap/pm/state"; import { countSelectedWords } from "../writing/caretStatus"; +import type { FontFamilyName, FontSizeName } from "../writing/fontChoices"; +import { latexFontState } from "./latexFontCommands"; export const LatexInlineOwnerContext = createContext(null); @@ -137,11 +139,14 @@ interface EditingPresentation { bold: boolean; italic: boolean; code: boolean; + fontFamily: FontFamilyName | null; + fontSize: FontSizeName | null; selectedWords: number | null; } function editingPresentation(editor: Editor | null): EditingPresentation { const selection = editor?.state.selection; + const font = latexFontState(editor); return { formattingAvailable: Boolean( editor?.isEditable && @@ -152,6 +157,8 @@ function editingPresentation(editor: Editor | null): EditingPresentation { bold: editor?.isActive("bold") ?? false, italic: editor?.isActive("italic") ?? false, code: editor?.isActive("code") ?? false, + fontFamily: font.family, + fontSize: font.size, selectedWords: editor ? countSelectedWords(editor.state) : null, }; } @@ -161,6 +168,8 @@ const sameEditingPresentation = (before: EditingPresentation, after: EditingPres before.bold === after.bold && before.italic === after.italic && before.code === after.code && + before.fontFamily === after.fontFamily && + before.fontSize === after.fontSize && before.selectedWords === after.selectedWords; /** Typing at a collapsed caret need not render unchanged controls. Selection, diff --git a/apps/web/src/scient/latex/latexFontCommands.ts b/apps/web/src/scient/latex/latexFontCommands.ts new file mode 100644 index 0000000000..23ae527fe7 --- /dev/null +++ b/apps/web/src/scient/latex/latexFontCommands.ts @@ -0,0 +1,46 @@ +import type { Editor } from "@tiptap/core"; +import { + FONT_FAMILIES, + FONT_SIZES, + type FontFamilyName, + type FontSizeName, +} from "../writing/fontChoices"; + +/** Generic family to the LaTeX Visual mark that writes it (`\textrm`, `\textsf`, `\texttt`). */ +const FAMILY_MARKS: Readonly> = { + serif: "latexRoman", + "sans-serif": "latexSans", + monospace: "code", +}; + +const sizeMark = (size: FontSizeName) => `latexSize_${size}`; + +/** The size and family shared by the whole selection; null when none or mixed. */ +export function latexFontState(editor: Editor | null): { + readonly size: FontSizeName | null; + readonly family: FontFamilyName | null; +} { + if (!editor) return { size: null, family: null }; + return { + size: FONT_SIZES.find(({ name }) => editor.isActive(sizeMark(name)))?.name ?? null, + family: FONT_FAMILIES.find(({ name }) => editor.isActive(FAMILY_MARKS[name]))?.name ?? null, + }; +} + +/** A size replaces the previous one, as in LaTeX; null returns to the document default. */ +export function setLatexFontSize(editor: Editor | null, size: FontSizeName | null): boolean { + if (!editor) return false; + let chain = editor.chain().focus(); + for (const { name } of FONT_SIZES) chain = chain.unsetMark(sizeMark(name)); + if (size) chain = chain.setMark(sizeMark(size)); + return chain.run(); +} + +/** A family replaces the previous one; null returns to the document default. */ +export function setLatexFontFamily(editor: Editor | null, family: FontFamilyName | null): boolean { + if (!editor) return false; + let chain = editor.chain().focus(); + for (const { name } of FONT_FAMILIES) chain = chain.unsetMark(FAMILY_MARKS[name]); + if (family) chain = chain.setMark(FAMILY_MARKS[family]); + return chain.run(); +} 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..eb34658db5 --- /dev/null +++ b/apps/web/src/scient/markdownEditor/documentFont.test.ts @@ -0,0 +1,39 @@ +import { describe, expect, it } from "vite-plus/test"; +import { + 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, and ignores unknown values", () => { + expect( + readMarkdownDocumentFont('---\ntitle: T\nfont-size: "11pt"\nfont-family: sans-serif\n---'), + ).toEqual({ fontFamily: "sans-serif", fontSize: "11pt" }); + expect(readMarkdownDocumentFont("---\nfont-size: 14pt\nfont-family: Arial\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: "serif", fontSize: "12pt" })).toBe( + "---\nfont-size: 12pt\nfont-family: serif\n---", + ); + expect(writeMarkdownDocumentFont(null, none)).toBeNull(); + }); + + it("keeps other keys, order and line endings", () => { + const source = "---\r\ntitle: T\r\nfont-size: 10pt\r\ntags: [a]\r\n---"; + expect(writeMarkdownDocumentFont(source, { fontFamily: "monospace", fontSize: "12pt" })).toBe( + "---\r\ntitle: T\r\ntags: [a]\r\nfont-size: 12pt\r\nfont-family: monospace\r\n---", + ); + }); + + it("removes the block when the last key goes, and refuses TOML", () => { + expect(writeMarkdownDocumentFont("---\nfont-size: 10pt\n---", none)).toBeNull(); + expect( + writeMarkdownDocumentFont("+++\ntitle = 'T'\n+++", { fontFamily: "serif", fontSize: null }), + ).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..7bb51d3f7c --- /dev/null +++ b/apps/web/src/scient/markdownEditor/documentFont.ts @@ -0,0 +1,64 @@ +import { FONT_FAMILIES, type FontFamilyName } from "../writing/fontChoices"; + +/** + * Whole-document font settings of a Markdown file, kept as two keys of its + * leading YAML front matter (`font-size: 11pt`, `font-family: serif`). The + * sizes match the LaTeX Document settings card. + */ +export const DOCUMENT_FONT_SIZES = ["10pt", "11pt", "12pt"] as const; +export type DocumentFontSize = (typeof DOCUMENT_FONT_SIZES)[number]; + +export interface MarkdownDocumentFont { + readonly fontFamily: FontFamilyName | null; + readonly fontSize: DocumentFontSize | null; +} + +// 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 FONT_KEYS = /^font-(?:size|family)[ \t]*:/u; + +function unquote(value: string): string { + return value.trim().replace(/^(["'])(.*)\1$/u, "$2"); +} + +function keyValue(lines: readonly string[], key: string): string | null { + const line = lines.find( + (candidate) => candidate.startsWith(`${key}:`) || candidate.startsWith(`${key} :`), + ); + return line === undefined ? null : unquote(line.slice(line.indexOf(":") + 1)); +} + +export function readMarkdownDocumentFont(frontMatter: string | null): MarkdownDocumentFont { + const match = frontMatter === null ? null : YAML_FRONT_MATTER.exec(frontMatter); + const lines = match?.[3]?.split(/\r?\n/u) ?? []; + const size = keyValue(lines, "font-size"); + const family = keyValue(lines, "font-family"); + return { + fontSize: DOCUMENT_FONT_SIZES.find((candidate) => candidate === size) ?? null, + fontFamily: FONT_FAMILIES.find((candidate) => candidate.name === family)?.name ?? null, + }; +} + +/** + * The front matter block after applying `font`, or null when it would be + * empty (the block is then removed). Other keys and the text around the block + * are kept as they are; undefined when the block is not YAML. + */ +export function writeMarkdownDocumentFont( + frontMatter: string | null, + font: MarkdownDocumentFont, +): string | null | undefined { + const wanted = [ + ...(font.fontSize ? [`font-size: ${font.fontSize}`] : []), + ...(font.fontFamily ? [`font-family: ${font.fontFamily}`] : []), + ]; + if (frontMatter === null) return wanted.length ? `---\n${wanted.join("\n")}\n---` : null; + const match = YAML_FRONT_MATTER.exec(frontMatter); + if (!match) return undefined; + const [, open, eol, body = "", close, after = ""] = match; + const kept = body.split(/\r?\n/u).filter((line) => line !== "" && !FONT_KEYS.test(line)); + const lines = [...kept, ...wanted]; + if (lines.length === 0) return null; + const newline = eol ?? "\n"; + 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..67bd8328a1 100644 --- a/apps/web/src/scient/markdownEditor/prosemirror/commands.ts +++ b/apps/web/src/scient/markdownEditor/prosemirror/commands.ts @@ -33,6 +33,12 @@ import { scientMarkdownSchema } from "./schema"; import { selectMarkdownTable } from "./tables"; import { nextScientMarkdownFootnoteLabel } from "../footnotes"; import { WRITING_COMMAND_LABELS } from "../../writing/commandNames"; +import type { FontFamilyName, FontSizeName } from "../../writing/fontChoices"; +import { + readMarkdownDocumentFont, + writeMarkdownDocumentFont, + type MarkdownDocumentFont, +} from "../documentFont"; export type ScientMarkdownCommand = | "add-column-after" @@ -55,6 +61,8 @@ export type ScientMarkdownCommand = | "direction-rtl" | "display-math" | "footnote" + | `font-family-${FontFamilyName | "default"}` + | `font-size-${FontSizeName | "default"}` | "clear-formatting" | "hard-break" | "heading-1" @@ -481,6 +489,82 @@ function clearMarkdownFormatting(): Command { }; } +/** Set one font mark on the selection (or the typing marks at a caret); `null` removes it. */ +function setMarkdownFontMark(markName: string, attrs: Attrs | null): Command { + return (state, dispatch) => { + if (!dispatch) return true; + const type = requiredMarkType(markName); + const { from, to, empty, $from } = state.selection; + if (empty) { + const kept = (state.storedMarks ?? $from.marks()).filter((mark) => mark.type !== type); + dispatch(state.tr.setStoredMarks(attrs ? type.create(attrs).addToSet(kept) : kept)); + return true; + } + let transaction = state.tr.removeMark(from, to, type); + if (attrs) { + // Like toggleMark: the written span cannot keep whitespace at its ends. + const isSpace = (at: number) => /^\s$/u.test(state.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; + transaction = transaction.addMark(start, end, type.create(attrs)); + } + dispatch(transaction); + return true; + }; +} + +function fontCommand( + command: `font-family-${FontFamilyName | "default"}` | `font-size-${FontSizeName | "default"}`, +): Command { + const [, kind, value] = /^font-(size|family)-(.+)$/u.exec(command) ?? []; + const attrs = value === "default" ? null : kind === "size" ? { size: value } : { family: value }; + return setMarkdownFontMark(kind === "size" ? "font_size" : "font_family", attrs); +} + +/** 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); + return front === null || front.attrs.sourceKind === "yaml"; +} + +/** 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) => { @@ -593,6 +677,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); } } 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..60859b186b --- /dev/null +++ b/apps/web/src/scient/markdownEditor/prosemirror/documentFontPresentation.ts @@ -0,0 +1,20 @@ +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; 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 } : {}), + }; + }, + }, + }); +} 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..6979913b19 --- /dev/null +++ b/apps/web/src/scient/markdownEditor/prosemirror/fontStyles.test.ts @@ -0,0 +1,128 @@ +import { TextSelection } from "prosemirror-state"; +import { describe, expect, it } from "vite-plus/test"; +import { runScientMarkdownCommand, type ScientMarkdownCommand } from "./commands"; +import { scientMarkdownSchema } from "./schema"; +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("large"); + }); + + it.each([ + '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("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-large"); + expect(session.session.draftSource).toBe( + 'one two three\n', + ); + run(session, "font-size-small"); + expect(session.session.draftSource).toBe( + 'one two three\n', + ); + run(session, "font-size-default"); + expect(session.session.draftSource).toBe("one two three\n"); + }); + + 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-LARGE"); + 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-huge"); + run(session, "font-family-sans-serif"); + 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-Large"); + const written = session.session.draftSource; + expect(written.startsWith("# Title\n\n")).toBe(true); + expect(written.endsWith("\n\nsecond paragraph\n")).toBe(true); + }); + + 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("defines both marks in the schema", () => { + expect(scientMarkdownSchema.marks.font_size).toBeDefined(); + expect(scientMarkdownSchema.marks.font_family).toBeDefined(); + }); +}); 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/schema.ts b/apps/web/src/scient/markdownEditor/prosemirror/schema.ts index 45f5d48933..bfcaa61d22 100644 --- a/apps/web/src/scient/markdownEditor/prosemirror/schema.ts +++ b/apps/web/src/scient/markdownEditor/prosemirror/schema.ts @@ -17,6 +17,14 @@ import type { import { Schema } from "prosemirror-model"; import { tableNodes } from "prosemirror-tables"; +import { + MARKDOWN_FONT_SIZES, + MARKDOWN_FONT_SPAN_CLOSE, + markdownFontSpanOpen, + parseMarkdownFontSpanOpen, + type MarkdownFontFamilyName, + type MarkdownFontSizeName, +} from "@scientfactory/scient-markdown"; import { findScientBackslashMathSpans, type ScientBackslashMathSpan, @@ -233,6 +241,42 @@ const strikeSpec: MarkSpec = { toDOM: () => ["s", 0], }; +const fontSizeSpec: MarkSpec = { + attrs: { size: { default: "normalsize" } }, + parseDOM: [ + { + tag: "span[data-scient-font-size]", + getAttrs: (element) => ({ size: element.getAttribute("data-scient-font-size") }), + }, + ], + toDOM: (mark) => [ + "span", + { + style: `font-size:${MARKDOWN_FONT_SIZES.find(({ name }) => name === mark.attrs.size)?.em}em`, + "data-scient-font-size": String(mark.attrs.size), + }, + 0, + ], +}; + +const fontFamilySpec: MarkSpec = { + attrs: { family: { default: "serif" } }, + parseDOM: [ + { + tag: "span[data-scient-font-family]", + getAttrs: (element) => ({ family: element.getAttribute("data-scient-font-family") }), + }, + ], + toDOM: (mark) => [ + "span", + { + style: `font-family:${String(mark.attrs.family)}`, + "data-scient-font-family": String(mark.attrs.family), + }, + 0, + ], +}; + const displayMathSpec: NodeSpec = { attrs: { tex: { default: "" }, @@ -452,7 +496,9 @@ export const scientMarkdownSchema: Schema = new Schema({ nodes, marks: defaultMarkdownParser.schema.spec.marks .update("link", { ...linkSpec, attrs: { ...linkSpec.attrs, ...referenceAttributes } }) - .addBefore("code", "strike", strikeSpec), + .addBefore("code", "strike", strikeSpec) + .addBefore("code", "font_size", fontSizeSpec) + .addBefore("code", "font_family", fontFamilySpec), } satisfies SchemaSpec); function tableAlignment(token: { readonly attrGet: (name: string) => string | null }): { @@ -519,6 +565,45 @@ 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; +} + +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; + if (!silent) { + const kind = "size" in span ? "font_size" : "font_family"; + const open = state.push(`${kind}_open`, "span", 1); + open.meta = span; + const oldPos = state.pos; + const oldMax = state.posMax; + state.pos = contentStart; + state.posMax = contentEnd; + state.md.inline.tokenize(state); + state.pos = oldPos; + state.posMax = oldMax; + state.push(`${kind}_close`, "span", -1); + } + state.pos = contentEnd + MARKDOWN_FONT_SPAN_CLOSE.length; + return true; +}); + // TeX-style delimiters are source syntax, not preprocessing. Recognizing them // here keeps the file bytes and ProseMirror positions aligned while sharing the // same code/HTML exclusions as the established Markdown preview. @@ -736,6 +821,8 @@ export const scientMarkdownParser = new MarkdownParser(scientMarkdownSchema, gfm }), }, s: { mark: "strike" }, + font_size: { mark: "font_size", getAttrs: (token) => ({ size: token.meta.size }) }, + font_family: { mark: "font_family", getAttrs: (token) => ({ family: token.meta.family }) }, scient_inline_math: { node: "inline_math", getAttrs: (token) => ({ @@ -925,6 +1012,20 @@ export const scientMarkdownSerializer = new ScientMarkdownSerializer( return typeof close === "string" ? close : close(state, mark, parent, index); }, }, + font_size: { + open: (_state, mark) => + markdownFontSpanOpen({ size: mark.attrs.size as MarkdownFontSizeName }), + close: MARKDOWN_FONT_SPAN_CLOSE, + expelEnclosingWhitespace: true, + mixable: true, + }, + font_family: { + open: (_state, mark) => + markdownFontSpanOpen({ family: mark.attrs.family as MarkdownFontFamilyName }), + close: MARKDOWN_FONT_SPAN_CLOSE, + expelEnclosingWhitespace: true, + mixable: true, + }, strike: { close: "~~", expelEnclosingWhitespace: true, diff --git a/apps/web/src/scient/markdownEditor/prosemirror/view.ts b/apps/web/src/scient/markdownEditor/prosemirror/view.ts index 1b2c7ddc99..9eb6d055e2 100644 --- a/apps/web/src/scient/markdownEditor/prosemirror/view.ts +++ b/apps/web/src/scient/markdownEditor/prosemirror/view.ts @@ -40,9 +40,13 @@ import type { ScientMarkdownImageNodeViewOptions, ScientMarkdownImageNodeViewRegistration, } from "../nodes/imageNodeView"; +import type { MarkdownDocumentFont } from "../documentFont"; import { + documentFontEditable, + documentFontOf, filterScientMarkdownSlashCommands, runScientMarkdownCommand, + runScientMarkdownDocumentFont, runScientMarkdownTableInsert, type ScientMarkdownCommand, type ScientMarkdownTableDimensions, @@ -141,6 +145,8 @@ export interface ScientMarkdownEditorSnapshot { readonly canRedo: boolean; readonly canSetWikiLink: boolean; readonly canUndo: boolean; + readonly documentFont: MarkdownDocumentFont; + readonly documentFontEditable: boolean; readonly editable: boolean; readonly headingLevel: number | null; readonly findActiveIndex: number; @@ -149,6 +155,8 @@ export interface ScientMarkdownEditorSnapshot { readonly findMatchCount: number; readonly findOpen: boolean; readonly findQuery: string; + readonly fontFamily: string | null; + readonly fontSize: string | null; readonly findWholeWord: boolean; readonly inTable: boolean; readonly listKind: "bullet" | "ordered" | "task" | null; @@ -618,6 +626,12 @@ export class ScientMarkdownEditorView { return handled; } + setDocumentFont(font: MarkdownDocumentFont): boolean { + const view = this.editorView; + if (!view || !modeIsEditable(this.mode)) return false; + return runScientMarkdownDocumentFont(font, view.state, view.dispatch); + } + insertTable(dimensions: ScientMarkdownTableDimensions): boolean { const view = this.editorView; if (!view || !modeIsEditable(this.mode)) return false; @@ -1705,6 +1719,23 @@ export class ScientMarkdownEditorView { : state.doc.rangeHasMark(selection.from, selection.to, mark), ) .map((mark) => mark.name); + // The shared value of a mark attribute over the selection; null when none or mixed. + const markAttribute = (markName: string, attribute: string) => { + const type = scientMarkdownSchema.marks[markName]!; + if (selection.empty) { + const mark = (state.storedMarks ?? selection.$from.marks()).find((m) => m.type === type); + return typeof mark?.attrs[attribute] === "string" + ? (mark.attrs[attribute] as string) + : null; + } + const values = new Set(); + state.doc.nodesBetween(selection.from, selection.to, (node) => { + if (!node.isText) return; + const value = node.marks.find((m) => m.type === type)?.attrs[attribute]; + values.add(typeof value === "string" ? value : null); + }); + return values.size === 1 ? ([...values][0] ?? null) : null; + }; let blockType = selection.$from.parent.type.name; let headingLevel: number | null = blockType === "heading" ? Number(selection.$from.parent.attrs.level) : null; @@ -1763,6 +1794,8 @@ export class ScientMarkdownEditorView { canRedo: redoDepth(state) > 0, canSetWikiLink: modeIsEditable(this.mode) && wikiLinkSelection !== null, canUndo: undoDepth(state) > 0, + documentFont: documentFontOf(state.doc), + documentFontEditable: documentFontEditable(state.doc), editable: modeIsEditable(this.mode), findActiveIndex: find.activeIndex, findCaseSensitive: find.caseSensitive, @@ -1770,6 +1803,8 @@ export class ScientMarkdownEditorView { findMatchCount: find.matches.length, findOpen: this.findOpen, findQuery: find.query, + fontFamily: markAttribute("font_family", "family"), + fontSize: markAttribute("font_size", "size"), findWholeWord: find.wholeWord, headingLevel, inTable, diff --git a/apps/web/src/scient/markdownEditor/scient-markdown-editor.css b/apps/web/src/scient/markdownEditor/scient-markdown-editor.css index 91269adc56..6b80a86e03 100644 --- a/apps/web/src/scient/markdownEditor/scient-markdown-editor.css +++ b/apps/web/src/scient/markdownEditor/scient-markdown-editor.css @@ -245,6 +245,41 @@ color: var(--contrast-muted-foreground); } +/* Whole-document font from the front matter (see documentFontPresentation.ts). */ +.scient-markdown-document[data-scient-font-size="10pt"] { + --scient-markdown-size-scale: 1; +} +.scient-markdown-document[data-scient-font-size="11pt"] { + --scient-markdown-size-scale: 1.1; +} +.scient-markdown-document[data-scient-font-size="12pt"] { + --scient-markdown-size-scale: 1.2; +} +.scient-markdown-document[data-scient-font-size] { + font-size: calc(var(--scient-font-size-markdown-body) * var(--scient-markdown-size-scale)); +} +.scient-markdown-document[data-scient-font-size] h1 { + font-size: calc(var(--scient-font-size-markdown-h1) * var(--scient-markdown-size-scale)); +} +.scient-markdown-document[data-scient-font-size] h2 { + font-size: calc(var(--scient-font-size-markdown-h2) * var(--scient-markdown-size-scale)); +} +.scient-markdown-document[data-scient-font-size] h3 { + font-size: calc(var(--scient-font-size-markdown-h3) * var(--scient-markdown-size-scale)); +} +.scient-markdown-document[data-scient-font-size] :is(h4, h5, h6) { + font-size: calc(var(--scient-font-size-markdown-body) * var(--scient-markdown-size-scale)); +} +.scient-markdown-document[data-scient-font-family="serif"] { + font-family: serif; +} +.scient-markdown-document[data-scient-font-family="sans-serif"] { + font-family: sans-serif; +} +.scient-markdown-document[data-scient-font-family="monospace"] { + font-family: var(--font-mono); +} + .scient-markdown-document p, .scient-markdown-document ul, .scient-markdown-document ol, diff --git a/apps/web/src/scient/markdownEditor/ui/MarkdownDocumentSettings.tsx b/apps/web/src/scient/markdownEditor/ui/MarkdownDocumentSettings.tsx new file mode 100644 index 0000000000..b22f14ed0b --- /dev/null +++ b/apps/web/src/scient/markdownEditor/ui/MarkdownDocumentSettings.tsx @@ -0,0 +1,111 @@ +import { useState } from "react"; +import { XIcon } from "lucide-react"; +import { Button } from "~/components/ui/button"; +import { LatexSelect } from "~/scient/latex/LatexSelect"; +import { DocumentSettingsField } from "~/scient/writing/DocumentSettingsField"; +import { FONT_FAMILIES, isFontFamilyName } from "~/scient/writing/fontChoices"; +import { DOCUMENT_FONT_SIZES, type MarkdownDocumentFont } from "../documentFont"; + +const DEFAULT_CHOICE = "default"; + +/** + * Document settings for a Markdown file: the same card, labels and order as + * the LaTeX one for the settings both formats can store. Apply writes the + * choices into the file's front matter. + */ +export function MarkdownDocumentSettings(props: { + readonly font: MarkdownDocumentFont; + readonly disabled: boolean; + readonly onApply: (font: MarkdownDocumentFont) => boolean; + readonly onClose: () => void; +}) { + // The parent mounts a fresh card for each opening. + const [original] = useState(props.font); + const [font, setFont] = useState(original); + const [error, setError] = useState(null); + const changed = font.fontSize !== original.fontSize || font.fontFamily !== original.fontFamily; + return ( +
{ + if (event.key !== "Escape") event.stopPropagation(); + }} + > +
+ +
+
{ + event.preventDefault(); + if (!changed || props.disabled) return; + if (props.onApply(font)) props.onClose(); + else setError("These settings could not be applied. The front matter is not YAML."); + }} + > +
+ + ({ + value: size, + label: size.replace("pt", " pt"), + })), + ]} + onValueChange={(value) => { + const fontSize = DOCUMENT_FONT_SIZES.find((size) => size === value) ?? null; + setFont((previous) => ({ ...previous, fontSize })); + setError(null); + }} + /> + + + ({ value: family.name, label: family.label })), + ]} + onValueChange={(value) => { + setFont((previous) => ({ + ...previous, + fontFamily: isFontFamilyName(value) ? value : null, + })); + setError(null); + }} + /> + +
+ {error && ( +

+ {error} +

+ )} +
+ + +
+
+
+ ); +} diff --git a/apps/web/src/scient/markdownEditor/ui/ScientMarkdownControls.tsx b/apps/web/src/scient/markdownEditor/ui/ScientMarkdownControls.tsx index 74965c08ca..5f60de8ba3 100644 --- a/apps/web/src/scient/markdownEditor/ui/ScientMarkdownControls.tsx +++ b/apps/web/src/scient/markdownEditor/ui/ScientMarkdownControls.tsx @@ -87,7 +87,9 @@ import { type InsertMenuAction, type InsertMenuLayout, } from "../../writing/InsertMenu"; +import { FontMenuItems } from "../../writing/FontMenuItems"; import { TextMenu, TextMenuItems } from "../../writing/TextMenu"; +import { MarkdownDocumentSettings } from "./MarkdownDocumentSettings"; import { DockCommandCheckboxItem } from "../../writing/dockChrome"; import { WRITING_COMMAND_LABELS } from "../../writing/commandNames"; @@ -355,6 +357,15 @@ function markdownTextContents( return { paragraphStyle: , formatting: , + font: ( + controller.execute(`font-family-${family ?? "default"}`)} + onSize={(size) => controller.execute(`font-size-${size ?? "default"}`)} + /> + ), direction: , directionLabel: snapshot.inTable ? "Table direction" : "Direction", }; @@ -1185,6 +1196,35 @@ function SelectionToolbar({ ); } +function DocumentSettingsMenu({ + controller, + snapshot, +}: { + readonly controller: ScientMarkdownEditorView; + readonly snapshot: ScientMarkdownEditorSnapshot; +}) { + const [open, setOpen] = useState(false); + return ( + + Document settings + + {open ? ( + controller.setDocumentFont(font)} + onClose={() => setOpen(false)} + /> + ) : null} + + + ); +} + export function ScientMarkdownControls({ controller, expanded, @@ -1385,6 +1425,8 @@ export function ScientMarkdownControls({ overflowItems={ <> + + {documentActions ? ( <> diff --git a/apps/web/src/scient/writing/DocumentSettingsField.tsx b/apps/web/src/scient/writing/DocumentSettingsField.tsx new file mode 100644 index 0000000000..410e356523 --- /dev/null +++ b/apps/web/src/scient/writing/DocumentSettingsField.tsx @@ -0,0 +1,14 @@ +import type { ReactNode } from "react"; + +/** A small label above its control, shared by both editors' Document settings cards. */ +export function DocumentSettingsField(props: { + readonly label: string; + readonly children: ReactNode; +}) { + return ( +
+ {props.label} + {props.children} +
+ ); +} diff --git a/apps/web/src/scient/writing/FontMenuItems.tsx b/apps/web/src/scient/writing/FontMenuItems.tsx new file mode 100644 index 0000000000..d1d18a2f39 --- /dev/null +++ b/apps/web/src/scient/writing/FontMenuItems.tsx @@ -0,0 +1,67 @@ +import { MenuGroup, MenuGroupLabel, MenuRadioGroup, MenuSeparator } from "~/components/ui/menu"; +import { DockCommandRadioItem } from "./dockChrome"; +import { FONT_FAMILIES, FONT_SIZES, type FontFamilyName, type FontSizeName } from "./fontChoices"; + +const DEFAULT_CHOICE = "default"; + +/** + * Content of `Text > Font / Size`, identical in both editors. A null value + * means the document default; choosing "Default" removes the style. + */ +export function FontMenuItems(props: { + readonly family: string | null; + readonly size: string | null; + readonly disabled: boolean; + readonly onFamily: (family: FontFamilyName | null) => void; + readonly onSize: (size: FontSizeName | null) => void; +}) { + return ( + <> + + Font + + props.onFamily(null)} + > + Default + + {FONT_FAMILIES.map((family) => ( + props.onFamily(family.name)} + > + {family.label} + + ))} + + + + + Size + + props.onSize(null)} + > + Default + + {FONT_SIZES.map((size) => ( + props.onSize(size.name)} + > + {size.label} + + ))} + + + + ); +} diff --git a/apps/web/src/scient/writing/TextMenu.tsx b/apps/web/src/scient/writing/TextMenu.tsx index a56ed16be7..4ee9eb272f 100644 --- a/apps/web/src/scient/writing/TextMenu.tsx +++ b/apps/web/src/scient/writing/TextMenu.tsx @@ -5,6 +5,7 @@ import { DockMenu } from "./dockChrome"; export type TextMenuContents = { paragraphStyle: ReactNode; formatting: ReactNode; + font?: ReactNode; alignment?: ReactNode; direction?: ReactNode; directionLabel?: string; @@ -29,6 +30,7 @@ export function TextMenuItems(props: TextMenuContents) { <> {category("Paragraph style", props.paragraphStyle)} {category("Formatting", props.formatting)} + {props.font ? category("Font / Size", props.font) : null} {props.alignment ? category("Alignment", props.alignment) : null} {props.direction ? category(props.directionLabel ?? "Direction", props.direction, true) diff --git a/apps/web/src/scient/writing/fontChoices.ts b/apps/web/src/scient/writing/fontChoices.ts new file mode 100644 index 0000000000..8b70be83d6 --- /dev/null +++ b/apps/web/src/scient/writing/fontChoices.ts @@ -0,0 +1,45 @@ +/** Font size and family choices shared by the Markdown and LaTeX Visual editors. */ +import { + MARKDOWN_FONT_FAMILIES, + MARKDOWN_FONT_SIZES, + type MarkdownFontFamilyName, + type MarkdownFontSizeName, +} from "@scientfactory/scient-markdown"; + +export type FontSizeName = MarkdownFontSizeName; +export type FontFamilyName = MarkdownFontFamilyName; + +const SIZE_LABELS: Readonly> = { + tiny: "Tiny", + scriptsize: "Very small", + footnotesize: "Footnote", + small: "Small", + normalsize: "Normal", + large: "Large", + Large: "Larger", + LARGE: "Very large", + huge: "Huge", + Huge: "Largest", +}; + +const FAMILY_LABELS: Readonly> = { + serif: "Serif", + "sans-serif": "Sans serif", + monospace: "Code", +}; + +/** The ten LaTeX size names; `em` is each size relative to `\normalsize` at 10 pt. */ +export const FONT_SIZES = MARKDOWN_FONT_SIZES.map((size) => ({ + ...size, + label: SIZE_LABELS[size.name], +})); + +/** Generic families only; the names are the CSS keywords written in Markdown. */ +export const FONT_FAMILIES = MARKDOWN_FONT_FAMILIES.map((name) => ({ + name, + label: FAMILY_LABELS[name], +})); + +export function isFontFamilyName(value: string): value is FontFamilyName { + return MARKDOWN_FONT_FAMILIES.some((family) => family === value); +} diff --git a/packages/scient-markdown/src/fontSpans.ts b/packages/scient-markdown/src/fontSpans.ts new file mode 100644 index 0000000000..2effc55e9d --- /dev/null +++ b/packages/scient-markdown/src/fontSpans.ts @@ -0,0 +1,59 @@ +/** + * The exact `` forms Scient reads and writes for local font size + * and family. Anything else stays literal HTML source. + */ + +/** Size names (the ten LaTeX names) with their `em` ratio at a 10 pt base. */ +export const MARKDOWN_FONT_SIZES = [ + { name: "tiny", em: 0.5 }, + { name: "scriptsize", em: 0.7 }, + { name: "footnotesize", em: 0.8 }, + { name: "small", em: 0.9 }, + { name: "normalsize", em: 1 }, + { name: "large", em: 1.2 }, + { name: "Large", em: 1.44 }, + { name: "LARGE", em: 1.73 }, + { name: "huge", em: 2.07 }, + { name: "Huge", em: 2.49 }, +] as const; + +export const MARKDOWN_FONT_FAMILIES = ["serif", "sans-serif", "monospace"] as const; + +export type MarkdownFontSizeName = (typeof MARKDOWN_FONT_SIZES)[number]["name"]; +export type MarkdownFontFamilyName = (typeof MARKDOWN_FONT_FAMILIES)[number]; + +export type MarkdownFontSpan = + | { readonly size: MarkdownFontSizeName } + | { readonly family: MarkdownFontFamilyName }; + +export const MARKDOWN_FONT_SPAN_CLOSE = ""; + +const STYLE_PATTERN = /^font-(?:size:(\d+(?:\.\d+)?)em|family:(serif|sans-serif|monospace))$/u; +const OPEN_PATTERN = /^$/u; + +/** The font a `style` value stands for, or null for any other CSS. */ +export function parseMarkdownFontSpanStyle(style: string): MarkdownFontSpan | null { + const match = STYLE_PATTERN.exec(style); + if (!match) return null; + if (match[1] !== undefined) { + const size = MARKDOWN_FONT_SIZES.find(({ em }) => em === Number(match[1])); + return size ? { size: size.name } : null; + } + return { family: match[2] as MarkdownFontFamilyName }; +} + +/** The font a complete opening tag stands for, or null for any other HTML. */ +export function parseMarkdownFontSpanOpen(html: string): MarkdownFontSpan | null { + const style = OPEN_PATTERN.exec(html)?.[1]; + return style === undefined ? null : parseMarkdownFontSpanStyle(style); +} + +export function markdownFontSpanStyle(span: MarkdownFontSpan): string { + if ("family" in span) return `font-family:${span.family}`; + const em = MARKDOWN_FONT_SIZES.find(({ name }) => name === span.size)?.em; + return `font-size:${em}em`; +} + +export function markdownFontSpanOpen(span: MarkdownFontSpan): string { + return ``; +} diff --git a/packages/scient-markdown/src/index.ts b/packages/scient-markdown/src/index.ts index 9ec36f7db5..c702fba0f5 100644 --- a/packages/scient-markdown/src/index.ts +++ b/packages/scient-markdown/src/index.ts @@ -41,3 +41,15 @@ export { resolveMarkdownDocumentRelativePath, type MarkdownDocumentInspection, } from "./documentResources.ts"; +export { + MARKDOWN_FONT_FAMILIES, + MARKDOWN_FONT_SIZES, + MARKDOWN_FONT_SPAN_CLOSE, + markdownFontSpanOpen, + markdownFontSpanStyle, + parseMarkdownFontSpanOpen, + parseMarkdownFontSpanStyle, + type MarkdownFontFamilyName, + type MarkdownFontSizeName, + type MarkdownFontSpan, +} from "./fontSpans.ts"; diff --git a/packages/scient-markdown/src/sourceLedger.test.ts b/packages/scient-markdown/src/sourceLedger.test.ts index abff3936c6..197dc48765 100644 --- a/packages/scient-markdown/src/sourceLedger.test.ts +++ b/packages/scient-markdown/src/sourceLedger.test.ts @@ -330,3 +330,15 @@ describe("nested block kinds", () => { expect(ledger.blocks[0]?.directionWrappedKind).toBe("heading"); }); }); + +describe("font spans inside containers", () => { + it("do not make a list or quote source-only, other inline HTML still does", () => { + const kinds = (source: string) => + createMarkdownSourceLedger(source).blocks.map((block) => block.nestedBlockKinds); + expect(kinds('- a b\n')[0]).not.toContain("html"); + expect(kinds('> a b\n')[0]).not.toContain("html"); + expect(kinds('- a b\n')[0]).toContain("html"); + expect(kinds('- a b\n')[0]).toContain("html"); + expect(kinds("- a \n")[0]).toContain("html"); + }); +}); diff --git a/packages/scient-markdown/src/sourceLedger.ts b/packages/scient-markdown/src/sourceLedger.ts index 922391ffc3..847977158c 100644 --- a/packages/scient-markdown/src/sourceLedger.ts +++ b/packages/scient-markdown/src/sourceLedger.ts @@ -6,6 +6,7 @@ import { mathFromMarkdown } from "mdast-util-math"; import { frontmatter } from "micromark-extension-frontmatter"; import { gfm } from "micromark-extension-gfm"; import { math } from "micromark-extension-math"; +import { MARKDOWN_FONT_SPAN_CLOSE, parseMarkdownFontSpanOpen } from "./fontSpans.ts"; export interface MarkdownSourceBlock { /** Stable only for the lifetime of this parsed ledger. */ @@ -129,15 +130,45 @@ function directionWrapperIndexes(children: ReadonlyArray): Set` that closes it among its siblings. + */ +function fontSpanIndexes(children: ReadonlyArray): Set { + const indexes = new Set(); + const html = (node: MdastValueNode | undefined) => + node?.type === "html" && typeof node.value === "string" ? node.value : null; + children.forEach((child, index) => { + const opening = html(child); + if (opening === null || parseMarkdownFontSpanOpen(opening) === null) return; + let depth = 1; + for (let next = index + 1; next < children.length; next += 1) { + const value = html(children[next]); + if (value === null) continue; + if (value === MARKDOWN_FONT_SPAN_CLOSE) depth -= 1; + else if (/^(); // Inline HTML inside a nested paragraph, heading or table is source the - // rich document shows as literal text; report it like an HTML block. + // rich document shows as literal text, except recognised font spans; + // report it like an HTML block. const visitInline = (parent: MdastValueNode): void => { - for (const child of parent.children ?? []) { - if (child.type === "html") kinds.add(child.type); + const children = parent.children ?? []; + const fontSpans = fontSpanIndexes(children); + children.forEach((child, index) => { + if (child.type === "html" && !fontSpans.has(index)) kinds.add(child.type); visitInline(child); - } + }); }; const visit = (container: MdastValueNode): void => { if (!CONTAINER_NODE_KINDS.has(container.type)) return; From 4602a3825ac170d573cc08b13f981010d3fcf14c Mon Sep 17 00:00:00 2001 From: Tova <291672564+Tova22@users.noreply.github.com> Date: Mon, 9 Nov 2026 19:41:27 +0200 Subject: [PATCH 02/42] Keep local font size and family in the Word export - Recognised Markdown forms become Word character styles (one per size, family, and size with family) before raw HTML is stripped; any other HTML is still dropped. - The font-size and font-family front matter keys set the base font of the reference document; local sizes scale from that base. - LaTeX: {\large ...} groups are rewritten to a form Pandoc keeps and mapped to the same styles; \textsf and \textrm are kept; the class option and \familydefault set the base font. Co-Authored-By: Claude Sonnet 5.5 --- .../PandocWordConverter.integration.test.ts | 130 ++++++++++ .../src/scient/pandoc/PandocWordConverter.ts | 17 +- .../src/scient/pandoc/pandocFont.test.ts | 60 +++++ apps/server/src/scient/pandoc/pandocFont.ts | 226 ++++++++++++++++++ .../scient/pandoc/scientReferenceDocument.ts | 103 +++++++- 5 files changed, 520 insertions(+), 16 deletions(-) create mode 100644 apps/server/src/scient/pandoc/pandocFont.test.ts create mode 100644 apps/server/src/scient/pandoc/pandocFont.ts diff --git a/apps/server/src/scient/pandoc/PandocWordConverter.integration.test.ts b/apps/server/src/scient/pandoc/PandocWordConverter.integration.test.ts index 625f0446da..320e4b7200 100644 --- a/apps/server/src/scient/pandoc/PandocWordConverter.integration.test.ts +++ b/apps/server/src/scient/pandoc/PandocWordConverter.integration.test.ts @@ -633,4 +633,134 @@ 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 recognised size span 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="ScientSize120"[\s\S]*?/u); + expect(warnings).not.toContain("Raw HTML"); + expect(document).not.toContain("<span"); + }), + ); + + it.live("applies a recognised family span 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="ScientFontmonospace"[\s\S]*?Consolas/u); + }), + ); + + it.live("keeps both when a size span and a family 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("ScientSize120"); + expect(wordsRun).toContain("ScientSize120Fontsansserif"); + }), + ); + + it.live("still drops every other span", () => + 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 scales local sizes from the front matter", () => + Effect.gen(function* () { + const { styles } = yield* exportMarkdown( + "font-front-matter", + '---\nfont-size: 12pt\nfont-family: serif\n---\n\nText with size.\n', + ); + expect(styles).toMatch(/[\s\S]*?Cambria[\s\S]*?/u); + expect(styles).toMatch(/w:styleId="ScientSize120"[\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 {\\Large 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("ScientSize144"); + expect(run("both")).toContain("ScientSize144Fontsansserif"); + expect(run("roman")).toContain("ScientFontserif"); + expect(run("tiny")).toContain("ScientSize90"); + expect(document).not.toContain("scient-size"); + }), + ); + + 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]*?Cambria[\s\S]*?/u); + }), + ); + }); }); diff --git a/apps/server/src/scient/pandoc/PandocWordConverter.ts b/apps/server/src/scient/pandoc/PandocWordConverter.ts index 09bfb17086..7c220f6ff5 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 } 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,10 @@ const make = Effect.gen(function* () { } } const citations = applyCitations(document.blocks, bibliography); + if (input.latex) applyLatexFontSpans(document.blocks); + else applyFontSpans(document.blocks); + // Read before the security pass, which clears the document's metadata. + const baseFont = input.latex ? latexBaseFontOf(source) : wordBaseFontOf(document.meta); const security = yield* securePandocDocument(document, { assets: input.bundle.assets, files: input.imageSnapshot === undefined ? (input.files ?? null) : null, @@ -407,7 +418,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), ); 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..9ec4a5679f --- /dev/null +++ b/apps/server/src/scient/pandoc/pandocFont.test.ts @@ -0,0 +1,60 @@ +/** + * Word font handling that needs no Pandoc: the LaTeX size-group rewrite and the base font reads. + */ +import { describe, expect, it } from "vite-plus/test"; + +import { latexBaseFontOf, rewriteLatexSizeGroups } from "./pandocFont.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("Large", "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("large", `a ${carrier("small", "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("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: "monospace" }); + }); + + it("keeps the Word default when nothing is set", () => { + expect(latexBaseFontOf("\\documentclass{article}")).toEqual({ + sizePoints: 11, + family: "sans-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..fedbdce0f1 --- /dev/null +++ b/apps/server/src/scient/pandoc/pandocFont.ts @@ -0,0 +1,226 @@ +/** + * Word export of local font size and family. Scient's recognised `` forms are turned + * into Word character styles before raw HTML is stripped; the `font-size` and `font-family` + * front matter keys set the base font of the reference document. + */ +import { + MARKDOWN_FONT_FAMILIES, + MARKDOWN_FONT_SIZES, + MARKDOWN_FONT_SPAN_CLOSE, + type MarkdownFontFamilyName, + type MarkdownFontSpan, + 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 = /^ name === span.size); + return size === undefined ? outer : { ...outer, em: size.em }; +} + +/** 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): 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, font); + inlines.splice(index, close - index + 1, customStyleSpan(wordFontStyleName(font), 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, outer: WordLocalFont = {}): void { + if (Array.isArray(value)) { + wrapFontSpans(value, outer); + for (const item of value) applyFontSpans(item, outer); + return; + } + if (Predicate.isObject(value)) { + for (const child of Object.values(value)) applyFontSpans(child, outer); + } +} + +function isFontFamilyName(value: string): value is MarkdownFontFamilyName { + return MARKDOWN_FONT_FAMILIES.some((family) => family === value); +} + +/** The base font named by the document's metadata; anything unrecognised keeps the default. */ +export function wordBaseFontOf(meta: Record): WordBaseFont { + const size = inlineText(meta["font-size"]).trim(); + const family = inlineText(meta["font-family"]).trim(); + return { + sizePoints: BASE_SIZE.test(size) + ? Number.parseInt(size, 10) + : DEFAULT_WORD_BASE_FONT.sizePoints, + family: isFontFamilyName(family) ? family : DEFAULT_WORD_BASE_FONT.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. + +const LATEX_SIZE_COMMAND = new RegExp( + String.raw`^\\(${MARKDOWN_FONT_SIZES.map(({ name }) => name).join("|")})(?![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 = /\\documentclass\[[^\]]*?\b(10|11|12)pt\b[^\]]*\]/u; +const LATEX_FAMILY_DEFAULT = /\\renewcommand\s*\{\\familydefault\}\s*\{\\(rm|sf|tt)default\}/u; +const LATEX_FAMILIES: Readonly> = { + rm: "serif", + sf: "sans-serif", + tt: "monospace", +}; + +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; +} + +function rewriteSizeGroups(text: string, counter: { found: boolean }): 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)) inMath = !inMath; + if (char === "{" && !inMath && !isEscaped(text, index)) { + const command = LATEX_SIZE_COMMAND.exec(text.slice(index + 1)); + const end = command === null ? -1 : braceEnd(text, index); + if (command !== null && end >= 0) { + counter.found = true; + const body = text.slice(index + 1 + command[0].length, end); + out += `\\ScientSize{${LATEX_SIZE_CARRIER}${command[1]}}{${rewriteSizeGroups(body, counter)}}`; + 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); + return counter.found ? `${LATEX_SIZE_MACRO}\n${rewritten}` : source; +} + +/** The base font set by the preamble's class option and `\familydefault`, as the Visual card writes them. */ +export function latexBaseFontOf(source: string): WordBaseFont { + const size = LATEX_CLASS_SIZE.exec(source)?.[1]; + const family = LATEX_FAMILY_DEFAULT.exec(source)?.[1]; + return { + sizePoints: size === undefined ? DEFAULT_WORD_BASE_FONT.sizePoints : Number.parseInt(size, 10), + family: + (family === undefined ? undefined : LATEX_FAMILIES[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: "sans-serif" }; + if (classes.includes("roman")) return { family: "serif" }; + } + if (!Array.isArray(pairs)) return null; + for (const pair of pairs) { + const style = Array.isArray(pair) && pair[0] === "style" ? pair[1] : null; + const name = Predicate.isString(style) + ? new RegExp(`^color:\\s*${LATEX_SIZE_CARRIER}(\\w+)$`, "u").exec(style)?.[1] + : undefined; + const size = MARKDOWN_FONT_SIZES.find((entry) => entry.name === name); + if (size !== undefined) return { em: size.em }; + } + return null; +} + +/** Turn the spans Pandoc made from LaTeX font commands into Word character style spans. */ +export function applyLatexFontSpans(value: unknown, outer: WordLocalFont = {}): void { + if (Array.isArray(value)) { + for (const item of value) applyLatexFontSpans(item, 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], font); + value.c[0] = attr([], [["custom-style", wordFontStyleName(font)]]); + return; + } + } + for (const child of Object.values(value)) applyLatexFontSpans(child, outer); +} diff --git a/apps/server/src/scient/pandoc/scientReferenceDocument.ts b/apps/server/src/scient/pandoc/scientReferenceDocument.ts index 9b65fb905f..21659a2000 100644 --- a/apps/server/src/scient/pandoc/scientReferenceDocument.ts +++ b/apps/server/src/scient/pandoc/scientReferenceDocument.ts @@ -7,6 +7,11 @@ import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as yazl from "yazl"; +import { + MARKDOWN_FONT_FAMILIES, + MARKDOWN_FONT_SIZES, + type MarkdownFontFamilyName, +} from "@scientfactory/scient-markdown"; const W = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"; const BODY_FONT = ``; @@ -343,13 +348,76 @@ export const SCIENT_REFERENCE_STYLES: ReadonlyArray = [ }, ]; -function scientReferenceStylesXml(): string { +/** The document's base text size and family, from the `font-size` and `font-family` front matter. */ +export interface WordBaseFont { + readonly sizePoints: number; + readonly family: MarkdownFontFamilyName; +} + +export const DEFAULT_WORD_BASE_FONT: WordBaseFont = { sizePoints: 11, family: "sans-serif" }; + +/** Office's own fonts, one per generic family. */ +const WORD_FONT_NAMES: Readonly> = { + serif: "Cambria", + "sans-serif": "Calibri", + monospace: "Consolas", +}; + +const familyFonts = (family: MarkdownFontFamilyName): string => + family === "sans-serif" + ? BODY_FONT + : ``; + +/** A local size (a share of the base size) and/or family; a Word run carries only one style. */ +export interface WordLocalFont { + readonly em?: number | undefined; + readonly family?: MarkdownFontFamilyName | undefined; +} + +/** + * Word style name for a local font. Sizes are named by percentage because Word style names + * ignore case, so the LaTeX names `large` and `LARGE` would collide. + */ +export const wordFontStyleName = (font: WordLocalFont): string => + [ + "Scient", + font.em === undefined ? null : `Size ${Math.round(font.em * 100)}%`, + font.family === undefined ? null : `Font ${font.family}`, + ] + .filter((part) => part !== null) + .join(" "); + +/** Character styles for every size, every family, and every size with a family. */ +function fontStyles(base: WordBaseFont): Array { + const sizes = [undefined, ...MARKDOWN_FONT_SIZES.map(({ em }) => em)]; + const families = [undefined, ...MARKDOWN_FONT_FAMILIES]; + return sizes.flatMap((em) => + families.flatMap((family): Array => { + if (em === undefined && family === undefined) return []; + const name = wordFontStyleName({ em, family }); + return [ + { + type: "character", + id: name.replaceAll(/[^A-Za-z0-9]/gu, ""), + name, + custom: true, + rPr: [ + family === undefined ? "" : familyFonts(family), + em === undefined ? "" : size(Math.round(em * base.sizePoints * 2) / 2), + ].join(""), + }, + ]; + }), + ); +} + +function scientReferenceStylesXml(base: WordBaseFont): string { return [ ``, ``, - `${BODY_FONT}${size(11)}`, + `${familyFonts(base.family)}${size(base.sizePoints)}`, ``, - ...SCIENT_REFERENCE_STYLES.map(style), + ...[...SCIENT_REFERENCE_STYLES, ...fontStyles(base)].map(style), ``, ].join(""); } @@ -421,34 +489,43 @@ 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, +): 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)], ]; } -let cached: Promise | null = null; +const cached = new Map>(); -function packReferenceDocument(): Promise { +function packReferenceDocument(base: WordBaseFont): 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)) { 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; built once per process for each. */ +export const scientReferenceDocumentFor = (base: WordBaseFont) => + Effect.promise(() => { + const key = `${base.sizePoints}/${base.family}`; + const existing = cached.get(key); + if (existing !== undefined) return existing; + const packed = packReferenceDocument(base); + cached.set(key, packed); + return packed; + }); + +export const scientReferenceDocument = scientReferenceDocumentFor(DEFAULT_WORD_BASE_FONT); From 9b390f1669cfd9e5934aee0d8423355429051d5d Mon Sep 17 00:00:00 2001 From: Tova <291672564+Tova22@users.noreply.github.com> Date: Tue, 10 Nov 2026 10:51:06 +0200 Subject: [PATCH 03/42] Reject unknown font names in pasted HTML and keep LaTeX size groups out of command arguments Found by an independent review. Pasted values are now checked against the known size and family names. The Word export no longer rewrites a size command that is a command argument (\textbf{\large x}), nor verbatim or bracket math. Co-Authored-By: Claude Sonnet 5.5 --- .../src/scient/pandoc/pandocFont.test.ts | 26 +++++++++++++++++++ apps/server/src/scient/pandoc/pandocFont.ts | 22 +++++++++++++++- .../prosemirror/fontStyles.test.ts | 14 ++++++++++ .../markdownEditor/prosemirror/schema.ts | 12 +++++++-- 4 files changed, 71 insertions(+), 3 deletions(-) diff --git a/apps/server/src/scient/pandoc/pandocFont.test.ts b/apps/server/src/scient/pandoc/pandocFont.test.ts index 9ec4a5679f..6ba5fa6ecc 100644 --- a/apps/server/src/scient/pandoc/pandocFont.test.ts +++ b/apps/server/src/scient/pandoc/pandocFont.test.ts @@ -36,6 +36,32 @@ describe("rewriteLatexSizeGroups", () => { } }); + it("leaves a size command inside a command argument alone", () => { + for (const source of [ + "\\textbf{\\large x}", + "\\section{\\large Title}", + "\\newcommand{\\a}{\\small z}", + "\\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("large", "x")); + }); + it("does not match a longer command that starts with a size name", () => { const source = "{\\largesse text}"; expect(rewriteLatexSizeGroups(source)).toBe(source); diff --git a/apps/server/src/scient/pandoc/pandocFont.ts b/apps/server/src/scient/pandoc/pandocFont.ts index fedbdce0f1..ef2aebc32b 100644 --- a/apps/server/src/scient/pandoc/pandocFont.ts +++ b/apps/server/src/scient/pandoc/pandocFont.ts @@ -139,6 +139,11 @@ function braceEnd(text: string, open: number): number { return -1; } +// Environments whose content is copied as is. +const LATEX_VERBATIM_START = /^\\begin\{(verbatim\*?|lstlisting|minted)\}/u; +// A brace right after a command name or a closing bracket is that command's argument, not a group. +const LATEX_ARGUMENT_BEFORE = /[A-Za-z}\]*@]/u; + function rewriteSizeGroups(text: string, counter: { found: boolean }): string { let out = ""; let inMath = false; @@ -151,8 +156,23 @@ function rewriteSizeGroups(text: string, counter: { found: boolean }): string { 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 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 standalone = index === 0 || !LATEX_ARGUMENT_BEFORE.test(text[index - 1] ?? ""); + if (char === "{" && standalone && !inMath && !isEscaped(text, index)) { const command = LATEX_SIZE_COMMAND.exec(text.slice(index + 1)); const end = command === null ? -1 : braceEnd(text, index); if (command !== null && end >= 0) { diff --git a/apps/web/src/scient/markdownEditor/prosemirror/fontStyles.test.ts b/apps/web/src/scient/markdownEditor/prosemirror/fontStyles.test.ts index 6979913b19..18e16d39d0 100644 --- a/apps/web/src/scient/markdownEditor/prosemirror/fontStyles.test.ts +++ b/apps/web/src/scient/markdownEditor/prosemirror/fontStyles.test.ts @@ -125,4 +125,18 @@ describe("Markdown font size and family", () => { expect(scientMarkdownSchema.marks.font_size).toBeDefined(); expect(scientMarkdownSchema.marks.font_family).toBeDefined(); }); + + it("ignores pasted HTML whose size or family is not a known name", () => { + 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("huge"))).toEqual({ size: "huge" }); + expect(parseRule("font_size")(attribute("x;background:url(https://example.invalid)"))).toBe( + false, + ); + expect(parseRule("font_family")(attribute("monospace"))).toEqual({ family: "monospace" }); + expect(parseRule("font_family")(attribute('serif" onmouseover="alert(1)'))).toBe(false); + }); }); diff --git a/apps/web/src/scient/markdownEditor/prosemirror/schema.ts b/apps/web/src/scient/markdownEditor/prosemirror/schema.ts index bfcaa61d22..4b6df17f49 100644 --- a/apps/web/src/scient/markdownEditor/prosemirror/schema.ts +++ b/apps/web/src/scient/markdownEditor/prosemirror/schema.ts @@ -18,6 +18,7 @@ import { Schema } from "prosemirror-model"; import { tableNodes } from "prosemirror-tables"; import { + MARKDOWN_FONT_FAMILIES, MARKDOWN_FONT_SIZES, MARKDOWN_FONT_SPAN_CLOSE, markdownFontSpanOpen, @@ -246,7 +247,11 @@ const fontSizeSpec: MarkSpec = { parseDOM: [ { tag: "span[data-scient-font-size]", - getAttrs: (element) => ({ size: element.getAttribute("data-scient-font-size") }), + // Pasted HTML is untrusted: only a known size name becomes a mark. + getAttrs: (element) => { + const size = element.getAttribute("data-scient-font-size"); + return MARKDOWN_FONT_SIZES.some(({ name }) => name === size) ? { size } : false; + }, }, ], toDOM: (mark) => [ @@ -264,7 +269,10 @@ const fontFamilySpec: MarkSpec = { parseDOM: [ { tag: "span[data-scient-font-family]", - getAttrs: (element) => ({ family: element.getAttribute("data-scient-font-family") }), + getAttrs: (element) => { + const family = element.getAttribute("data-scient-font-family"); + return MARKDOWN_FONT_FAMILIES.some((name) => name === family) ? { family } : false; + }, }, ], toDOM: (mark) => [ From d281e8b9c5944734f3649d9a8ab891496f704cac Mon Sep 17 00:00:00 2001 From: Tova <291672564+Tova22@users.noreply.github.com> Date: Tue, 10 Nov 2026 11:20:11 +0200 Subject: [PATCH 04/42] Keep font size proportions in the Word export, keep blank lines in front matter, share the document sizes A local size inside a heading or a footnote is now a share of that text's size in the Word export, as in the editor. Writing the document font no longer drops blank lines of the front matter. The 10/11/12 pt sizes and the leading front matter pattern are defined once. Added guards for tags inside code or links within a font span. Co-Authored-By: Claude Sonnet 5.5 --- .../src/scient/pandoc/PandocWordConverter.ts | 9 +- .../src/scient/pandoc/pandocFont.test.ts | 56 ++++++++++- apps/server/src/scient/pandoc/pandocFont.ts | 75 +++++++++++--- .../scient/pandoc/scientReferenceDocument.ts | 99 ++++++++++++------- .../src/scient/documentPage/documentFont.ts | 4 +- .../markdownEditor/documentFont.test.ts | 7 ++ .../src/scient/markdownEditor/documentFont.ts | 14 ++- .../prosemirror/fontStyles.test.ts | 18 ++++ .../ui/MarkdownDocumentSettings.tsx | 3 +- packages/scient-markdown/src/fontSpans.ts | 4 + packages/scient-markdown/src/index.ts | 2 + 11 files changed, 229 insertions(+), 62 deletions(-) diff --git a/apps/server/src/scient/pandoc/PandocWordConverter.ts b/apps/server/src/scient/pandoc/PandocWordConverter.ts index 7c220f6ff5..a76e49f7b3 100644 --- a/apps/server/src/scient/pandoc/PandocWordConverter.ts +++ b/apps/server/src/scient/pandoc/PandocWordConverter.ts @@ -43,7 +43,7 @@ import { } from "./pandocFont.ts"; import { securePandocDocument } from "./pandocResources.ts"; import { spaceTextAroundTables } from "./pandocTableSpacing.ts"; -import { scientReferenceDocumentFor } from "./scientReferenceDocument.ts"; +import { scientReferenceDocumentFor, type WordLocalFont } from "./scientReferenceDocument.ts"; import type { PreparedLatexProject } from "./latexProjectPreparation.ts"; import type { CapturedWorkspaceImage } from "./wordImageSnapshot.ts"; @@ -375,10 +375,11 @@ const make = Effect.gen(function* () { } } const citations = applyCitations(document.blocks, bibliography); - if (input.latex) applyLatexFontSpans(document.blocks); - else applyFontSpans(document.blocks); // Read before the security pass, which clears the document's metadata. const baseFont = input.latex ? latexBaseFontOf(source) : wordBaseFontOf(document.meta); + const fontPass = { base: baseFont, inContext: 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, @@ -418,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* scientReferenceDocumentFor(baseFont), + yield* scientReferenceDocumentFor(baseFont, [...fontPass.inContext.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 index 6ba5fa6ecc..313bbe6265 100644 --- a/apps/server/src/scient/pandoc/pandocFont.test.ts +++ b/apps/server/src/scient/pandoc/pandocFont.test.ts @@ -3,7 +3,13 @@ */ import { describe, expect, it } from "vite-plus/test"; -import { latexBaseFontOf, rewriteLatexSizeGroups } from "./pandocFont.ts"; +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}}`; @@ -84,3 +90,51 @@ describe("latexBaseFontOf", () => { }); }); }); + +describe("a local size keeps its share of the surrounding text", () => { + const open = { t: "RawInline", c: ["html", ''] }; + const close = { t: "RawInline", c: ["html", ""] }; + const word = { t: "Str", c: "word" }; + const pass = (sizePoints = 11): FontPass => ({ + base: { sizePoints, family: "sans-serif" }, + inContext: new Map(), + }); + const attributes = ["", [], []]; + const styleOf = (inlines: Array) => + JSON.stringify(inlines).match(/Scient[^"]*/u)?.[0] ?? null; + + it("names the heading size in the style of a size set inside a heading", () => { + const heading = [{ t: "Header", c: [1, attributes, [open, word, close]] }]; + const used = pass(); + applyFontSpans(heading, used); + expect(styleOf(heading)).toBe("Scient Size 120% of 18pt"); + expect([...used.inContext.keys()]).toEqual(["Scient Size 120% of 18pt"]); + }); + + it("uses the footnote size inside a footnote", () => { + const note = [{ t: "Para", c: [{ t: "Note", c: [{ t: "Para", c: [open, word, close] }] }] }]; + const used = pass(); + applyFontSpans(note, used); + expect(styleOf(note)).toBe("Scient Size 120% of 9pt"); + }); + + it("keeps the plain style in a paragraph, and in a heading the size of the base", () => { + const text = [{ t: "Para", c: [open, word, close] }]; + const same = [{ t: "Header", c: [5, attributes, [open, word, close]] }]; + const used = pass(); + applyFontSpans(text, used); + applyFontSpans(same, used); + expect(styleOf(text)).toBe("Scient Size 120%"); + expect(styleOf(same)).toBe("Scient Size 120%"); + expect(used.inContext.size).toBe(0); + }); + + it("writes the style of a heading size with the heading size times the share", () => { + const font = { em: 1.2, context: 18 }; + const styles = scientReferenceDocumentParts(undefined, [font]).find( + ([name]) => name === "word/styles.xml", + )?.[1]; + // 1.2 x 18 pt = 21.6 pt, kept to the half point: 21.5 pt, which Word writes as 43. + expect(styles).toMatch(/w:styleId="ScientSize120of18pt"[\s\S]*?; +} + +/** The Word style name for a font, noting it when it needs a style of its own. */ +function styleNameOf(font: WordLocalFont, pass: FontPass): string { + const name = wordFontStyleName(font); + if (font.em !== undefined && font.context !== undefined) pass.inContext.set(name, font); + return name; +} + +/** + * The size in points of the text a node holds, when it is not the base size. A size in a heading + * or a footnote is a share of that text's size, as in the editor, not of the base size. + */ +function contextOf(node: PandocNode, pass: FontPass): number | undefined { + const points = + node.t === "Header" && Array.isArray(node.c) + ? HEADING_POINTS[Number(node.c[0]) - 1] + : node.t === "Note" + ? FOOTNOTE_POINTS + : undefined; + return points === pass.base.sizePoints ? undefined : points; +} /** The font of a span laid over the font already in force around it. */ function layered(outer: WordLocalFont, span: MarkdownFontSpan): WordLocalFont { @@ -51,7 +84,7 @@ function closingIndex(inlines: Array, open: number): number { return -1; } -function wrapFontSpans(inlines: Array, outer: WordLocalFont): void { +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); @@ -61,8 +94,8 @@ function wrapFontSpans(inlines: Array, outer: WordLocalFont): void { 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, font); - inlines.splice(index, close - index + 1, customStyleSpan(wordFontStyleName(font), inner)); + applyFontSpans(inner, pass, font); + inlines.splice(index, close - index + 1, customStyleSpan(styleNameOf(font, pass), inner)); } } @@ -70,15 +103,16 @@ function wrapFontSpans(inlines: Array, outer: WordLocalFont): void { * 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, outer: WordLocalFont = {}): void { +export function applyFontSpans(value: unknown, pass: FontPass, outer: WordLocalFont = {}): void { if (Array.isArray(value)) { - wrapFontSpans(value, outer); - for (const item of value) applyFontSpans(item, outer); + wrapFontSpans(value, outer, pass); + for (const item of value) applyFontSpans(item, pass, outer); return; } - if (Predicate.isObject(value)) { - for (const child of Object.values(value)) applyFontSpans(child, outer); - } + if (!Predicate.isObject(value)) return; + const context = isPandocNode(value) ? contextOf(value, pass) : undefined; + const within = context === undefined ? outer : { ...outer, context }; + for (const child of Object.values(value)) applyFontSpans(child, pass, within); } function isFontFamilyName(value: string): value is MarkdownFontFamilyName { @@ -107,7 +141,10 @@ const LATEX_SIZE_COMMAND = new RegExp( ); const LATEX_SIZE_CARRIER = "scient-size-"; const LATEX_SIZE_MACRO = String.raw`\newcommand{\ScientSize}[2]{\textcolor{#1}{#2}}`; -const LATEX_CLASS_SIZE = /\\documentclass\[[^\]]*?\b(10|11|12)pt\b[^\]]*\]/u; +const LATEX_CLASS_SIZE = new RegExp( + String.raw`\\documentclass\[[^\]]*?\b(${DOCUMENT_FONT_SIZES.join("|")})\b[^\]]*\]`, + "u", +); const LATEX_FAMILY_DEFAULT = /\\renewcommand\s*\{\\familydefault\}\s*\{\\(rm|sf|tt)default\}/u; const LATEX_FAMILIES: Readonly> = { rm: "serif", @@ -227,9 +264,13 @@ function latexSpanFont(attributes: unknown): WordLocalFont | null { } /** Turn the spans Pandoc made from LaTeX font commands into Word character style spans. */ -export function applyLatexFontSpans(value: unknown, outer: WordLocalFont = {}): void { +export function applyLatexFontSpans( + value: unknown, + pass: FontPass, + outer: WordLocalFont = {}, +): void { if (Array.isArray(value)) { - for (const item of value) applyLatexFontSpans(item, outer); + for (const item of value) applyLatexFontSpans(item, pass, outer); return; } if (!Predicate.isObject(value)) return; @@ -237,10 +278,12 @@ export function applyLatexFontSpans(value: unknown, outer: WordLocalFont = {}): const own = latexSpanFont(value.c[0]); if (own !== null) { const font = { ...outer, ...own }; - applyLatexFontSpans(value.c[1], font); - value.c[0] = attr([], [["custom-style", wordFontStyleName(font)]]); + applyLatexFontSpans(value.c[1], pass, font); + value.c[0] = attr([], [["custom-style", styleNameOf(font, pass)]]); return; } } - for (const child of Object.values(value)) applyLatexFontSpans(child, outer); + const context = isPandocNode(value) ? contextOf(value, pass) : undefined; + const within = context === undefined ? outer : { ...outer, context }; + 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 21659a2000..2551c6817b 100644 --- a/apps/server/src/scient/pandoc/scientReferenceDocument.ts +++ b/apps/server/src/scient/pandoc/scientReferenceDocument.ts @@ -51,9 +51,13 @@ function style(spec: StyleSpec): string { const size = (points: number) => ``; +/** Heading sizes in points, level 1 first; a local size in a heading is a share of its level's. */ +export const HEADING_POINTS = [18, 15, 13, 12, 11, 11, 11, 11, 11] as const; +/** Footnote text size in points. */ +export 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}`, @@ -193,7 +197,7 @@ export const SCIENT_REFERENCE_STYLES: ReadonlyArray = [ name: "footnote text", basedOn: "Normal", pPr: ``, - rPr: size(9), + rPr: size(FOOTNOTE_POINTS), }, { type: "paragraph", @@ -368,10 +372,15 @@ const familyFonts = (family: MarkdownFontFamilyName): string => ? BODY_FONT : ``; -/** A local size (a share of the base size) and/or family; a Word run carries only one style. */ +/** + * A local size (a share of the surrounding text) and/or family; a Word run carries only one + * style. `context` is the size in points of the surrounding text when that is not the base size, + * as inside a heading or a footnote, so the share is kept there too. + */ export interface WordLocalFont { readonly em?: number | undefined; readonly family?: MarkdownFontFamilyName | undefined; + readonly context?: number | undefined; } /** @@ -381,43 +390,55 @@ export interface WordLocalFont { export const wordFontStyleName = (font: WordLocalFont): string => [ "Scient", - font.em === undefined ? null : `Size ${Math.round(font.em * 100)}%`, + font.em === undefined + ? null + : `Size ${Math.round(font.em * 100)}%${font.context === undefined ? "" : ` of ${font.context}pt`}`, font.family === undefined ? null : `Font ${font.family}`, ] .filter((part) => part !== null) .join(" "); -/** Character styles for every size, every family, and every size with a family. */ -function fontStyles(base: WordBaseFont): Array { +function fontStyle(font: WordLocalFont, base: WordBaseFont): StyleSpec { + const name = wordFontStyleName(font); + return { + type: "character", + id: name.replaceAll(/[^A-Za-z0-9]/gu, ""), + name, + custom: true, + rPr: [ + font.family === undefined ? "" : familyFonts(font.family), + font.em === undefined + ? "" + : size(Math.round(font.em * (font.context ?? base.sizePoints) * 2) / 2), + ].join(""), + }; +} + +/** + * Character styles for every size, every family, and every size with a family, then the styles + * for sizes used inside headings or footnotes. + */ +function fontStyles(base: WordBaseFont, inContext: ReadonlyArray): Array { const sizes = [undefined, ...MARKDOWN_FONT_SIZES.map(({ em }) => em)]; const families = [undefined, ...MARKDOWN_FONT_FAMILIES]; - return sizes.flatMap((em) => - families.flatMap((family): Array => { - if (em === undefined && family === undefined) return []; - const name = wordFontStyleName({ em, family }); - return [ - { - type: "character", - id: name.replaceAll(/[^A-Za-z0-9]/gu, ""), - name, - custom: true, - rPr: [ - family === undefined ? "" : familyFonts(family), - em === undefined ? "" : size(Math.round(em * base.sizePoints * 2) / 2), - ].join(""), - }, - ]; - }), + const fonts: Array = sizes.flatMap((em) => + families.flatMap((family) => + em === undefined && family === undefined ? [] : [{ em, family }], + ), ); + return [...fonts, ...inContext].map((font) => fontStyle(font, base)); } -function scientReferenceStylesXml(base: WordBaseFont): string { +function scientReferenceStylesXml( + base: WordBaseFont, + inContext: ReadonlyArray, +): string { return [ ``, ``, `${familyFonts(base.family)}${size(base.sizePoints)}`, ``, - ...[...SCIENT_REFERENCE_STYLES, ...fontStyles(base)].map(style), + ...[...SCIENT_REFERENCE_STYLES, ...fontStyles(base, inContext)].map(style), ``, ].join(""); } @@ -491,39 +512,51 @@ const ENTRY_TIME = DateTime.toDateUtc(DateTime.makeUnsafe("2026-01-01T00:00:00Z" export function scientReferenceDocumentParts( base: WordBaseFont = DEFAULT_WORD_BASE_FONT, + inContext: 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(base)], + ["word/styles.xml", scientReferenceStylesXml(base, inContext)], ]; } const cached = new Map>(); -function packReferenceDocument(base: WordBaseFont): Promise { +function packReferenceDocument( + base: WordBaseFont, + inContext: 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(base)) { + for (const [name, contents] of scientReferenceDocumentParts(base, inContext)) { zip.addBuffer(Buffer.from(contents, "utf8"), name, { mtime: ENTRY_TIME, mode: 0o100644 }); } zip.end(); }); } -/** The packed reference document for a base font; built once per process for each. */ -export const scientReferenceDocumentFor = (base: WordBaseFont) => +/** + * The packed reference document for a base font and the sizes used inside headings or + * footnotes; built once per process for each combination. + */ +export const scientReferenceDocumentFor = ( + base: WordBaseFont, + inContext: ReadonlyArray = [], +) => Effect.promise(() => { - const key = `${base.sizePoints}/${base.family}`; + const key = [`${base.sizePoints}/${base.family}`, ...inContext.map(wordFontStyleName)].join( + "|", + ); const existing = cached.get(key); if (existing !== undefined) return existing; - const packed = packReferenceDocument(base); + const packed = packReferenceDocument(base, inContext); cached.set(key, packed); return packed; }); diff --git a/apps/web/src/scient/documentPage/documentFont.ts b/apps/web/src/scient/documentPage/documentFont.ts index e5cbf7c8ce..1a471783c4 100644 --- a/apps/web/src/scient/documentPage/documentFont.ts +++ b/apps/web/src/scient/documentPage/documentFont.ts @@ -3,7 +3,7 @@ import { markdownFontSpanStyle, parseMarkdownFontSpanStyle, } from "@scientfactory/scient-markdown"; -import { readMarkdownDocumentFont } from "../markdownEditor/documentFont"; +import { LEADING_FRONT_MATTER, readMarkdownDocumentFont } from "../markdownEditor/documentFont"; import { isFontFamilyName } from "../writing/fontChoices"; /** @@ -62,6 +62,6 @@ export function rehypeApplyFontSpans() { /** The leading `---` block of the document, if it starts with one. */ export function documentFontOfMarkdown(markdown: string) { - const front = /^---[ \t]*\r?\n[\s\S]*?\r?\n---[ \t]*(?:\r?\n|$)/u.exec(markdown); + const front = LEADING_FRONT_MATTER.exec(markdown); return readMarkdownDocumentFont(front?.[0] ?? null); } diff --git a/apps/web/src/scient/markdownEditor/documentFont.test.ts b/apps/web/src/scient/markdownEditor/documentFont.test.ts index eb34658db5..d1e489dcd8 100644 --- a/apps/web/src/scient/markdownEditor/documentFont.test.ts +++ b/apps/web/src/scient/markdownEditor/documentFont.test.ts @@ -30,6 +30,13 @@ describe("Markdown document font front matter", () => { ); }); + it("keeps the blank lines of the block", () => { + const source = "---\ntitle: T\n\n# notes\ntags: [a]\n\nfont-size: 10pt\n---"; + expect(writeMarkdownDocumentFont(source, { fontFamily: null, fontSize: "12pt" })).toBe( + "---\ntitle: T\n\n# notes\ntags: [a]\nfont-size: 12pt\n\n---", + ); + }); + it("removes the block when the last key goes, and refuses TOML", () => { expect(writeMarkdownDocumentFont("---\nfont-size: 10pt\n---", none)).toBeNull(); expect( diff --git a/apps/web/src/scient/markdownEditor/documentFont.ts b/apps/web/src/scient/markdownEditor/documentFont.ts index 7bb51d3f7c..f6841c3f3d 100644 --- a/apps/web/src/scient/markdownEditor/documentFont.ts +++ b/apps/web/src/scient/markdownEditor/documentFont.ts @@ -1,3 +1,4 @@ +import { DOCUMENT_FONT_SIZES, type DocumentFontSize } from "@scientfactory/scient-markdown"; import { FONT_FAMILIES, type FontFamilyName } from "../writing/fontChoices"; /** @@ -5,14 +6,14 @@ import { FONT_FAMILIES, type FontFamilyName } from "../writing/fontChoices"; * leading YAML front matter (`font-size: 11pt`, `font-family: serif`). The * sizes match the LaTeX Document settings card. */ -export const DOCUMENT_FONT_SIZES = ["10pt", "11pt", "12pt"] as const; -export type DocumentFontSize = (typeof DOCUMENT_FONT_SIZES)[number]; export interface MarkdownDocumentFont { readonly fontFamily: FontFamilyName | 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 FONT_KEYS = /^font-(?:size|family)[ \t]*:/u; @@ -56,9 +57,12 @@ export function writeMarkdownDocumentFont( const match = YAML_FRONT_MATTER.exec(frontMatter); if (!match) return undefined; const [, open, eol, body = "", close, after = ""] = match; - const kept = body.split(/\r?\n/u).filter((line) => line !== "" && !FONT_KEYS.test(line)); - const lines = [...kept, ...wanted]; - if (lines.length === 0) return null; + // The font keys go after the last other key; blank lines inside the block are kept. + const others = body.split(/\r?\n/u).filter((line) => !FONT_KEYS.test(line)); + const kept = others.every((line) => line === "") ? [] : others; + if (wanted.length === 0 && kept.length === 0) return null; + const insertAt = kept.findLastIndex((line) => line !== "") + 1; + const lines = [...kept.slice(0, insertAt), ...wanted, ...kept.slice(insertAt)]; const newline = eol ?? "\n"; return `${open}${newline}${lines.join(newline)}${newline}${close}${after}`; } diff --git a/apps/web/src/scient/markdownEditor/prosemirror/fontStyles.test.ts b/apps/web/src/scient/markdownEditor/prosemirror/fontStyles.test.ts index 18e16d39d0..84c4c830e9 100644 --- a/apps/web/src/scient/markdownEditor/prosemirror/fontStyles.test.ts +++ b/apps/web/src/scient/markdownEditor/prosemirror/fontStyles.test.ts @@ -121,6 +121,24 @@ describe("Markdown font size and family", () => { } }); + 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"); + expect(session.session.draftSource.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(); diff --git a/apps/web/src/scient/markdownEditor/ui/MarkdownDocumentSettings.tsx b/apps/web/src/scient/markdownEditor/ui/MarkdownDocumentSettings.tsx index b22f14ed0b..3b715f2964 100644 --- a/apps/web/src/scient/markdownEditor/ui/MarkdownDocumentSettings.tsx +++ b/apps/web/src/scient/markdownEditor/ui/MarkdownDocumentSettings.tsx @@ -4,7 +4,8 @@ import { Button } from "~/components/ui/button"; import { LatexSelect } from "~/scient/latex/LatexSelect"; import { DocumentSettingsField } from "~/scient/writing/DocumentSettingsField"; import { FONT_FAMILIES, isFontFamilyName } from "~/scient/writing/fontChoices"; -import { DOCUMENT_FONT_SIZES, type MarkdownDocumentFont } from "../documentFont"; +import { DOCUMENT_FONT_SIZES } from "@scientfactory/scient-markdown"; +import type { MarkdownDocumentFont } from "../documentFont"; const DEFAULT_CHOICE = "default"; diff --git a/packages/scient-markdown/src/fontSpans.ts b/packages/scient-markdown/src/fontSpans.ts index 2effc55e9d..5adb6e7f60 100644 --- a/packages/scient-markdown/src/fontSpans.ts +++ b/packages/scient-markdown/src/fontSpans.ts @@ -17,6 +17,10 @@ export const MARKDOWN_FONT_SIZES = [ { name: "Huge", em: 2.49 }, ] as const; +/** Whole-document base sizes: the `font-size` front matter values and the LaTeX class options. */ +export const DOCUMENT_FONT_SIZES = ["10pt", "11pt", "12pt"] as const; +export type DocumentFontSize = (typeof DOCUMENT_FONT_SIZES)[number]; + export const MARKDOWN_FONT_FAMILIES = ["serif", "sans-serif", "monospace"] as const; export type MarkdownFontSizeName = (typeof MARKDOWN_FONT_SIZES)[number]["name"]; diff --git a/packages/scient-markdown/src/index.ts b/packages/scient-markdown/src/index.ts index c702fba0f5..8078808e5f 100644 --- a/packages/scient-markdown/src/index.ts +++ b/packages/scient-markdown/src/index.ts @@ -42,6 +42,7 @@ export { type MarkdownDocumentInspection, } from "./documentResources.ts"; export { + DOCUMENT_FONT_SIZES, MARKDOWN_FONT_FAMILIES, MARKDOWN_FONT_SIZES, MARKDOWN_FONT_SPAN_CLOSE, @@ -49,6 +50,7 @@ export { markdownFontSpanStyle, parseMarkdownFontSpanOpen, parseMarkdownFontSpanStyle, + type DocumentFontSize, type MarkdownFontFamilyName, type MarkdownFontSizeName, type MarkdownFontSpan, From 2f907d3c6e83c2cea17f5a3b82a6cd40caddc159 Mon Sep 17 00:00:00 2001 From: Tova <291672564+Tova22@users.noreply.github.com> Date: Tue, 10 Nov 2026 11:36:01 +0200 Subject: [PATCH 05/42] Do not carry a font around a footnote reference into the footnote, and test heading and footnote sizes with Pandoc Found by a second independent review. A heading or a footnote now starts from its own size and no outer font; the reference document cache key no longer depends on span order. Added integration tests for sizes inside a heading and a footnote, and stricter unit tests. Co-Authored-By: Claude Sonnet 5.5 --- .../PandocWordConverter.integration.test.ts | 43 +++++++++++++++++++ .../src/scient/pandoc/pandocFont.test.ts | 31 ++++++++++++- apps/server/src/scient/pandoc/pandocFont.ts | 16 +++---- .../scient/pandoc/scientReferenceDocument.ts | 7 +-- .../prosemirror/fontStyles.test.ts | 4 +- 5 files changed, 88 insertions(+), 13 deletions(-) diff --git a/apps/server/src/scient/pandoc/PandocWordConverter.integration.test.ts b/apps/server/src/scient/pandoc/PandocWordConverter.integration.test.ts index 320e4b7200..50f6f36f87 100644 --- a/apps/server/src/scient/pandoc/PandocWordConverter.integration.test.ts +++ b/apps/server/src/scient/pandoc/PandocWordConverter.integration.test.ts @@ -687,6 +687,49 @@ describe.skipIf(binary === null)("Word export with the real Pandoc (local integr }), ); + it.live("keeps the share of the heading size for a size inside a heading", () => + Effect.gen(function* () { + const { document, styles } = yield* exportMarkdown( + "font-heading", + '# Title with big word\n\nPlain body.\n', + ); + expect(document).toMatch( + /[\s\S]*?]*>big<\/w:t>/u, + ); + // 1.2 x 18 pt = 21.6 pt, kept to the half point: 21.5 pt. + expect(styles).toMatch( + /]*w:styleId="ScientSize120of18pt"(?:(?!<\/w:style>)[\s\S])*?/u, + ); + // The same size in the body stays a share of the base size. + expect(document).toMatch( + /[\s\S]*?]*>body<\/w:t>/u, + ); + }), + ); + + it.live("keeps the share of the footnote size for a size inside a footnote", () => + Effect.gen(function* () { + const { styles, footnotes } = yield* withConverter(({ converter, directory }) => + Effect.gen(function* () { + const { docx } = yield* convertTo(converter, directory, "font-footnote", { + bundle: makeBundle({ + markdown: 'Text[^1]\n\n[^1]: Note with big.\n', + }), + }); + return { + styles: docx.text("word/styles.xml"), + footnotes: docx.text("word/footnotes.xml"), + }; + }), + ); + expect(footnotes).toMatch(//u); + // 1.2 x 9 pt = 10.8 pt, kept to the half point: 11 pt. + expect(styles).toMatch( + /]*w:styleId="ScientSize120of9pt"(?:(?!<\/w:style>)[\s\S])*?/u, + ); + }), + ); + it.live("still drops every other span", () => Effect.gen(function* () { const { document, warnings } = yield* exportMarkdown( diff --git a/apps/server/src/scient/pandoc/pandocFont.test.ts b/apps/server/src/scient/pandoc/pandocFont.test.ts index 313bbe6265..81cbf14897 100644 --- a/apps/server/src/scient/pandoc/pandocFont.test.ts +++ b/apps/server/src/scient/pandoc/pandocFont.test.ts @@ -135,6 +135,35 @@ describe("a local size keeps its share of the surrounding text", () => { ([name]) => name === "word/styles.xml", )?.[1]; // 1.2 x 18 pt = 21.6 pt, kept to the half point: 21.5 pt, which Word writes as 43. - expect(styles).toMatch(/w:styleId="ScientSize120of18pt"[\s\S]*?]*w:styleId="ScientSize120of18pt"(?:(?!<\/w:style>)[\s\S])*? { + const family = { t: "RawInline", c: ["html", ''] }; + const text = [ + { + t: "Para", + c: [open, { t: "Note", c: [{ t: "Para", c: [family, word, close] }] }, close], + }, + ]; + applyFontSpans(text, pass()); + expect(JSON.stringify(text)).toContain("Scient Font monospace"); + expect(JSON.stringify(text)).not.toContain("120% of 9pt Font"); + }); + + it("combines a size and a family in a heading", () => { + const family = { t: "RawInline", c: ["html", ''] }; + const heading = [{ t: "Header", c: [2, attributes, [open, family, word, close, close]] }]; + const used = pass(); + applyFontSpans(heading, used); + // Pandoc keeps only the innermost style of a run, so the innermost one names both. + expect( + JSON.stringify(heading) + .match(/Scient[^"]*/gu) + ?.at(-1), + ).toBe("Scient Size 120% of 15pt Font serif"); + expect(used.inContext.has("Scient Size 120% of 15pt Font serif")).toBe(true); }); }); diff --git a/apps/server/src/scient/pandoc/pandocFont.ts b/apps/server/src/scient/pandoc/pandocFont.ts index 32907af79f..d2a188d05d 100644 --- a/apps/server/src/scient/pandoc/pandocFont.ts +++ b/apps/server/src/scient/pandoc/pandocFont.ts @@ -44,17 +44,19 @@ function styleNameOf(font: WordLocalFont, pass: FontPass): string { } /** - * The size in points of the text a node holds, when it is not the base size. A size in a heading - * or a footnote is a share of that text's size, as in the editor, not of the base size. + * The font in force inside a node. A heading or a footnote starts afresh at its own size: a size + * in it is a share of that size, as in the editor, not of the base size, and a font set around a + * footnote reference does not reach the footnote text. */ -function contextOf(node: PandocNode, pass: FontPass): number | undefined { +function fontWithin(node: PandocNode, outer: WordLocalFont, pass: FontPass): WordLocalFont { const points = node.t === "Header" && Array.isArray(node.c) ? HEADING_POINTS[Number(node.c[0]) - 1] : node.t === "Note" ? FOOTNOTE_POINTS : undefined; - return points === pass.base.sizePoints ? undefined : points; + if (points === undefined) return outer; + return points === pass.base.sizePoints ? {} : { context: points }; } /** The font of a span laid over the font already in force around it. */ @@ -110,8 +112,7 @@ export function applyFontSpans(value: unknown, pass: FontPass, outer: WordLocalF return; } if (!Predicate.isObject(value)) return; - const context = isPandocNode(value) ? contextOf(value, pass) : undefined; - const within = context === undefined ? outer : { ...outer, context }; + const within = isPandocNode(value) ? fontWithin(value, outer, pass) : outer; for (const child of Object.values(value)) applyFontSpans(child, pass, within); } @@ -283,7 +284,6 @@ export function applyLatexFontSpans( return; } } - const context = isPandocNode(value) ? contextOf(value, pass) : undefined; - const within = context === undefined ? outer : { ...outer, context }; + const within = isPandocNode(value) ? fontWithin(value, outer, pass) : 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 2551c6817b..0762ba09cb 100644 --- a/apps/server/src/scient/pandoc/scientReferenceDocument.ts +++ b/apps/server/src/scient/pandoc/scientReferenceDocument.ts @@ -551,9 +551,10 @@ export const scientReferenceDocumentFor = ( inContext: ReadonlyArray = [], ) => Effect.promise(() => { - const key = [`${base.sizePoints}/${base.family}`, ...inContext.map(wordFontStyleName)].join( - "|", - ); + const key = [ + `${base.sizePoints}/${base.family}`, + ...inContext.map(wordFontStyleName).toSorted(), + ].join("|"); const existing = cached.get(key); if (existing !== undefined) return existing; const packed = packReferenceDocument(base, inContext); diff --git a/apps/web/src/scient/markdownEditor/prosemirror/fontStyles.test.ts b/apps/web/src/scient/markdownEditor/prosemirror/fontStyles.test.ts index 84c4c830e9..cea47241e3 100644 --- a/apps/web/src/scient/markdownEditor/prosemirror/fontStyles.test.ts +++ b/apps/web/src/scient/markdownEditor/prosemirror/fontStyles.test.ts @@ -136,7 +136,9 @@ describe("Markdown font size and family", () => { "user", ); session.applyTransaction(session.state.tr.insertText("X"), "user"); - expect(session.session.draftSource.startsWith(`${block}\n\n`)).toBe(true); + const written = session.session.draftSource; + expect(written).toContain("X"); + expect(written.startsWith(`${block}\n\n`)).toBe(true); }); it("defines both marks in the schema", () => { From acd7bf1bb85e33fe90389a96d6d7ed930e46e56e Mon Sep 17 00:00:00 2001 From: Tova <291672564+Tova22@users.noreply.github.com> Date: Wed, 11 Nov 2026 19:40:57 +0200 Subject: [PATCH 06/42] feat(documents): numeric font sizes in points and a named-font catalogue Sizes are free numbers of points (1 to 100) in both editors and in the Word export; fonts come from one shared catalogue. Markdown stores `font-size:12pt` and `font-family:'Times New Roman'`; LaTeX Visual stores `{\fontsize{N}{M}\selectfont ...}` groups. Both editors share one FontControls panel. The Word export defines one character style per used size and font. Co-Authored-By: Claude Sonnet 5.5 --- .../PandocWordConverter.integration.test.ts | 87 ++++------ .../src/scient/pandoc/PandocWordConverter.ts | 4 +- .../src/scient/pandoc/pandocFont.test.ts | 135 ++++++++-------- apps/server/src/scient/pandoc/pandocFont.ts | 128 ++++++++------- .../scient/pandoc/scientReferenceDocument.ts | 128 ++++++--------- .../documentPage/ScientDocumentPage.tsx | 8 + .../scient/documentPage/documentFont.test.ts | 24 +-- .../src/scient/documentPage/documentFont.ts | 25 ++- .../documentPage/scient-document-page.css | 12 +- .../scient/latex/LatexDocumentSettings.tsx | 12 +- .../src/scient/latex/LatexVisualEditor.tsx | 34 +++- .../scient/latex/latexContentLayouts.test.ts | 5 +- .../src/scient/latex/latexEditingTarget.ts | 19 ++- .../web/src/scient/latex/latexFontCommands.ts | 72 +++++---- .../src/scient/latex/latexFontSize.test.ts | 43 +++++ .../src/scient/latex/latexTextFormatting.ts | 55 ++++++- .../src/scient/latex/latexVisualDocument.ts | 55 +++++-- .../markdownEditor/documentFont.test.ts | 57 +++++-- .../src/scient/markdownEditor/documentFont.ts | 117 ++++++++++---- .../markdownEditor/prosemirror/commands.ts | 41 +++-- .../prosemirror/documentFontPresentation.ts | 10 +- .../prosemirror/fontStyles.test.ts | 56 +++---- .../markdownEditor/prosemirror/schema.ts | 32 ++-- .../scient/markdownEditor/prosemirror/view.ts | 22 +-- .../markdownEditor/scient-markdown-editor.css | 10 +- .../ui/MarkdownDocumentSettings.tsx | 8 +- .../ui/ScientMarkdownControls.tsx | 8 +- apps/web/src/scient/writing/FontControls.tsx | 153 ++++++++++++++++++ apps/web/src/scient/writing/FontMenuItems.tsx | 67 -------- apps/web/src/scient/writing/fontChoices.ts | 55 +++---- packages/scient-markdown/src/fontCatalogue.ts | 127 +++++++++++++++ .../scient-markdown/src/fontSpans.test.ts | 38 +++++ packages/scient-markdown/src/fontSpans.ts | 59 +++---- packages/scient-markdown/src/index.ts | 13 +- .../scient-markdown/src/sourceLedger.test.ts | 8 +- 35 files changed, 1090 insertions(+), 637 deletions(-) create mode 100644 apps/web/src/scient/latex/latexFontSize.test.ts create mode 100644 apps/web/src/scient/writing/FontControls.tsx delete mode 100644 apps/web/src/scient/writing/FontMenuItems.tsx create mode 100644 packages/scient-markdown/src/fontCatalogue.ts create mode 100644 packages/scient-markdown/src/fontSpans.test.ts diff --git a/apps/server/src/scient/pandoc/PandocWordConverter.integration.test.ts b/apps/server/src/scient/pandoc/PandocWordConverter.integration.test.ts index 50f6f36f87..494ab212fd 100644 --- a/apps/server/src/scient/pandoc/PandocWordConverter.integration.test.ts +++ b/apps/server/src/scient/pandoc/PandocWordConverter.integration.test.ts @@ -648,85 +648,53 @@ describe.skipIf(binary === null)("Word export with the real Pandoc (local integr }), ); - it.live("applies a recognised size span as a Word character style", () => + 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.', + 'Some big words.', ); expect(document).toMatch( - /[\s\S]*?]*>big<\/w:t>/u, + /[\s\S]*?]*>big<\/w:t>/u, ); - expect(styles).toMatch(/w:styleId="ScientSize120"[\s\S]*?/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 recognised family span as a Word character style", () => + 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.', + "Some code words.", ); - expect(document).toMatch(/[\s\S]*?code/u); - expect(styles).toMatch(/w:styleId="ScientFontmonospace"[\s\S]*?Consolas/u); + 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 family span are nested", () => + 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.', + '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("ScientSize120"); - expect(wordsRun).toContain("ScientSize120Fontsansserif"); + expect(sizeRun).toContain("Scient14pt"); + expect(wordsRun).toContain("ScientArial14pt"); }), ); - it.live("keeps the share of the heading size for a size inside a heading", () => + 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\nPlain body.\n', - ); - expect(document).toMatch( - /[\s\S]*?]*>big<\/w:t>/u, - ); - // 1.2 x 18 pt = 21.6 pt, kept to the half point: 21.5 pt. - expect(styles).toMatch( - /]*w:styleId="ScientSize120of18pt"(?:(?!<\/w:style>)[\s\S])*?/u, - ); - // The same size in the body stays a share of the base size. - expect(document).toMatch( - /[\s\S]*?]*>body<\/w:t>/u, - ); - }), - ); - - it.live("keeps the share of the footnote size for a size inside a footnote", () => - Effect.gen(function* () { - const { styles, footnotes } = yield* withConverter(({ converter, directory }) => - Effect.gen(function* () { - const { docx } = yield* convertTo(converter, directory, "font-footnote", { - bundle: makeBundle({ - markdown: 'Text[^1]\n\n[^1]: Note with big.\n', - }), - }); - return { - styles: docx.text("word/styles.xml"), - footnotes: docx.text("word/footnotes.xml"), - }; - }), - ); - expect(footnotes).toMatch(//u); - // 1.2 x 9 pt = 10.8 pt, kept to the half point: 11 pt. - expect(styles).toMatch( - /]*w:styleId="ScientSize120of9pt"(?:(?!<\/w:style>)[\s\S])*?/u, + '# 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); }), ); @@ -743,14 +711,15 @@ describe.skipIf(binary === null)("Word export with the real Pandoc (local integr }), ); - it.live("sets the base font and scales local sizes from the front matter", () => + it.live("sets the base font and size from the front matter", () => Effect.gen(function* () { const { styles } = yield* exportMarkdown( "font-front-matter", - '---\nfont-size: 12pt\nfont-family: serif\n---\n\nText with size.\n', + "---\nfontsize: 12pt\nmainfont: Times New Roman\n---\n\nText.\n", + ); + expect(styles).toMatch( + /[\s\S]*?w:ascii="Times New Roman"[\s\S]*?/u, ); - expect(styles).toMatch(/[\s\S]*?Cambria[\s\S]*?/u); - expect(styles).toMatch(/w:styleId="ScientSize120"[\s\S]*?/u); }), ); const exportLatex = (name: string, tex: string) => @@ -776,16 +745,16 @@ describe.skipIf(binary === null)("Word export with the real Pandoc (local integr [ "\\documentclass{article}", "\\begin{document}", - "A {\\Large big \\textsf{both}} and \\textrm{roman} and {\\small tiny}.", + "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("ScientSize144"); - expect(run("both")).toContain("ScientSize144Fontsansserif"); - expect(run("roman")).toContain("ScientFontserif"); - expect(run("tiny")).toContain("ScientSize90"); + 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"); }), ); @@ -802,7 +771,9 @@ describe.skipIf(binary === null)("Word export with the real Pandoc (local integr "\\end{document}", ].join("\n"), ); - expect(styles).toMatch(/[\s\S]*?Cambria[\s\S]*?/u); + expect(styles).toMatch( + /[\s\S]*?Times New Roman[\s\S]*?/u, + ); }), ); }); diff --git a/apps/server/src/scient/pandoc/PandocWordConverter.ts b/apps/server/src/scient/pandoc/PandocWordConverter.ts index a76e49f7b3..6cf0dd64cd 100644 --- a/apps/server/src/scient/pandoc/PandocWordConverter.ts +++ b/apps/server/src/scient/pandoc/PandocWordConverter.ts @@ -377,7 +377,7 @@ 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, inContext: new Map() }; + const fontPass = { base: baseFont, used: new Map() }; if (input.latex) applyLatexFontSpans(document.blocks, fontPass); else applyFontSpans(document.blocks, fontPass); const security = yield* securePandocDocument(document, { @@ -419,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* scientReferenceDocumentFor(baseFont, [...fontPass.inContext.values()]), + 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 index 81cbf14897..940c3113f7 100644 --- a/apps/server/src/scient/pandoc/pandocFont.test.ts +++ b/apps/server/src/scient/pandoc/pandocFont.test.ts @@ -16,13 +16,13 @@ const carrier = (name: string, body: string) => `\\ScientSize{scient-size-${name 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("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("large", `a ${carrier("small", "b")} \\textsf{c}`), + carrier("12", `a ${carrier("9", "b")} \\textsf{c}`), ); }); @@ -65,7 +65,7 @@ describe("rewriteLatexSizeGroups", () => { }); it("still rewrites a group after bracket math", () => { - expect(rewriteLatexSizeGroups("\\[ a \\] {\\large x}")).toContain(carrier("large", "x")); + expect(rewriteLatexSizeGroups("\\[ a \\] {\\large x}")).toContain(carrier("12", "x")); }); it("does not match a longer command that starts with a size name", () => { @@ -80,90 +80,97 @@ describe("latexBaseFontOf", () => { latexBaseFontOf( "\\documentclass[a4paper,12pt]{article}\n\\renewcommand{\\familydefault}{\\ttdefault}", ), - ).toEqual({ sizePoints: 12, family: "monospace" }); + ).toEqual({ sizePoints: 12, family: "Courier New" }); }); it("keeps the Word default when nothing is set", () => { expect(latexBaseFontOf("\\documentclass{article}")).toEqual({ sizePoints: 11, - family: "sans-serif", + family: null, }); }); }); -describe("a local size keeps its share of the surrounding text", () => { - const open = { t: "RawInline", c: ["html", ''] }; - const close = { t: "RawInline", c: ["html", ""] }; +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 = (sizePoints = 11): FontPass => ({ - base: { sizePoints, family: "sans-serif" }, - inContext: new Map(), + const pass = (): FontPass => ({ + base: { sizePoints: 11, family: null }, + used: new Map(), }); - const attributes = ["", [], []]; - const styleOf = (inlines: Array) => - JSON.stringify(inlines).match(/Scient[^"]*/u)?.[0] ?? null; + const stylesOf = (inlines: unknown) => + JSON.stringify(inlines).match(/custom-style","([^"]*)/gu) ?? []; - it("names the heading size in the style of a size set inside a heading", () => { - const heading = [{ t: "Header", c: [1, attributes, [open, word, close]] }]; - const used = pass(); - applyFontSpans(heading, used); - expect(styleOf(heading)).toBe("Scient Size 120% of 18pt"); - expect([...used.inContext.keys()]).toEqual(["Scient Size 120% of 18pt"]); - }); - - it("uses the footnote size inside a footnote", () => { - const note = [{ t: "Para", c: [{ t: "Note", c: [{ t: "Para", c: [open, word, close] }] }] }]; - const used = pass(); - applyFontSpans(note, used); - expect(styleOf(note)).toBe("Scient Size 120% of 9pt"); - }); - - it("keeps the plain style in a paragraph, and in a heading the size of the base", () => { - const text = [{ t: "Para", c: [open, word, close] }]; - const same = [{ t: "Header", c: [5, attributes, [open, word, close]] }]; + it("names an absolute size in points", () => { + const text = [{ t: "Para", c: [raw(''), word, close] }]; const used = pass(); applyFontSpans(text, used); - applyFontSpans(same, used); - expect(styleOf(text)).toBe("Scient Size 120%"); - expect(styleOf(same)).toBe("Scient Size 120%"); - expect(used.inContext.size).toBe(0); - }); - - it("writes the style of a heading size with the heading size times the share", () => { - const font = { em: 1.2, context: 18 }; - const styles = scientReferenceDocumentParts(undefined, [font]).find( - ([name]) => name === "word/styles.xml", - )?.[1]; - // 1.2 x 18 pt = 21.6 pt, kept to the half point: 21.5 pt, which Word writes as 43. - expect(styles).toMatch( - /]*w:styleId="ScientSize120of18pt"(?:(?!<\/w:style>)[\s\S])*? { - const family = { t: "RawInline", c: ["html", ''] }; + it("names a font and combines a nested size and font in one style", () => { const text = [ { t: "Para", - c: [open, { t: "Note", c: [{ t: "Para", c: [family, word, close] }] }, close], + 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(JSON.stringify(text)).toContain("Scient Font monospace"); - expect(JSON.stringify(text)).not.toContain("120% of 9pt Font"); + expect(stylesOf(text)).toEqual([]); }); - it("combines a size and a family in a heading", () => { - const family = { t: "RawInline", c: ["html", ''] }; - const heading = [{ t: "Header", c: [2, attributes, [open, family, word, close, close]] }]; - const used = pass(); - applyFontSpans(heading, used); - // Pandoc keeps only the innermost style of a run, so the innermost one names both. - expect( - JSON.stringify(heading) - .match(/Scient[^"]*/gu) - ?.at(-1), - ).toBe("Scient Size 120% of 15pt Font serif"); - expect(used.inContext.has("Scient Size 120% of 15pt Font serif")).toBe(true); + 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: 11, family: null }); }); }); diff --git a/apps/server/src/scient/pandoc/pandocFont.ts b/apps/server/src/scient/pandoc/pandocFont.ts index d2a188d05d..e91887bf4a 100644 --- a/apps/server/src/scient/pandoc/pandocFont.ts +++ b/apps/server/src/scient/pandoc/pandocFont.ts @@ -1,15 +1,14 @@ /** * Word export of local font size and family. Scient's recognised `` forms are turned - * into Word character styles before raw HTML is stripped; the `font-size` and `font-family` - * front matter keys set the base font of the reference document. + * 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_FAMILIES, - MARKDOWN_FONT_SIZES, MARKDOWN_FONT_SPAN_CLOSE, - type MarkdownFontFamilyName, type MarkdownFontSpan, + catalogueFont, + normalizeFontSize, parseMarkdownFontSpanOpen, } from "@scientfactory/scient-markdown"; import * as Predicate from "effect/Predicate"; @@ -17,8 +16,6 @@ import * as Predicate from "effect/Predicate"; import { attr, customStyleSpan, inlineText, isPandocNode, type PandocNode } from "./pandocAst.ts"; import { DEFAULT_WORD_BASE_FONT, - FOOTNOTE_POINTS, - HEADING_POINTS, type WordBaseFont, type WordLocalFont, wordFontStyleName, @@ -27,43 +24,22 @@ import { const SPAN_OPEN = /^; + readonly used: Map; } -/** The Word style name for a font, noting it when it needs a style of its own. */ +/** 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); - if (font.em !== undefined && font.context !== undefined) pass.inContext.set(name, font); + pass.used.set(name, font); return name; } -/** - * The font in force inside a node. A heading or a footnote starts afresh at its own size: a size - * in it is a share of that size, as in the editor, not of the base size, and a font set around a - * footnote reference does not reach the footnote text. - */ -function fontWithin(node: PandocNode, outer: WordLocalFont, pass: FontPass): WordLocalFont { - const points = - node.t === "Header" && Array.isArray(node.c) - ? HEADING_POINTS[Number(node.c[0]) - 1] - : node.t === "Note" - ? FOOTNOTE_POINTS - : undefined; - if (points === undefined) return outer; - return points === pass.base.sizePoints ? {} : { context: points }; -} - /** The font of a span laid over the font already in force around it. */ function layered(outer: WordLocalFont, span: MarkdownFontSpan): WordLocalFont { - if ("family" in span) return { ...outer, family: span.family }; - const size = MARKDOWN_FONT_SIZES.find(({ name }) => name === span.size); - return size === undefined ? outer : { ...outer, em: size.em }; + 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. */ @@ -112,23 +88,18 @@ export function applyFontSpans(value: unknown, pass: FontPass, outer: WordLocalF return; } if (!Predicate.isObject(value)) return; - const within = isPandocNode(value) ? fontWithin(value, outer, pass) : outer; - for (const child of Object.values(value)) applyFontSpans(child, pass, within); -} - -function isFontFamilyName(value: string): value is MarkdownFontFamilyName { - return MARKDOWN_FONT_FAMILIES.some((family) => family === value); + for (const child of Object.values(value)) applyFontSpans(child, pass, outer); } /** The base font named by the document's metadata; anything unrecognised keeps the default. */ export function wordBaseFontOf(meta: Record): WordBaseFont { - const size = inlineText(meta["font-size"]).trim(); - const family = inlineText(meta["font-family"]).trim(); + 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: isFontFamilyName(family) ? family : DEFAULT_WORD_BASE_FONT.family, + family: catalogueFont(family) === null ? DEFAULT_WORD_BASE_FONT.family : family, }; } @@ -136,8 +107,22 @@ export function wordBaseFontOf(meta: Record): WordBaseFont { // 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`^\\(${MARKDOWN_FONT_SIZES.map(({ name }) => name).join("|")})(?![A-Za-z@])\s?`, + String.raw`^\\(?:(${Object.keys(LATEX_NAMED_SIZES).join("|")})|fontsize\{(\d+(?:\.\d+)?)\}\{[^{}]*\}\\selectfont)(?:\{\}|(?![A-Za-z@])\s?)`, "u", ); const LATEX_SIZE_CARRIER = "scient-size-"; @@ -147,12 +132,28 @@ const LATEX_CLASS_SIZE = new RegExp( "u", ); const LATEX_FAMILY_DEFAULT = /\\renewcommand\s*\{\\familydefault\}\s*\{\\(rm|sf|tt)default\}/u; -const LATEX_FAMILIES: Readonly> = { - rm: "serif", - sf: "sans-serif", - tt: "monospace", +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(/(? { let backslashes = 0; while (index - 1 - backslashes >= 0 && text[index - 1 - backslashes] === "\\") backslashes += 1; @@ -182,7 +183,11 @@ const LATEX_VERBATIM_START = /^\\begin\{(verbatim\*?|lstlisting|minted)\}/u; // A brace right after a command name or a closing bracket is that command's argument, not a group. const LATEX_ARGUMENT_BEFORE = /[A-Za-z}\]*@]/u; -function rewriteSizeGroups(text: string, counter: { found: boolean }): string { +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) { @@ -213,10 +218,12 @@ function rewriteSizeGroups(text: string, counter: { found: boolean }): string { if (char === "{" && standalone && !inMath && !isEscaped(text, index)) { const command = LATEX_SIZE_COMMAND.exec(text.slice(index + 1)); const end = command === null ? -1 : braceEnd(text, index); - if (command !== null && end >= 0) { + const points = command === null ? null : latexCommandPoints(command, classSize); + if (command !== null && points !== null && end >= 0) { counter.found = true; const body = text.slice(index + 1 + command[0].length, end); - out += `\\ScientSize{${LATEX_SIZE_CARRIER}${command[1]}}{${rewriteSizeGroups(body, counter)}}`; + const carrier = `${LATEX_SIZE_CARRIER}${String(points).replace(".", "p")}`; + out += `\\ScientSize{${carrier}}{${rewriteSizeGroups(body, counter, classSize)}}`; index = end; continue; } @@ -229,14 +236,15 @@ function rewriteSizeGroups(text: string, counter: { found: boolean }): string { /** 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); + const rewritten = rewriteSizeGroups(source, counter, latexClassSize(source)); return counter.found ? `${LATEX_SIZE_MACRO}\n${rewritten}` : source; } /** The base font set by the preamble's class option and `\familydefault`, as the Visual card writes them. */ export function latexBaseFontOf(source: string): WordBaseFont { - const size = LATEX_CLASS_SIZE.exec(source)?.[1]; - const family = LATEX_FAMILY_DEFAULT.exec(source)?.[1]; + const active = withoutComments(source); + const size = LATEX_CLASS_SIZE.exec(active)?.[1]; + const family = LATEX_FAMILY_DEFAULT.exec(active)?.[1]; return { sizePoints: size === undefined ? DEFAULT_WORD_BASE_FONT.sizePoints : Number.parseInt(size, 10), family: @@ -249,17 +257,16 @@ 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: "sans-serif" }; - if (classes.includes("roman")) return { family: "serif" }; + 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 name = Predicate.isString(style) - ? new RegExp(`^color:\\s*${LATEX_SIZE_CARRIER}(\\w+)$`, "u").exec(style)?.[1] + const carried = Predicate.isString(style) + ? new RegExp(`^color:\\s*${LATEX_SIZE_CARRIER}(\\d+(?:p\\d+)?)$`, "u").exec(style)?.[1] : undefined; - const size = MARKDOWN_FONT_SIZES.find((entry) => entry.name === name); - if (size !== undefined) return { em: size.em }; + if (carried !== undefined) return { size: Number(carried.replace("p", ".")) }; } return null; } @@ -284,6 +291,5 @@ export function applyLatexFontSpans( return; } } - const within = isPandocNode(value) ? fontWithin(value, outer, pass) : outer; - for (const child of Object.values(value)) applyLatexFontSpans(child, pass, within); + for (const child of Object.values(value)) applyLatexFontSpans(child, pass, outer); } diff --git a/apps/server/src/scient/pandoc/scientReferenceDocument.ts b/apps/server/src/scient/pandoc/scientReferenceDocument.ts index 0762ba09cb..348b9ce287 100644 --- a/apps/server/src/scient/pandoc/scientReferenceDocument.ts +++ b/apps/server/src/scient/pandoc/scientReferenceDocument.ts @@ -7,11 +7,7 @@ import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as yazl from "yazl"; -import { - MARKDOWN_FONT_FAMILIES, - MARKDOWN_FONT_SIZES, - type MarkdownFontFamilyName, -} from "@scientfactory/scient-markdown"; +import { catalogueFont } from "@scientfactory/scient-markdown"; const W = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"; const BODY_FONT = ``; @@ -49,12 +45,16 @@ 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; a local size in a heading is a share of its level's. */ -export const HEADING_POINTS = [18, 15, 13, 12, 11, 11, 11, 11, 11] as const; +/** 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. */ -export const FOOTNOTE_POINTS = 9; +const FOOTNOTE_POINTS = 9; function headingStyles(): Array { return HEADING_POINTS.map((points, index) => ({ @@ -352,93 +352,62 @@ export const SCIENT_REFERENCE_STYLES: ReadonlyArray = [ }, ]; -/** The document's base text size and family, from the `font-size` and `font-family` front matter. */ +/** 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: MarkdownFontFamilyName; + readonly family: string | null; } -export const DEFAULT_WORD_BASE_FONT: WordBaseFont = { sizePoints: 11, family: "sans-serif" }; - -/** Office's own fonts, one per generic family. */ -const WORD_FONT_NAMES: Readonly> = { - serif: "Cambria", - "sans-serif": "Calibri", - monospace: "Consolas", -}; +export const DEFAULT_WORD_BASE_FONT: WordBaseFont = { sizePoints: 11, family: null }; -const familyFonts = (family: MarkdownFontFamilyName): string => - family === "sans-serif" - ? BODY_FONT - : ``; - -/** - * A local size (a share of the surrounding text) and/or family; a Word run carries only one - * style. `context` is the size in points of the surrounding text when that is not the base size, - * as inside a heading or a footnote, so the share is kept there too. - */ +/** A local size in points and/or a font name; a Word run carries only one style. */ export interface WordLocalFont { - readonly em?: number | undefined; - readonly family?: MarkdownFontFamilyName | undefined; - readonly context?: number | undefined; + readonly size?: number | undefined; + readonly family?: string | undefined; } -/** - * Word style name for a local font. Sizes are named by percentage because Word style names - * ignore case, so the LaTeX names `large` and `LARGE` would collide. - */ +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 => - [ - "Scient", - font.em === undefined - ? null - : `Size ${Math.round(font.em * 100)}%${font.context === undefined ? "" : ` of ${font.context}pt`}`, - font.family === undefined ? null : `Font ${font.family}`, - ] - .filter((part) => part !== null) + [font.family, font.size === undefined ? null : `${font.size} pt`] + .filter((part) => part !== undefined && part !== null) .join(" "); -function fontStyle(font: WordLocalFont, base: WordBaseFont): StyleSpec { +function fontStyle(font: WordLocalFont): StyleSpec { const name = wordFontStyleName(font); return { type: "character", - id: name.replaceAll(/[^A-Za-z0-9]/gu, ""), + id: `Scient${name.replaceAll(".", "_").replaceAll(/[^A-Za-z0-9_]/gu, "")}`, name, custom: true, rPr: [ font.family === undefined ? "" : familyFonts(font.family), - font.em === undefined - ? "" - : size(Math.round(font.em * (font.context ?? base.sizePoints) * 2) / 2), + font.size === undefined ? "" : size(font.size), ].join(""), }; } -/** - * Character styles for every size, every family, and every size with a family, then the styles - * for sizes used inside headings or footnotes. - */ -function fontStyles(base: WordBaseFont, inContext: ReadonlyArray): Array { - const sizes = [undefined, ...MARKDOWN_FONT_SIZES.map(({ em }) => em)]; - const families = [undefined, ...MARKDOWN_FONT_FAMILIES]; - const fonts: Array = sizes.flatMap((em) => - families.flatMap((family) => - em === undefined && family === undefined ? [] : [{ em, family }], - ), - ); - return [...fonts, ...inContext].map((font) => fontStyle(font, base)); -} - -function scientReferenceStylesXml( - base: WordBaseFont, - inContext: ReadonlyArray, -): string { +function scientReferenceStylesXml(base: WordBaseFont, used: ReadonlyArray): string { return [ ``, ``, `${familyFonts(base.family)}${size(base.sizePoints)}`, ``, - ...[...SCIENT_REFERENCE_STYLES, ...fontStyles(base, inContext)].map(style), + ...[...SCIENT_REFERENCE_STYLES, ...used.map(fontStyle)].map(style), ``, ].join(""); } @@ -512,14 +481,14 @@ const ENTRY_TIME = DateTime.toDateUtc(DateTime.makeUnsafe("2026-01-01T00:00:00Z" export function scientReferenceDocumentParts( base: WordBaseFont = DEFAULT_WORD_BASE_FONT, - inContext: ReadonlyArray = [], + 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(base, inContext)], + ["word/styles.xml", scientReferenceStylesXml(base, used)], ]; } @@ -527,7 +496,7 @@ const cached = new Map>(); function packReferenceDocument( base: WordBaseFont, - inContext: ReadonlyArray, + used: ReadonlyArray, ): Promise { return new Promise((resolve, reject) => { const zip = new yazl.ZipFile(); @@ -535,29 +504,26 @@ function packReferenceDocument( 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(base, inContext)) { + 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 for a base font and the sizes used inside headings or - * footnotes; built once per process for each combination. - */ +/** The packed reference document for a base font and the local fonts used; built once per combination. */ export const scientReferenceDocumentFor = ( base: WordBaseFont, - inContext: ReadonlyArray = [], + used: ReadonlyArray = [], ) => Effect.promise(() => { const key = [ - `${base.sizePoints}/${base.family}`, - ...inContext.map(wordFontStyleName).toSorted(), + `${base.sizePoints}/${base.family ?? ""}`, + ...used.map(wordFontStyleName).toSorted(), ].join("|"); const existing = cached.get(key); if (existing !== undefined) return existing; - const packed = packReferenceDocument(base, inContext); + const packed = packReferenceDocument(base, used); cached.set(key, packed); return packed; }); diff --git a/apps/web/src/scient/documentPage/ScientDocumentPage.tsx b/apps/web/src/scient/documentPage/ScientDocumentPage.tsx index 5d87691e3f..9ae76e659d 100644 --- a/apps/web/src/scient/documentPage/ScientDocumentPage.tsx +++ b/apps/web/src/scient/documentPage/ScientDocumentPage.tsx @@ -10,6 +10,7 @@ import { use, useEffect, useState, + type CSSProperties, type ReactNode, type SyntheticEvent, } from "react"; @@ -33,6 +34,7 @@ import { scientMarkdownRemarkPlugins } from "../markdown/scientMarkdownProfiles" import type { DocumentPageTracker } from "./documentPageReadiness"; import { DOCUMENT_FONT_SANITIZE_ATTRIBUTES, + documentFontFamilyCss, documentFontOfMarkdown, rehypeApplyFontSpans, rehypeMarkFontSpans, @@ -508,6 +510,7 @@ export function ScientDocumentPage(props: ScientDocumentPageProps) { ); const direction = resolveMarkdownDirection(input.markdown, input.direction); const documentFont = documentFontOfMarkdown(input.markdown); + const documentFontCss = documentFontFamilyCss(documentFont.fontFamily); const context = { assets: new Map(input.assets.map((asset) => [asset.id, asset])), assetBaseUrl: props.inputUrl, @@ -538,6 +541,11 @@ export function ScientDocumentPage(props: ScientDocumentPageProps) { 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) + } > { 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('a big b')).toContain( + 'big', ); - expect(await exported('x')).toContain( - 'style="font-family:serif,', + expect(await exported(`x`)).toContain( + "font-family:'Times New Roman',", ); }); it.each([ 'x', - 'x', - '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("3em"); + 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'); + 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\nfont-size: 12pt\nfont-family: monospace\n---\n\ntext"), - ).toEqual({ fontFamily: "monospace", fontSize: "12pt" }); - expect(documentFontOfMarkdown("text\n\n---\nfont-size: 12pt\n---\n")).toEqual({ + 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 index 1a471783c4..f00e1282b3 100644 --- a/apps/web/src/scient/documentPage/documentFont.ts +++ b/apps/web/src/scient/documentPage/documentFont.ts @@ -1,10 +1,10 @@ import { - MARKDOWN_FONT_SIZES, + catalogueFont, markdownFontSpanStyle, + normalizeFontSize, parseMarkdownFontSpanStyle, } from "@scientfactory/scient-markdown"; import { LEADING_FRONT_MATTER, readMarkdownDocumentFont } from "../markdownEditor/documentFont"; -import { isFontFamilyName } from "../writing/fontChoices"; /** * Font styles of an exported Markdown document: the local `` forms @@ -47,15 +47,16 @@ export function rehypeMarkFontSpans() { export function rehypeApplyFontSpans() { return (tree: HastNode) => visitSpans(tree, (properties) => { - const size = properties.dataScientFontSize; + const sizeValue = properties.dataScientFontSize; const family = properties.dataScientFontFamily; delete properties.dataScientFontSize; delete properties.dataScientFontFamily; - const sizeName = MARKDOWN_FONT_SIZES.find(({ name }) => name === size)?.name; - if (sizeName !== undefined) { - properties.style = markdownFontSpanStyle({ size: sizeName }); - } else if (typeof family === "string" && isFontFamilyName(family)) { - properties.style = `font-family:${family}, "Noto Sans Hebrew", "Arial Hebrew", "Noto Sans Arabic"`; + 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)}`; } }); } @@ -65,3 +66,11 @@ 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 3943ed9b12..8ecd122423 100644 --- a/apps/web/src/scient/documentPage/scient-document-page.css +++ b/apps/web/src/scient/documentPage/scient-document-page.css @@ -117,16 +117,8 @@ body { .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="serif"] { - font-family: serif, "Noto Sans Hebrew", "Arial Hebrew", "Noto Sans Arabic"; -} -.scient-document[data-scient-font-family="sans-serif"] { - font-family: sans-serif, "Noto Sans Hebrew", "Arial Hebrew", "Noto Sans Arabic"; -} -.scient-document[data-scient-font-family="monospace"] { - font-family: - ui-monospace, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace, "Noto Sans Hebrew", - "Arial Hebrew"; +.scient-document[data-scient-font-family] { + font-family: var(--scient-document-font-family); } .scient-document :where(p, ul, ol, blockquote, .scient-document-table, figure) { diff --git a/apps/web/src/scient/latex/LatexDocumentSettings.tsx b/apps/web/src/scient/latex/LatexDocumentSettings.tsx index e19e991a3f..b70f967654 100644 --- a/apps/web/src/scient/latex/LatexDocumentSettings.tsx +++ b/apps/web/src/scient/latex/LatexDocumentSettings.tsx @@ -3,7 +3,6 @@ import { XIcon } from "lucide-react"; import { Button } from "~/components/ui/button"; import { Input } from "~/components/ui/input"; import { DocumentSettingsField } from "../writing/DocumentSettingsField"; -import { FONT_FAMILIES } from "../writing/fontChoices"; import { LatexSelect } from "./LatexSelect"; import { latexVisualLayoutProfile, type LatexVisualLayoutUpdate } from "./latexVisualDocument"; import { LATEX_PAPER_SIZES } from "./latexVisualLayout"; @@ -127,6 +126,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; @@ -287,10 +292,7 @@ export function LatexDocumentSettings(props: { width="fluid" aria-label="Document font" value={changes.fontFamily ?? extended.fontFamily} - options={[ - { value: "default", label: "Default" }, - ...FONT_FAMILIES.map((family) => ({ value: family.name, label: family.label })), - ]} + options={[{ value: "default", label: "Default" }, ...GENERIC_FAMILIES]} onValueChange={(value) => setLayout("fontFamily", value as DocumentLayoutSettings["fontFamily"]) } diff --git a/apps/web/src/scient/latex/LatexVisualEditor.tsx b/apps/web/src/scient/latex/LatexVisualEditor.tsx index ab247ea891..a841ef2679 100644 --- a/apps/web/src/scient/latex/LatexVisualEditor.tsx +++ b/apps/web/src/scient/latex/LatexVisualEditor.tsx @@ -1,7 +1,7 @@ import type { PagedTableLayout } from "./latexPagedGeometry"; import { resolvedLatexFontSize } from "./latexVisualLayout"; import { latexSelectionClipboard } from "./latexClipboard"; -import { FontMenuItems } from "../writing/FontMenuItems"; +import { FontControls } from "../writing/FontControls"; import { TextMenu, TextMenuItems } from "../writing/TextMenu"; import { setLatexFontFamily, setLatexFontSize } from "./latexFontCommands"; import { LatexDirectionMenuItems } from "./LatexDirectionMenuItems"; @@ -5577,6 +5577,29 @@ 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, + ]; + }, +}); + const LatexColor = Mark.create({ name: "latexColor", priority: 1100, @@ -5626,6 +5649,7 @@ const LatexMonospace = Code.extend({ excludes: "" }); const inlineFieldExtensions = [ ...LatexTextMarks, + LatexFontSize, LatexColor, LatexColor.extend({ name: "latexBackground", @@ -5660,6 +5684,7 @@ const baseExtensions = [ trailingNode: false, }), ...LatexTextMarks, + LatexFontSize, LatexColor, LatexColor.extend({ name: "latexBackground", @@ -9246,7 +9271,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 = [ @@ -9656,7 +9684,7 @@ function LatexVisualEditorReady( paragraphStyle: writingStyleItems, formatting: writingFormattingItems, font: ( - 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/latexEditingTarget.ts b/apps/web/src/scient/latex/latexEditingTarget.ts index 2da15ab0ba..5673f3460d 100644 --- a/apps/web/src/scient/latex/latexEditingTarget.ts +++ b/apps/web/src/scient/latex/latexEditingTarget.ts @@ -1,8 +1,8 @@ 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 type { FontFamilyName, FontSizeName } from "../writing/fontChoices"; import { latexFontState } from "./latexFontCommands"; export const LatexInlineOwnerContext = createContext(null); @@ -139,14 +139,14 @@ interface EditingPresentation { bold: boolean; italic: boolean; code: boolean; - fontFamily: FontFamilyName | null; - fontSize: FontSizeName | null; + fontFamily: string | null; + fontSize: number | null; 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); + const font = latexFontState(editor, baseFontPt); return { formattingAvailable: Boolean( editor?.isEditable && @@ -175,11 +175,10 @@ const sameEditingPresentation = (before: EditingPresentation, after: EditingPres /** 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.ts b/apps/web/src/scient/latex/latexFontCommands.ts index 23ae527fe7..c161520cc1 100644 --- a/apps/web/src/scient/latex/latexFontCommands.ts +++ b/apps/web/src/scient/latex/latexFontCommands.ts @@ -1,46 +1,56 @@ import type { Editor } from "@tiptap/core"; -import { - FONT_FAMILIES, - FONT_SIZES, - type FontFamilyName, - type FontSizeName, -} from "../writing/fontChoices"; +import { latexVisualFontMetrics } from "./latexVisualLayout"; +import { normalizeFontSize } from "../writing/fontChoices"; -/** Generic family to the LaTeX Visual mark that writes it (`\textrm`, `\textsf`, `\texttt`). */ -const FAMILY_MARKS: Readonly> = { - serif: "latexRoman", - "sans-serif": "latexSans", - monospace: "code", -}; +const NAMED_SIZES = [ + "tiny", + "scriptsize", + "footnotesize", + "small", + "normalsize", + "large", + "Large", + "LARGE", + "huge", + "Huge", +] as const; -const sizeMark = (size: FontSizeName) => `latexSize_${size}`; +/** Baseline written with a new size: 1.2 times the size, as the class sizes mostly are. */ +const LEADING_RATIO = 1.2; -/** The size and family shared by the whole selection; null when none or mixed. */ -export function latexFontState(editor: Editor | null): { - readonly size: FontSizeName | null; - readonly family: FontFamilyName | null; -} { +/** + * The size in points shared by the whole selection, or null when none or mixed. + * A named size (`\large`) reports its number for the document's class size. + */ +export function latexFontState( + editor: Editor | null, + baseFontPt: 10 | 11 | 12 = 10, +): { readonly size: number | null; readonly family: string | null } { if (!editor) return { size: null, family: null }; + const numeric = editor.getAttributes("latexFontSize").points; + if (typeof numeric === "number") return { size: numeric, family: null }; + const named = NAMED_SIZES.find((name) => editor.isActive(`latexSize_${name}`)); return { - size: FONT_SIZES.find(({ name }) => editor.isActive(sizeMark(name)))?.name ?? null, - family: FONT_FAMILIES.find(({ name }) => editor.isActive(FAMILY_MARKS[name]))?.name ?? null, + size: named === undefined ? null : latexVisualFontMetrics(baseFontPt)[named][0], + family: null, }; } /** A size replaces the previous one, as in LaTeX; null returns to the document default. */ -export function setLatexFontSize(editor: Editor | null, size: FontSizeName | null): boolean { +export function setLatexFontSize(editor: Editor | null, points: number | null): boolean { if (!editor) return false; - let chain = editor.chain().focus(); - for (const { name } of FONT_SIZES) chain = chain.unsetMark(sizeMark(name)); - if (size) chain = chain.setMark(sizeMark(size)); + const size = points === null ? null : normalizeFontSize(points); + if (points !== null && size === null) return false; + let chain = editor.chain().focus().unsetMark("latexFontSize"); + for (const name of NAMED_SIZES) chain = chain.unsetMark(`latexSize_${name}`); + if (size !== null) { + const leading = Math.round(size * LEADING_RATIO * 100) / 100; + chain = chain.setMark("latexFontSize", { points: size, leading }); + } return chain.run(); } -/** A family replaces the previous one; null returns to the document default. */ -export function setLatexFontFamily(editor: Editor | null, family: FontFamilyName | null): boolean { - if (!editor) return false; - let chain = editor.chain().focus(); - for (const { name } of FONT_FAMILIES) chain = chain.unsetMark(FAMILY_MARKS[name]); - if (family) chain = chain.setMark(FAMILY_MARKS[family]); - return chain.run(); +/** Named fonts are not yet written by the Visual editor. */ +export function setLatexFontFamily(_editor: Editor | null, _family: string | null): boolean { + return false; } 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..f2f1d47080 --- /dev/null +++ b/apps/web/src/scient/latex/latexFontSize.test.ts @@ -0,0 +1,43 @@ +import { describe, expect, it } from "vite-plus/test"; +import { latexTextDeclarationAt, latexFontSizeGroupSource } 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(latexFontSizeGroupSource(13, 15.6, "word")).toBe( + "{\\fontsize{13}{15.6}\\selectfont word}", + ); + expect(latexFontSizeGroupSource(13, 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); + }); +}); diff --git a/apps/web/src/scient/latex/latexTextFormatting.ts b/apps/web/src/scient/latex/latexTextFormatting.ts index e81251ef8f..c6a13b6037 100644 --- a/apps/web/src/scient/latex/latexTextFormatting.ts +++ b/apps/web/src/scient/latex/latexTextFormatting.ts @@ -1,3 +1,4 @@ +import { normalizeFontSize } from "@scientfactory/scient-markdown"; import { LATEX_DIRECTION_MARKS, latexDirectionMark } from "./latexLanguage"; /** Text styles understood by both the source adapter and the editable canvas. */ @@ -29,7 +30,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 +43,56 @@ 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}`; +} + +/** The ProseMirror mark a string mark stands for. */ +export function latexMarkNode(key: string): { type: string; attrs?: Record } { + const size = new RegExp(`^${FONT_SIZE_MARK}:([\\d.]+)/([\\d.]+)$`, "u").exec(key); + return size + ? { type: FONT_SIZE_MARK, attrs: { points: Number(size[1]), leading: Number(size[2]) } } + : { type: key }; +} + +/** The string mark key of a ProseMirror mark: the inverse of `latexMarkNode`. */ +export function latexMarkKey(mark: { type: string; attrs?: Record }): string { + 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; + +/** 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 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 size group around already serialised text; `\selectfont{}` keeps a leading space. */ +export function latexFontSizeGroupSource(points: number, leading: number, text: string): string { + const separator = /^\s/u.test(text) ? "{}" : " "; + return `{\\fontsize{${points}}{${leading}}\\selectfont${separator}${text}}`; +} + export const LATEX_CANVAS_TEXT_MARKS = [ { name: "latexSmallCaps", style: "small-caps" }, { name: "latexRoman", style: "roman" }, @@ -54,7 +105,7 @@ 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 (["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..d93dce32fb 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, + latexFontSizeGroupSource, + 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 size group covers a whole run of equal size, with its math and other marks inside. + const sizeType = "latexFontSize"; + if (nodes?.some((node) => node.marks?.some((mark) => mark.type === sizeType))) { + let result = ""; + for (let at = 0; at < nodes.length;) { + const size = nodes[at]!.marks?.find((mark) => mark.type === sizeType); + const signature = JSON.stringify(size); + let end = at + 1; + while ( + end < nodes.length && + JSON.stringify(nodes[end]!.marks?.find((mark) => mark.type === sizeType)) === signature + ) + end++; + const content = nodes.slice(at, end).map((node) => ({ + ...node, + marks: (node.marks ?? []).filter((mark) => mark.type !== sizeType), + })); + const inner = serializeInline(content); + result += size + ? latexFontSizeGroupSource(Number(size.attrs?.points), Number(size.attrs?.leading), 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/markdownEditor/documentFont.test.ts b/apps/web/src/scient/markdownEditor/documentFont.test.ts index d1e489dcd8..e8d9f0e4c6 100644 --- a/apps/web/src/scient/markdownEditor/documentFont.test.ts +++ b/apps/web/src/scient/markdownEditor/documentFont.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from "vite-plus/test"; import { + canWriteMarkdownDocumentFont, readMarkdownDocumentFont, writeMarkdownDocumentFont, type MarkdownDocumentFont, @@ -8,39 +9,67 @@ import { const none: MarkdownDocumentFont = { fontFamily: null, fontSize: null }; describe("Markdown document font front matter", () => { - it("reads the two keys, quoted or not, and ignores unknown values", () => { + it("reads the two keys, quoted or not, with a trailing comment, and ignores unknown values", () => { expect( - readMarkdownDocumentFont('---\ntitle: T\nfont-size: "11pt"\nfont-family: sans-serif\n---'), - ).toEqual({ fontFamily: "sans-serif", fontSize: "11pt" }); - expect(readMarkdownDocumentFont("---\nfont-size: 14pt\nfont-family: Arial\n---")).toEqual(none); + 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: "serif", fontSize: "12pt" })).toBe( - "---\nfont-size: 12pt\nfont-family: serif\n---", + 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", () => { - const source = "---\r\ntitle: T\r\nfont-size: 10pt\r\ntags: [a]\r\n---"; - expect(writeMarkdownDocumentFont(source, { fontFamily: "monospace", fontSize: "12pt" })).toBe( - "---\r\ntitle: T\r\ntags: [a]\r\nfont-size: 12pt\r\nfont-family: monospace\r\n---", + 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\nfont-size: 10pt\n---"; + 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]\nfont-size: 12pt\n\n---", + "---\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("---\nfont-size: 10pt\n---", none)).toBeNull(); + 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("+++\ntitle = 'T'\n+++", { fontFamily: "serif", fontSize: null }), + 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 index f6841c3f3d..a2b15a494f 100644 --- a/apps/web/src/scient/markdownEditor/documentFont.ts +++ b/apps/web/src/scient/markdownEditor/documentFont.ts @@ -1,14 +1,18 @@ -import { DOCUMENT_FONT_SIZES, type DocumentFontSize } from "@scientfactory/scient-markdown"; -import { FONT_FAMILIES, type FontFamilyName } from "../writing/fontChoices"; +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 (`font-size: 11pt`, `font-family: serif`). The - * sizes match the LaTeX Document settings card. + * 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: FontFamilyName | null; + readonly fontFamily: string | null; readonly fontSize: DocumentFontSize | null; } @@ -16,53 +20,98 @@ export interface MarkdownDocumentFont { 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 FONT_KEYS = /^font-(?:size|family)[ \t]*:/u; -function unquote(value: string): string { - return value.trim().replace(/^(["'])(.*)\1$/u, "$2"); +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 keyValue(lines: readonly string[], key: string): string | null { - const line = lines.find( - (candidate) => candidate.startsWith(`${key}:`) || candidate.startsWith(`${key} :`), - ); - return line === undefined ? null : unquote(line.slice(line.indexOf(":") + 1)); +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 match = frontMatter === null ? null : YAML_FRONT_MATTER.exec(frontMatter); - const lines = match?.[3]?.split(/\r?\n/u) ?? []; - const size = keyValue(lines, "font-size"); - const family = keyValue(lines, "font-family"); + 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: FONT_FAMILIES.find((candidate) => candidate.name === family)?.name ?? null, + fontFamily: family !== null && catalogueFont(family) !== null ? family : null, }; } /** - * The front matter block after applying `font`, or null when it would be - * empty (the block is then removed). Other keys and the text around the block - * are kept as they are; undefined when the block is not YAML. + * 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 { - const wanted = [ - ...(font.fontSize ? [`font-size: ${font.fontSize}`] : []), - ...(font.fontFamily ? [`font-family: ${font.fontFamily}`] : []), - ]; - if (frontMatter === null) return wanted.length ? `---\n${wanted.join("\n")}\n---` : null; + 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) return undefined; - const [, open, eol, body = "", close, after = ""] = match; - // The font keys go after the last other key; blank lines inside the block are kept. - const others = body.split(/\r?\n/u).filter((line) => !FONT_KEYS.test(line)); - const kept = others.every((line) => line === "") ? [] : others; - if (wanted.length === 0 && kept.length === 0) return null; - const insertAt = kept.findLastIndex((line) => line !== "") + 1; - const lines = [...kept.slice(0, insertAt), ...wanted, ...kept.slice(insertAt)]; + 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 67bd8328a1..bfd8aa7c6f 100644 --- a/apps/web/src/scient/markdownEditor/prosemirror/commands.ts +++ b/apps/web/src/scient/markdownEditor/prosemirror/commands.ts @@ -33,7 +33,7 @@ import { scientMarkdownSchema } from "./schema"; import { selectMarkdownTable } from "./tables"; import { nextScientMarkdownFootnoteLabel } from "../footnotes"; import { WRITING_COMMAND_LABELS } from "../../writing/commandNames"; -import type { FontFamilyName, FontSizeName } from "../../writing/fontChoices"; +import { catalogueFont, normalizeFontSize } from "@scientfactory/scient-markdown"; import { readMarkdownDocumentFont, writeMarkdownDocumentFont, @@ -61,8 +61,9 @@ export type ScientMarkdownCommand = | "direction-rtl" | "display-math" | "footnote" - | `font-family-${FontFamilyName | "default"}` - | `font-size-${FontSizeName | "default"}` + | `font-family-${string}` + | `font-size-${number}` + | "font-size-default" | "clear-formatting" | "hard-break" | "heading-1" @@ -489,19 +490,26 @@ function clearMarkdownFormatting(): Command { }; } -/** Set one font mark on the selection (or the typing marks at a caret); `null` removes it. */ +/** + * Set one font mark on the selection (or the typing marks at a caret); `null` removes it. + * Every selected range gets it, so a selection across table cells reaches all of them. + */ function setMarkdownFontMark(markName: string, attrs: Attrs | null): Command { return (state, dispatch) => { if (!dispatch) return true; const type = requiredMarkType(markName); - const { from, to, empty, $from } = state.selection; + const { empty, $from } = state.selection; if (empty) { const kept = (state.storedMarks ?? $from.marks()).filter((mark) => mark.type !== type); dispatch(state.tr.setStoredMarks(attrs ? type.create(attrs).addToSet(kept) : kept)); return true; } - let transaction = state.tr.removeMark(from, to, type); - if (attrs) { + let transaction = state.tr; + for (const range of state.selection.ranges) { + const from = range.$from.pos; + const to = range.$to.pos; + transaction = transaction.removeMark(from, to, type); + if (!attrs) continue; // Like toggleMark: the written span cannot keep whitespace at its ends. const isSpace = (at: number) => /^\s$/u.test(state.doc.textBetween(at, at + 1)); let start = from; @@ -515,12 +523,19 @@ function setMarkdownFontMark(markName: string, attrs: Attrs | null): Command { }; } -function fontCommand( - command: `font-family-${FontFamilyName | "default"}` | `font-size-${FontSizeName | "default"}`, -): Command { - const [, kind, value] = /^font-(size|family)-(.+)$/u.exec(command) ?? []; - const attrs = value === "default" ? null : kind === "size" ? { size: value } : { family: value }; - return setMarkdownFontMark(kind === "size" ? "font_size" : "font_family", attrs); +/** 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. */ diff --git a/apps/web/src/scient/markdownEditor/prosemirror/documentFontPresentation.ts b/apps/web/src/scient/markdownEditor/prosemirror/documentFontPresentation.ts index 60859b186b..89adfb2399 100644 --- a/apps/web/src/scient/markdownEditor/prosemirror/documentFontPresentation.ts +++ b/apps/web/src/scient/markdownEditor/prosemirror/documentFontPresentation.ts @@ -1,9 +1,10 @@ +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; the stylesheet turns them into size and family. + * data attributes and a CSS variable; the stylesheet turns them into size and family. */ export function scientMarkdownDocumentFontPlugin(): Plugin { return new Plugin({ @@ -12,7 +13,12 @@ export function scientMarkdownDocumentFontPlugin(): Plugin { const { fontFamily, fontSize } = documentFontOf(state.doc); return { ...(fontSize ? { "data-scient-font-size": fontSize } : {}), - ...(fontFamily ? { "data-scient-font-family": fontFamily } : {}), + ...(fontFamily + ? { + "data-scient-font-family": fontFamily, + style: `--scient-markdown-font-family:${catalogueFont(fontFamily)?.css ?? "inherit"}`, + } + : {}), }; }, }, diff --git a/apps/web/src/scient/markdownEditor/prosemirror/fontStyles.test.ts b/apps/web/src/scient/markdownEditor/prosemirror/fontStyles.test.ts index cea47241e3..f76c687d4d 100644 --- a/apps/web/src/scient/markdownEditor/prosemirror/fontStyles.test.ts +++ b/apps/web/src/scient/markdownEditor/prosemirror/fontStyles.test.ts @@ -33,20 +33,22 @@ function markedText(session: ScientProseMirrorSession, markName: string) { describe("Markdown font size and family", () => { it("reads the recognised span forms as marks", () => { const session = open( - 'a big and code\n', + `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("large"); + expect(size.attrs.size).toBe(14); }); it.each([ - 'x', + 'x', + 'x', 'x', 'x', - 'x', - 'unclosed', + `x`, + 'x', + 'unclosed', "plain stray close", ])("leaves other HTML as text: %s", (source) => { const session = open(`${source}\n`); @@ -58,13 +60,11 @@ describe("Markdown font size and family", () => { 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-large"); + 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-small"); - expect(session.session.draftSource).toBe( - 'one two three\n', + 'one two three\n', ); run(session, "font-size-default"); expect(session.session.draftSource).toBe("one two three\n"); @@ -73,17 +73,15 @@ describe("Markdown font size and family", () => { 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-LARGE"); - expect(session.session.draftSource).toBe( - 'one two three\n', - ); + 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-huge"); - run(session, "font-family-sans-serif"); + 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); @@ -98,7 +96,7 @@ describe("Markdown font size and family", () => { session.state.tr.setSelection(TextSelection.create(session.state.doc, 10, 14)), "user", ); - run(session, "font-size-Large"); + 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); @@ -106,9 +104,9 @@ describe("Markdown font size and family", () => { 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', + '**a b c**\n', + `- item x\n`, + '| A |\n| --- |\n| t |\n', ]) { const session = open(source); expect( @@ -122,9 +120,9 @@ describe("Markdown font size and family", () => { }); it.each([ - '- a x `` y', - '- a x `` y', - '- [](https://example.com) y', + '- 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); @@ -146,17 +144,19 @@ describe("Markdown font size and family", () => { expect(scientMarkdownSchema.marks.font_family).toBeDefined(); }); - it("ignores pasted HTML whose size or family is not a known name", () => { + 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("huge"))).toEqual({ size: "huge" }); + 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("monospace"))).toEqual({ family: "monospace" }); - expect(parseRule("font_family")(attribute('serif" onmouseover="alert(1)'))).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); }); }); diff --git a/apps/web/src/scient/markdownEditor/prosemirror/schema.ts b/apps/web/src/scient/markdownEditor/prosemirror/schema.ts index 4b6df17f49..1f9f9d45c6 100644 --- a/apps/web/src/scient/markdownEditor/prosemirror/schema.ts +++ b/apps/web/src/scient/markdownEditor/prosemirror/schema.ts @@ -18,13 +18,11 @@ import { Schema } from "prosemirror-model"; import { tableNodes } from "prosemirror-tables"; import { - MARKDOWN_FONT_FAMILIES, - MARKDOWN_FONT_SIZES, MARKDOWN_FONT_SPAN_CLOSE, + catalogueFont, markdownFontSpanOpen, + normalizeFontSize, parseMarkdownFontSpanOpen, - type MarkdownFontFamilyName, - type MarkdownFontSizeName, } from "@scientfactory/scient-markdown"; import { findScientBackslashMathSpans, @@ -243,42 +241,40 @@ const strikeSpec: MarkSpec = { }; const fontSizeSpec: MarkSpec = { - attrs: { size: { default: "normalsize" } }, + attrs: { size: { default: 12 } }, parseDOM: [ { tag: "span[data-scient-font-size]", - // Pasted HTML is untrusted: only a known size name becomes a mark. + // Pasted HTML is untrusted: only a size inside the allowed range becomes a mark. getAttrs: (element) => { - const size = element.getAttribute("data-scient-font-size"); - return MARKDOWN_FONT_SIZES.some(({ name }) => name === size) ? { size } : false; + const size = normalizeFontSize(Number(element.getAttribute("data-scient-font-size"))); + return size === null ? false : { size }; }, }, ], toDOM: (mark) => [ "span", - { - style: `font-size:${MARKDOWN_FONT_SIZES.find(({ name }) => name === mark.attrs.size)?.em}em`, - "data-scient-font-size": String(mark.attrs.size), - }, + { style: `font-size:${mark.attrs.size}pt`, "data-scient-font-size": String(mark.attrs.size) }, 0, ], }; const fontFamilySpec: MarkSpec = { - attrs: { family: { default: "serif" } }, + 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 MARKDOWN_FONT_FAMILIES.some((name) => name === family) ? { family } : false; + return family !== null && catalogueFont(family) !== null ? { family } : false; }, }, ], toDOM: (mark) => [ "span", { - style: `font-family:${String(mark.attrs.family)}`, + style: `font-family:${catalogueFont(String(mark.attrs.family))?.css ?? "inherit"}`, "data-scient-font-family": String(mark.attrs.family), }, 0, @@ -1021,15 +1017,13 @@ export const scientMarkdownSerializer = new ScientMarkdownSerializer( }, }, font_size: { - open: (_state, mark) => - markdownFontSpanOpen({ size: mark.attrs.size as MarkdownFontSizeName }), + open: (_state, mark) => markdownFontSpanOpen({ size: mark.attrs.size as number }), close: MARKDOWN_FONT_SPAN_CLOSE, expelEnclosingWhitespace: true, mixable: true, }, font_family: { - open: (_state, mark) => - markdownFontSpanOpen({ family: mark.attrs.family as MarkdownFontFamilyName }), + open: (_state, mark) => markdownFontSpanOpen({ family: String(mark.attrs.family) }), close: MARKDOWN_FONT_SPAN_CLOSE, expelEnclosingWhitespace: true, mixable: true, diff --git a/apps/web/src/scient/markdownEditor/prosemirror/view.ts b/apps/web/src/scient/markdownEditor/prosemirror/view.ts index 9eb6d055e2..020301428b 100644 --- a/apps/web/src/scient/markdownEditor/prosemirror/view.ts +++ b/apps/web/src/scient/markdownEditor/prosemirror/view.ts @@ -156,7 +156,7 @@ export interface ScientMarkdownEditorSnapshot { readonly findOpen: boolean; readonly findQuery: string; readonly fontFamily: string | null; - readonly fontSize: string | null; + readonly fontSize: number | null; readonly findWholeWord: boolean; readonly inTable: boolean; readonly listKind: "bullet" | "ordered" | "task" | null; @@ -1720,19 +1720,23 @@ export class ScientMarkdownEditorView { ) .map((mark) => mark.name); // The shared value of a mark attribute over the selection; null when none or mixed. - const markAttribute = (markName: string, attribute: string) => { + const markAttribute = ( + markName: string, + attribute: string, + kind: "string" | "number", + ): T | null => { const type = scientMarkdownSchema.marks[markName]!; + const valid = (value: unknown): value is T => typeof value === kind; if (selection.empty) { const mark = (state.storedMarks ?? selection.$from.marks()).find((m) => m.type === type); - return typeof mark?.attrs[attribute] === "string" - ? (mark.attrs[attribute] as string) - : null; + const value = mark?.attrs[attribute]; + return valid(value) ? value : null; } - const values = new Set(); + const values = new Set(); state.doc.nodesBetween(selection.from, selection.to, (node) => { if (!node.isText) return; const value = node.marks.find((m) => m.type === type)?.attrs[attribute]; - values.add(typeof value === "string" ? value : null); + values.add(valid(value) ? value : null); }); return values.size === 1 ? ([...values][0] ?? null) : null; }; @@ -1803,8 +1807,8 @@ export class ScientMarkdownEditorView { findMatchCount: find.matches.length, findOpen: this.findOpen, findQuery: find.query, - fontFamily: markAttribute("font_family", "family"), - fontSize: markAttribute("font_size", "size"), + fontFamily: markAttribute("font_family", "family", "string"), + fontSize: markAttribute("font_size", "size", "number"), findWholeWord: find.wholeWord, headingLevel, inTable, diff --git a/apps/web/src/scient/markdownEditor/scient-markdown-editor.css b/apps/web/src/scient/markdownEditor/scient-markdown-editor.css index 6b80a86e03..7bc7bcef1f 100644 --- a/apps/web/src/scient/markdownEditor/scient-markdown-editor.css +++ b/apps/web/src/scient/markdownEditor/scient-markdown-editor.css @@ -270,14 +270,8 @@ .scient-markdown-document[data-scient-font-size] :is(h4, h5, h6) { font-size: calc(var(--scient-font-size-markdown-body) * var(--scient-markdown-size-scale)); } -.scient-markdown-document[data-scient-font-family="serif"] { - font-family: serif; -} -.scient-markdown-document[data-scient-font-family="sans-serif"] { - font-family: sans-serif; -} -.scient-markdown-document[data-scient-font-family="monospace"] { - font-family: var(--font-mono); +.scient-markdown-document[data-scient-font-family] { + font-family: var(--scient-markdown-font-family); } .scient-markdown-document p, diff --git a/apps/web/src/scient/markdownEditor/ui/MarkdownDocumentSettings.tsx b/apps/web/src/scient/markdownEditor/ui/MarkdownDocumentSettings.tsx index 3b715f2964..d41c530ac7 100644 --- a/apps/web/src/scient/markdownEditor/ui/MarkdownDocumentSettings.tsx +++ b/apps/web/src/scient/markdownEditor/ui/MarkdownDocumentSettings.tsx @@ -3,7 +3,7 @@ import { XIcon } from "lucide-react"; import { Button } from "~/components/ui/button"; import { LatexSelect } from "~/scient/latex/LatexSelect"; import { DocumentSettingsField } from "~/scient/writing/DocumentSettingsField"; -import { FONT_FAMILIES, isFontFamilyName } from "~/scient/writing/fontChoices"; +import { FONT_GROUPS, catalogueFont } from "~/scient/writing/fontChoices"; import { DOCUMENT_FONT_SIZES } from "@scientfactory/scient-markdown"; import type { MarkdownDocumentFont } from "../documentFont"; @@ -81,12 +81,14 @@ export function MarkdownDocumentSettings(props: { value={font.fontFamily ?? DEFAULT_CHOICE} options={[ { value: DEFAULT_CHOICE, label: "Default" }, - ...FONT_FAMILIES.map((family) => ({ value: family.name, label: family.label })), + ...FONT_GROUPS.flatMap((group) => + group.fonts.map((font) => ({ value: font.name, label: font.name })), + ), ]} onValueChange={(value) => { setFont((previous) => ({ ...previous, - fontFamily: isFontFamilyName(value) ? value : null, + fontFamily: catalogueFont(value)?.name ?? null, })); setError(null); }} diff --git a/apps/web/src/scient/markdownEditor/ui/ScientMarkdownControls.tsx b/apps/web/src/scient/markdownEditor/ui/ScientMarkdownControls.tsx index 5f60de8ba3..6a98d5191c 100644 --- a/apps/web/src/scient/markdownEditor/ui/ScientMarkdownControls.tsx +++ b/apps/web/src/scient/markdownEditor/ui/ScientMarkdownControls.tsx @@ -87,7 +87,7 @@ import { type InsertMenuAction, type InsertMenuLayout, } from "../../writing/InsertMenu"; -import { FontMenuItems } from "../../writing/FontMenuItems"; +import { FontControls } from "../../writing/FontControls"; import { TextMenu, TextMenuItems } from "../../writing/TextMenu"; import { MarkdownDocumentSettings } from "./MarkdownDocumentSettings"; import { DockCommandCheckboxItem } from "../../writing/dockChrome"; @@ -358,12 +358,14 @@ function markdownTextContents( paragraphStyle: , formatting: , font: ( - controller.execute(`font-family-${family ?? "default"}`)} - onSize={(size) => controller.execute(`font-size-${size ?? "default"}`)} + onSize={(size) => + controller.execute(size === null ? "font-size-default" : `font-size-${size}`) + } /> ), direction: , diff --git a/apps/web/src/scient/writing/FontControls.tsx b/apps/web/src/scient/writing/FontControls.tsx new file mode 100644 index 0000000000..6638d165a0 --- /dev/null +++ b/apps/web/src/scient/writing/FontControls.tsx @@ -0,0 +1,153 @@ +import { useState } from "react"; +import { Input } from "~/components/ui/input"; +import { + NumberField, + NumberFieldDecrement, + NumberFieldGroup, + NumberFieldIncrement, + NumberFieldInput, +} from "~/components/ui/number-field"; +import { cn } from "~/lib/utils"; +import { + FONT_GROUPS, + FONT_SIZE_MAX, + FONT_SIZE_MIN, + FONT_SIZE_PRESETS, + normalizeFontSize, +} from "./fontChoices"; + +/** + * Content of `Text > Font / Size`, identical in both editors: a scrolling list of + * fonts, each drawn in its own face, and a size row (minus, number, plus, presets). + * A null value means the document default; "Default font" removes the style. + */ +export function FontControls(props: { + readonly family: string | null; + readonly size: number | null; + readonly disabled: boolean; + readonly onFamily: (family: string | null) => void; + readonly onSize: (size: number | null) => void; +}) { + const [query, setQuery] = useState(""); + const needle = query.trim().toLowerCase(); + const groups = FONT_GROUPS.map((group) => ({ + ...group, + fonts: group.fonts.filter((font) => font.name.toLowerCase().includes(needle)), + })).filter((group) => group.fonts.length > 0); + return ( +
{ + if (event.key !== "Escape") event.stopPropagation(); + }} + > +
+ Font + setQuery(event.target.value)} + /> +
+ props.onFamily(null)} + /> + {groups.map((group) => ( +
+
{group.label}
+ {group.fonts.map((font) => ( + props.onFamily(font.name)} + /> + ))} +
+ ))} +
+
+
+ Size (pt) + { + const size = value === null ? null : normalizeFontSize(value); + if (size !== null) props.onSize(size); + }} + > + + + + + + +
+ {FONT_SIZE_PRESETS.map((preset) => ( + + ))} + +
+
+
+ ); +} + +function FontOption(props: { + readonly label: string; + readonly css?: string; + readonly selected: boolean; + readonly disabled: boolean; + readonly onSelect: () => void; +}) { + return ( + + ); +} diff --git a/apps/web/src/scient/writing/FontMenuItems.tsx b/apps/web/src/scient/writing/FontMenuItems.tsx deleted file mode 100644 index d1d18a2f39..0000000000 --- a/apps/web/src/scient/writing/FontMenuItems.tsx +++ /dev/null @@ -1,67 +0,0 @@ -import { MenuGroup, MenuGroupLabel, MenuRadioGroup, MenuSeparator } from "~/components/ui/menu"; -import { DockCommandRadioItem } from "./dockChrome"; -import { FONT_FAMILIES, FONT_SIZES, type FontFamilyName, type FontSizeName } from "./fontChoices"; - -const DEFAULT_CHOICE = "default"; - -/** - * Content of `Text > Font / Size`, identical in both editors. A null value - * means the document default; choosing "Default" removes the style. - */ -export function FontMenuItems(props: { - readonly family: string | null; - readonly size: string | null; - readonly disabled: boolean; - readonly onFamily: (family: FontFamilyName | null) => void; - readonly onSize: (size: FontSizeName | null) => void; -}) { - return ( - <> - - Font - - props.onFamily(null)} - > - Default - - {FONT_FAMILIES.map((family) => ( - props.onFamily(family.name)} - > - {family.label} - - ))} - - - - - Size - - props.onSize(null)} - > - Default - - {FONT_SIZES.map((size) => ( - props.onSize(size.name)} - > - {size.label} - - ))} - - - - ); -} diff --git a/apps/web/src/scient/writing/fontChoices.ts b/apps/web/src/scient/writing/fontChoices.ts index 8b70be83d6..284b963b8d 100644 --- a/apps/web/src/scient/writing/fontChoices.ts +++ b/apps/web/src/scient/writing/fontChoices.ts @@ -1,45 +1,34 @@ /** Font size and family choices shared by the Markdown and LaTeX Visual editors. */ import { - MARKDOWN_FONT_FAMILIES, - MARKDOWN_FONT_SIZES, - type MarkdownFontFamilyName, - type MarkdownFontSizeName, + FONT_CATALOGUE, + FONT_SIZE_MAX, + FONT_SIZE_MIN, + catalogueFont, + normalizeFontSize, + type CatalogueFont, + type FontCategory, } from "@scientfactory/scient-markdown"; -export type FontSizeName = MarkdownFontSizeName; -export type FontFamilyName = MarkdownFontFamilyName; +export { FONT_SIZE_MAX, FONT_SIZE_MIN, catalogueFont, normalizeFontSize }; -const SIZE_LABELS: Readonly> = { - tiny: "Tiny", - scriptsize: "Very small", - footnotesize: "Footnote", - small: "Small", - normalsize: "Normal", - large: "Large", - Large: "Larger", - LARGE: "Very large", - huge: "Huge", - Huge: "Largest", -}; +/** Sizes offered as shortcuts under the number field. */ +export const FONT_SIZE_PRESETS: ReadonlyArray = [8, 9, 10, 11, 12, 14, 18, 24, 36]; -const FAMILY_LABELS: Readonly> = { +const CATEGORY_LABELS: Readonly> = { serif: "Serif", "sans-serif": "Sans serif", - monospace: "Code", + monospace: "Monospace", }; -/** The ten LaTeX size names; `em` is each size relative to `\normalsize` at 10 pt. */ -export const FONT_SIZES = MARKDOWN_FONT_SIZES.map((size) => ({ - ...size, - label: SIZE_LABELS[size.name], -})); +export interface FontGroup { + readonly label: string; + readonly fonts: ReadonlyArray; +} -/** Generic families only; the names are the CSS keywords written in Markdown. */ -export const FONT_FAMILIES = MARKDOWN_FONT_FAMILIES.map((name) => ({ - name, - label: FAMILY_LABELS[name], +/** The catalogue grouped for the picker, in catalogue order. */ +export const FONT_GROUPS: ReadonlyArray = ( + ["serif", "sans-serif", "monospace"] as const +).map((category) => ({ + label: CATEGORY_LABELS[category], + fonts: FONT_CATALOGUE.filter((font) => font.category === category), })); - -export function isFontFamilyName(value: string): value is FontFamilyName { - return MARKDOWN_FONT_FAMILIES.some((family) => family === value); -} diff --git a/packages/scient-markdown/src/fontCatalogue.ts b/packages/scient-markdown/src/fontCatalogue.ts new file mode 100644 index 0000000000..1971c6c8ff --- /dev/null +++ b/packages/scient-markdown/src/fontCatalogue.ts @@ -0,0 +1,127 @@ +/** + * Named fonts offered for text, shared by both editors and both exports. A name is written + * to a file, CSS, LaTeX or Word XML only when it is in this list. + */ + +export type FontCategory = "serif" | "sans-serif" | "monospace"; + +export interface CatalogueFont { + /** The name written in files; also the Word font name. */ + readonly name: string; + readonly category: FontCategory; + /** CSS fallback stack used when rendering; the name itself comes first. */ + readonly css: string; + /** True when the font has Hebrew letters on the usual systems. */ + readonly hebrew: boolean; + readonly latex: { + /** pdfLaTeX font family code (`\fontfamily{code}`) of a free look-alike, or null. */ + readonly pdftex: string | null; + /** Name for `fontspec` under XeLaTeX or LuaLaTeX. */ + readonly fontspec: string; + /** Free font used when the named one is not installed (fontspec fallback). */ + readonly fallback: string | null; + }; +} + +const GENERIC: Readonly> = { + serif: "serif", + "sans-serif": "sans-serif", + monospace: "monospace", +}; + +function font( + name: string, + category: FontCategory, + stack: string, + hebrew: boolean, + latex: CatalogueFont["latex"], +): CatalogueFont { + return { name, category, css: `'${name}', ${stack}, ${GENERIC[category]}`, hebrew, latex }; +} + +export const FONT_CATALOGUE: ReadonlyArray = [ + font("Times New Roman", "serif", "Tinos, 'Liberation Serif', Times", true, { + pdftex: "qtm", + fontspec: "Times New Roman", + fallback: "TeX Gyre Termes", + }), + font("Cambria", "serif", "Caladea", false, { + pdftex: null, + fontspec: "Cambria", + fallback: "Latin Modern Roman", + }), + font("Georgia", "serif", "'Gelasio'", false, { + pdftex: null, + fontspec: "Georgia", + fallback: "Latin Modern Roman", + }), + font("Palatino", "serif", "'Palatino Linotype', 'Book Antiqua'", false, { + pdftex: "qpl", + fontspec: "Palatino", + fallback: "TeX Gyre Pagella", + }), + font("Garamond", "serif", "'EB Garamond'", false, { + pdftex: null, + fontspec: "Garamond", + fallback: "Latin Modern Roman", + }), + font("Libertinus Serif", "serif", "'Linux Libertine'", false, { + pdftex: null, + fontspec: "Libertinus Serif", + fallback: "Latin Modern Roman", + }), + font("Latin Modern Roman", "serif", "'CMU Serif'", false, { + pdftex: "lmr", + fontspec: "Latin Modern Roman", + fallback: null, + }), + font("Arial", "sans-serif", "Arimo, 'Liberation Sans', Helvetica", true, { + pdftex: "qhv", + fontspec: "Arial", + fallback: "TeX Gyre Heros", + }), + font("Helvetica", "sans-serif", "'Helvetica Neue', Arimo", false, { + pdftex: "qhv", + fontspec: "Helvetica", + fallback: "TeX Gyre Heros", + }), + font("Calibri", "sans-serif", "Carlito", false, { + pdftex: null, + fontspec: "Calibri", + fallback: "Latin Modern Sans", + }), + font("Latin Modern Sans", "sans-serif", "'CMU Sans Serif'", false, { + pdftex: "lmss", + fontspec: "Latin Modern Sans", + fallback: null, + }), + font("David", "serif", "'David Libre'", true, { + pdftex: null, + fontspec: "David", + fallback: "Times New Roman", + }), + font("Courier New", "monospace", "Cousine, 'Liberation Mono', Courier", false, { + pdftex: "qcr", + fontspec: "Courier New", + fallback: "TeX Gyre Cursor", + }), + font("Consolas", "monospace", "Inconsolata, Menlo", false, { + pdftex: null, + fontspec: "Consolas", + fallback: "Latin Modern Mono", + }), + font("Latin Modern Mono", "monospace", "'CMU Typewriter Text'", false, { + pdftex: "lmtt", + fontspec: "Latin Modern Mono", + fallback: null, + }), +]; + +const BY_NAME: ReadonlyMap = new Map( + FONT_CATALOGUE.map((entry) => [entry.name, entry]), +); + +/** The catalogue entry for a name written in a file, or null for any other string. */ +export function catalogueFont(name: string): CatalogueFont | null { + return BY_NAME.get(name) ?? null; +} diff --git a/packages/scient-markdown/src/fontSpans.test.ts b/packages/scient-markdown/src/fontSpans.test.ts new file mode 100644 index 0000000000..f790e76314 --- /dev/null +++ b/packages/scient-markdown/src/fontSpans.test.ts @@ -0,0 +1,38 @@ +import { describe, expect, it } from "vite-plus/test"; +import { markdownFontSpanOpen, normalizeFontSize, parseMarkdownFontSpanOpen } from "./fontSpans.ts"; + +describe("font span forms", () => { + it("reads and writes a size in points and a catalogue font", () => { + expect(parseMarkdownFontSpanOpen('')).toEqual({ size: 12 }); + expect(parseMarkdownFontSpanOpen('')).toEqual({ size: 10.5 }); + expect(parseMarkdownFontSpanOpen(``)).toEqual({ + family: "Times New Roman", + }); + expect(markdownFontSpanOpen({ size: 14 })).toBe(''); + expect(markdownFontSpanOpen({ family: "Arial" })).toBe(``); + }); + + it("rejects every other form, size outside the range and unknown font names", () => { + for (const style of [ + "font-size:1.2em", + "font-size:12px", + "font-size:0pt", + "font-size:101pt", + "font-size:12pt;color:red", + "font-family:serif", + `font-family:'Comic Sans MS'`, + `font-family:'Arial';color:red`, + `font-family:'Arial', serif`, + `font-family:'x