-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathText.svelte
33 lines (26 loc) · 973 Bytes
/
Text.svelte
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
<script lang="ts">
import type { Node, Text } from "@contentful/rich-text-types";
import escape from "lodash/escape";
import { isText } from "../predicates";
type MarkType = "bold" | "code" | "italic" | "subscript" | "superscript" | "underline";
export let node: Node;
let textNode: Text;
if (!isText(node)) {
throw new Error("node is not text");
}
textNode = node;
const wrapWith = (open: string, close: string) => (text: string) => `${open}${text}${close}`;
const wrappers: Record<MarkType, (text: string) => string> = {
bold: wrapWith("<strong>", "</strong>"),
code: wrapWith("<code>", "</code>"),
italic: wrapWith("<em>", "</em>"),
subscript: wrapWith("<sub>", "</sub>"),
superscript: wrapWith("<sup>", "</sup>"),
underline: wrapWith("<u>", "</u>"),
};
const wrapped = textNode.marks.reduce(
(text, { type }) => wrappers[type as MarkType](text),
escape(textNode.value)
);
</script>
{@html wrapped}