Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/fix-formatted-body-linkify.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
default: patch
---

Fixes links not being clickable in formatted messages, including messages that use abbreviations.
58 changes: 50 additions & 8 deletions src/app/components/message/RenderBody.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { MouseEventHandler, useEffect, useState } from 'react';
import parse, { HTMLReactParserOptions } from 'html-react-parser';
import Linkify from 'linkify-react';
import { Opts } from 'linkifyjs';
import { find, Opts } from 'linkifyjs';
import { PopOut, RectCords, Text, Tooltip, TooltipProvider, toRem } from 'folds';
import { sanitizeCustomHtml } from '$utils/sanitize';
import { highlightText, scaleSystemEmoji } from '$plugins/react-custom-html-parser';
import { useRoomAbbreviationsContext } from '$hooks/useRoomAbbreviations';
import { splitByAbbreviations } from '$utils/abbreviations';
import { splitByAbbreviations, TextSegment } from '$utils/abbreviations';
import { MessageEmptyContent } from './content';

function getRenderedBodyText(text: string, highlightRegex?: RegExp): (string | JSX.Element)[] {
Expand All @@ -28,6 +28,47 @@ function renderLinkifiedBodyText(
);
}

type RenderTextFn = (text: string, key?: string) => JSX.Element;

function splitBodyTextByAbbreviations(
text: string,
abbrMap: Map<string, string>,
linkifyOpts?: Opts
): TextSegment[] {
if (abbrMap.size === 0) return [{ id: 'txt-0', text }];

const linkMatches = find(text, linkifyOpts).filter((match) => match.isLink);
if (linkMatches.length === 0) return splitByAbbreviations(text, abbrMap);

const segments: Array<Omit<TextSegment, 'id'>> = [];
let lastIndex = 0;

linkMatches.forEach(({ start, end }) => {
if (start > lastIndex) {
splitByAbbreviations(text.slice(lastIndex, start), abbrMap).forEach(
({ text: segmentText, termKey }) => {
segments.push({ text: segmentText, termKey });
}
);
}

segments.push({ text: text.slice(start, end) });
lastIndex = end;
});

if (lastIndex < text.length) {
splitByAbbreviations(text.slice(lastIndex), abbrMap).forEach(
({ text: segmentText, termKey }) => {
segments.push({ text: segmentText, termKey });
}
);
}

return segments.length > 0
? segments.map((segment, index) => ({ ...segment, id: `txt-${index}` }))
: [{ id: 'txt-0', text }];
}

type AbbreviationTermProps = {
text: string;
definition: string;
Expand Down Expand Up @@ -84,11 +125,12 @@ function AbbreviationTerm({ text, definition }: AbbreviationTermProps) {
* extra closures in the common case).
*/
export function buildAbbrReplaceTextNode(
abbrMap: Map<string, string>
): ((text: string) => JSX.Element | undefined) | undefined {
abbrMap: Map<string, string>,
linkifyOpts?: Opts
): ((text: string, renderText: RenderTextFn) => JSX.Element | undefined) | undefined {
if (abbrMap.size === 0) return undefined;
return function replaceTextNode(text: string) {
const segments = splitByAbbreviations(text, abbrMap);
return function replaceTextNode(text: string, renderText: RenderTextFn) {
const segments = splitBodyTextByAbbreviations(text, abbrMap, linkifyOpts);
if (!segments.some((s) => s.termKey !== undefined)) return undefined;
return (
<>
Expand All @@ -100,7 +142,7 @@ export function buildAbbrReplaceTextNode(
definition={abbrMap.get(seg.termKey) ?? ''}
/>
) : (
seg.text
renderText(seg.text, seg.id)
)
)}
</>
Expand Down Expand Up @@ -130,7 +172,7 @@ export function RenderBody({
if (body === '') return <MessageEmptyContent />;

if (abbrMap.size > 0) {
const segments = splitByAbbreviations(body, abbrMap);
const segments = splitBodyTextByAbbreviations(body, abbrMap, linkifyOpts);
if (segments.some((s) => s.termKey !== undefined)) {
return (
<>
Expand Down
2 changes: 1 addition & 1 deletion src/app/features/room/RoomTimeline.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -520,7 +520,7 @@ export function RoomTimeline({
handleMentionClick: mentionClickHandler,
nicknames,
autoplayEmojis,
replaceTextNode: buildAbbrReplaceTextNode(abbrMap),
replaceTextNode: buildAbbrReplaceTextNode(abbrMap, linkifyOpts),
}),
[
mx,
Expand Down
2 changes: 1 addition & 1 deletion src/app/features/room/ThreadDrawer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -412,7 +412,7 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra
handleSpoilerClick: spoilerClickHandler,
handleMentionClick: mentionClickHandler,
nicknames,
replaceTextNode: buildAbbrReplaceTextNode(abbrMap),
replaceTextNode: buildAbbrReplaceTextNode(abbrMap, linkifyOpts),
}),
[
mx,
Expand Down
50 changes: 50 additions & 0 deletions src/app/plugins/react-custom-html-parser.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { render, screen } from '@testing-library/react';
import parse from 'html-react-parser';
import { afterEach, describe, expect, it, vi } from 'vitest';
import * as customHtmlCss from '$styles/CustomHtml.css';
import { buildAbbrReplaceTextNode } from '$components/message/RenderBody';
import { sanitizeCustomHtml } from '$utils/sanitize';
import {
LINKIFY_OPTS,
Expand Down Expand Up @@ -257,4 +258,53 @@ describe('react custom html parser', () => {

expect(logSpy).not.toHaveBeenCalled();
});

it('linkifies bare urls in formatted html text nodes even when abbreviation replacement runs', () => {
const parserOptions = getReactCustomHtmlParser(createMatrixClient(), '!room:example.com', {
settingsLinkBaseUrl,
linkifyOpts: LINKIFY_OPTS,
handleMentionClick: undefined,
replaceTextNode: buildAbbrReplaceTextNode(new Map([['PR', 'Pull request']]), LINKIFY_OPTS),
});

render(
<div>
{parse(
'<p>figured out the section could be removed; set up a PR for it: https://github.com/SableClient/Sable/pull/626</p>',
parserOptions
)}
</div>
);

expect(screen.getByText('PR')).toBeInTheDocument();
expect(
screen.getByRole('link', {
name: 'https://github.com/SableClient/Sable/pull/626',
})
).toHaveAttribute('href', 'https://github.com/SableClient/Sable/pull/626');
});

it('keeps the full link intact when an abbreviation term appears inside the url token', () => {
const parserOptions = getReactCustomHtmlParser(createMatrixClient(), '!room:example.com', {
settingsLinkBaseUrl,
linkifyOpts: LINKIFY_OPTS,
handleMentionClick: undefined,
replaceTextNode: buildAbbrReplaceTextNode(new Map([['PR', 'Pull request']]), LINKIFY_OPTS),
});

render(
<div>
{parse(
'<p>see https://github.com/SableClient/Sable/pull/PR/626 for context</p>',
parserOptions
)}
</div>
);

expect(
screen.getByRole('link', {
name: 'https://github.com/SableClient/Sable/pull/PR/626',
})
).toHaveAttribute('href', 'https://github.com/SableClient/Sable/pull/PR/626');
});
});
59 changes: 46 additions & 13 deletions src/app/plugins/react-custom-html-parser.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import {
CSSProperties,
ComponentPropsWithoutRef,
Fragment,
ReactEventHandler,
ReactNode,
useMemo,
Expand Down Expand Up @@ -500,14 +501,52 @@ export const getReactCustomHtmlParser = (
useAuthentication?: boolean;
nicknames?: Nicknames;
autoplayEmojis?: boolean;
replaceTextNode?: (text: string) => JSX.Element | undefined;
replaceTextNode?: (
text: string,
renderText: (text: string, key?: string) => JSX.Element
) => JSX.Element | undefined;
}
): HTMLReactParserOptions => {
const { replaceTextNode } = params;

const shouldLinkifyDomText = (domNode: DOMText): boolean =>
!(domNode.parent && 'name' in domNode.parent && domNode.parent.name === 'code') &&
!(domNode.parent && 'name' in domNode.parent && domNode.parent.name === 'a');

const decorateText = (text: string) => {
let jsx = scaleSystemEmoji(text);

if (params.highlightRegex) {
jsx = highlightText(params.highlightRegex, jsx);
}

return jsx;
};

const renderReplacementText = (text: string, linkify: boolean, key?: string): JSX.Element => {
const decoratedText = decorateText(text);

if (linkify) {
return (
<Linkify key={key} options={params.linkifyOpts}>
{decoratedText}
</Linkify>
);
}

return <Fragment key={key}>{decoratedText}</Fragment>;
};

const opts: HTMLReactParserOptions = {
replace: (domNode) => {
if (replaceTextNode && domNode instanceof DOMText) {
return replaceTextNode(domNode.data) ?? undefined;
const replacement = replaceTextNode(domNode.data, (text, key) =>
renderReplacementText(text, shouldLinkifyDomText(domNode), key)
);

if (replacement !== undefined) {
return replacement;
}
}
if (domNode instanceof Element && 'name' in domNode) {
const { name, attribs, children, parent } = domNode;
Expand Down Expand Up @@ -839,20 +878,14 @@ export const getReactCustomHtmlParser = (
}

if (domNode instanceof DOMText) {
const linkify =
!(domNode.parent && 'name' in domNode.parent && domNode.parent.name === 'code') &&
!(domNode.parent && 'name' in domNode.parent && domNode.parent.name === 'a');

let jsx = scaleSystemEmoji(domNode.data);

if (params.highlightRegex) {
jsx = highlightText(params.highlightRegex, jsx);
}
const linkify = shouldLinkifyDomText(domNode);
const decoratedText = decorateText(domNode.data);

if (linkify) {
return <Linkify options={params.linkifyOpts}>{jsx}</Linkify>;
return <Linkify options={params.linkifyOpts}>{decoratedText}</Linkify>;
}
return jsx;

return decoratedText;
}
return undefined;
},
Expand Down
Loading