-
Notifications
You must be signed in to change notification settings - Fork 298
Expand file tree
/
Copy pathrenderText.tsx
More file actions
205 lines (184 loc) Β· 5.84 KB
/
renderText.tsx
File metadata and controls
205 lines (184 loc) Β· 5.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
import React from 'react';
import ReactMarkdown, { defaultUrlTransform } from 'react-markdown';
import { find } from 'linkifyjs';
import remarkGfm from 'remark-gfm';
import type { ComponentType } from 'react';
import type { Options } from 'react-markdown/lib';
import type { UserResponse } from 'stream-chat';
import type { PluggableList } from 'unified'; // A sub-dependency of react-markdown. The type is not declared or re-exported from anywhere else
import { Anchor, Emoji, Mention } from './componentRenderers';
import { detectHttp, matchMarkdownLinks, messageCodeBlocks } from './regex';
import { emojiMarkdownPlugin, mentionsMarkdownPlugin } from './rehypePlugins';
import {
htmlToTextPlugin,
imageToLink,
keepLineBreaksPlugin,
plusPlusToEmphasis,
} from './remarkPlugins';
import { ErrorBoundary } from '../../UtilityComponents';
import type { MentionProps } from './componentRenderers';
export type RenderTextPluginConfigurator = (
defaultPlugins: PluggableList,
) => PluggableList;
export const defaultAllowedTagNames: Array<
keyof React.JSX.IntrinsicElements | 'emoji' | 'mention'
> = [
'html',
'text',
'br',
'p',
'em',
'strong',
'a',
'ol',
'ul',
'li',
'code',
'pre',
'blockquote',
'del',
'table',
'thead',
'tbody',
'th',
'tr',
'td',
'tfoot',
// custom types (tagNames)
'emoji',
'mention',
'h1',
'h2',
'h3',
'h4',
'h5',
'h6',
'ins',
];
function formatUrlForDisplay(url: string) {
try {
return decodeURIComponent(url).replace(detectHttp, '');
} catch (e) {
return url;
}
}
function encodeDecode(url: string) {
try {
return encodeURI(decodeURIComponent(url));
} catch (error) {
return url;
}
}
const urlTransform = (uri: string) =>
uri.startsWith('app://') ? uri : defaultUrlTransform(uri);
const getPluginsForward: RenderTextPluginConfigurator = (plugins: PluggableList) =>
plugins;
export const markDownRenderers: RenderTextOptions['customMarkDownRenderers'] = {
a: Anchor,
emoji: Emoji,
mention: Mention,
};
export type RenderTextOptions = {
allowedTagNames?: Array<
keyof React.JSX.IntrinsicElements | 'emoji' | 'mention' | (string & {})
>;
customMarkDownRenderers?: Options['components'] &
Partial<{
emoji: ComponentType;
mention: ComponentType<MentionProps>;
}>;
getRehypePlugins?: RenderTextPluginConfigurator;
getRemarkPlugins?: RenderTextPluginConfigurator;
};
export const renderText = (
text?: string,
mentionedUsers?: UserResponse[],
{
allowedTagNames = defaultAllowedTagNames,
customMarkDownRenderers,
getRehypePlugins = getPluginsForward,
getRemarkPlugins = getPluginsForward,
}: RenderTextOptions = {},
) => {
// take the @ mentions and turn them into markdown?
// translate links
if (!text) return null;
if (text.trim().length === 1) return <>{text}</>;
let newText = text;
const markdownLinks = matchMarkdownLinks(newText);
const codeBlocks = messageCodeBlocks(newText);
// Extract all valid links/emails within text and replace it with proper markup
// Revert the link order to avoid getting out of sync of the original start and end positions of links
// - due to the addition of new characters when creating Markdown links
const links = [...find(newText, 'email'), ...find(newText, 'url')];
for (let i = links.length - 1; i >= 0; i--) {
const { end, href, start, type, value } = links[i];
const linkIsInBlock = codeBlocks.some((block) => block?.includes(value));
// check if message is already markdown
const noParsingNeeded =
markdownLinks &&
markdownLinks.filter((text) => {
const strippedHref = href?.replace(detectHttp, '');
const strippedText = text?.replace(detectHttp, '');
if (!strippedHref || !strippedText) return false;
return strippedHref.includes(strippedText) || strippedText.includes(strippedHref);
});
if (noParsingNeeded.length > 0 || linkIsInBlock) continue;
try {
// special case for mentions:
// it could happen that a user's name matches with an e-mail format pattern.
// in that case, we check whether the found e-mail is actually a mention
// by naively checking for an existence of @ sign in front of it.
if (type === 'email' && mentionedUsers) {
const emailMatchesWithName = mentionedUsers.find((u) => u.name === value);
if (emailMatchesWithName) {
// FIXME: breaks if the mention symbol is not '@'
const isMention = newText.charAt(start - 1) === '@';
// in case of mention, we leave the match in its original form,
// and we let `mentionsMarkdownPlugin` to do its job
newText =
newText.slice(0, start) +
(isMention ? value : `[${value}](${encodeDecode(href)})`) +
newText.slice(end);
}
} else {
const displayLink = type === 'email' ? value : formatUrlForDisplay(href);
newText =
newText.slice(0, start) +
`[${displayLink}](${encodeDecode(href)})` +
newText.slice(end);
}
} catch (e) {
void e;
}
}
const remarkPlugins: PluggableList = [
htmlToTextPlugin,
keepLineBreaksPlugin,
[remarkGfm, { singleTilde: false }],
plusPlusToEmphasis,
imageToLink,
];
const rehypePlugins: PluggableList = [emojiMarkdownPlugin];
if (mentionedUsers?.length) {
rehypePlugins.push(mentionsMarkdownPlugin(mentionedUsers));
}
return (
<ErrorBoundary fallback={<>{text}</>}>
<ReactMarkdown
allowedElements={allowedTagNames}
components={{
...markDownRenderers,
...customMarkDownRenderers,
}}
rehypePlugins={getRehypePlugins(rehypePlugins)}
remarkPlugins={getRemarkPlugins(remarkPlugins)}
skipHtml
unwrapDisallowed
urlTransform={urlTransform}
>
{newText}
</ReactMarkdown>
</ErrorBoundary>
);
};