frontend: let the writer set a figure's size in the editor

Figures come out of a plotting tool at whatever size they were made. On the
paper this was written for, the sixteen of them are 1441, 1857, 2409 and 4169
pixels wide — every one wider than the 1276px column — so with no size they all
printed at the full width, and the near-square ones (1857×1986, 1974×2068) took
1365px of height, a page each. Measured in the browser, all sixteen came out at
exactly 1276px: not one of them was the size its author wanted.

`{width=…}` has been in the syntax all along, so this is the control that was
missing, not the feature. A row that is a figure now carries 宽度 in its header:
25/50/70/100%, or any value typed in — the size a panel wants is what it
measures, not a round number — with 原尺寸 as the empty value. Beside it, what
the picture will measure on the page (`原图 1857×1986 · 显示 893×955`), worked
out against the column actually rendered behind the dialog, which is the number
the writer is deciding with.

Two rules keep it honest. The value goes through `parseImageWidth` — the same
function that parses the attribute when the paper is printed — so what the
control shows is what will be printed, and a value it cannot read is refused
with the forms that work instead of stored as a size that quietly does nothing.
And the attribute is written into the sentence content by `withImageWidth`,
which edits only the first picture: the control is offered for a figure, and a
sentence with words around its picture is not one. Reading the size back out of
the content rather than keeping a copy of it in the draft means there is one
place it can be wrong instead of two.

`check-image.mjs` grows from 15 checks to 24, driving the real control: that
only figure rows offer one, that it shows what each is set to, that typing 30%
converts to 383×239 immediately, that what was typed is what gets stored, that
the paper then prints it at 30% of the column, that clearing it goes back to the
natural 480×300, and that "宽一点" is refused while the sentence keeps its size.

The MCP side of the same rule was wrong and is fixed with it: `image_upload(width=
"60")` wrote `{width=60px}`, and the reader takes a bare number as a share of the
column — `parseImageWidth` only reads pixels when the value says `px`. A model
asking for 60% got a 60-pixel figure. v7 is deployed with the corrected reading,
and smoke_mcp.py checks it.
This commit is contained in:
2026-09-24 11:25:18 +08:00
parent 9e6a1f8c3e
commit 48f0c12fd2
9 changed files with 357 additions and 12 deletions
+97
View File
@@ -268,6 +268,103 @@ try {
check('the inserted figure is in the paper', saved.count === 2, JSON.stringify(saved))
check('and it is the one that was uploaded', saved.captions.includes('第二张图'), saved.captions.join())
check('both pictures decoded', saved.decoded.every((width) => width === 480), saved.decoded.join())
// --- the figure's size, set from the editor ------------------------------
//
// Figures come out of the plotting tool at whatever size they were made —
// one paper's are 1441, 2400 and 4169 pixels wide — and every one of them can
// be wider than the column, so with no size they all print at the full column
// and a near-square panel fills a page. This control is the answer to that,
// and what has to hold is that what it writes is what the reader prints.
await page.locator('.paragraph-actions button:has-text("编辑")').first().click()
await page.waitForSelector('.editor .rows', { timeout: 15000 })
await page.waitForSelector('.width-select')
// The hint divides the column by the picture's own size, so it needs the
// thumbnail to have decoded first.
await page.waitForFunction(
() => document.querySelector('.size-hint')?.textContent?.includes('原图'),
{ timeout: 15000 },
)
// What each select is showing: Element Plus prints the chosen label in its
// own element, not as the value of the input the writer types into.
const controls = await page.evaluate(() =>
[...document.querySelectorAll('.width-select')].map((node) =>
(node.querySelector('.el-select__selected-item')?.textContent ?? '').trim() ||
(node.querySelector('.el-select__placeholder')?.textContent ?? '').trim(),
),
)
check('only a figure row offers a size', controls.length === 2, JSON.stringify(controls))
check(
'and each one shows the size it is set to',
controls[0] === '50%' && controls[1] !== '50%',
JSON.stringify(controls),
)
const hint = async () =>
(await page.locator('.size-hint').first().innerText()).replace(/\s+/g, ' ')
check(
'the hint says what it will measure on the page',
/显示 638×399/.test(await hint()),
await hint(),
)
// Typing a value that is not one of the presets is the point of the control:
// the size a panel wants is what it measures, not a round number.
await page.locator('.width-select input').first().fill('30%')
await page.keyboard.press('Enter')
await page.waitForTimeout(400)
check('typing 30% converts immediately', /显示 383×239/.test(await hint()), await hint())
await page.getByRole('button', { name: '保存段落' }).click()
await page.waitForSelector('.el-dialog', { state: 'detached', timeout: 15000 })
await page.waitForTimeout(700)
const stored = await api('GET', `/papers/${paperId}/paragraphs/${sort}`)
const sized = stored.paragraph.sentences.find((sentence) =>
sentence.content.includes('试验装置示意图'),
)
check('what was typed is what is stored', sized?.content.endsWith('{width=30%}'), sized?.content)
const shrunk = await page.evaluate(() => {
const body = document.querySelector('.paragraph-body')
const column = Math.round(body.getBoundingClientRect().width)
const figure = [...document.querySelectorAll('.sentence--figure')].find(
(node) => node.querySelector('.figure-caption')?.textContent.trim() === '试验装置示意图',
)
const box = figure.querySelector('img').getBoundingClientRect()
return { column, width: Math.round(box.width), height: Math.round(box.height) }
})
check(
'and the paper prints it at that size',
Math.abs(shrunk.width - shrunk.column * 0.3) <= 2,
`${shrunk.width} vs ${shrunk.column * 0.3}`,
)
// Taking the size off again: 原尺寸, which is what the placeholder promises.
await page.locator('.paragraph-actions button:has-text("编辑")').first().click()
await page.waitForSelector('.width-select', { timeout: 15000 })
await page.waitForFunction(
() => document.querySelector('.size-hint')?.textContent?.includes('原图'),
{ timeout: 15000 },
)
await page.locator('.width-select').first().hover()
await page.locator('.width-select .el-select__clear').first().click({ force: true })
await page.waitForTimeout(300)
check('clearing it goes back to the natural size', /显示 480×300/.test(await hint()), await hint())
// A size the reader cannot read is refused rather than stored: a figure that
// quietly prints at its natural size is the bug this control exists to fix.
await page.locator('.width-select input').first().fill('宽一点')
await page.keyboard.press('Enter')
await page.waitForTimeout(400)
check(
'a size that is not one is refused',
await page.evaluate(() => Boolean(document.querySelector('.el-message--warning'))),
)
check('and the sentence keeps the size it had', /显示 480×300/.test(await hint()), await hint())
await page.getByRole('button', { name: '取消' }).click()
await page.waitForSelector('.el-dialog', { state: 'detached', timeout: 15000 })
} finally {
await browser.close()
if (paperId) {
@@ -46,7 +46,14 @@ import {
type SentenceInput,
} from '@/api/papers'
import { PARAGRAPH_UNSET_LABEL, foldWhitespace } from '@/utils/format'
import { hasDisplayMath, imagesOf, type ImageSegment } from '@/utils/rich'
import {
figureOf,
hasDisplayMath,
imagesOf,
parseImageWidth,
withImageWidth,
type ImageSegment,
} from '@/utils/rich'
const props = defineProps<{
/** Visibility, used with `v-model`. */
@@ -82,6 +89,15 @@ interface SentenceDraft {
/** How a display formula in this sentence is set. */
align: FormulaAlign
citations: CitationDraft[]
/**
* The natural size of the row's first picture, once it has decoded.
*
* Measured from the loaded thumbnail rather than stored: it is a property of
* the file, and the editor's job here is to tell the writer what 50% of *this*
* picture would come to, which cannot be guessed from the Markdown.
*/
naturalWidth: number | null
naturalHeight: number | null
}
const visible = computed({
@@ -154,6 +170,8 @@ watch(
reference_id: citation.reference_id,
quote: citation.quote,
})),
naturalWidth: null,
naturalHeight: null,
}))
} catch (error) {
ElMessage.error(errorMessage(error))
@@ -177,6 +195,8 @@ function addSentence(): void {
lineBreak: false,
align: 'center',
citations: [],
naturalWidth: null,
naturalHeight: null,
})
}
@@ -189,6 +209,97 @@ function rowImages(row: SentenceDraft): ImageSegment[] {
return imagesOf(row.content)
}
// --- how wide a figure prints ---------------------------------------------
/** The sizes the select offers; anything else is typed into it. */
const WIDTH_PRESETS = ['25%', '50%', '70%', '100%']
/**
* The size a row's figure prints at, as the reader parsed it.
*
* Read from the content, never stored beside it: `{width=70%}` *is* the size,
* and a second copy of it in the draft is a second thing that can be wrong.
* A row that holds no figure, or one whose attribute the reader would not
* accept, answers `null` — which is what "原尺寸" means.
*/
function figureWidth(row: SentenceDraft): string | null {
return figureOf(row.content)?.width ?? null
}
/** Remember a picture's own size, so the hint below can do the arithmetic. */
function rememberNatural(row: SentenceDraft, event: Event): void {
const image = event.target as HTMLImageElement
row.naturalWidth = image.naturalWidth || null
row.naturalHeight = image.naturalHeight || null
}
/**
* The column the paper prints in, measured from the page behind the dialog.
*
* A percentage is a share of *that*, so without it the editor could only say
* "70%" and leave the writer to find out how tall that is. Falls back to
* `null`, and the hint then says nothing rather than something invented.
*/
function paperColumn(): number | null {
const body = document.querySelector('.paragraph-body')
const width = body?.getBoundingClientRect().width ?? 0
return width > 0 ? Math.round(width) : null
}
/**
* What a row's figure will measure on the page — `893×955` — or `null`.
*
* This is the number the writer actually needs. A paper's figures come out of
* the plotting tool at whatever size they were made — a 4169-pixel panel and a
* 1296-pixel one — and both are wider than the column, so without a size they
* all print at the full column and a near-square one fills a whole page.
* Measured on this paper's column: 1276px wide, and 图12 (1857×1986) would come
* out 1365px tall at 原尺寸 against 955px at 70%.
*/
function drawnSize(row: SentenceDraft): string | null {
const { naturalWidth, naturalHeight } = row
if (!naturalWidth || !naturalHeight) return null
const width = figureWidth(row)
let pixels: number | null = null
if (!width) {
// No size: the picture prints at its own unless the column is narrower.
const column = paperColumn()
pixels = column ? Math.min(naturalWidth, column) : naturalWidth
} else if (width.endsWith('%')) {
const column = paperColumn()
pixels = column ? Math.round((column * Number.parseFloat(width)) / 100) : null
} else {
pixels = Number.parseInt(width, 10)
}
if (!pixels) return null
return `${pixels}×${Math.round((pixels * naturalHeight) / naturalWidth)}`
}
/**
* Apply what the writer chose, or said, to the row's figure.
*
* The value goes through the same `parseImageWidth` the reader uses, so what is
* written into the sentence is exactly what will be printed; a value it cannot
* read is refused here with the two forms that work, rather than stored as a
* size that quietly does not apply.
*/
function onWidthChange(row: SentenceDraft, value: string | null | undefined): void {
const text = (value ?? '').trim()
if (!text) {
row.content = withImageWidth(row.content, null)
return
}
const parsed = parseImageWidth(`{width=${text}}`)
if (!parsed) {
ElMessage.warning('宽度填百分比或像素:70%、60 或 400px(百分比 1–100,像素 1–4000)')
return
}
row.content = withImageWidth(row.content, parsed)
}
// --- images ---------------------------------------------------------------
/** The hidden file picker the 「插入图片」 button drives. */
@@ -240,6 +351,8 @@ async function insertImages(files: File[]): Promise<void> {
lineBreak: true,
align: 'center',
citations: [],
naturalWidth: null,
naturalHeight: null,
})
} catch (error) {
ElMessage.error(errorMessage(error))
@@ -500,6 +613,45 @@ async function submit(): Promise<void> {
:label="option.label"
/>
</el-select>
<!-- A figure's size. Only a sentence that is nothing but a picture
prints as a 插图, and only that one has a size worth setting:
an image inside a sentence belongs to the line it sits in.
Typing is allowed as well as the presets, because the size that
suits a panel is whatever it measures, not a round number. -->
<template v-if="figureOf(row.content)">
<el-select
:model-value="figureWidth(row) ?? ''"
size="small"
class="width-select"
placeholder="原尺寸"
clearable
filterable
allow-create
default-first-option
@change="onWidthChange(row, $event)"
>
<el-option
v-for="preset in WIDTH_PRESETS"
:key="preset"
:value="preset"
:label="preset"
/>
</el-select>
<el-tooltip
content="图片在版面上的实际大小(宽×高)。不填就是原尺寸,最多不超过栏宽。"
placement="top"
:show-after="300"
>
<span class="size-hint">
<template v-if="row.naturalWidth">
原图 {{ row.naturalWidth }}×{{ row.naturalHeight }}
</template>
<template v-if="drawnSize(row)">· 显示 {{ drawnSize(row) }}</template>
</span>
</el-tooltip>
</template>
<div class="toolbar-spacer" />
<el-button
link
@@ -530,7 +682,15 @@ async function submit(): Promise<void> {
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" />
<!-- Thumbnails are identification, not a preview of the printed
size — they are a fixed 168px box, and the size control above
says what the figure will actually measure. -->
<img
:src="image.src"
:alt="image.alt"
loading="lazy"
@load="rememberNatural(row, $event)"
/>
<figcaption>{{ image.alt || '方括号里写的就是图注' }}</figcaption>
</figure>
</div>
@@ -699,6 +859,18 @@ async function submit(): Promise<void> {
width: 112px;
}
.width-select {
width: 118px;
}
/* What the figure will measure on the page: a number the writer acts on, so it
sits beside the control rather than in a tooltip nobody opens. */
.size-hint {
font-size: 12px;
color: var(--el-text-color-secondary);
white-space: nowrap;
}
.citations {
display: flex;
flex-direction: column;
+33
View File
@@ -103,6 +103,39 @@ export function parseImageWidth(attributes: string | undefined): string | null {
return value >= 1 && value <= 100 ? `${value}%` : null
}
/**
* The image alternative on its own, with its parts captured separately.
*
* Written out rather than reused from `RICH_PATTERN` because this one *rebuilds*
* the markup: a replace over the combined pattern would have to reconstruct the
* groups of formulas it never touched, and a mis-copied group is a sentence the
* writer did not write. It has to keep matching what that pattern calls an
* image — the alternative is the first one there, for the same reason (`![` is
* not how a formula starts).
*/
const IMAGE_AT = /!\[([^\]]*)\]\(([^()\s]+)(?:\s+"([^"]*)")?\)(?:\{([^}]*)\})?/
/**
* Write a size onto the picture a sentence holds — or take it off again.
*
* Only the first picture is touched. The control that calls this is offered for
* a *figure* (a sentence holding nothing but one image), and a sentence with
* words around its picture is a different thing that this must not silently
* resize.
*
* `width` is what `parseImageWidth` returned — already canonical, e.g. `70%` or
* `400px` — or `null` for "leave it at its natural size".
*/
export function withImageWidth(content: string, width: string | null): string {
let replaced = false
return content.replace(IMAGE_AT, (whole, alt: string, src: string, title?: string) => {
if (replaced) return whole
replaced = true
const name = title === undefined ? '' : ` "${title}"`
return `![${alt}](${src}${name})${width ? `{width=${width}}` : ''}`
})
}
/** Split a sentence into its plain, mathematical and pictorial parts. */
export function splitRich(content: string): RichSegment[] {
const segments: RichSegment[] = []