Skip to content

Commit

Permalink
refactor: simplify image+link regexes, allow data image URLs (#472)
Browse files Browse the repository at this point in the history
  • Loading branch information
quantizor committed Feb 2, 2023
1 parent ceebf8e commit adf9eab
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 13 deletions.
14 changes: 14 additions & 0 deletions index.compiler.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -624,6 +624,20 @@ describe('images', () => {
expect(root.innerHTML).toMatchInlineSnapshot(`<img src="/xyz.png">`)
})

it('should handle a base64-encoded image', () => {
render(
compiler(
'![Red Dot](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==)'
)
)

expect(root.innerHTML).toMatchInlineSnapshot(`
<img alt="Red Dot"
src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="
>
`)
})

it('should handle an image with alt text', () => {
render(compiler('![test](/xyz.png)'))

Expand Down
17 changes: 4 additions & 13 deletions index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -343,7 +343,7 @@ const TRIM_STARTING_NEWLINES = /^\n+/

const HTML_LEFT_TRIM_AMOUNT_R = /^([ \t]*)/

const UNESCAPE_URL_R = /\\([^0-9A-Z\s])/gi
const UNESCAPE_URL_R = /\\([^\\])/g

type LIST_TYPE = 1 | 2
const ORDERED: LIST_TYPE = 1
Expand Down Expand Up @@ -553,17 +553,8 @@ function generateListRule(h: any, type: LIST_TYPE) {
}>
}

const LINK_INSIDE = '(?:\\[[^\\]]*\\]|[^\\[\\]]|\\](?=[^\\[]*\\]))*'
const LINK_HREF_AND_TITLE =
'\\s*<?((?:[^\\s\\\\]|\\\\.)*?)>?(?:\\s+[\'"]([\\s\\S]*?)[\'"])?\\s*'

const LINK_R = new RegExp(
'^\\[(' + LINK_INSIDE + ')\\]\\(' + LINK_HREF_AND_TITLE + '\\)'
)

const IMAGE_R = new RegExp(
'^!\\[(' + LINK_INSIDE + ')\\]\\(' + LINK_HREF_AND_TITLE + '\\)'
)
const LINK_R = /^\[([^\]]*)]\( *([^) ]*) *"?([^)"]*)?"?\)/
const IMAGE_R = /^!\[([^\]]*)]\( *([^) ]*) *"?([^)"]*)?"?\)/

const NON_PARAGRAPH_BLOCK_SYNTAXES = [
BLOCKQUOTE_R,
Expand Down Expand Up @@ -987,7 +978,7 @@ function sanitizeUrl(url: string): string | null {
try {
const decoded = decodeURIComponent(url).replace(/[^A-Za-z0-9/:]/g, '')

if (decoded.match(/^\s*(javascript|vbscript|data):/i)) {
if (decoded.match(/^\s*(javascript|vbscript|data(?!:image)):/i)) {
if (process.env.NODE_ENV !== 'production') {
console.warn(
'Anchor URL contains an unsafe JavaScript/VBScript/data expression, it will not be rendered.',
Expand Down

0 comments on commit adf9eab

Please sign in to comment.