fix(web): space consecutive Markdown images like paragraphs

Co-authored-by: Yifffan <133629972+Yifffan@users.noreply.github.com>
This commit is contained in:
TurtleandYifffan committed 2026-11-25 00:16:38 +08:00
1 parent 56acc26908
commit cd1cc61042
5 files changed
+86 -1

No files matched your search

@@ -38,6 +38,11 @@
- img "Outside workspace image"
- paragraph: Image preview unavailable · Missing image
- paragraph: Image preview unavailable · {{cwd}}/corrupt.png
- paragraph:
- 'button "View full image: Stacked page 1"':
- img "Stacked page 1"
- 'button "View full image: Stacked page 2"':
- img "Stacked page 2"
- paragraph: REMOTE_IMAGE_DONE
- button "Copy"
- button "Good response"
+38
View File
@@ -3,6 +3,7 @@ import { mkdir, open, writeFile } from 'node:fs/promises'
import { createServer, type Server } from 'node:http'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { crc32, deflateSync } from 'node:zlib'
import type { Browser, Page } from 'playwright'
import { chromium } from 'playwright'
import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
@@ -37,6 +38,31 @@ const PNG = Buffer.from(
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=',
'base64',
)
const STACKED_ALTS = ['Stacked page 1', 'Stacked page 2']
/** Encode one opaque gray RGB PNG wide enough that consecutive images stack. */
function grayPng(width: number, height: number): Buffer {
const chunk = (type: string, data: Buffer) => {
const body = Buffer.concat([Buffer.from(type, 'ascii'), data])
const frame = Buffer.alloc(body.length + 8)
frame.writeUInt32BE(data.length, 0)
body.copy(frame, 4)
frame.writeUInt32BE(crc32(body), body.length + 4)
return frame
}
const header = Buffer.alloc(13)
header.writeUInt32BE(width, 0)
header.writeUInt32BE(height, 4)
header.set([8, 2, 0, 0, 0], 8)
const row = Buffer.alloc(1 + width * 3, 0xb0)
row[0] = 0
return Buffer.concat([
Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
chunk('IHDR', header),
chunk('IDAT', deflateSync(Buffer.concat(Array.from({ length: height }, () => row)))),
chunk('IEND', Buffer.alloc(0)),
])
}
interface ImageOrigin {
server: Server
@@ -129,6 +155,8 @@ function markdownImageFixture(remoteUrl: string, outsidePath: string): string {
'',
'![]({{cwd}}/corrupt.png)',
'',
...STACKED_ALTS.map(alt => `![${alt}]({{cwd}}/page.png)`),
'',
'REMOTE_IMAGE_DONE',
].join('\n'),
}],
@@ -178,6 +206,7 @@ describe('web e2e: Markdown image rendering', () => {
await writeFile(join(scaffold.workspaceCwd, 'test workspace/测试图.png'), PNG)
await writeFile(join(scaffold.workspaceCwd, 'test workspace/测试#100%.png'), PNG)
await writeFile(join(scaffold.workspaceCwd, 'corrupt.png'), 'invalid image')
await writeFile(join(scaffold.workspaceCwd, 'page.png'), grayPng(640, 120))
const oversized = await open(join(scaffold.workspaceCwd, 'oversized.png'), 'w')
try {
// One byte over attachment-local's default maxImageBytes (50 MiB), which also bounds /api/file.
@@ -284,7 +313,16 @@ describe('web e2e: Markdown image rendering', () => {
[join(scaffold.persistenceRoot, 'outside.png'), 200],
[join(scaffold.workspaceCwd, 'missing.png'), 404],
[join(scaffold.workspaceCwd, 'corrupt.png'), 200],
[join(scaffold.workspaceCwd, 'page.png'), 200],
]))
// Images on consecutive source lines share one paragraph; their rows keep the paragraph gap.
const stacked = STACKED_ALTS.map(name => page.getByRole('img', { name, exact: true }))
for (const image of stacked) {
await image.scrollIntoViewIfNeeded()
await expect.poll(() => image.evaluate(element => (element as HTMLImageElement).naturalWidth)).toBe(640)
}
const [first, second] = await Promise.all(stacked.map(image => image.boundingBox()))
expect(second!.y - (first!.y + first!.height)).toBeCloseTo(16, 0)
await page.getByRole('button', { name: `View full image: ${WORKSPACE_ALT}`, exact: true }).click()
const lightbox = page.getByRole('dialog', { name: 'Image preview', exact: true })
@@ -491,6 +491,12 @@
}
.imageButton .image { max-width: min(100%, 640px); max-height: 360px; }
.imageButton:focus-visible { outline: var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary)); outline-offset: 3px; }
/* A paragraph of several images wraps them into rows separated by the paragraph gap. */
.imageRow { display: flex; flex-wrap: wrap; align-items: center; gap: 16px 4px; }
.compact .imageRow { row-gap: 4px; }
/* Flex items keep their borders, so the anchors' transparent hit-area borders would widen the row gap. */
.imageRow > a { border-block-width: 0; }
.imageRow > br { display: none; }
.previewName {
display: block;
margin-top: 8px;
@@ -317,7 +317,9 @@ function renderNode(node: Md.RootContent, key: Key, context: MarkdownRenderConte
case 'text':
return node.value
case 'paragraph':
return <p key={key}>{renderChildren(node.children, context)}</p>
return <p key={key} className={isImageRow(node.children) ? css.imageRow : undefined}>
{renderChildren(node.children, context)}
</p>
case 'heading':
return createElement(`h${node.depth}`, { key }, ...renderChildren(node.children, context))
case 'blockquote':
@@ -592,6 +594,19 @@ function anchorWrapsOnlyImages(children: Md.PhrasingContent[]): boolean {
return children.length > 0 && children.every(child => child.type === 'image' || child.type === 'imageReference')
}
/** True when a paragraph holds several images, optionally linked, and only whitespace or line breaks between them. */
function isImageRow(children: Md.PhrasingContent[]): boolean {
let images = 0
for (const child of children) {
if (child.type === 'break' || (child.type === 'text' && child.value.trim() === '')) continue
const image = child.type === 'image' || child.type === 'imageReference'
|| ((child.type === 'link' || child.type === 'linkReference') && anchorWrapsOnlyImages(child.children))
if (!image) return false
images += 1
}
return images > 1
}
/** Anchor over a safe absolute href, with optional owner navigation for HTTP(S). */
function renderSafeLink(href: string, children: ReactNode[], key: Key, glyph = true): ReactNode {
const safeHref = sanitizeUrl(href)
@@ -141,3 +141,24 @@ describe('MarkdownText local-path images', () => {
.toBe('https://cdn.example.com/graph.png')
})
})
describe('MarkdownText image rows', () => {
const pathImages: MarkdownPathImages = { resolve: value => `https://example.com${value}` }
const rowCount = (text: string) => render(<MarkdownText text={text} pathImages={pathImages} />)
.container.querySelectorAll('p[class*="imageRow"]').length
it.each([
['consecutive images', '![a](/a.png)\n![b](/b.png)'],
['images split by a hard break', '![a](/a.png)\\\n![b](/b.png)'],
['linked and referenced images', '[![a](/a.png)](https://example.com) ![b][b]\n[![c](/c.png)][l]\n\n[b]: /b.png\n[l]: https://example.com'],
])('lays out %s as one wrapping row', (_name, text) => {
expect(rowCount(text)).toBe(1)
})
it.each([
['a single image', '![a](/a.png)'],
['images mixed with text', '![a](/a.png) caption ![b](/b.png)'],
])('keeps %s inline', (_name, text) => {
expect(rowCount(text)).toBe(0)
})
})