frontend: insert a figure into a sentence, and print it as one

The editor gains 「插入图片」: it uploads the file and appends the sentence that
shows it, and a file dropped anywhere in the dialog does the same. Each row then
prints the picture it holds, not only the path to it — checking that the right
curve landed in the right paragraph is the whole reason to look at the editor.

Reading it back, one rule decides the layout: a sentence holding nothing but an
image is a figure — its own line, centred, the text in the brackets printed
underneath as its 图注 — while an image inside a run of text stays on the line,
height capped so a pasted screenshot cannot stretch a line of prose. The size is
optional, in pandoc's `{width=70%}` form, and is validated to digits plus one
unit before it becomes a CSS length.

`utils/math.ts` becomes `utils/rich.ts`, because it now reads two families of
markup rather than one: the formulas it always parsed, and the images a sentence
keeps as Markdown. A figure is deliberately not built inside the `v-html` string
the rest of a sentence is: `PaperParagraph` prints it as a real `<img>`, so it
can carry the writer's size and open at full resolution when clicked — an
experiment figure on a page is often too small to check a curve against.
This commit is contained in:
2026-09-23 13:31:31 +08:00
parent 6f37120dc4
commit 0e0fde8f02
5 changed files with 556 additions and 55 deletions
+61
View File
@@ -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<StoredImage> {
const form = new FormData()
form.append('file', file)
const { data } = await http.post<StoredImage>('/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
}
@@ -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 `<img>` 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<RenderedSentence[]>(() =>
@@ -75,6 +88,7 @@ const rendered = computed<RenderedSentence[]>(() =>
renderRich(sentence.content),
display: hasDisplayMath(sentence.content),
lineBreak: sentence.line_break_before,
figure: figureOf(sentence.content),
})),
)
@@ -89,7 +103,8 @@ const rendered = computed<RenderedSentence[]>(() =>
* 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<RenderedLine[]>(() => {
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<RenderedLine[]>(() => {
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<string | null>(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_
</div>
</header>
<div v-if="hasContent" class="paragraph-body">
<div v-if="hasContent" class="paragraph-body" @click="onBodyClick">
<p
v-for="(line, index) in renderedLines"
:key="index"
@@ -178,11 +211,28 @@ const anchor = computed(() => `paragraph-${props.paragraph.paper_template_filed_
:class="{ 'is-indented': line.indent }"
>
<template v-for="item in line.items" :key="item.sentence.id">
<!-- A figure: the image, and the text in its brackets printed below
it. It is a block, so it takes a line of its own whether or not
the writer asked for a break. -->
<span v-if="item.figure" class="sentence sentence--figure">
<img
class="figure-image"
:src="item.figure.src"
:alt="item.figure.alt"
:style="item.figure.width ? { width: item.figure.width } : undefined"
loading="lazy"
decoding="async"
/>
<span v-if="item.figure.alt" class="figure-caption">
{{ item.figure.alt }}
</span>
</span>
<!-- A display formula is a block by definition, so it takes its own
line whether or not the writer asked for a break. How it sits on
that line is the writer's choice, per formula. -->
<span
v-if="item.display"
v-else-if="item.display"
class="sentence sentence--display"
:class="`is-${item.sentence.formula_align}`"
v-html="item.html"
@@ -225,6 +275,17 @@ const anchor = computed(() => `paragraph-${props.paragraph.paper_template_filed_
「(本段暂无内容)」 into a paper puts words there that the paper did
not ask for, and on export they would go with it. The blank body is
the honest rendering of a blank paragraph. -->
<!-- Full size, over the paper. `teleported` because the paper lives in a
scrolling column, and an overlay positioned inside it would scroll
away with the text. -->
<el-image-viewer
v-if="previewing"
:url-list="[previewing]"
:hide-on-click-modal="true"
teleported
@close="previewing = null"
/>
</section>
</template>
@@ -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) {
@@ -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<HTMLInputElement | null>(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<void> {
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<void> {
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<void> {
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<void> {
</div>
</template>
<div v-loading="loading" class="editor">
<div
v-loading="loading"
class="editor"
@dragover.prevent
@drop.prevent="onDrop"
>
<!-- Driven by the 「插入图片」 button; hidden because the dialog has its
own button rather than the browser's default file control. -->
<input
ref="fileInput"
type="file"
:accept="IMAGE_ACCEPT"
multiple
class="file-input"
@change="onFilePicked"
/>
<el-alert
v-if="heading && !heading.matched"
type="warning"
@@ -351,9 +440,17 @@ async function submit(): Promise<void> {
<span class="toolbar-title">共 {{ orderedRows.length }} 句</span>
<span class="toolbar-hint">
按 sort 升序拼成这个段落;公式写 LaTeX:行内 $x$,独立成行 $$x$$(编号用
\tag{1},自动靠右)
\tag{1},自动靠右);图片也写在句子里:![图注](地址),可加 {width=60%}
</span>
<div class="toolbar-spacer" />
<el-button
size="small"
:icon="Picture"
:loading="uploading > 0"
@click="pickImage"
>
插入图片
</el-button>
<el-button size="small" :icon="Refresh" :disabled="!orderedRows.length" @click="autoNumber">
自动编号
</el-button>
@@ -428,6 +525,16 @@ async function submit(): Promise<void> {
placeholder="这一句的内容(只留空白的句子保存时会删除)"
/>
<!-- The picture itself, not only the path to it. The reason to look
at the editor at all is to see that the right curve landed in the
right paragraph. -->
<div class="row-images">
<figure v-for="image in rowImages(row)" :key="image.src" class="row-image">
<img :src="image.src" :alt="image.alt" loading="lazy" />
<figcaption>{{ image.alt || '方括号里写的就是图注' }}</figcaption>
</figure>
</div>
<div class="citations">
<div v-for="citation in row.citations" :key="citation.key" class="citation">
<el-input-number
@@ -621,4 +728,47 @@ async function submit(): Promise<void> {
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;
}
</style>
+140 -34
View File
@@ -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<RichSegment, { kind: 'image' }>
/**
* 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`!\[(?<alt>[^\]]*)\]\((?<src>[^()\s]+)(?:\s+"(?<title>[^"]*)")?\)(?<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> = {
'&': '&amp;',
@@ -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('')
}