Fix link editing behaviors (#847)

<!-- 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. -->

Fixes the random \<> and links being too aggressive with parsing leading
to the entire markdown structure being seen as part of it and fixes
editing messages with suppressed links not remaining suppressed.

#### 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-14 23:51:36 -05:00
commit 0edf45cf93
8 files changed
+99 -9

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
---
default: patch
---
Fix issues related to editing messages with links losing previews or gaining \<>
@@ -32,6 +32,15 @@ describe('getLinks', () => {
expect(links).toContain('https://example.com');
});
it('does not merge link text URL with destination when both are https (edited bare link)', () => {
const node: ParagraphElement = {
type: BlockType.Paragraph,
children: [{ text: '[https://example.com/](https://example.com/)' }],
};
const links = getLinks([node]);
expect(links).toEqual(['https://example.com/']);
});
it('excludes URLs inside markdown inline code spans', () => {
const node: ParagraphElement = {
type: BlockType.Paragraph,
+1 -1
View File
@@ -156,7 +156,7 @@ const elementToPlainText = (node: CustomElement, children: string): string => {
};
const SPOILERINPUTREGEX = /\|\|.+?\|\|/g;
const LINK_URL = `(https?:\\/\\/.[A-Za-z0-9-._~:/?#[\\]()@!$&'*+,;%=]+)`;
const LINK_URL = `(https?:\\/\\/.[A-Za-z0-9-._~:/?#[\\()@!$&'*+,;%=]+)`;
export const LINKINPUTREGEX = new RegExp(`\\(?(${LINK_URL})\\)?`, 'g');
const SPOILEREDLINKINPUTREGEX = new RegExp(`<(${LINK_URL})>`, 'g');
const SPOILEREDLINKDIRECTREGEX = new RegExp(`\\|\\|(${LINK_URL})\\|\\|`, 'g');
@@ -121,9 +121,9 @@ export const MessageEditor = as<'div', MessageEditorProps>(
);
}
const bundleContent = content['com.beeper.linkpreviews'] as BundleContent[];
const bundleContent =
(content['com.beeper.linkpreviews'] as BundleContent[] | undefined) ?? [];
const markHiddenLinks = (original: string, isHTML?: boolean) => {
if (!bundleContent) return original;
if (!isHTML) {
return readdAngleBracketsForHiddenPreviews(original, bundleContent);
}
@@ -155,7 +155,14 @@ export const MessageEditor = as<'div', MessageEditorProps>(
(bundleContent?.length === 0 ||
bundleContent.filter((b) => s.includes(b.matched_url)).length === 0) &&
strippedS.match(LINKINPUTREGEX) !== null;
newBody += `${isHidden ? (isHTML && ((s.startsWith('<a') && `&lt;${s[0]}`) || `${s[0]}&lt;`)) || `${s[0]}<` : s[0]}${strippedS}${isHidden ? (isHTML && '&gt;') || '>' : ''}`;
// Wrap whole <a>…</a> as &lt;…&gt; once; duplicating the leading "<" breaks htmlToMarkdown's [<][a][>] detection.
if (isHidden && isHTML && s.toLowerCase().startsWith('<a')) {
newBody += `&lt;${s}&gt;`;
return;
}
newBody += `${isHidden ? (isHTML && `${s[0]}&lt;`) || `${s[0]}<` : s[0]}${strippedS}${isHidden ? (isHTML && '&gt;') || '>' : ''}`;
});
return newBody;
};
@@ -25,6 +25,22 @@ describe('stripMarkdownEscapesForHiddenPreviews', () => {
String.raw`keep \*this\* and \<not-a-url\>`
);
});
it('unwraps outer \\< \\> around a preview-suppressed markdown link from htmlToMarkdown', () => {
expect(
stripMarkdownEscapesForHiddenPreviews(
String.raw`\<[https://example.org/](<https://example.org/>)\>`
)
).toBe('[https://example.org/](<https://example.org/>)');
});
it('fixes escaped outer brackets when destination lost angle brackets (bad HTML wrap)', () => {
expect(
stripMarkdownEscapesForHiddenPreviews(
String.raw`\<[https://example.com/](https://example.com/)>`
)
).toBe('[https://example.com/](<https://example.com/>)');
});
});
describe('readdAngleBracketsForHiddenPreviews', () => {
@@ -47,4 +63,13 @@ describe('readdAngleBracketsForHiddenPreviews', () => {
'see <https://example.org/>'
);
});
it('does not corrupt markdown suppressed links [url](<url>)', () => {
expect(
readdAngleBracketsForHiddenPreviews(
'see [https://example.org/](<https://example.org/>) thanks',
[]
)
).toBe('see [https://example.org/](<https://example.org/>) thanks');
});
});
@@ -1,6 +1,6 @@
import type { BundleContent } from '$components/message';
const LINK_URL = `(https?:\\/\\/.[A-Za-z0-9-._~:/?#[\\]()@!$&'*+,;%=]+)`;
const LINK_URL = `(https?:\\/\\/.[A-Za-z0-9-._~:/?#[\\()@!$&'*+,;%=]+)`;
const LINKINPUTREGEX = new RegExp(`\\(?(${LINK_URL})\\)?`, 'g');
/**
@@ -18,7 +18,20 @@ export function stripMarkdownEscapesForHiddenPreviews(markdown: string): string
const OPEN_ONLY = new RegExp(String.raw`\\<(${LINK_URL})`, 'g');
const CLOSE_ONLY = new RegExp(String.raw`(${LINK_URL})\\>`, 'g');
return markdown.replace(WRAPPED, '<$1>').replace(OPEN_ONLY, '<$1').replace(CLOSE_ONLY, '$1>');
let s = markdown.replace(WRAPPED, '<$1>').replace(OPEN_ONLY, '<$1').replace(CLOSE_ONLY, '$1>');
// Restore [label](<url>) after htmlToMarkdown escaped a surrounding "\<...\>".
const ESCAPED_SUPPRESSED_MD_LINK = new RegExp(
String.raw`\\<\[([^\]]*)\]\((<https?:\/\/[^>\s]+>)\)\\>`,
'g'
);
s = s.replace(ESCAPED_SUPPRESSED_MD_LINK, '[$1]($2)');
// Same for "\<[label](bare-url)>" when angle brackets were lost on the destination.
const WRONG_OUTER_ESCAPED_AUTOLINK = /\\<\[([^\]]+)\]\((https?:\/\/[^)\s]+)\)(?:>|\\>)/g;
s = s.replace(WRONG_OUTER_ESCAPED_AUTOLINK, '[$1](<$2>)');
return s;
}
export function readdAngleBracketsForHiddenPreviews(
@@ -30,9 +43,23 @@ export function readdAngleBracketsForHiddenPreviews(
const previewed = new Set(linkPreviews.map((b) => b.matched_url));
LINKINPUTREGEX.lastIndex = 0;
return body.replace(LINKINPUTREGEX, (full, url: string, offset: number) => {
return body.replace(LINKINPUTREGEX, (...args: unknown[]) => {
const full = args[0] as string;
const url = args[args.length - 3] as string;
const offset = args[args.length - 2] as number;
if (!url || previewed.has(url)) return full;
// URL is the label of a markdown link [url](...) — do not insert "<" into the label.
const after = body.slice(offset + full.length, offset + full.length + 2);
if (after === '](') {
return full;
}
// Already a preview-suppressed destination ...](<https://...>)
if (offset >= 3 && body.slice(offset - 3, offset) === '](<') {
return full;
}
// If the URL is already wrapped as <url>, leave it alone.
const urlIndex = body.indexOf(url, offset);
if (urlIndex !== -1 && body.slice(urlIndex - 1, urlIndex + url.length + 1) === `<${url}>`) {
@@ -67,6 +67,11 @@ describe('htmlToMarkdown', () => {
expect(htmlToMarkdown(html)).toBe('[https://example.org/](<https://example.org/>)');
});
it('converts hidden-preview wrapped links when angle brackets are decimal entities', () => {
const html = '<p>&#60;<a href="https://example.org/">https://example.org/</a>&#62;</p>';
expect(htmlToMarkdown(html)).toBe('[https://example.org/](<https://example.org/>)');
});
it('converts spoiler spans', () => {
expect(htmlToMarkdown('<span data-mx-spoiler>hidden</span>')).toContain('||hidden||');
});
+14 -2
View File
@@ -196,6 +196,17 @@ function processInlineElements(
return processChildren(node.children, listDepth, insideCode);
}
/** Text node is a literal or entity-encoded angle bracket (preview-suppressed autolink wrapper). */
function isOpeningAngleBracketText(data: string): boolean {
const t = data.trim();
return t === '<' || t === '&lt;' || t === '&#60;' || t === '&#x3c;';
}
function isClosingAngleBracketText(data: string): boolean {
const t = data.trim();
return t === '>' || t === '&gt;' || t === '&#62;' || t === '&#x3e;';
}
function processChildren(
children: ChildNode[],
listDepth: number = 0,
@@ -213,14 +224,15 @@ function processChildren(
next &&
next2 &&
isText(cur) &&
cur.data === '<' &&
isOpeningAngleBracketText(cur.data) &&
isTag(next) &&
next.name.toLowerCase() === 'a' &&
isText(next2) &&
next2.data === '>'
isClosingAngleBracketText(next2.data)
) {
const href = next.attribs.href ?? '';
const content = next.children.map((c) => processNode(c, listDepth, insideCode)).join('');
// Suppressed autolink: [label](<href>) so bracket text is not run through escapeMarkdown as "\<".
out.push(`[${content}](<${href}>)`);
i += 2;
continue;