Fix formatting behavior around <p> tags (#799)

<!-- Please read
https://github.com/SableClient/Sable/blob/dev/CONTRIBUTING.md before
submitting your pull request -->

### Description

<!-- Please include a summary of the change. Please also include
relevant motivation and context. List any dependencies that are required
for this change. -->

A few fixes:
- When emotes are sent (/me), the leading paragraph block is always
dropped so that the action doesn't appear on a new line, subsequent
blocks are still sent.
- For single line messages, paragraph tags are stripped.
- For multiline messages, there's two behaviors, which distinguish the
space between lines Sable (and some other clients probably) display.
    - Single new line = \n
    - Two new lines = \<p> tag

#### Type of change

- [x] Bug fix (non-breaking change which fixes an issue)
- [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to not work as expected)
- [ ] This change requires a documentation update

### Checklist:

- [ ] My code follows the style guidelines of this project
- [ ] I have performed a self-review of my own code
- [ ] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [ ] My changes generate no new warnings

### AI disclosure:

- [x] Partially AI assisted (clarify which code was AI assisted and
briefly explain what it does).
- [ ] Fully AI generated (explain what all the generated code does in
moderate detail).
<!-- Write any explanation required here, but do not generate the
explanation using AI!! You must prove you understand what the code in
this PR does. -->

Tests were AI generated
This commit is contained in:
7w1 authored and GitHub committed 2026-05-13 20:02:11 -05:00
commit b868f1d52f
9 files changed
+118 -21

No files matched your search

@@ -0,0 +1,5 @@
---
default: patch
---
Drops paragraph tags when messages are only a single paragraph, use markdown (two new lines) to define a new paragraph rather than a line break.
+4 -2
View File
@@ -19,6 +19,8 @@ export type OutputOptions = {
* a map of regex patterns to replace nicknames with, used when stripNickname is true
*/
nickNameReplacement?: Map<RegExp, string>;
/** When true, markdown HTML omits the leading `<p>` wrapper (for `m.emote` / `/me`). */
forEmote?: boolean;
};
const textToCustomHtml = (node: Text): string => sanitizeText(node.text);
@@ -86,13 +88,13 @@ export const toMatrixCustomHTML = (
}
markdownLines += line;
if (index === targetNodes.length - 1) {
const html = markdownToHtml(markdownLines);
const html = markdownToHtml(markdownLines, { emote: opts.forEmote });
return injectDataMd(html);
}
return '';
}
const parsedMarkdown = markdownToHtml(markdownLines);
const parsedMarkdown = markdownToHtml(markdownLines, { emote: opts.forEmote });
markdownLines = '';
return `${parsedMarkdown}${toMatrixCustomHTML(n, opts)}`;
};
+2
View File
@@ -777,6 +777,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
toMatrixCustomHTML(serializedChildren, {
stripNickname: true,
nickNameReplacement: nicknameReplacement,
forEmote: commandName === Command.Me,
})
);
@@ -851,6 +852,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
toMatrixCustomHTML(serializedChildren, {
stripNickname: true,
nickNameReplacement: nicknameReplacement,
forEmote: commandName === Command.Me,
})
);
}
@@ -170,8 +170,11 @@ export const MessageEditor = as<'div', MessageEditorProps>(
const [saveState, save] = useAsyncCallback(
useCallback(async () => {
const oldContent = mEvent.getContent();
const msgtype = mEvent.getContent().msgtype as RoomMessageTextEventContent['msgtype'];
let plainText = toPlainText(editor.children).trim();
let customHtml = trimCustomHtml(toMatrixCustomHTML(editor.children, {}));
let customHtml = trimCustomHtml(
toMatrixCustomHTML(editor.children, { forEmote: msgtype === MsgType.Emote })
);
const [prevBody, prevCustomHtml, prevMentions] = getPrevBodyAndFormattedBody();
@@ -192,8 +195,6 @@ export const MessageEditor = as<'div', MessageEditorProps>(
}
}
const msgtype = mEvent.getContent().msgtype as RoomMessageTextEventContent['msgtype'];
const newContent: IContent = {
msgtype,
body: plainText,
@@ -111,6 +111,10 @@ describe('htmlToMarkdown', () => {
expect(result).toContain('\\*');
});
it('inserts a blank line between adjacent paragraphs for editor round-trip', () => {
expect(htmlToMarkdown('<p>First</p><p>Second</p>')).toBe('First\n\nSecond');
});
it('encodes mx emoticons as private-use placeholders instead of literal img snippets', () => {
const src = 'mxc://matrix.org/emote';
const html = `<p>hi<img data-mx-emoticon src="${src}" alt="blobcat" title="blobcat" height="32" />bye</p>`;
+30 -13
View File
@@ -45,19 +45,36 @@ function isBlockTag(node: ChildNode | undefined): boolean {
}
function processNodes(nodes: ChildNode[]): string {
return nodes
.filter((n, i) => {
if (isText(n) && /^\s*$/.test(n.data)) {
const prev = nodes[i - 1];
const next = nodes[i + 1];
// Ignore whitespace between block tags or at the edges
const isBetweenBlocks = (!prev || isBlockTag(prev)) && (!next || isBlockTag(next));
if (isBetweenBlocks) return false;
}
return true;
})
.map((n) => processNode(n))
.join('');
const filtered = nodes.filter((n, i) => {
if (isText(n) && /^\s*$/.test(n.data)) {
const prev = nodes[i - 1];
const next = nodes[i + 1];
// Ignore whitespace between block tags or at the edges
const isBetweenBlocks = (!prev || isBlockTag(prev)) && (!next || isBlockTag(next));
if (isBetweenBlocks) return false;
}
return true;
});
const parts: string[] = [];
for (let i = 0; i < filtered.length; i += 1) {
const cur = filtered[i]!;
const prev = filtered[i - 1];
// Adjacent <p> blocks must become \n\n in markdown so the editor gets separate Slate
// paragraphs and marked emits <p> per block again on send (single \n would collapse).
if (
i > 0 &&
prev &&
isTag(prev) &&
isTag(cur) &&
prev.name.toLowerCase() === 'p' &&
cur.name.toLowerCase() === 'p'
) {
parts.push('\n');
}
parts.push(processNode(cur));
}
return parts.join('');
}
function processNode(node: ChildNode, listDepth: number = 0, insideCode: boolean = false): string {
+1 -1
View File
@@ -1,3 +1,3 @@
export * from './utils';
export { markdownToHtml } from './markdownToHtml';
export { markdownToHtml, type MarkdownToHtmlOptions } from './markdownToHtml';
export { htmlToMarkdown, injectDataMd } from './markdownPipeline';
@@ -143,10 +143,43 @@ describe('markdownToHtml', () => {
expect(result).toContain('Plain text');
});
it('omits a single outer paragraph wrapper for one-paragraph messages', () => {
expect(markdownToHtml('Hello')).toBe('Hello');
expect(markdownToHtml('**bold**')).toBe('<strong>bold</strong>');
expect(markdownToHtml('a<br>b')).toBe('a<br>b');
});
it('keeps paragraph tags when there are multiple paragraphs', () => {
const result = markdownToHtml('First\n\nSecond');
expect(result).toContain('<p>');
expect(result).toContain('First');
expect(result).toContain('Second');
});
it('does not strip the first <p> when there are three paragraphs with extra blank lines', () => {
const result = markdownToHtml('test\n\ntest 2\n\n\ntest 3');
expect(result).toMatch(/^<p>test<\/p>/i);
expect(result).toContain('<p>test 2</p>');
expect(result).toContain('<p>test 3</p>');
expect(result).not.toMatch(/^test<\/p>/i);
});
it('with emote: strips only the first <p> when multiple paragraphs are present', () => {
const result = markdownToHtml('first\n\nsecond', { emote: true });
expect(result).toMatch(/^first<p>/i);
expect(result).toContain('second');
expect(result).not.toMatch(/^<p>first<\/p>\s*<p>second<\/p>$/i);
});
it('with emote: still unwraps a single-paragraph body like the default path', () => {
expect(markdownToHtml('**waves**', { emote: true })).toBe('<strong>waves</strong>');
});
it('handles multiline content', () => {
const result = markdownToHtml('Line 1\nLine 2\nLine 3');
expect(result).toContain('Line 1');
expect(result).toContain('Line 2');
expect(result).toContain('Line 3');
});
it('handles escaped markdown characters', () => {
+35 -2
View File
@@ -85,14 +85,43 @@ const unshieldBareMatrixToLinks = (html: string, placeholders: Map<string, strin
return result;
};
/** When the whole message is a single paragraph, drop the redundant wrapper. */
const unwrapSingleOuterParagraph = (html: string): string => {
const trimmed = html.trim();
const m = trimmed.match(/^<p\b[^>]*>([\s\S]*)<\/p>$/i);
if (!m) return html;
const inner = m[1] ?? '';
if (/<\/p>/i.test(inner)) return html;
return inner;
};
/**
* For `m.emote`, the sender display name is added at render time. Strips the leading `<p>…</p>`
* block (when its inner HTML has no `</p>`) so we don't send `<p>` around the action.
*/
const stripLeadingEmoteParagraph = (html: string): string | null => {
const trimmed = html.trim();
const m = trimmed.match(/^<p\b[^>]*>([\s\S]*?)<\/p>/i);
if (!m) return null;
const inner = m[1] ?? '';
if (/<\/p>/i.test(inner)) return null;
const rest = trimmed.slice(m[0].length).trimStart();
return rest.length > 0 ? `${inner}${rest}` : inner;
};
export type MarkdownToHtmlOptions = {
emote?: boolean;
};
/**
* Converts markdown string to sanitized Matrix-compatible HTML.
* Uses marked for parsing and DOMPurify for sanitization per Matrix spec.
*
* @param markdown - Input markdown string
* @param options - Optional; set `emote` for `/me` outgoing HTML
* @returns Sanitized HTML string safe for Matrix client output
*/
export function markdownToHtml(markdown: string): string {
export function markdownToHtml(markdown: string, options?: MarkdownToHtmlOptions): string {
// Decode HTML entities so marked can properly parse markdown syntax
// (e.g., &lt; becomes < for link URLs)
const decoded = decodeHtmlEntities(markdown);
@@ -207,5 +236,9 @@ export function markdownToHtml(markdown: string): string {
matrixToPlaceholders
);
return unshieldedMatrixTo.replace(/<li>(<p><\/p>)?<\/li>/gi, '<li><br></li>');
const listFixed = unshieldedMatrixTo.replace(/<li>(<p><\/p>)?<\/li>/gi, '<li><br></li>');
if (options?.emote) {
return stripLeadingEmoteParagraph(listFixed) ?? unwrapSingleOuterParagraph(listFixed);
}
return unwrapSingleOuterParagraph(listFixed);
}