diff --git a/docs/OVERVIEW.md b/docs/OVERVIEW.md index d8a4951..3494f29 100644 --- a/docs/OVERVIEW.md +++ b/docs/OVERVIEW.md @@ -358,6 +358,68 @@ sentences printed correctly by accident (the full stop hides the missing space), so nothing looked wrong until the first English paper, whose sentences would have run together. +### An image is an object, and the sentence keeps only its address + +Not everything in a paper is text, and the parts that are not do not get a table. +The bytes of a 插图 live in **MinIO** (k3s, S3 protocol) and the sentence keeps +the address, as Markdown: + +``` +试验装置如 ![行内示意图](/api/images/2026/09/9f8c1a4b7e2d0c33.png) 所示。 +![试验装置示意图](/api/images/2026/09/9f8c1a4b7e2d0c33.png){width=70%} +``` + +A table was the obvious alternative — `paper_image` with a `sort`, a caption and +a paragraph position — and it is wrong here, for the reason the sentence model +already gives: a paragraph is *reassembled from sentences ordered by one number*, +and a second table holding its own `sort` beside that one gives a paragraph two +orderings that eventually disagree. Keeping the picture inside `content` means a +figure moves between paragraphs by being cut and pasted, survives a template +switch with the sentence it belongs to, and needs no new endpoint to write. The +same argument that made citations a table (a citation carries data of its own, +and is queried in both directions) is what keeps images out of one. + +Three properties of the storage are deliberate: + +- **The key is the digest of the picture.** `2026/09/9f8c1a4b7e2d0c33.png` is + derived from the bytes, so uploading the same screenshot twice — from two + paragraphs, or by accident — stores one object, and the address can never come + to mean a different picture than the one it was written for. That is what makes + the year-long `immutable` cache header safe to hand out. +- **The format is sniffed, never trusted.** The declared content type and the + filename are the uploader's claims; the magic bytes are the fact. PNG, JPEG, + GIF and WebP are accepted — and **SVG is not**, because an uploaded SVG served + from this origin is stored XSS, while the page already renders text the writer + controls. The served content type comes from a whitelist on our side, with + `X-Content-Type-Options: nosniff`. +- **The key space is also the access rule.** `GET /api/images/{key}` serves keys + of the shape this application writes and nothing else, so the read route cannot + become a browser for the rest of the bucket, whatever else is in it. + +Images are served through the API rather than from a public bucket URL so that a +sentence never embeds a host name: the same paper is read from the LAN in +development and from the public address later, and a hard-coded origin would +break on the other. It also means the bucket stays private. The response streams +the object out of MinIO rather than reading it into memory, and releases the +connection when the reader stops. + +Two rules decide how a picture prints, and both follow from "a sentence is a +line": + +| What the sentence holds | How it prints | +|---|---| +| nothing but `![图注](地址)` | a **figure**: its own line, centred, the brackets' text as 图注 underneath | +| an image inside a run of text | **inline**, on the line with the words, height capped at `12em` | + +The size is optional and comes from pandoc's attribute form — `{width=70%}`, +`{width=400px}` — and is validated to digits plus one unit before it becomes a +CSS length, so no second declaration can be smuggled through it. + +Configuration is three variables (`MINIO_ENDPOINT`, `MINIO_ACCESS_KEY`, +`MINIO_SECRET_KEY`, plus `MINIO_BUCKET`). Left empty, the paper still writes and +reads: only the image routes answer `503`, saying which variables are missing. +The bucket is created on the first upload if it is not there. + ### Citations are a table, not a column One sentence may quote several references, so @@ -465,6 +527,8 @@ All routes are mounted under `/api`. Interactive docs at `/docs`. | `PUT` | `/papers/{id}/paragraphs/{sort}` | full replacement; optional `target_sort` moves it | | `POST` | `/papers/{id}/sentences` | append one sentence | | `PATCH` `DELETE` | `/papers/{id}/sentences/{id}` | edit or remove one sentence | +| `POST` | `/images` | `multipart/form-data`, one `file` field; answers `key`, `url`, ready-to-paste `markdown`, `content_type`, `size`, `sha256` | +| `GET` | `/images/{key}` | streams the picture; only keys this app wrote, cached `immutable` for a year | Conventions worth knowing: @@ -510,6 +574,12 @@ Conventions worth knowing: rail's labels compose with the toolbar's. - A DOI is stored without its ``https://doi.org/`` prefix, so the column holds one spelling whichever way it was pasted. +- An uploaded image is refused with `415` when its bytes are not PNG/JPEG/GIF/ + WebP (SVG included), `413` when it is over `MAX_IMAGE_BYTES` (20 MiB) and `400` + when it is empty. A key that has no object, or one this application did not + write, is `404`. +- An image URL is relative (`/api/images/…`) and same-origin on purpose: the + client prints it as it stands, and the paper does not name a host. ## MCP server @@ -693,15 +763,16 @@ are not lists (the paper document) keep scrolling normally. A formula is stored exactly as the writer typed it — `$\ell$`, `$$ … \tag{1} $$` — because that is the form that can be edited; an equation image cannot be -changed by one character. Typesetting happens when the paper is read, in -`src/utils/math.ts`, which splits a sentence into text and formulas, hands the -formulas to KaTeX and escapes everything else. +changed by one character. The same is true of a picture: the sentence keeps the +Markdown that points at it. Typesetting happens when the paper is read, in +`src/utils/rich.ts`, which splits a sentence into text, formulas and images, +hands the formulas to KaTeX and escapes everything else. Four delimiters are recognised, because a writer's habit decides which they use: `$$…$$` and `\[…\]` for display, `$…$` and `\(…\)` for inline. An unmatched `$` is left alone rather than swallowing the rest of the paragraph. -Three rules are worth knowing when reading the renderer: +Four rules are worth knowing when reading the renderer: - **A display formula is a block.** It takes its own line whether or not the sentence asked for a break, because that is what "display" means. @@ -723,6 +794,14 @@ Three rules are worth knowing when reading the renderer: through `v-html`, and KaTeX runs with `trust` off, so a sentence cannot inject markup. +An image is the one thing the renderer does *not* build inside that HTML string. +A figure is printed by `PaperParagraph` as a real `` — so it can carry the +writer's size and be opened at full resolution by a click — and `figureOf()` +decides whether a sentence is a figure: it is one when the sentence holds nothing +but a picture and whitespace. The reader's click is handled once, on the +paragraph body, because inline pictures arrive through `v-html`, where no +listener can be bound to them from a template. + ### The paper view `PapersView` is the library; `papers/PaperDetailView` is the writing surface. @@ -780,11 +859,12 @@ in correctly. paper-doc/ ├── backend/ # FastAPI application │ ├── app/ -│ │ ├── api/routes/ # route handlers (health, papers, references, +│ │ ├── api/routes/ # route handlers (health, images, papers, references, │ │ │ # reference_tags, templates, template_title) │ │ ├── citation_styles/ # how a reference prints: springer.py, and the │ │ │ # registry that names the styles -│ │ ├── core/ # settings and configuration +│ │ ├── core/ # settings, and the object store (MinIO) the +│ │ │ # images a paper embeds are kept in │ │ ├── crud/ # data-access helpers │ │ ├── db/ # engine, session, declarative base │ │ ├── mcp/ # MCP server: tools, specs, transports, self-check @@ -795,6 +875,7 @@ paper-doc/ │ ├── scripts/smoke_papers.py # end-to-end check of the writing loop │ ├── scripts/smoke_references.py # end-to-end check of the reference library │ │ # and its tags +│ ├── scripts/smoke_images.py # end-to-end check of upload, serve and refusal │ ├── scripts/check_citation_styles.py # the formatter, one entry per type │ │ # (no server, no database) │ ├── scripts/mcp_server.py # MCP entry point (stdio / http) @@ -811,7 +892,8 @@ paper-doc/ │ │ ├── stores/ # pinia stores (UI prefs persisted, the paper and │ │ │ # tag lists not) │ │ ├── styles/ # global reset and the shell viewport contract -│ │ ├── utils/ # formatting helpers +│ │ ├── utils/ # formatting helpers, and rich.ts — the reader for +│ │ │ # a sentence's LaTeX and its images │ │ └── views/ # route-level components (papers/, references/, │ │ # templates/) │ ├── package.json @@ -832,6 +914,8 @@ paper-doc/ - Python 3.10+ with `venv` - Node.js 18+ with `pnpm` - Network access to the TiDB instance (local development uses the NodePort) +- *Optional:* a MinIO (or any S3-compatible) endpoint, for the images a paper + embeds. Without one, everything still works except uploading pictures. **Backend** @@ -839,7 +923,8 @@ paper-doc/ cd backend python3 -m venv .venv && source .venv/bin/activate pip install -r requirements.txt -cp .env.example .env # then fill in the database credentials +cp .env.example .env # then fill in the database credentials, and the + # MINIO_* ones if the paper is to hold images uvicorn app.main:app --reload --port 8000 ``` diff --git a/frontend/src/api/images.ts b/frontend/src/api/images.ts new file mode 100644 index 0000000..64f6b4a --- /dev/null +++ b/frontend/src/api/images.ts @@ -0,0 +1,61 @@ +import http from './client' + +/** + * Images (插图) — the pictures a sentence embeds. + * + * An image is not stored in the database. The upload puts the bytes in the + * object store and answers with a URL *and* the Markdown that embeds it; the + * sentence keeps that Markdown and nothing else. So inserting a figure is + * ordinary text editing, moving one between paragraphs is cut and paste, and + * nothing about the paper has to be re-saved when a picture is replaced. + * + * The server decides the Markdown (see `app/core/storage.markdown_for`) rather + * than this module, so the syntax written here and the syntax the reader parses + * cannot drift apart. + */ + +/** One stored image, as the API reports it. */ +export interface StoredImage { + /** Its key in the bucket — the same picture always gets the same key. */ + key: string + /** Same-origin path, e.g. `/api/images/2026/09/9f8c1a4b7e2d0c33.png`. */ + url: string + /** Ready to paste: `![图注](/api/images/…)`. */ + markdown: string + content_type: string + /** Size in bytes. */ + size: number + sha256: string +} + +/** What the server will accept; the browser's picker filters on the same list. */ +export const IMAGE_ACCEPT = 'image/png,image/jpeg,image/gif,image/webp' + +/** Refuse a file the server would refuse, before spending a request on it. */ +export function imageRejection(file: File): string | null { + if (!IMAGE_ACCEPT.split(',').includes(file.type)) { + return '只支持 PNG / JPEG / GIF / WebP 图片。' + } + return null +} + +/** + * Upload one image and get back the Markdown that embeds it. + * + * The Content-Type is set explicitly and *without* a boundary: axios recognises + * a `FormData` body and drops the header, letting the browser write it with the + * boundary it generated. Leaving the shared client's `application/json` default + * in place would send the file as JSON and the server would never see it. + */ +export async function uploadImage(file: File): Promise { + const form = new FormData() + form.append('file', file) + + const { data } = await http.post('/images', form, { + headers: { 'Content-Type': 'multipart/form-data' }, + // The shared client's 15s is sized for queries; a figure over a slow link + // is not a hung request. + timeout: 120000, + }) + return data +} diff --git a/frontend/src/components/papers/PaperParagraph.vue b/frontend/src/components/papers/PaperParagraph.vue index 369c1c5..e89ecd9 100644 --- a/frontend/src/components/papers/PaperParagraph.vue +++ b/frontend/src/components/papers/PaperParagraph.vue @@ -21,13 +21,24 @@ * * A sentence that quotes something gets a superscript marker numbered by the * paper's citation list, so the marker and the 参考文献 entry cannot disagree. + * + * A sentence that is nothing but an image is a figure: its own line, centred, + * with the text in the brackets printed underneath as its 图注. It is built as + * a real `` rather than through `renderRich`, so it can carry the writer's + * size and be opened at full resolution — a figure is read, not just seen. */ -import { computed } from 'vue' +import { computed, ref } from 'vue' import { Edit } from '@element-plus/icons-vue' import type { PaperParagraph } from '@/api/papers' import { PARAGRAPH_UNSET_LABEL, levelIndent } from '@/utils/format' -import { escapeHtml, hasDisplayMath, renderRich } from '@/utils/math' +import { + escapeHtml, + figureOf, + hasDisplayMath, + renderRich, + type ImageSegment, +} from '@/utils/rich' const props = defineProps<{ paragraph: PaperParagraph @@ -65,6 +76,8 @@ interface RenderedSentence { display: boolean /** The writer asked for a line break before this sentence. */ lineBreak: boolean + /** The image this sentence is, when it is nothing but an image. */ + figure: ImageSegment | null } const rendered = computed(() => @@ -75,6 +88,7 @@ const rendered = computed(() => renderRich(sentence.content), display: hasDisplayMath(sentence.content), lineBreak: sentence.line_break_before, + figure: figureOf(sentence.content), })), ) @@ -89,7 +103,8 @@ const rendered = computed(() => * paragraph should be indented. * * A line starts when the writer breaks one, when a display formula needs a line - * of its own, or after one (a block always ends the line it sits in). + * of its own, when a figure does, or after one (a block always ends the line it + * sits in). */ interface RenderedLine { /** Whether the first line of this block is indented by two characters. */ @@ -102,17 +117,19 @@ const renderedLines = computed(() => { rendered.value.forEach((item, index) => { const previous = rendered.value[index - 1] + const isBlock = item.display || item.figure !== null + const previousIsBlock = previous !== undefined && (previous.display || previous.figure !== null) const startsLine = index === 0 || // the paragraph's own first line item.lineBreak || // the writer asked for one - item.display || // a display formula takes a line of its own - Boolean(previous?.display) // …and the line after it starts fresh + isBlock || // a display formula or a figure is a block by definition + previousIsBlock // …and the line after one starts fresh if (startsLine) { lines.push({ // Indented at the start of the paragraph, and after a break the writer - // asked for. Not after a display formula: that text continues the same - // paragraph, and a Chinese manuscript does not indent a continuation. + // asked for. Not after a block: that text continues the same paragraph, + // and a Chinese manuscript does not indent a continuation. indent: index === 0 || item.lineBreak, items: [], }) @@ -123,6 +140,22 @@ const renderedLines = computed(() => { return lines }) +/** + * The image being read at full size. + * + * An experiment figure on a page is often too small to check a curve against — + * so clicking one opens it over the paper, and clicking away closes it. The + * handler sits on the body and looks at what was clicked rather than being + * attached to each picture: inline images arrive through `v-html`, where no + * listener can be bound to them from a template. + */ +const previewing = ref(null) + +function onBodyClick(event: MouseEvent): void { + const target = event.target + if (target instanceof HTMLImageElement) previewing.value = target.currentSrc || target.src +} + /** Whether anything has actually been written here. */ const hasContent = computed(() => rendered.value.some( @@ -170,7 +203,7 @@ const anchor = computed(() => `paragraph-${props.paragraph.paper_template_filed_ -
+

`paragraph-${props.paragraph.paper_template_filed_ :class="{ 'is-indented': line.indent }" > @@ -346,6 +407,44 @@ const anchor = computed(() => `paragraph-${props.paragraph.paper_template_filed_ text-align: right; } +/* A figure: the picture centred on its own line, its 图注 under it. Sized by its + natural width unless the writer asked for `{width=…}` — an experiment figure + is usually already cropped to what it should show, and stretching it to the + full column would only make the axes bigger. */ +.sentence--figure { + display: block; + text-indent: 0; + text-align: center; + margin: 10px 0 6px; + white-space: normal; +} + +.figure-image { + max-width: 100%; + height: auto; + border-radius: 4px; + cursor: zoom-in; + vertical-align: middle; +} + +.figure-caption { + display: block; + margin-top: 6px; + font-size: 13px; + line-height: 1.7; + color: var(--el-text-color-regular); +} + +/* An image inside a run of text — not a figure, so it sits on the line with the + words. Its height is capped because a line of a paragraph is not a place to + discover that someone pasted a screenshot. */ +.paragraph-body :deep(.rich-image) { + max-width: 100%; + max-height: 12em; + vertical-align: middle; + cursor: zoom-in; +} + /* The fallback when KaTeX cannot read a formula: the source, in red, so it can be found and fixed instead of silently vanishing. */ .paragraph-body :deep(.math-error) { diff --git a/frontend/src/components/papers/ParagraphEditDialog.vue b/frontend/src/components/papers/ParagraphEditDialog.vue index 9d31a84..abe0d38 100644 --- a/frontend/src/components/papers/ParagraphEditDialog.vue +++ b/frontend/src/components/papers/ParagraphEditDialog.vue @@ -21,12 +21,21 @@ * The optional 「所属段落」 select moves the whole paragraph to another position, * appending after whatever that paragraph already holds. That is the manual * form of what switching the paper's template does by itself. + * + * 「插入图片」 uploads a picture and appends the sentence that shows it — a + * screenshot does not go through the clipboard, and an experiment figure belongs + * on its own line with its 图注 under it, which is exactly what a sentence + * holding nothing but an image renders as. The row then shows the picture, not + * just the path to it, because checking that the right curve went into the right + * paragraph is the whole reason one look at the editor is worth more than three + * reads of a URL. */ import { computed, reactive, ref, watch } from 'vue' -import { ArrowDown, ArrowUp, Delete, Plus, Refresh } from '@element-plus/icons-vue' +import { ArrowDown, ArrowUp, Delete, Picture, Plus, Refresh } from '@element-plus/icons-vue' import { ElMessage } from 'element-plus' import { errorMessage } from '@/api/client' +import { IMAGE_ACCEPT, imageRejection, uploadImage } from '@/api/images' import { FORMULA_ALIGN_OPTIONS, getParagraph, @@ -37,7 +46,7 @@ import { type SentenceInput, } from '@/api/papers' import { PARAGRAPH_UNSET_LABEL, foldWhitespace } from '@/utils/format' -import { hasDisplayMath } from '@/utils/math' +import { hasDisplayMath, imagesOf, type ImageSegment } from '@/utils/rich' const props = defineProps<{ /** Visibility, used with `v-model`. */ @@ -175,6 +184,71 @@ function removeSentence(key: number): void { rows.value = rows.value.filter((row) => row.key !== key) } +/** The pictures a row shows, so the editor can print them and not just their URLs. */ +function rowImages(row: SentenceDraft): ImageSegment[] { + return imagesOf(row.content) +} + +// --- images --------------------------------------------------------------- + +/** The hidden file picker the 「插入图片」 button drives. */ +const fileInput = ref(null) +/** How many uploads are in flight, so the button can say so. */ +const uploading = ref(0) + +function pickImage(): void { + fileInput.value?.click() +} + +async function onFilePicked(event: Event): Promise { + const input = event.target as HTMLInputElement + const files = Array.from(input.files ?? []) + // Cleared straight away: without it, picking the same file twice in a row + // fires no `change` event the second time and the upload looks broken. + input.value = '' + await insertImages(files) +} + +/** Drop a file anywhere in the dialog to insert it. */ +async function onDrop(event: DragEvent): Promise { + const files = Array.from(event.dataTransfer?.files ?? []) + if (files.length) await insertImages(files) +} + +/** + * Upload each picture and append the sentence that shows it. + * + * One row per image, with 另起一行 set: a figure on a line of its own is what an + * experiment picture is for, and the writer who wants it inline instead is one + * text edit away from it. + */ +async function insertImages(files: File[]): Promise { + for (const file of files) { + const rejection = imageRejection(file) + if (rejection) { + ElMessage.warning(`${file.name}:${rejection}`) + continue + } + + uploading.value += 1 + try { + const stored = await uploadImage(file) + rows.value.push({ + key: nextKey++, + sort: nextSort(), + content: stored.markdown, + lineBreak: true, + align: 'center', + citations: [], + }) + } catch (error) { + ElMessage.error(errorMessage(error)) + } finally { + uploading.value -= 1 + } + } +} + function addCitation(row: SentenceDraft): void { row.citations.push({ key: nextKey++, reference_id: null, quote: '' }) } @@ -307,7 +381,22 @@ async function submit(): Promise {

-
+
+ + { 共 {{ orderedRows.length }} 句 按 sort 升序拼成这个段落;公式写 LaTeX:行内 $x$,独立成行 $$x$$(编号用 - \tag{1},自动靠右) + \tag{1},自动靠右);图片也写在句子里:![图注](地址),可加 {width=60%}
+ + 插入图片 + 自动编号 @@ -428,6 +525,16 @@ async function submit(): Promise { placeholder="这一句的内容(只留空白的句子保存时会删除)" /> + +
+
+ +
{{ image.alt || '方括号里写的就是图注' }}
+
+
+
{ color: var(--el-text-color-secondary); line-height: 32px; } + +/* The picker is driven by the toolbar button. A browser file control would put + a second, differently-worded uploader in the middle of the dialog. */ +.file-input { + display: none; +} + +/* The pictures a row holds, printed under its text. `:empty` keeps a row with + no images from reserving a box for them. */ +.row-images { + display: flex; + flex-wrap: wrap; + gap: 10px; +} + +.row-images:empty { + display: none; +} + +.row-image { + display: flex; + flex-direction: column; + gap: 4px; + max-width: 168px; + margin: 0; +} + +.row-image img { + max-width: 168px; + max-height: 112px; + height: auto; + object-fit: contain; + border: 1px solid var(--el-border-color-lighter); + border-radius: 4px; + background-color: var(--el-fill-color-lighter); +} + +.row-image figcaption { + font-size: 12px; + line-height: 1.5; + color: var(--el-text-color-secondary); + overflow-wrap: anywhere; +} diff --git a/frontend/src/utils/rich.ts b/frontend/src/utils/rich.ts index 2cacb88..70976bf 100644 --- a/frontend/src/utils/rich.ts +++ b/frontend/src/utils/rich.ts @@ -1,13 +1,14 @@ /** - * Rendering a sentence that contains LaTeX. + * Reading a sentence: what the writer typed, turned into what the paper shows. * - * A sentence is stored as the writer typed it, LaTeX and all, because that is - * what can be edited — `$\ell$` is one character to change and an equation - * image is not. Reading it is this module's job: it splits the text into plain - * segments and formulas, hands the formulas to KaTeX, and escapes everything - * that is not a formula. + * A sentence is stored as one string, because that is the only form of it that + * can be *edited*: `$\ell$` is one character to change, a typeset equation is + * not, and `![图注](/api/images/…)` moves between paragraphs by being cut and + * pasted. Everything here exists to make that decision readable. * - * Four delimiters are recognised, because a paper written in LaTeX, in + * Two families of markup are recognised. + * + * **Formulas** — four delimiters, because a paper written in LaTeX, in * Markdown, or by hand uses whichever the writer's habit prefers: * * ================== ========== @@ -17,25 +18,63 @@ * `\( … \)` inline * ================== ========== * - * An unmatched `$` is left alone: money in a sentence, or a formula half - * typed, must not swallow the rest of the paragraph. + * **Images** — `![图注](地址)`, the Markdown every editor already writes, with + * an optional size in pandoc's attribute form: * - * `throwOnError: false` is deliberate. A broken formula renders as its own - * source in red rather than an exception, so one typo cannot blank out the - * paper the writer is reading. + * ============================ ========================================= + * `![图注](地址)` drawn at its natural size, capped to the column + * `![图注](地址){width=70%}` 70% of the column + * `![图注](地址){width=400px}` 400 pixels + * ============================ ========================================= + * + * An image alone in a sentence is a *figure*: it takes a line of its own with + * its 图注 underneath (see `figureOf`). The same markup inside a run of text + * stays inline, at the size of the text around it. + * + * An unmatched `$` is left alone: money in a sentence, or a formula half typed, + * must not swallow the rest of the paragraph. The same goes for a half-typed + * image — an unclosed `![` prints as the characters it is. */ import katex from 'katex' -/** One piece of a sentence: plain text, or a formula and how to set it. */ +/** One piece of a sentence: plain text, a formula, or a picture. */ export type RichSegment = | { kind: 'text'; value: string } | { kind: 'math'; value: string; display: boolean } + | { kind: 'image'; src: string; alt: string; width: string | null } + +/** An image segment, which is what a figure is made of. */ +export type ImageSegment = Extract /** - * Display delimiters are matched first: `$$…$$` contains `$…$`, so the other - * order would read an empty inline formula and leave the rest as text. + * The image alternative comes first: `![a](b)` starts with `!`, which no + * formula does, so the two never compete for the same characters. Within the + * formulas, display delimiters are matched before inline ones because `$$…$$` + * contains `$…$`. */ -const MATH_PATTERN = /\$\$([\s\S]+?)\$\$|\\\[([\s\S]+?)\\\]|\$([^$\n]+?)\$|\\\(([\s\S]+?)\\\)/g +const RICH_PATTERN = new RegExp( + [ + String.raw`!\[(?[^\]]*)\]\((?[^()\s]+)(?:\s+"(?[^"]*)")?\)(?<attrs>\{[^}]*\})?`, + String.raw`\$\$(?<displayDollar>[\s\S]+?)\$\$`, + String.raw`\\\[(?<displayBracket>[\s\S]+?)\\\]`, + String.raw`\$(?<inlineDollar>[^$\n]+?)\$`, + String.raw`\\\((?<inlineBracket>[\s\S]+?)\\\)`, + ].join('|'), + 'g', +) + +/** + * `{width=70%}` / `{w=400px}` — pandoc's attribute form, with both spellings of + * the key that people type. + * + * The value is validated here rather than trusted and escaped later, because + * what it becomes is a CSS length on the element. Digits and at most one unit, + * nothing else: there is no way to express a second declaration through it. + */ +const WIDTH_PATTERN = /^\s*(?:w|width)\s*=\s*(\d{1,4})\s*(%|px)?\s*$/i + +/** The largest absolute width we will set, so a typo cannot push a figure off. */ +const MAX_PIXELS = 4000 const HTML_ESCAPES: Record<string, string> = { '&': '&', @@ -50,23 +89,53 @@ export function escapeHtml(value: string): string { return value.replace(/[&<>"']/g, (character) => HTML_ESCAPES[character] ?? character) } -/** Split a sentence into its plain and mathematical parts. */ +/** Read a size out of an image's attributes, or refuse to guess one. */ +export function parseImageWidth(attributes: string | undefined): string | null { + if (!attributes) return null + + const match = WIDTH_PATTERN.exec(attributes.replace(/^\{|\}$/g, '')) + if (!match) return null + + const value = Number(match[1]) + if (match[2] === 'px') { + return value >= 1 && value <= MAX_PIXELS ? `${value}px` : null + } + return value >= 1 && value <= 100 ? `${value}%` : null +} + +/** Split a sentence into its plain, mathematical and pictorial parts. */ export function splitRich(content: string): RichSegment[] { const segments: RichSegment[] = [] let cursor = 0 - MATH_PATTERN.lastIndex = 0 - for (let match = MATH_PATTERN.exec(content); match; match = MATH_PATTERN.exec(content)) { + RICH_PATTERN.lastIndex = 0 + for (let match = RICH_PATTERN.exec(content); match; match = RICH_PATTERN.exec(content)) { if (match.index > cursor) { segments.push({ kind: 'text', value: content.slice(cursor, match.index) }) } - const [whole, doubleDollar, doubleBracket, singleDollar, singleBracket] = match - segments.push({ - kind: 'math', - value: doubleDollar ?? doubleBracket ?? singleDollar ?? singleBracket ?? '', - display: doubleDollar !== undefined || doubleBracket !== undefined, - }) - cursor = match.index + whole.length + + const groups = match.groups ?? {} + if (groups.src !== undefined) { + segments.push({ + kind: 'image', + src: groups.src, + alt: groups.alt ?? '', + width: parseImageWidth(groups.attrs), + }) + } else { + segments.push({ + kind: 'math', + value: + groups.displayDollar ?? + groups.displayBracket ?? + groups.inlineDollar ?? + groups.inlineBracket ?? + '', + display: groups.displayDollar !== undefined || groups.displayBracket !== undefined, + }) + } + + cursor = match.index + match[0].length } if (cursor < content.length) { @@ -80,6 +149,32 @@ export function hasDisplayMath(content: string): boolean { return splitRich(content).some((segment) => segment.kind === 'math' && segment.display) } +/** + * The image a sentence consists of, when it consists of one. + * + * This is the rule that separates a 插图 from an inline picture: a sentence + * holding nothing but an image is a figure — it starts its own line, is + * centred, and the text in the brackets prints underneath as its 图注. Anything + * else — a picture inside a sentence that says something — stays in the line, + * at the size of the text around it. + */ +export function figureOf(content: string): ImageSegment | null { + const meaningful = splitRich(content).filter( + (segment) => segment.kind !== 'text' || segment.value.trim().length > 0, + ) + if (meaningful.length !== 1) return null + + const only = meaningful[0]! + return only.kind === 'image' ? only : null +} + +/** Every image in a sentence, in the order it appears. */ +export function imagesOf(content: string): ImageSegment[] { + return splitRich(content).filter( + (segment): segment is ImageSegment => segment.kind === 'image', + ) +} + /** Render one formula, or the source in red when KaTeX cannot read it. */ function renderMath(value: string, display: boolean): string { try { @@ -96,18 +191,29 @@ function renderMath(value: string, display: boolean): string { } /** - * Render a sentence to HTML: text escaped, formulas typeset. + * Render the *inline* content of a sentence: text escaped, formulas typeset, + * pictures placed in the running line. + * + * A figure is deliberately not built here. It is a block with a caption, and + * the component that prints a paragraph makes it from `figureOf` so that the + * picture is a real `<img>` it can bind to and click, rather than markup + * assembled inside a string. * * The result is for `v-html`. KaTeX's own output is the only markup in it — - * `trust` is off, so no command can inject HTML — and every text segment is - * escaped here. + * `trust` is off, so no command can inject HTML — and every text segment and + * every attribute is escaped here. */ export function renderRich(content: string): string { return splitRich(content) - .map((segment) => - segment.kind === 'text' - ? escapeHtml(segment.value) - : renderMath(segment.value, segment.display), - ) + .map((segment) => { + if (segment.kind === 'text') return escapeHtml(segment.value) + if (segment.kind === 'math') return renderMath(segment.value, segment.display) + + const width = segment.width ? ` style="width:${segment.width}"` : '' + return ( + `<img class="rich-image" src="${escapeHtml(segment.src)}"` + + ` alt="${escapeHtml(segment.alt)}" loading="lazy" decoding="async"${width}>` + ) + }) .join('') }