From c54d30dfb645b37b349f6bbb7f486311b25b8672 Mon Sep 17 00:00:00 2001 From: Gustav Westling Date: Thu, 21 Mar 2024 02:45:35 +0100 Subject: [PATCH] Brackets in link text (#551) * Add brackets in link text tests * Update LINK_R to handle link texts with brackets inside Supports links like [[this]](https://example.com), which is perfectly valid markdown by most parsers. --- index.compiler.spec.tsx | 23 +++++++++++++++++++++++ index.tsx | 9 +++++++-- 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/index.compiler.spec.tsx b/index.compiler.spec.tsx index 05453f2c..190137d0 100644 --- a/index.compiler.spec.tsx +++ b/index.compiler.spec.tsx @@ -4067,3 +4067,26 @@ it('handles a holistic example', () => { expect(root.innerHTML).toMatchSnapshot() }) + + +it('handles brackets in link text', () => { + render(compiler('[`[text]`](https://example.com)')) + + expect(root.innerHTML).toMatchInlineSnapshot(` + + + [text] + + + `) +}) + +it('handles naked brackets in link text', () => { + render(compiler('[[text]](https://example.com)')) + + expect(root.innerHTML).toMatchInlineSnapshot(` + + [text] + + `) +}) \ No newline at end of file diff --git a/index.tsx b/index.tsx index cb68d27c..0a8e5b48 100644 --- a/index.tsx +++ b/index.tsx @@ -482,8 +482,13 @@ function generateListRule( } } -const LINK_R = /^\[([^\]]*)]\( *((?:\([^)]*\)|[^() ])*) *"?([^)"]*)?"?\)/ -const IMAGE_R = /^!\[([^\]]*)]\( *((?:\([^)]*\)|[^() ])*) *"?([^)"]*)?"?\)/ +const LINK_INSIDE = "(?:\\[[^\\]]*\\]|[^\\[\\]]|\\](?=[^\\[]*\\]))*"; +const LINK_HREF_AND_TITLE = + "\\s*?(?:\\s+['\"]([\\s\\S]*?)['\"])?\\s*"; +const LINK_R = new RegExp( + "^\\[(" + LINK_INSIDE + ")\\]\\(" + LINK_HREF_AND_TITLE + "\\)", + ) +const IMAGE_R = /^!\[(.*?)\]\( *((?:\([^)]*\)|[^() ])*) *"?([^)"]*)?"?\)/ const NON_PARAGRAPH_BLOCK_SYNTAXES = [ BLOCKQUOTE_R,