-
Notifications
You must be signed in to change notification settings - Fork 74
/
Copy pathparseExpensiMark.ts
279 lines (257 loc) · 9.88 KB
/
parseExpensiMark.ts
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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
'worklet';
import {ExpensiMark} from 'expensify-common';
import {unescapeText} from 'expensify-common/dist/utils';
import type {MarkdownType, MarkdownRange} from './commonTypes';
const MAX_PARSABLE_LENGTH = 4000;
type Token = ['TEXT' | 'HTML', string];
type StackItem = {tag: string; children: Array<StackItem | string>};
function parseMarkdownToHTML(markdown: string): string {
const parser = new ExpensiMark();
const html = parser.replace(markdown, {
shouldKeepRawInput: true,
});
return html as string;
}
function parseHTMLToTokens(html: string): Token[] {
const tokens: Token[] = [];
let left = 0;
// eslint-disable-next-line no-constant-condition
while (true) {
const open = html.indexOf('<', left);
if (open === -1) {
if (left < html.length) {
tokens.push(['TEXT', html.substring(left)]);
}
break;
}
if (open !== left) {
tokens.push(['TEXT', html.substring(left, open)]);
}
const close = html.indexOf('>', open);
if (close === -1) {
throw new Error('[react-native-live-markdown] Error in function parseHTMLToTokens: Invalid HTML: no matching ">"');
}
tokens.push(['HTML', html.substring(open, close + 1)]);
left = close + 1;
}
return tokens;
}
function parseTokensToTree(tokens: Token[]): StackItem {
const stack: StackItem[] = [{tag: '<>', children: []}];
tokens.forEach(([type, payload]) => {
if (type === 'TEXT') {
const text = unescapeText(payload);
const top = stack[stack.length - 1];
top!.children.push(text);
} else if (type === 'HTML') {
if (payload.startsWith('</')) {
// closing tag
const child = stack.pop();
const top = stack[stack.length - 1];
top!.children.push(child!);
} else if (payload.endsWith('/>')) {
// self-closing tag
const top = stack[stack.length - 1];
top!.children.push({tag: payload, children: []});
} else {
// opening tag
stack.push({tag: payload, children: []});
}
} else {
throw new Error(
`[react-native-live-markdown] Error in function parseTokensToTree: Unknown token type: ${type as string}. Expected 'TEXT' or 'HTML'. Please ensure tokens only contain these types.`,
);
}
});
if (stack.length !== 1) {
const unclosedTags =
stack.length > 0
? stack
.slice(1)
.map((item) => item.tag)
.join(', ')
: '';
throw new Error(
`[react-native-live-markdown] Invalid HTML structure: the following tags are not properly closed: ${unclosedTags}. Ensure each opening tag has a corresponding closing tag.`,
);
}
return stack[0]!;
}
function parseTreeToTextAndRanges(tree: StackItem): [string, MarkdownRange[]] {
let text = '';
function processChildren(node: StackItem | string) {
if (typeof node === 'string') {
text += node;
} else {
node.children.forEach(dfs);
}
}
function appendSyntax(syntax: string) {
addChildrenWithStyle(syntax, 'syntax');
}
function addChildrenWithStyle(node: StackItem | string, type: MarkdownType) {
const start = text.length;
processChildren(node);
const end = text.length;
ranges.push({type, start, length: end - start});
}
const ranges: MarkdownRange[] = [];
function dfs(node: StackItem | string) {
if (typeof node === 'string') {
text += node;
} else {
// eslint-disable-next-line no-lonely-if
if (node.tag === '<>') {
processChildren(node);
} else if (node.tag === '<strong>') {
appendSyntax('*');
addChildrenWithStyle(node, 'bold');
appendSyntax('*');
} else if (node.tag === '<em>') {
appendSyntax('_');
addChildrenWithStyle(node, 'italic');
appendSyntax('_');
} else if (node.tag === '<del>') {
appendSyntax('~');
addChildrenWithStyle(node, 'strikethrough');
appendSyntax('~');
} else if (node.tag === '<emoji>') {
addChildrenWithStyle(node, 'emoji');
} else if (node.tag === '<code>') {
appendSyntax('`');
addChildrenWithStyle(node, 'code');
appendSyntax('`');
} else if (node.tag === '<mention-here>') {
addChildrenWithStyle(node, 'mention-here');
} else if (node.tag === '<mention-user>') {
addChildrenWithStyle(node, 'mention-user');
} else if (node.tag === '<mention-report>') {
addChildrenWithStyle(node, 'mention-report');
} else if (node.tag === '<blockquote>') {
appendSyntax('>');
addChildrenWithStyle(node, 'blockquote');
// compensate for "> " at the beginning
if (ranges.length > 0) {
const curr = ranges[ranges.length - 1];
curr!.start -= 1;
curr!.length += 1;
}
} else if (node.tag === '<h1>') {
appendSyntax('# ');
addChildrenWithStyle(node, 'h1');
} else if (node.tag === '<br />') {
text += '\n';
} else if (node.tag.startsWith('<pre')) {
appendSyntax('```');
const content = node.children.join('').replaceAll(' ', ' ');
addChildrenWithStyle(content, 'pre');
appendSyntax('```');
} else if (node.tag.startsWith('<a href="')) {
const rawHref = node.tag.match(/href="([^"]*)"/)![1]!; // always present
const href = unescapeText(rawHref);
const isLabeledLink = node.tag.match(/data-link-variant="([^"]*)"/)![1] === 'labeled';
const dataRawHref = node.tag.match(/data-raw-href="([^"]*)"/);
const matchString = dataRawHref ? unescapeText(dataRawHref[1]!) : href;
if (!isLabeledLink && node.children.length === 1 && typeof node.children[0] === 'string' && (node.children[0] === matchString || `mailto:${node.children[0]}` === href)) {
addChildrenWithStyle(node.children[0], 'link');
} else {
appendSyntax('[');
processChildren(node);
appendSyntax('](');
addChildrenWithStyle(matchString, 'link');
appendSyntax(')');
}
} else if (node.tag.startsWith('<img src="')) {
const src = node.tag.match(/src="([^"]*)"/)![1]!; // always present
const alt = node.tag.match(/alt="([^"]*)"/);
const hasAlt = node.tag.match(/data-link-variant="([^"]*)"/)![1] === 'labeled';
const rawLink = node.tag.match(/data-raw-href="([^"]*)"/);
const linkString = rawLink ? unescapeText(rawLink[1]!) : src;
const start = text.length;
const length = 3 + (hasAlt ? 2 + unescapeText(alt?.[1] || '').length : 0) + linkString.length;
ranges.push({type: 'inline-image', start, length});
appendSyntax('!');
if (hasAlt) {
appendSyntax('[');
processChildren(unescapeText(alt?.[1] || ''));
appendSyntax(']');
}
appendSyntax('(');
addChildrenWithStyle(linkString, 'link');
appendSyntax(')');
} else if (node.tag.startsWith('<video data-expensify-source="')) {
const src = node.tag.match(/data-expensify-source="([^"]*)"/)![1]!; // always present
const rawLink = node.tag.match(/data-raw-href="([^"]*)"/);
const hasAlt = node.tag.match(/data-link-variant="([^"]*)"/)![1] === 'labeled';
const linkString = rawLink ? unescapeText(rawLink[1]!) : src;
appendSyntax('!');
if (hasAlt) {
appendSyntax('[');
node.children.forEach((child) => processChildren(child));
appendSyntax(']');
}
appendSyntax('(');
addChildrenWithStyle(linkString, 'link');
appendSyntax(')');
} else {
throw new Error(`[react-native-live-markdown] Error in function parseTreeToTextAndRanges: Unknown tag '${node.tag}'. This tag is not supported in this function's logic.`);
}
}
}
dfs(tree);
return [text, ranges];
}
// getTagPriority returns a priority for a tag, higher priority means the tag should be processed first
function getTagPriority(tag: string) {
switch (tag) {
case 'blockquote':
return 2;
case 'h1':
return 1;
case 'emoji':
return -1;
default:
return 0;
}
}
function sortRanges(ranges: MarkdownRange[]) {
// sort ranges by start position, then by length, then by tag hierarchy
return ranges.sort((a, b) => a.start - b.start || b.length - a.length || getTagPriority(b.type) - getTagPriority(a.type) || 0);
}
function groupRanges(ranges: MarkdownRange[]) {
const lastVisibleRangeIndex: {[key in MarkdownType]?: number} = {};
return ranges.reduce((acc, range) => {
const start = range.start;
const end = range.start + range.length;
const rangeWithSameStyleIndex = lastVisibleRangeIndex[range.type];
const sameStyleRange = rangeWithSameStyleIndex !== undefined ? acc[rangeWithSameStyleIndex] : undefined;
if (sameStyleRange && sameStyleRange.start <= start && sameStyleRange.start + sameStyleRange.length >= end && range.length > 1) {
// increment depth of overlapping range
sameStyleRange.depth = (sameStyleRange.depth || 1) + 1;
} else {
lastVisibleRangeIndex[range.type] = acc.length;
acc.push(range);
}
return acc;
}, [] as MarkdownRange[]);
}
function parseExpensiMark(markdown: string): MarkdownRange[] {
if (markdown.length > MAX_PARSABLE_LENGTH) {
return [];
}
const html = parseMarkdownToHTML(markdown);
const tokens = parseHTMLToTokens(html);
const tree = parseTokensToTree(tokens);
const [text, ranges] = parseTreeToTextAndRanges(tree);
if (text !== markdown) {
throw new Error(
`[react-native-live-markdown] Parsing error: the processed text does not match the original Markdown input. This may be caused by incorrect parsing functions or invalid input Markdown.\nProcessed input: '${JSON.stringify(
text,
)}'\nOriginal input: '${JSON.stringify(markdown)}'`,
);
}
const sortedRanges = sortRanges(ranges);
const groupedRanges = groupRanges(sortedRanges);
return groupedRanges;
}
export default parseExpensiMark;