refactor: improve relative image path normalization (#5314)

pull/4517/merge
Bjorn Lu 12 hours ago committed by GitHub
parent 9ee401d7ad
commit 262b78f1ca
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -0,0 +1,33 @@
import { MarkdownItAsync } from 'markdown-it-async'
import { imagePlugin } from 'node/markdown/plugins/image'
describe('node/markdown/plugins/image', () => {
const md = new MarkdownItAsync()
imagePlugin(md as any)
test('default image output', async () => {
const html = await md.renderAsync('![logo](foo.png)')
expect(html.trim()).toMatchInlineSnapshot(
`"<p><img src="./foo.png" alt="logo"></p>"`
)
})
test.for([
['foo.png', './foo.png'],
['./foo.png', './foo.png'],
['../foo.png', '../foo.png'],
['../../foo.png', '../../foo.png'],
['/foo.png', '/foo.png'],
['https://example.com/foo.png', 'https://example.com/foo.png']
])('normalizes image src: %s → %s', async ([src, expected]) => {
const html = await md.renderAsync(`![logo](${src})`)
expect(html).toContain(`src="${expected}"`)
})
test('adds loading="lazy" attribute when lazyLoading is enabled', async () => {
const mdLazy = new MarkdownItAsync()
imagePlugin(mdLazy as any, { lazyLoading: true })
const html = await mdLazy.renderAsync('![logo](foo.png)')
expect(html).toContain('loading="lazy"')
})
})

@ -20,7 +20,8 @@ export const imagePlugin = (
const token = tokens[idx]
let url = token.attrGet('src')
if (url && !EXTERNAL_URL_RE.test(url)) {
if (!/^\.?\//.test(url)) url = './' + url
// Normalize relative "foo.png" to "./foo.png" and decode for processing by bundlers
if (!/^\.*?\//.test(url)) url = './' + url
token.attrSet('src', decodeURIComponent(url))
}
if (lazyLoading) {

Loading…
Cancel
Save