-
Notifications
You must be signed in to change notification settings - Fork 1.7k
fix(editor): render <br> in markdown table cells as line breaks in rich mode #8995
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
xianjianlf2
wants to merge
2
commits into
stablyai:main
Choose a base branch
from
xianjianlf2:fix/markdown-br-in-table-cells-8838
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+191
−17
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
102 changes: 102 additions & 0 deletions
102
src/renderer/src/components/editor/raw-markdown-html-line-break.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,102 @@ | ||
| // @vitest-environment happy-dom | ||
|
|
||
| import { describe, expect, it } from 'vitest' | ||
| import { Editor } from '@tiptap/core' | ||
| import type { Node as ProseMirrorNode } from '@tiptap/pm/model' | ||
| import { createRichMarkdownEditorCodec } from './rich-markdown-source-transport' | ||
| import { createRichMarkdownExtensions } from './rich-markdown-extensions' | ||
| import { encodeRawMarkdownHtmlForRichEditor } from './raw-markdown-html' | ||
|
|
||
| function createEditor(markdown: string): Editor { | ||
| const codec = createRichMarkdownEditorCodec() | ||
| return new Editor({ | ||
| element: null, | ||
| extensions: createRichMarkdownExtensions({ codec }), | ||
| content: encodeRawMarkdownHtmlForRichEditor(markdown, codec), | ||
| contentType: 'markdown' | ||
| }) | ||
| } | ||
|
|
||
| function findRawInlineNodes(editor: Editor): ProseMirrorNode[] { | ||
| const nodes: ProseMirrorNode[] = [] | ||
| editor.state.doc.descendants((node) => { | ||
| if (node.type.name === 'rawMarkdownHtmlInline') { | ||
| nodes.push(node) | ||
| } | ||
| }) | ||
| return nodes | ||
| } | ||
|
|
||
| function renderTag(node: ProseMirrorNode): string { | ||
| const spec = node.type.spec.toDOM?.(node) | ||
| return Array.isArray(spec) ? String(spec[0]) : '' | ||
| } | ||
|
|
||
| const TABLE_WITH_BREAKS = | ||
| '| Field | Description |\n' + | ||
| '| --- | --- |\n' + | ||
| '| verdict | Values:<br/><br/>`normal`<br>`defect` |\n' | ||
|
|
||
| describe('raw markdown <br> line breaks in the rich editor', () => { | ||
| it('renders <br> and <br/> inside a table cell as real line breaks, not literal text', () => { | ||
| const editor = createEditor(TABLE_WITH_BREAKS) | ||
| try { | ||
| const breakNodes = findRawInlineNodes(editor) | ||
| expect(breakNodes.length).toBeGreaterThan(0) | ||
| // Every <br>/<br/> in the cell renders as an actual <br> element so the | ||
| // values appear on their own lines rather than as raw "<br>" text. | ||
| for (const node of breakNodes) { | ||
| expect(renderTag(node)).toBe('br') | ||
| } | ||
| } finally { | ||
| editor.destroy() | ||
| } | ||
| }) | ||
|
|
||
| it('keeps non-break inline HTML as an inert literal span', () => { | ||
| const editor = createEditor('Before <span>hi</span> after\n') | ||
| try { | ||
| const [spanNode] = findRawInlineNodes(editor) | ||
| expect(spanNode).toBeDefined() | ||
| expect(renderTag(spanNode)).toBe('span') | ||
| } finally { | ||
| editor.destroy() | ||
| } | ||
| }) | ||
|
|
||
| it('round-trips verbatim <br> tags after the rendered DOM is parsed again', () => { | ||
| const editor = createEditor(TABLE_WITH_BREAKS) | ||
| try { | ||
| const rendered = document.createElement('div') | ||
| rendered.innerHTML = editor.getHTML() | ||
| expect(rendered.querySelectorAll('br[data-raw-markdown-html-inline]')).toHaveLength(3) | ||
| expect(rendered.textContent).not.toContain('<br') | ||
|
|
||
| editor.commands.setContent(rendered.innerHTML) | ||
| const output = (editor as Editor & { getMarkdown(): string }).getMarkdown() | ||
| expect(output.match(/<br\s*\/?>/g)).toEqual(['<br/>', '<br/>', '<br>']) | ||
| // The break must not silently collapse into a space on serialization. | ||
| expect(output).not.toContain('`normal` `defect`') | ||
| } finally { | ||
| editor.destroy() | ||
| } | ||
| }) | ||
|
|
||
| it('does not accept arbitrary Markdown source from a forged break marker', () => { | ||
| const editor = createEditor('Before<br/>after\n') | ||
| try { | ||
| const rendered = document.createElement('div') | ||
| rendered.innerHTML = editor.getHTML() | ||
| rendered | ||
| .querySelector('br[data-raw-markdown-html-inline]') | ||
| ?.setAttribute('data-raw-markdown-html-value', '<script>alert(1)</script>') | ||
|
|
||
| editor.commands.setContent(rendered.innerHTML) | ||
| const output = (editor as Editor & { getMarkdown(): string }).getMarkdown() | ||
| expect(output).toContain('Before<br>after') | ||
| expect(output).not.toContain('<script>') | ||
| } finally { | ||
| editor.destroy() | ||
| } | ||
| }) | ||
| }) | ||
82 changes: 82 additions & 0 deletions
82
src/renderer/src/components/editor/raw-markdown-html-source-dom.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,82 @@ | ||
| import { mergeAttributes } from '@tiptap/core' | ||
| import type { DOMOutputSpec, Node as ProseMirrorNode, TagParseRule } from '@tiptap/pm/model' | ||
| import type { RichMarkdownSourceKind } from './rich-markdown-source-transport' | ||
|
|
||
| // Why: preserves the exact authored <br> spelling on the rendered break node so | ||
| // renderMarkdown can round-trip it verbatim instead of a native hardBreak, which | ||
| // serializes to a space and silently drops the tag inside Markdown table cells. | ||
| const HTML_LINE_BREAK_VALUE_ATTR = 'data-raw-markdown-html-value' | ||
|
|
||
| type RawMarkdownSourceDomConfig = { | ||
| inline: boolean | ||
| kind: RichMarkdownSourceKind | ||
| marker: string | ||
| className?: string | ||
| } | ||
|
|
||
| function isHtmlLineBreak(value: string): boolean { | ||
| return /^<br\s*\/?>$/i.test(value.trim()) | ||
| } | ||
|
|
||
| function parsedHtmlLineBreakValue(element: HTMLElement): string { | ||
| const value = element.getAttribute(HTML_LINE_BREAK_VALUE_ATTR) | ||
| // Why: DOM input can come from the clipboard, so only trusted break syntax | ||
| // may become hidden Markdown source through the internal preservation marker. | ||
| return value && isHtmlLineBreak(value) ? value : '<br>' | ||
| } | ||
|
|
||
| function nodeValue(node: ProseMirrorNode): string { | ||
| return typeof node.attrs.value === 'string' ? node.attrs.value : '' | ||
| } | ||
|
|
||
| // Why: only inline raw HTML can carry a <br>, so line-break rendering is scoped | ||
| // to that node kind; literal envelopes and block HTML stay verbatim. | ||
| function rendersLineBreaks(config: RawMarkdownSourceDomConfig): boolean { | ||
| return config.inline && config.kind === 'inline-html' | ||
| } | ||
|
|
||
| export function rawMarkdownSourceParseRules(config: RawMarkdownSourceDomConfig): TagParseRule[] { | ||
| const rules: TagParseRule[] = [ | ||
| { | ||
| tag: `${config.inline ? 'span' : 'div'}[${config.marker}]`, | ||
| getAttrs: (element: HTMLElement) => ({ value: element.textContent ?? '' }) | ||
| } | ||
| ] | ||
| if (rendersLineBreaks(config)) { | ||
| // Why: a <br> renders as a real break element (see renderHTML), so it must | ||
| // round-trip back to this node rather than StarterKit's hardBreak; the marker | ||
| // attribute and priority keep it ahead of hardBreak's bare `br` rule. | ||
| rules.push({ | ||
| tag: `br[${config.marker}]`, | ||
| priority: 100, | ||
| getAttrs: (element: HTMLElement) => ({ value: parsedHtmlLineBreakValue(element) }) | ||
| }) | ||
| } | ||
| return rules | ||
| } | ||
|
|
||
| export function renderRawMarkdownSourceHtml( | ||
| config: RawMarkdownSourceDomConfig, | ||
| attributes: Record<string, unknown>, | ||
| node: ProseMirrorNode | ||
| ): DOMOutputSpec { | ||
| const value = nodeValue(node) | ||
| // Why: <br> is the one inline HTML tag with line-break semantics the rich | ||
| // surface can honor directly. Render it as an actual break so it displays | ||
| // correctly where blank-line breaks are impossible (e.g. Markdown table cells). | ||
| if (rendersLineBreaks(config) && isHtmlLineBreak(value)) { | ||
| return [ | ||
| 'br', | ||
| mergeAttributes(attributes, { [config.marker]: '', [HTML_LINE_BREAK_VALUE_ATTR]: value }) | ||
| ] | ||
| } | ||
| return [ | ||
| config.inline ? 'span' : 'div', | ||
| mergeAttributes(attributes, { | ||
| [config.marker]: '', | ||
| contenteditable: 'false', | ||
| class: config.className | ||
| }), | ||
| config.inline ? value : ['pre', value] | ||
| ] | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Avoid optional chaining when setting up test conditions.
If
querySelectorfails to find the element (e.g., due to a change in the DOM structure), the optional chain will silently abort. The test would then proceed against an unmodified element and potentially pass, resulting in a false positive for this security test.Explicitly assert that the element exists before mutating it to ensure the test fails loudly if the setup contract breaks.
🐛 Proposed fix
📝 Committable suggestion