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:
@@ -68,6 +68,15 @@ def register(server: MCPServer) -> None:
|
||||
)
|
||||
),
|
||||
] = None,
|
||||
height: Annotated[
|
||||
str | None,
|
||||
Field(
|
||||
description=(
|
||||
"可选高度,只能填像素(300 或 300px,1–4000):图片不会超过这个高度,"
|
||||
"宽度按原比例跟着变。高度不能用百分比(句子里没有可参照的高度)"
|
||||
)
|
||||
),
|
||||
] = None,
|
||||
) -> str:
|
||||
"""上传一张图片,返回可直接写进句子的 Markdown 与那个句子对象。"""
|
||||
data = _decode(data_base64)
|
||||
@@ -83,7 +92,9 @@ def register(server: MCPServer) -> None:
|
||||
# origin, and the caller's content type or filename is only a claim.
|
||||
key, content_type, digest = get_store().save(data)
|
||||
|
||||
markdown = _embed(key, caption=caption or _stem(filename), width=width)
|
||||
markdown = _embed(
|
||||
key, caption=caption or _stem(filename), width=width, height=height
|
||||
)
|
||||
return s.dumps(
|
||||
{
|
||||
"key": key,
|
||||
@@ -119,6 +130,10 @@ def register(server: MCPServer) -> None:
|
||||
#: silently does not apply is worse than a refusal that says so.
|
||||
_WIDTH_ATTRIBUTE = re.compile(r"^\s*(?:w|width)\s*=\s*(\d{1,4})\s*(%|px)?\s*$", re.IGNORECASE)
|
||||
_WIDTH_BARE = re.compile(r"^\s*(\d{1,4})\s*(%|px)?\s*$")
|
||||
#: A height is pixels and nothing else; see :func:`_height_declaration`. A bare
|
||||
#: number is pixels because there is nothing else it could be.
|
||||
_HEIGHT_ATTRIBUTE = re.compile(r"^\s*(?:h|height)\s*=\s*(\d{1,4})\s*(?:px)?\s*$", re.IGNORECASE)
|
||||
_HEIGHT_BARE = re.compile(r"^\s*(\d{1,4})\s*(?:px)?\s*$", re.IGNORECASE)
|
||||
_MAX_PIXELS = 4000
|
||||
_MAX_PERCENT = 100
|
||||
|
||||
@@ -152,19 +167,55 @@ def _stem(filename: str | None) -> str:
|
||||
return name.rsplit(".", 1)[0] if "." in name else name
|
||||
|
||||
|
||||
def _embed(key: str, *, caption: str, width: str | None) -> str:
|
||||
"""The Markdown a sentence carries: the address, plus an optional width.
|
||||
def _embed(
|
||||
key: str, *, caption: str, width: str | None, height: str | None = None
|
||||
) -> str:
|
||||
"""The Markdown a sentence carries: the address, plus an optional size.
|
||||
|
||||
``markdown_for`` writes the ```` half — the same function the
|
||||
upload endpoint answers with — and this adds the size, which the endpoint
|
||||
does not take because a browser appends it in the editor.
|
||||
"""
|
||||
parts = [
|
||||
part
|
||||
for part in (_width_declaration(width), _height_declaration(height))
|
||||
if part
|
||||
]
|
||||
markdown = markdown_for(key, caption)
|
||||
attribute = _width_attribute(width)
|
||||
return f"{markdown}{attribute}" if attribute else markdown
|
||||
return f"{markdown}{{{' '.join(parts)}}}" if parts else markdown
|
||||
|
||||
|
||||
def _width_attribute(width: str | None) -> str:
|
||||
def _height_declaration(height: str | None) -> str:
|
||||
"""``height=300px`` from what the caller wrote, or a refusal saying why not.
|
||||
|
||||
**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 reader's answer to one is to ignore it, which is a size that silently
|
||||
does not apply. ``1–4000`` for the same reason as a width: a typo should be
|
||||
refused, not laid out.
|
||||
"""
|
||||
if height is None or not str(height).strip():
|
||||
return ""
|
||||
|
||||
written = str(height).strip().strip("{}").strip()
|
||||
match = _HEIGHT_ATTRIBUTE.match(written) or _HEIGHT_BARE.match(written)
|
||||
if match is None:
|
||||
# A percentage gets the reason it cannot work; anything else just gets
|
||||
# told what a height looks like.
|
||||
why = (
|
||||
"百分比高度在句子里没有参照物,读的时候会被忽略"
|
||||
if "%" in written
|
||||
else "填像素数字,例如 300"
|
||||
)
|
||||
s.fail(f"height 只能填像素,例如 300 或 300px,收到的是“{height}”。{why}")
|
||||
|
||||
digits = int(match.group(1))
|
||||
if not 1 <= digits <= _MAX_PIXELS:
|
||||
s.fail(f"height 要在 1 到 {_MAX_PIXELS} 之间,收到的是“{height}”")
|
||||
return f"height={digits}px"
|
||||
|
||||
|
||||
def _width_declaration(width: str | None) -> str:
|
||||
"""``{width=70%}`` from what the caller wrote, or a refusal saying why not.
|
||||
|
||||
Tolerant about how it is written — ``70%``, ``70 %``, ``{width=70%}`` and
|
||||
@@ -198,7 +249,7 @@ def _width_attribute(width: str | None) -> str:
|
||||
s.fail(
|
||||
f"width 的 {unit} 值要在 1 到 {limit} 之间,收到的是“{width}”。{hint}"
|
||||
)
|
||||
return f"{{width={digits}{unit}}}"
|
||||
return f"width={digits}{unit}"
|
||||
|
||||
|
||||
__all__ = ["register"]
|
||||
|
||||
@@ -1045,6 +1045,39 @@ async def _run(url: str | None = None, token: str | None = None) -> int:
|
||||
bare["markdown"] == f"{{width=60%}}",
|
||||
bare["markdown"],
|
||||
)
|
||||
|
||||
# A height, which is how a tall panel is made short: the width follows
|
||||
# the picture's own shape rather than being stretched to fit.
|
||||
sized = await call(
|
||||
session,
|
||||
"image_upload",
|
||||
data_base64=GIF_1PX_BASE64,
|
||||
caption="宽高都写",
|
||||
width="70%",
|
||||
height="300",
|
||||
)
|
||||
check(
|
||||
"a height is written beside the width, in pixels",
|
||||
sized["markdown"]
|
||||
== f"{{width=70% height=300px}}",
|
||||
sized["markdown"],
|
||||
)
|
||||
tall = await call(
|
||||
session, "image_upload", data_base64=GIF_1PX_BASE64, caption="只限高", height="240px"
|
||||
)
|
||||
check(
|
||||
"a height on its own is enough",
|
||||
tall["markdown"] == f"{{height=240px}}",
|
||||
tall["markdown"],
|
||||
)
|
||||
message = await expect_error(
|
||||
session, "image_upload", data_base64=GIF_1PX_BASE64, height="50%"
|
||||
)
|
||||
check(
|
||||
"a percentage height is refused, with the reason it cannot work",
|
||||
"没有参照物" in message,
|
||||
message,
|
||||
)
|
||||
message = await expect_error(
|
||||
session, "image_upload", data_base64=GIF_1PX_BASE64, width="70em"
|
||||
)
|
||||
|
||||
+3
-3
@@ -18,11 +18,11 @@ paper-doc 的 MCP 服务跑在 k3s 里,命名空间 **`paper-doc`**,客户
|
||||
| Secret | `paper-doc-secrets` | `DB_USER` / `DB_PASSWORD` / `MCP_HTTP_TOKEN` / `MINIO_ACCESS_KEY` / `MINIO_SECRET_KEY` |
|
||||
| Secret | `aliyun-acr` | 镜像仓库拉取凭证(从 `default` 复制) |
|
||||
|
||||
镜像:`registry.cn-hangzhou.aliyuncs.com/mcp_skill/paper-doc-mcp:v7`
|
||||
(`sha256:f55a0d4e5ac790b78aaeb95a58034a28266e33282a379a2e1e8ffa10c191f611`;
|
||||
镜像:`registry.cn-hangzhou.aliyuncs.com/mcp_skill/paper-doc-mcp:v8`
|
||||
(`sha256:fbbc4b1ab91ce80a3045f2990d85357f1cc267a2644639efe522a25cf42c4bc0`;
|
||||
`kubectl -n paper-doc get pods -o jsonpath='{.items[0].status.containerStatuses[0].imageID}'`
|
||||
对得上,才说明跑的就是 ACR 上那一版。历史:v1 首发布 → v2 重命名表 → v3 参考文献库 →
|
||||
v4 补参考文献 MCP 工具 → v5 换行与参考文献表 → v6 插图与公式对齐 → **v7 插图的宽度写法与页面一致**。)
|
||||
v4 补参考文献 MCP 工具 → v5 换行与参考文献表 → v6 插图与公式对齐 → v7 插图的宽度写法与页面一致 → **v8 插图可分别填宽与高**。)
|
||||
|
||||
**数据库**:TiDB 已经在这个集群里,Deployment 用集群内的 Service
|
||||
`tidb-tidb.tidb:4000`,而不是宿主机用的 NodePort `192.168.1.88:32738`。
|
||||
|
||||
@@ -75,7 +75,7 @@ spec:
|
||||
type: RuntimeDefault
|
||||
containers:
|
||||
- name: mcp
|
||||
image: registry.cn-hangzhou.aliyuncs.com/mcp_skill/paper-doc-mcp:v7
|
||||
image: registry.cn-hangzhou.aliyuncs.com/mcp_skill/paper-doc-mcp:v8
|
||||
imagePullPolicy: IfNotPresent
|
||||
ports:
|
||||
- name: http
|
||||
@@ -199,14 +199,14 @@ spec:
|
||||
# imagePullSecrets: [{name: aliyun-acr}]
|
||||
# initContainers:
|
||||
# - name: migrate
|
||||
# image: registry.cn-hangzhou.aliyuncs.com/mcp_skill/paper-doc-mcp:v7
|
||||
# image: registry.cn-hangzhou.aliyuncs.com/mcp_skill/paper-doc-mcp:v8
|
||||
# command: ["alembic", "upgrade", "head"]
|
||||
# envFrom: [{configMapRef: {name: paper-doc-config}}]
|
||||
# env: [...] # the same secret keys as above; the MinIO
|
||||
# # pair is what lets the API serve the figures
|
||||
# containers:
|
||||
# - name: api
|
||||
# image: registry.cn-hangzhou.aliyuncs.com/mcp_skill/paper-doc-mcp:v7
|
||||
# image: registry.cn-hangzhou.aliyuncs.com/mcp_skill/paper-doc-mcp:v8
|
||||
# command: ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
|
||||
# ports: [{name: http, containerPort: 8000}]
|
||||
# envFrom: [{configMapRef: {name: paper-doc-config}}]
|
||||
|
||||
+28
-6
@@ -442,13 +442,14 @@ Header: Authorization: Bearer <MCP_HTTP_TOKEN>
|
||||
|
||||
| 工具 | 作用 | 关键参数 |
|
||||
|---|---|---|
|
||||
| `image_upload` | 传一张图,返回可写进句子的 Markdown 与那个句子对象 | `data_base64`、`caption?` `filename?` `width?` |
|
||||
| `image_upload` | 传一张图,返回可写进句子的 Markdown 与那个句子对象 | `data_base64`、`caption?` `filename?` `width?` `height?` |
|
||||
|
||||
```jsonc
|
||||
{"name": "image_upload", "arguments": {
|
||||
"data_base64": "iVBORw0KGgo…", // 也可以直接给 data:image/png;base64,…
|
||||
"caption": "图 3 惯性—冲量相空间", // 不给就用 filename 的主干
|
||||
"width": "70%" // 或 400px;不传按原尺寸(不超过栏宽)
|
||||
"width": "70%", // 或 400px;不传按原尺寸(不超过栏宽)
|
||||
"height": "300px" // 可选,只能像素;图不会超过这个高
|
||||
}}
|
||||
// → {"key": "2026/09/9f8c1a4b7e2d0c33.png",
|
||||
// "url": "/api/images/2026/09/9f8c1a4b7e2d0c33.png",
|
||||
@@ -469,10 +470,31 @@ Header: Authorization: Bearer <MCP_HTTP_TOKEN>
|
||||
`paragraph_get` / `paper_document` 的 `text` 按同一条规则断行,图以它存储的 Markdown 原样印在自己的行上——
|
||||
文本画不出图片,而地址是"哪一张图"的唯一答案,读回来还能原样搬走。
|
||||
|
||||
`width` 写法宽容(`70%`、`70 %`、`{width=70%}`、`w=400px` 都收),含义严格:像素 1–4000、百分比 1–100,
|
||||
超出会被拒绝而不是默默忽略——网页端读不懂的尺寸会退回原尺寸,那等于写了个不生效的值。
|
||||
**只写数字按百分比算**(`60` = `60%`),和网页端一致:只有写成 `px` 才算像素,因为这是
|
||||
`frontend/src/utils/rich.ts` 里 `parseImageWidth` 的读法,页面和工具必须读同一种。
|
||||
**宽和高可以分别填**,写法都在句子正文里:
|
||||
|
||||
| 想要的效果 | 句子正文里写 | 结果 |
|
||||
|---|---|---|
|
||||
| 宽正好 500px,高自动 | `{width=500px}` | 500×(按原比例算) |
|
||||
| 占栏宽的 70% | `{width=70%}` | 列宽×0.7,高自动 |
|
||||
| **高不超过 300px**,宽自动 | `{height=300px}` | 宽 = 300×原比例,按比例缩 |
|
||||
| 放进 500×300 的框里 | `{width=500px height=300px}` | 等比缩放塞进框内 |
|
||||
| 原尺寸 | 不写 | 按原图,最多不超过栏宽 |
|
||||
|
||||
三条规则:
|
||||
|
||||
1. **宽是精确值,高是上限。** 宽有参照物(栏宽或你给的像素),所以给多少就是多少;高没有参照物,
|
||||
也没必要把图放大到比它本身还大(只会糊),所以 `height` 是"不超过这个高"。你说的场景(把太高的图压矮)
|
||||
两种情况结果一样。
|
||||
2. **永远只给宽度或只给高度时,另一边由浏览器按原比例算**——所以图不可能被拉变形。两个都给就是
|
||||
"放进这个框里",也是等比缩放,不会拉伸。
|
||||
3. **写法宽容,含义严格。** `70%`、`70 %`、`{width=70%}`、`w=400px` 都收;宽 1–4000px 或 1–100%,
|
||||
高 1–4000px(**高不能用百分比**:句子里没有可参照的高度,浏览器会直接忽略,那等于写了个不生效的值)。
|
||||
`width` 只写数字按**百分比**算(`60` = `60%`);`height` 只写数字按**像素**算。
|
||||
超出范围或读不懂的一律拒绝并说明,而不是默默退回原尺寸。
|
||||
|
||||
这几种写法在网页端可以点着填:段落编辑器里,凡是"整句只有一张图"的行都有「宽」「高」两个框,
|
||||
可以用预设,也可以直接打字(如 `63%`、`380px`、`250`),旁边实时显示这会在版面上占多大
|
||||
(如 `原图 1857×1986 · 显示 893×955`)。
|
||||
|
||||
同一个大小在网页端也能改:段落编辑器里,凡是"整句只有一张图"的行都会出现「宽度」下拉框,
|
||||
可以选 25/50/70/100%,也可以直接填任意值(如 `63%`、`380px`),旁边实时显示这会在版面上
|
||||
|
||||
+29
-23
@@ -412,30 +412,36 @@ line":
|
||||
| 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. It is a
|
||||
**width and only a width**: the height is whatever keeps the picture's own shape,
|
||||
which is why a figure can be resized but not stretched, and why the format has
|
||||
nowhere to put a second number even if a writer wanted one. Measured on the
|
||||
sixteen figures of the paper this was built for, every drawn rectangle matched
|
||||
its picture's aspect ratio to within 0.2% — the rounding of the measurement,
|
||||
not the layout. A bare number
|
||||
is a **share of the column**, because `parseImageWidth` only reads a value as
|
||||
pixels when it says `px`; the MCP tool that writes the same attribute follows
|
||||
that rule rather than inventing its own.
|
||||
`{width=400px}`, `{height=300px}`, or both in one block — and each declaration is
|
||||
validated to digits plus at most one unit before it becomes a CSS length, so no
|
||||
second declaration can be smuggled through it. A **width is exact and 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. A bare number is a share of
|
||||
the column for a width — `parseImageWidth` only reads pixels when the value says
|
||||
`px` — and pixels for a height, because there is nothing else it could be; a
|
||||
percentage *height* is refused rather than stored, since it has nothing to be a
|
||||
percentage of and the browser's answer to one is to ignore it.
|
||||
|
||||
Leaving the size off means the picture prints at its own width, capped to the
|
||||
column — and that turned out to be the wrong default to *live* with. Figures
|
||||
come out of a plotting tool at whatever size they were made: one paper's are
|
||||
1441, 1857, 2409 and 4169 pixels wide, so every one of them is wider than the
|
||||
1276px column and they all printed at the full width, with the near-square ones
|
||||
(1857×1986, 1974×2068) filling a whole page at 1365px tall. A written size is
|
||||
therefore part of the editor: a row that is a figure carries a 宽度 control —
|
||||
presets, or any value typed in — and beside it what the picture will measure on
|
||||
the page (`原图 1857×1986 · 显示 893×955`), measured against the real column
|
||||
behind the dialog. The control writes the attribute through the reader's own
|
||||
`parseImageWidth`, so what it shows is what gets printed, and a value that
|
||||
function cannot read is refused instead of stored as a size that does nothing.
|
||||
Whichever of the two is given alone, the other follows from the picture's own
|
||||
shape, so a figure can be sized but not stretched; when a writer does give both,
|
||||
they are read as a box to fit *inside* rather than a box to fill. Measured across
|
||||
the sixteen figures of the paper this was built for, every drawn rectangle
|
||||
matched its picture's aspect ratio to within 0.2% — the rounding of the
|
||||
measurement, not the layout.
|
||||
|
||||
Leaving the size off was the wrong default to *live* with. Figures come out of a
|
||||
plotting tool at whatever size they were made: that paper's are 1441, 1857, 2409
|
||||
and 4169 pixels wide, so all sixteen were wider than the 1276px column and every
|
||||
one printed at the full width, with the near-square ones (1857×1986, 1974×2068)
|
||||
filling a page at 1365px tall. So the size became part of the editor: a row that
|
||||
is a figure carries a 宽度 and a 高度 box — presets, or any value typed in — with
|
||||
what the picture will measure on the page beside them (`原图 1857×1986 · 显示
|
||||
638×682`), worked out against the column actually rendered behind the dialog.
|
||||
Both boxes write through the reader's own `parseImageWidth` /
|
||||
`parseImageHeight`, so what they show is what gets printed, and a value those
|
||||
functions cannot read is refused instead of stored as a size that does nothing.
|
||||
|
||||
Configuration is three variables (`MINIO_ENDPOINT`, `MINIO_ACCESS_KEY`,
|
||||
`MINIO_SECRET_KEY`, plus `MINIO_BUCKET`). Left empty, the paper still writes and
|
||||
|
||||
@@ -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: `${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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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 `${width ? `{width=${width}}` : ''}`
|
||||
return `${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({
|
||||
|
||||
Reference in New Issue
Block a user