-
Notifications
You must be signed in to change notification settings - Fork 66
Expand file tree
/
Copy pathtiptapHtmlNormalizer.ts
More file actions
43 lines (37 loc) · 1.31 KB
/
Copy pathtiptapHtmlNormalizer.ts
File metadata and controls
43 lines (37 loc) · 1.31 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
import { sanitizeHtml } from '../sanitization/htmlSanitizer';
import {
checkboxHtmlForTiptap,
checkboxHtmlFromTiptap,
} from './checkboxHtmlNormalizer';
import { normalizeHtml } from './htmlNormalizer';
export function prepareHtmlForTiptap(
html: string,
useHtmlNormalizer: boolean | undefined
): string {
html = sanitizeHtml(html);
if (useHtmlNormalizer) {
html = normalizeHtml(html);
}
html = checkboxHtmlForTiptap(html);
html = html.replace(/<br\s*\/?>/gi, '<p></p>');
return html;
}
export function normalizeHtmlFromTiptap(html: string): string {
html = sanitizeHtml(html);
html = checkboxHtmlFromTiptap(html);
// Strip <p> wrappers inside <li> elements.
// TipTap renders <li><p>text</p></li> but native expects <li>text</li>.
// This regex is safe because EnrichedListItem.content is 'paragraph', which
// prevents TipTap from ever emitting nested lists
html = html.replace(/<li([^>]*)><p>(.*?)<\/p><\/li>/gs, '<li$1>$2</li>');
// Convert remaining empty <p></p> to <br> (outside of lists)
html = html.replace(/<p><\/p>/g, '<br>');
// Convert <img> tags to self-closing tags
html = html.replace(/<img\b([^>]*)>/gi, (_, attrs: string) => {
if (attrs.trimEnd().endsWith('/')) {
return `<img${attrs}>`;
}
return `<img${attrs}/>`;
});
return `<html>${html}</html>`;
}