Merge branch 'dev' into refactor-calls

# Conflicts:
#	src/app/components/message/content/ImageContent.tsx
This commit is contained in:
7w1 committed 2026-05-14 22:36:18 -05:00
commit f07d331d30
11 files changed
+411 -26

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
---
default: patch
---
Made markdown headers also function properly with single new lines instead of only two new lines.
+5
View File
@@ -0,0 +1,5 @@
---
default: patch
---
Fix mentions not being linkfied.
+5
View File
@@ -0,0 +1,5 @@
---
default: patch
---
Fixed room pings looking like normal message links instead of pings.
+125 -2
View File
@@ -1,7 +1,14 @@
import { describe, expect, it } from 'vitest';
import { toMatrixCustomHTML, trimCustomHtml } from '$components/editor/output';
import type { Room } from '$types/matrix-sdk';
import { toMatrixCustomHTML, toPlainText, trimCustomHtml } from '$components/editor/output';
import { BlockType } from '$components/editor/types';
const roomWithMember = (userId: string, rawDisplayName: string): Room =>
({
getMember: (id: string) =>
id === userId ? ({ userId: id, rawDisplayName } as never) : undefined,
}) as unknown as Room;
describe('toMatrixCustomHTML emoticons', () => {
it('always serializes custom emoji images with height=32', () => {
const html = trimCustomHtml(
@@ -30,7 +37,31 @@ describe('toMatrixCustomHTML emoticons', () => {
});
describe('toMatrixCustomHTML matrix.to', () => {
it('serializes room mentions as raw matrix.to URL text, not an anchor', () => {
it('serializes @room pings as a markdown link so the label is @room, not a bare permalink', () => {
const html = trimCustomHtml(
toMatrixCustomHTML(
[
{
type: BlockType.Paragraph,
children: [
{
type: BlockType.Mention,
id: '!room:example.org',
name: '@room',
children: [{ text: '' }],
} as never,
],
} as never,
],
{}
)
);
expect(html).toMatch(/<a\b[^>]*href="https:\/\/matrix\.to\/#\/!room:example\.org"/i);
expect(html).toContain('@room');
});
it('serializes non–@room room mentions as bare matrix.to URL text', () => {
const html = trimCustomHtml(
toMatrixCustomHTML(
[
@@ -54,6 +85,82 @@ describe('toMatrixCustomHTML matrix.to', () => {
expect(html).not.toMatch(/<a\b[^>]*matrix\.to/i);
});
it('serializes user mentions using room membership display name, not private Slate node.name', () => {
const room = roomWithMember('@alice:example.org', 'Alice');
const html = trimCustomHtml(
toMatrixCustomHTML(
[
{
type: BlockType.Paragraph,
children: [
{
type: BlockType.Mention,
id: '@alice:example.org',
name: 'Secret local only nickname',
highlight: true,
children: [{ text: '' }],
} as never,
],
} as never,
],
{ room }
)
);
expect(html).toMatch(/<a\b[^>]*href="https:\/\/matrix\.to\/#\/@alice:example\.org"/i);
expect(html).toContain('Alice');
expect(html).not.toContain('Secret local only nickname');
});
it('serializes user mentions without room using MXID localpart as link label', () => {
const html = trimCustomHtml(
toMatrixCustomHTML(
[
{
type: BlockType.Paragraph,
children: [
{
type: BlockType.Mention,
id: '@alice:example.org',
name: 'Secret local only nickname',
highlight: true,
children: [{ text: '' }],
} as never,
],
} as never,
],
{}
)
);
expect(html).toMatch(/<a\b[^>]*href="https:\/\/matrix\.to\/#\/@alice:example\.org"/i);
expect(html).toMatch(/>alice<\/a>/i);
expect(html).not.toContain('Secret local only nickname');
});
it('uses @room in plain body for room pings, not the room id', () => {
const plain = toPlainText(
[
{
type: BlockType.Paragraph,
children: [
{
type: BlockType.Mention,
id: '!room:example.org',
name: '@room',
highlight: true,
children: [{ text: '' }],
} as never,
],
} as never,
],
false,
undefined
).trim();
expect(plain).toBe('@room');
});
it('serializes matrix.to links as raw URL text, not an anchor', () => {
const html = trimCustomHtml(
toMatrixCustomHTML(
@@ -77,3 +184,19 @@ describe('toMatrixCustomHTML matrix.to', () => {
expect(html).not.toMatch(/<a\b[^>]*matrix\.to/i);
});
});
describe('toMatrixCustomHTML single-newline markdown blocks', () => {
it('parses -# on a second Slate paragraph joined with a single newline', () => {
const html = trimCustomHtml(
toMatrixCustomHTML(
[
{ type: BlockType.Paragraph, children: [{ text: 'test' }] } as never,
{ type: BlockType.Paragraph, children: [{ text: '-# caption' }] } as never,
],
{}
)
);
expect(html).toContain('<sub');
expect(html).toContain('data-md="-#"');
});
});
+36 -6
View File
@@ -1,10 +1,11 @@
import type { Descendant, Editor } from 'slate';
import { Text } from 'slate';
import type { MatrixClient } from '$types/matrix-sdk';
import type { MatrixClient, Room } from '$types/matrix-sdk';
import { sanitizeText } from '$utils/sanitize';
import { markdownToHtml, injectDataMd } from '$plugins/markdown';
import { sanitizeForRegex } from '$utils/regex';
import { isUserId } from '$utils/matrix';
import { getMxIdLocalPart, isUserId } from '$utils/matrix';
import { getMemberDisplayName } from '$utils/room';
import type { CustomElement } from './slate';
import { BlockType } from './types';
import { getMarkdownCodeSpanRanges, isInsideMarkdownCodeSpan } from './utils';
@@ -21,11 +22,33 @@ export type OutputOptions = {
nickNameReplacement?: Map<RegExp, string>;
/** When true, markdown HTML omits the leading `<p>` wrapper (for `m.emote` / `/me`). */
forEmote?: boolean;
room?: Room;
};
const textToCustomHtml = (node: Text): string => sanitizeText(node.text);
const elementToCustomHtml = (node: CustomElement, children: string): string => {
const markdownInlineLinkLabel = (label: string, fallback: string): string => {
const t = label.trim();
if (!t) return fallback;
if (t.includes(']')) return fallback;
for (let i = 0; i < t.length; i++) {
if (t.charCodeAt(i) <= 0x1f) return fallback;
}
return t;
};
const userMentionMarkdownLinkLabel = (userId: string, room: Room | undefined): string => {
const fallback = getMxIdLocalPart(userId) ?? userId;
if (!room) return fallback;
const fromMembership = getMemberDisplayName(room, userId);
return markdownInlineLinkLabel(fromMembership ?? '', fallback);
};
const elementToCustomHtml = (
node: CustomElement,
children: string,
opts: OutputOptions
): string => {
switch (node.type) {
case BlockType.Paragraph:
return `${children}<br/>`;
@@ -41,6 +64,13 @@ const elementToCustomHtml = (node: CustomElement, children: string): string => {
}
const matrixTo = `${MATRIX_TO_BASE}#/${fragment}`;
if (node.name === '@room') {
return `[@room](${encodeURI(matrixTo)})`;
}
if (isUserId(node.id)) {
const label = userMentionMarkdownLinkLabel(node.id, opts.room);
return `[${label}](${encodeURI(matrixTo)})`;
}
return sanitizeText(matrixTo);
}
case BlockType.Emoticon:
@@ -105,7 +135,7 @@ export const toMatrixCustomHTML = (
const children = node.children
.map((element, index, array) => parseNode(element, index, array))
.join('');
return elementToCustomHtml(node, children);
return elementToCustomHtml(node, children, opts);
};
const elementToPlainText = (node: CustomElement, children: string): string => {
@@ -113,7 +143,7 @@ const elementToPlainText = (node: CustomElement, children: string): string => {
case BlockType.Paragraph:
return `${children}\n`;
case BlockType.Mention:
return node.id;
return node.name === '@room' ? node.name : node.id;
case BlockType.Emoticon:
return node.key.startsWith('mxc://') ? `:${node.shortcode}:` : node.key;
case BlockType.Link:
@@ -184,7 +214,7 @@ export const toRawText = (node: Descendant | Descendant[]): string => {
case BlockType.Emoticon:
return node.key.startsWith('mxc://') ? `:${node.shortcode}:` : node.key;
case BlockType.Mention:
return node.id;
return node.name === '@room' ? node.name : node.id;
case BlockType.Command:
return `/${node.command}`;
default:
@@ -142,21 +142,24 @@ export const ImageContent = as<'div', ImageContentProps>(
);
useEffect(() => {
let cancelled = false;
if (!viewer) {
setViewerFullSrc(null);
} else if (
typeof matrixThumbnailMaxEdge === 'number' &&
matrixThumbnailMaxEdge > 0 &&
!encInfo &&
!url.startsWith('http')
) {
void (async () => {
const mediaUrl = mxcUrlToHttp(mx, url, useAuthentication);
if (!mediaUrl || cancelled) return;
setViewerFullSrc(mediaUrl);
})();
return undefined;
}
if (
typeof matrixThumbnailMaxEdge !== 'number' ||
matrixThumbnailMaxEdge <= 0 ||
encInfo ||
url.startsWith('http')
) {
return undefined;
}
let cancelled = false;
void (async () => {
const mediaUrl = mxcUrlToHttp(mx, url, useAuthentication);
if (!mediaUrl || cancelled) return;
setViewerFullSrc(mediaUrl);
})();
return () => {
cancelled = true;
};
@@ -179,7 +182,9 @@ export const ImageContent = as<'div', ImageContentProps>(
if (autoPlay) loadSrc();
}, [autoPlay, loadSrc]);
const hasDimensions = typeof info?.w === 'number' && typeof info?.h === 'number';
const imageW = info?.w;
const imageH = info?.h;
const hasDimensions = typeof imageW === 'number' && typeof imageH === 'number';
const isContained = mediaLayout === 'contained';
const fillsSlot = Boolean(fillsPreviewSlot && isContained);
const containedReserveStrip =
@@ -192,14 +197,12 @@ export const ImageContent = as<'div', ImageContentProps>(
const rootClass = isContained ? css.ContainedMediaRoot : css.RelativeBase;
const stripMin = containedStripMinPx ?? 56;
const imageWidth = info?.w;
const imageHeight = info?.h;
const intrinsicSizingStyle = fillsSlot
? {}
: isContained
? { minHeight: containedReserveStrip ? toRem(stripMin) : undefined }
: hasDimensions
? { aspectRatio: `${imageWidth} / ${imageHeight}` }
? { aspectRatio: `${imageW} / ${imageH}` }
: { minHeight: '150px' };
const fillPreviewSlotStyle = fillsSlot
+2
View File
@@ -778,6 +778,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
stripNickname: true,
nickNameReplacement: nicknameReplacement,
forEmote: commandName === Command.Me,
room,
})
);
@@ -853,6 +854,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
stripNickname: true,
nickNameReplacement: nicknameReplacement,
forEmote: commandName === Command.Me,
room,
})
);
}
@@ -173,7 +173,10 @@ export const MessageEditor = as<'div', MessageEditorProps>(
const msgtype = mEvent.getContent().msgtype as RoomMessageTextEventContent['msgtype'];
let plainText = toPlainText(editor.children).trim();
let customHtml = trimCustomHtml(
toMatrixCustomHTML(editor.children, { forEmote: msgtype === MsgType.Emote })
toMatrixCustomHTML(editor.children, {
forEmote: msgtype === MsgType.Emote,
room,
})
);
const [prevBody, prevCustomHtml, prevMentions] = getPrevBodyAndFormattedBody();
@@ -0,0 +1,154 @@
/**
* Inserts an extra newline before block-level markdown lines that follow a single `\n`,
* so CommonMark/marked see a real paragraph boundary. Skips fenced code regions.
*/
function findSameLineFenceClose(md: string, from: number, tick: string, minLen: number): number {
let j = from;
while (j < md.length && md[j] !== '\n') {
if (md[j] === tick) {
let run = 0;
while (j + run < md.length && md[j + run] === tick) run++;
if (run >= minLen) return j;
j += run;
} else {
j++;
}
}
return -1;
}
function findMultilineFenceEnd(
md: string,
contentStart: number,
tick: string,
minLen: number
): { blockEnd: number; contentEnd: number } | null {
let p = contentStart;
while (p <= md.length) {
const nl = md.indexOf('\n', p);
const lineStart = p;
const lineEnd = nl === -1 ? md.length : nl;
const line = md.slice(lineStart, lineEnd);
const m = tick === '`' ? /^ {0,3}(`{3,})\s*$/.exec(line) : /^ {0,3}(~{3,})\s*$/.exec(line);
const fenceRun = m?.[1];
if (fenceRun && fenceRun.length >= minLen && fenceRun[0] === tick) {
return {
blockEnd: nl === -1 ? md.length : nl + 1,
contentEnd: lineStart,
};
}
if (nl === -1) return null;
p = nl + 1;
}
return null;
}
/** Returns index just past the fence block, or null if `i` is not a fence opener at line start. */
function trySkipFenceEnd(md: string, i: number): number | null {
const atLineStart = i === 0 || md[i - 1] === '\n';
if (!atLineStart) return null;
const rest = md.slice(i);
const open = /^(\s{0,3})(`{3,}|~{3,})/.exec(rest);
if (!open?.[2]) return null;
const fenceStr = open[2];
const tick = fenceStr.charAt(0);
const openLen = fenceStr.length;
const afterOpen = i + open[0].length;
if (afterOpen < md.length && md[afterOpen] === '\n') {
const contentStart = afterOpen + 1;
const close = findMultilineFenceEnd(md, contentStart, tick, openLen);
if (!close) return md.length;
return close.blockEnd;
}
const closeIdx = findSameLineFenceClose(md, afterOpen, tick, openLen);
if (closeIdx < 0) return null;
let closeRun = 0;
while (closeIdx + closeRun < md.length && md[closeIdx + closeRun] === tick) closeRun++;
return closeIdx + closeRun;
}
function afterLeadingIndent(line: string): string {
let k = 0;
while (k < line.length && k < 3 && line[k] === ' ') k++;
return line.slice(k);
}
function effectiveContentAfterEscapes(line: string): string | null {
const rest = afterLeadingIndent(line);
if (rest.length === 0) return null;
let bs = 0;
while (bs < rest.length && rest[bs] === '\\') bs++;
if (bs % 2 === 1) return null;
return rest.slice(bs);
}
function looksLikeBlockStart(effective: string): boolean {
if (effective.length === 0) return false;
if (/^#{1,6}(?:\s|$)/.test(effective)) return true;
if (/^-# +/.test(effective)) return true;
if (/^>\s/.test(effective)) return true;
if (/^[-*+]\s/.test(effective)) return true;
if (/^\d{1,9}\.\s/.test(effective)) return true;
if (/^(?:`{3,}|~{3,})/.test(effective)) return true;
if (effective.startsWith('$$')) return true;
if (/^(?:-{3,}|\*{3,}|_{3,})\s*$/.test(effective)) return true;
return false;
}
function nextLineIsBlockStarter(md: string, newlineIdx: number): boolean {
const start = newlineIdx + 1;
if (start >= md.length) return false;
const nextNl = md.indexOf('\n', start);
const line = nextNl === -1 ? md.slice(start) : md.slice(start, nextNl);
const effective = effectiveContentAfterEscapes(line);
if (effective === null) return false;
return looksLikeBlockStart(effective);
}
/**
* After a single newline (not part of `\n\n`), inserts one more `\n` when the following line
* opens a block the marked stack understands. Fenced code is copied verbatim without changes.
*/
export function expandBlockBoundariesAfterSingleNewlines(markdown: string): string {
const md = markdown.replace(/\r\n/g, '\n');
let out = '';
let i = 0;
const n = md.length;
while (i < n) {
const atLineStart = i === 0 || md[i - 1] === '\n';
if (atLineStart) {
const fenceEnd = trySkipFenceEnd(md, i);
if (fenceEnd !== null) {
out += md.slice(i, fenceEnd);
i = fenceEnd;
continue;
}
}
if (
md[i] === '\n' &&
(i === 0 || md[i - 1] !== '\n') &&
(i + 1 >= n || md[i + 1] !== '\n') &&
nextLineIsBlockStarter(md, i)
) {
out += '\n\n';
i += 1;
continue;
}
out += md[i];
i += 1;
}
return out;
}
@@ -114,6 +114,58 @@ describe('markdownToHtml', () => {
expect(html).toContain('fenced');
});
describe('single-newline block boundaries', () => {
it('parses matrix -# after a single newline following text', () => {
const result = markdownToHtml('test\n-# caption');
expect(result).toContain('<sub');
expect(result).toContain('data-md="-#"');
expect(result).toContain('caption');
});
it('parses ATX heading after a single newline', () => {
expect(markdownToHtml('intro\n# Heading')).toContain('<h1');
expect(markdownToHtml('intro\n# Heading')).toContain('Heading');
});
it('parses unordered list after a single newline', () => {
const html = markdownToHtml('intro\n- item');
expect(html).toContain('<ul');
expect(html).toContain('<li');
});
it('parses blockquote after a single newline', () => {
expect(markdownToHtml('intro\n> quote')).toContain('<blockquote>');
});
it('does not promote -# inside fenced code when the fence follows a single newline', () => {
const html = markdownToHtml('test\n```\n-# not sub\n```');
expect(html).not.toContain('<sub');
expect(html).toContain('-# not sub');
});
it('parses -# after a fenced block when separated by a single newline', () => {
const html = markdownToHtml('test\n```\ncode\n```\n-# cap');
expect(html).toContain('<pre>');
expect(html).toContain('<sub');
expect(html).toContain('cap');
});
it('keeps existing double-newline behavior before -#', () => {
const result = markdownToHtml('test\n\n-# caption');
expect(result).toContain('<sub');
expect(result).toContain('caption');
});
it('does not treat the second line of k. Hello as a new ordered list', () => {
const html = markdownToHtml('k. Hello world\nHello again');
expect(html).not.toContain('<ol>');
});
it('does not promote escaped line-start -# after a single newline', () => {
expect(markdownToHtml('x\n\\-# literal')).not.toContain('data-md="-#"');
});
});
it('does not parse escaped \\-# as small/sub', () => {
const result = markdownToHtml('\\-# literal caption');
expect(result).not.toContain('<sub');
+4 -1
View File
@@ -16,6 +16,7 @@ import {
escapeLineStartBlockquoteWithoutFollowingSpace,
unescapeMarkdownInlineSequencesExceptInCodeHtml,
} from './utils';
import { expandBlockBoundariesAfterSingleNewlines } from './expandBlockNewlines';
// Configure marked with Matrix extensions
const processor = marked.use({
@@ -131,8 +132,10 @@ export function markdownToHtml(markdown: string, options?: MarkdownToHtmlOptions
const preprocessed = preprocessEmoticon(blockquotePrefixed);
const boundaryExpanded = expandBlockBoundariesAfterSingleNewlines(preprocessed);
const { shielded: matrixToShielded, placeholders: matrixToPlaceholders } =
shieldBareMatrixToLinks(preprocessed);
shieldBareMatrixToLinks(boundaryExpanded);
const mathInput = shieldDollarRunsForMarked(maskDollarSignsInsideMarkdownCode(matrixToShielded));