frontend: let a figure be sized by its height as well as its width

A writer with a tall panel does not want to shrink it from the left edge: what
they know is "this one is too tall". The format had a width and nothing else, so
the only way to make a figure shorter was to guess a percentage and check the
page — and the previous commit's answer, "type 638px", asked them to do the
arithmetic themselves.

So `{height=300px}` joins `{width=…}`, in the same attribute block, and the
editor grows a second box beside the first. Both are typeable as well as
pre-set, both write through the reader's own parse function, and the hint beside
them says what the picture will measure on the page.

Three rules, and the point of all three is that a figure cannot be stretched:

* **a width is exact, a height is a cap.** A width has a reference — the column,
  or a length the writer chose — while nothing measures a height against
  anything, and enlarging a picture past its own pixels only makes it soft. In
  the flow of a sentence a height is always a downscale, which comes to the same
  thing as exact.
* **given one, the other follows from the picture's own shape** — `max-height`
  for a height, `width` for a width — so the height is never written by hand.
* **given both, they are a box to fit inside**, not a box to fill. Two numbers
  that need not have the picture's proportions can only mean "no bigger than",
  and the check asserts the drawn rectangle still matches the file's ratio.

Whichever box is left empty keeps the other's setting, so a size can be set in
two steps, and clearing either goes back to the natural size.

`check-image.mjs`: 26 checks to 36. Two of the new ones found real bugs while
being written. The first: with both a width and a height in one `{…}` block,
neither side parsed — the patterns were anchored to the whole block, so a figure
with two numbers silently printed at its natural size. The attribute block is now
split into declarations first. The second was mine: returning "contain" for a
height-only figure left a 1276×2000 box around a small picture, which the caption
then sat under. A height is a cap, and a cap needs no contain.

The MCP tool takes the same two arguments, so a model can write either number,
and a percentage height is refused with the reason it cannot work: a sentence is
flowed text, so there is nothing for it to be a percentage of and the browser
ignores it. v8 is deployed and DSH has verified both numbers round-tripping.
This commit is contained in:
2026-09-24 13:18:52 +08:00
parent b19f28492e
commit 1531263bd2
10 changed files with 499 additions and 104 deletions
+122 -10
View File
@@ -307,17 +307,36 @@ try {
// 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))
const boxes = await page.evaluate(() => {
const rows = [...document.querySelectorAll('.row')]
const withSize = rows.filter((row) => row.querySelector('.width-select'))
return {
rows: rows.length,
withSize: withSize.length,
// Two boxes per figure — a width and a height, in that order.
values: withSize.map((row) =>
[...row.querySelectorAll('.width-select')].map(
(node) =>
(node.querySelector('.el-select__selected-item')?.textContent ?? '').trim() ||
(node.querySelector('.el-select__placeholder')?.textContent ?? '').trim(),
),
),
}
})
check(
'and each one shows the size it is set to',
controls[0] === '50%' && controls[1] !== '50%',
JSON.stringify(controls),
'a size is offered on the figure rows and nowhere else',
boxes.withSize === 2 && boxes.rows === 3,
JSON.stringify(boxes),
)
check(
'each figure row has a width box and a height box',
boxes.values.every((pair) => pair.length === 2),
JSON.stringify(boxes.values),
)
check(
'and the width box shows the size that row is set to',
boxes.values[0][0] === '50%' && boxes.values[1][0] !== '50%',
JSON.stringify(boxes.values),
)
const hint = async () =>
@@ -384,6 +403,99 @@ try {
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 })
// --- a height, which is what a writer asks for when the width is fine -----
//
// Not every figure needs resizing from the left edge: a tall panel is made
// short by its *height*, and its width has to follow or the picture deforms.
// Written through the API so what is checked is the reader's rule, not the
// editor's; the 480×300 fixture makes the arithmetic checkable by hand.
const shapeOf = async (attributes) => {
await api('PUT', `/papers/${paperId}/paragraphs/${sort}`, {
sentences: [{ content: `![尺寸试验](${image.url})${attributes}`, line_break_before: true }],
})
await page.reload({ waitUntil: 'networkidle' })
await page.waitForSelector('.sentence--figure img')
await page.waitForFunction(
() => document.querySelector('.sentence--figure img')?.complete,
{ timeout: 15000 },
)
return page.evaluate(() => {
const body = document.querySelector('.paragraph-body')
const img = document.querySelector('.sentence--figure img')
const box = img.getBoundingClientRect()
return {
column: Math.round(body.getBoundingClientRect().width),
width: Math.round(box.width),
height: Math.round(box.height),
ratio: box.width / box.height,
natural: img.naturalWidth / img.naturalHeight,
style: img.getAttribute('style') ?? '',
}
})
}
const onlyHeight = await shapeOf('{height=200px}')
check(
'只填高度时,高度就是填的那个数',
Math.abs(onlyHeight.height - 200) <= 1,
JSON.stringify(onlyHeight),
)
check(
'只填高度时,宽度按原比例跟着算(480×300 → 320×200)',
Math.abs(onlyHeight.width - 320) <= 2,
JSON.stringify(onlyHeight),
)
check(
'只填高度时,图还是原来的形状',
Math.abs(onlyHeight.ratio / onlyHeight.natural - 1) < 0.01,
JSON.stringify(onlyHeight),
)
const both = await shapeOf('{width=400px height=100px}')
check(
'宽高都填时,图放进这个框里(400×100 的框 → 160×100)',
Math.abs(both.width - 160) <= 2 && Math.abs(both.height - 100) <= 1,
JSON.stringify(both),
)
check(
'宽高都填时也没有被拉变形',
Math.abs(both.ratio / both.natural - 1) < 0.01,
JSON.stringify(both),
)
const huge = await shapeOf('{height=2000px}')
check(
'高度是个上限:不会把图放大,也不会把它推出栏外',
huge.width === 480 && huge.height === 300,
JSON.stringify(huge),
)
// …and the same thing typed into the editor's 高 box.
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 },
)
check(
'编辑器里宽、高各有一个框',
(await page.locator('.width-select').count()) === 2,
`${await page.locator('.width-select').count()} boxes`,
)
await page.locator('.width-select').nth(1).locator('input').fill('250')
await page.keyboard.press('Enter')
await page.waitForTimeout(400)
check('填高度后立刻换算(250 → 400×250)', /显示 400×250/.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 savedHeight = await api('GET', `/papers/${paperId}/paragraphs/${sort}`)
check(
'存下来的也是高度',
savedHeight.paragraph.sentences[0].content.endsWith('{height=250px}'),
savedHeight.paragraph.sentences[0].content,
)
} finally {
await browser.close()
if (paperId) {
@@ -40,6 +40,34 @@ import {
type ImageSegment,
} from '@/utils/rich'
/**
* The CSS a figure's size becomes.
*
* The writer may give a width, a height, or both, and the picture is never
* stretched in any of the three cases:
*
* * **a width** — that width, exactly, and the height follows from the picture's
* own shape (which is what `height: auto` means);
* * **a height** — a *cap* on it, with the width following. A cap rather than an
* exact number because nothing enlarges a picture usefully: a height is the
* one dimension with no reference to measure against — the column gives a
* percentage its meaning, and a height has nothing — so asking for one only
* ever means "no taller than this". In the flow of a sentence it always is a
* downscale, which is the same thing as exact;
* * **both** — a box to fit *inside*, which is the only honest reading of two
* numbers that need not have the picture's proportions.
*
* In all three the height is left to the browser, so the picture keeps its own
* shape. Nothing here can stretch one.
*/
function sizeStyle(figure: ImageSegment): Record<string, string> | undefined {
const { width, height } = figure
if (width && height) return { maxWidth: width, maxHeight: height }
if (width) return { width }
if (height) return { maxHeight: height }
return undefined
}
const props = defineProps<{
paragraph: PaperParagraph
/** Citation id -> the number shown in the text, assigned by reading order. */
@@ -219,7 +247,7 @@ const anchor = computed(() => `paragraph-${props.paragraph.paper_template_filed_
class="figure-image"
:src="item.figure.src"
:alt="item.figure.alt"
:style="item.figure.width ? { width: item.figure.width } : undefined"
:style="sizeStyle(item.figure)"
loading="lazy"
decoding="async"
/>
@@ -50,8 +50,9 @@ import {
figureOf,
hasDisplayMath,
imagesOf,
parseImageHeight,
parseImageWidth,
withImageWidth,
withImageSize,
type ImageSegment,
} from '@/utils/rich'
@@ -211,8 +212,9 @@ function rowImages(row: SentenceDraft): ImageSegment[] {
// --- how wide a figure prints ---------------------------------------------
/** The sizes the select offers; anything else is typed into it. */
/** The sizes the selects offer; anything else is typed into them. */
const WIDTH_PRESETS = ['25%', '50%', '70%', '100%']
const HEIGHT_PRESETS = ['120px', '200px', '300px', '400px']
/**
* The size a row's figure prints at, as the reader parsed it.
@@ -226,6 +228,11 @@ function figureWidth(row: SentenceDraft): string | null {
return figureOf(row.content)?.width ?? null
}
/** The height a row's figure prints at, as the reader parsed it — pixels only. */
function figureHeight(row: SentenceDraft): string | null {
return figureOf(row.content)?.height ?? 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
@@ -260,21 +267,40 @@ function drawnSize(row: SentenceDraft): string | null {
const { naturalWidth, naturalHeight } = row
if (!naturalWidth || !naturalHeight) return null
const column = paperColumn()
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
const height = figureHeight(row)
return `${pixels}×${Math.round((pixels * naturalHeight) / naturalWidth)}`
/** A width in pixels: a percentage is a share of the column. */
const askWidth = (): number | null => {
if (!width) return null
if (width.endsWith('%')) {
return column ? Math.round((column * Number.parseFloat(width)) / 100) : null
}
return Number.parseInt(width, 10)
}
// A width on its own is exact — the page sets `width` — and the height follows
// from the picture's shape.
if (width && !height) {
let pixels = askWidth()
if (!pixels) return null
if (column && pixels > column) pixels = column
return `${pixels}×${Math.round((pixels * naturalHeight) / naturalWidth)}`
}
// Otherwise the numbers are a box to fit inside, which is what the page does
// with `max-width` / `max-height` — and nothing ever enlarges a picture, so
// the scale starts at 1.
let scale = 1
if (column) scale = Math.min(scale, column / naturalWidth)
const asked = askWidth()
if (asked) scale = Math.min(scale, asked / naturalWidth)
if (height) scale = Math.min(scale, Number.parseInt(height, 10) / naturalHeight)
const drawnWidth = Math.max(1, Math.round(naturalWidth * scale))
const drawnHeight = Math.max(1, Math.round(naturalHeight * scale))
return `${drawnWidth}×${drawnHeight}`
}
/**
@@ -287,17 +313,39 @@ function drawnSize(row: SentenceDraft): string | null {
*/
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) {
const parsed = text ? parseImageWidth(`{width=${text}}`) : null
if (text && !parsed) {
ElMessage.warning('宽度填百分比或像素:70%、60 或 400px(百分比 1–100,像素 1–4000)')
return
}
row.content = withImageWidth(row.content, parsed)
// The height is passed through untouched: typing in one box must not clear
// the other, or setting a size in two steps would be impossible.
row.content = withImageSize(row.content, {
width: parsed,
height: figureHeight(row),
})
}
/**
* Apply a height, in pixels.
*
* Pixels only, and that is not a limitation to work around: a sentence is flowed
* text, so there is no container height for a `%` to mean anything against, and
* the browser's answer to one is to ignore it — a size that silently does not
* apply. `parseImageHeight` is the reader's own rule, so what is stored is what
* will be printed.
*/
function onHeightChange(row: SentenceDraft, value: string | null | undefined): void {
const text = (value ?? '').trim()
const parsed = text ? parseImageHeight(`{height=${text}}`) : null
if (text && !parsed) {
ElMessage.warning('高度填像素:300、300px 都行,范围 1–4000(高度不能用百分比)')
return
}
row.content = withImageSize(row.content, {
width: figureWidth(row),
height: parsed,
})
}
// --- images ---------------------------------------------------------------
@@ -620,26 +668,48 @@ async function submit(): Promise<void> {
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="宽:70% 表示占栏宽的 70%,也可以填 400px" placement="top" :show-after="300">
<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>
<el-tooltip content="高:像素(340px 或 340),填了就让高度是这个值" placement="top" :show-after="300">
<el-select
:model-value="figureHeight(row) ?? ''"
size="small"
class="width-select"
placeholder="高 原尺寸"
clearable
filterable
allow-create
default-first-option
@change="onHeightChange(row, $event)"
>
<el-option
v-for="preset in HEIGHT_PRESETS"
:key="preset"
:value="preset"
:label="preset"
/>
</el-select>
</el-tooltip>
<el-tooltip
content="图片在版面上的实际大小(宽×高)。不填就是原尺寸,最多不超过栏宽。"
content="图片在版面上一共占多大(宽×高)。两个都填就是「放进这个框里」,图不会被拉变形。"
placement="top"
:show-after="300"
>
@@ -843,6 +913,7 @@ async function submit(): Promise<void> {
.row-head {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 8px;
}
+81 -9
View File
@@ -41,7 +41,15 @@ import katex from 'katex'
export type RichSegment =
| { kind: 'text'; value: string }
| { kind: 'math'; value: string; display: boolean }
| { kind: 'image'; src: string; alt: string; width: string | null }
| {
kind: 'image'
src: string
alt: string
/** `70%`, `400px`, or `null` for the picture's own width. */
width: string | null
/** `300px`, or `null` — never a percentage, which has nothing to be one of. */
height: string | null
}
/** An image segment, which is what a figure is made of. */
export type ImageSegment = Extract<RichSegment, { kind: 'image' }>
@@ -70,8 +78,14 @@ const RICH_PATTERN = new RegExp(
* 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.
*
* The height is read the same way, but **pixels only**. A percentage height has
* nothing to be a percentage *of* — a sentence is flowed text, so there is no
* container height to measure against — and the browser's answer to one is to
* ignore it, which is a size that silently does not apply.
*/
const WIDTH_PATTERN = /^\s*(?:w|width)\s*=\s*(\d{1,4})\s*(%|px)?\s*$/i
const HEIGHT_PATTERN = /^\s*(?:h|height)\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
@@ -89,11 +103,34 @@ export function escapeHtml(value: string): string {
return value.replace(/[&<>"']/g, (character) => HTML_ESCAPES[character] ?? character)
}
/**
* The declarations inside an attribute block: `{width=400 height=200}` is two.
*
* Splitting first is what lets the two patterns below stay anchored to a whole
* declaration. Matching them against the raw block instead looks equivalent and
* is not: with both a width and a height written, neither pattern matches
* anything, and the size silently falls back to the picture's own — which is
* exactly the bug the browser check found here.
*/
function declarations(attributes: string | undefined): string[] {
if (!attributes) return []
return attributes
.replace(/^\{|\}$/g, '')
.trim()
.split(/\s+/)
.filter(Boolean)
}
function declared(attributes: string | undefined, key: RegExp): string | undefined {
return declarations(attributes).find((part) => key.test(part))
}
/** 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 part = declared(attributes, /^(?:w|width)\s*=/i)
if (!part) return null
const match = WIDTH_PATTERN.exec(attributes.replace(/^\{|\}$/g, ''))
const match = WIDTH_PATTERN.exec(part)
if (!match) return null
const value = Number(match[1])
@@ -103,6 +140,32 @@ export function parseImageWidth(attributes: string | undefined): string | null {
return value >= 1 && value <= 100 ? `${value}%` : null
}
/** Read a height, in pixels, or `null` for "whatever the shape works out to". */
export function parseImageHeight(attributes: string | undefined): string | null {
const part = declared(attributes, /^(?:h|height)\s*=/i)
if (!part) return null
const match = HEIGHT_PATTERN.exec(part)
if (!match) return null
const value = Number(match[1])
return value >= 1 && value <= MAX_PIXELS ? `${value}px` : null
}
/** The size a picture is asked for: either half may be missing. */
export interface ImageSize {
width: string | null
height: string | null
}
/** Both halves of an image's size, read from its attribute block. */
export function parseImageSize(attributes: string | undefined): ImageSize {
return {
width: parseImageWidth(attributes),
height: parseImageHeight(attributes),
}
}
/**
* The image alternative on its own, with its parts captured separately.
*
@@ -118,21 +181,28 @@ 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
* Only the first picture is touched. The controls that call this are 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".
* Both halves are written together, so a call that sets only a height keeps the
* width it did not mention — which is what the editor expects when the writer
* types into one of the two boxes. `null` on both leaves the picture at its
* natural size.
*/
export function withImageWidth(content: string, width: string | null): string {
export function withImageSize(content: string, size: ImageSize): string {
const parts: string[] = []
if (size.width) parts.push(`width=${size.width}`)
if (size.height) parts.push(`height=${size.height}`)
const attribute = parts.length ? `{${parts.join(' ')}}` : ''
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}}` : ''}`
return `![${alt}](${src}${name})${attribute}`
})
}
@@ -149,11 +219,13 @@ export function splitRich(content: string): RichSegment[] {
const groups = match.groups ?? {}
if (groups.src !== undefined) {
const size = parseImageSize(groups.attrs)
segments.push({
kind: 'image',
src: groups.src,
alt: groups.alt ?? '',
width: parseImageWidth(groups.attrs),
width: size.width,
height: size.height,
})
} else {
segments.push({