forked from stack-auth/stack-auth
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhtml.tsx
More file actions
60 lines (46 loc) · 1.94 KB
/
html.tsx
File metadata and controls
60 lines (46 loc) · 1.94 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
import { templateIdentity } from "./strings";
export function escapeHtml(unsafe: string): string {
return `${unsafe}`
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, """)
.replace(/'/g, "'");
}
import.meta.vitest?.test("escapeHtml", ({ expect }) => {
// Test with empty string
expect(escapeHtml("")).toBe("");
// Test with string without special characters
expect(escapeHtml("hello world")).toBe("hello world");
// Test with special characters
expect(escapeHtml("<div>")).toBe("<div>");
expect(escapeHtml("a & b")).toBe("a & b");
expect(escapeHtml('a "quoted" string')).toBe("a "quoted" string");
expect(escapeHtml("it's a test")).toBe("it's a test");
// Test with multiple special characters
expect(escapeHtml("<a href=\"test\">It's a link</a>")).toBe(
"<a href="test">It's a link</a>"
);
});
export function html(strings: TemplateStringsArray, ...values: any[]): string {
return templateIdentity(strings, ...values.map(v => escapeHtml(`${v}`)));
}
import.meta.vitest?.test("html", ({ expect }) => {
// Test with no interpolation
expect(html`simple string`).toBe("simple string");
// Test with string interpolation
expect(html`Hello, ${"world"}!`).toBe("Hello, world!");
// Test with number interpolation
expect(html`Count: ${42}`).toBe("Count: 42");
// Test with HTML special characters in interpolated values
expect(html`<div>${"<script>"}</div>`).toBe("<div><script></div>");
// Test with multiple interpolations
expect(html`${1} + ${2} = ${"<3"}`).toBe("1 + 2 = <3");
// Test with object interpolation
const obj = { toString: () => "<object>" };
expect(html`Object: ${obj}`).toBe("Object: <object>");
});
export function htmlToText(untrustedHtml: string): string {
const doc = new DOMParser().parseFromString(untrustedHtml, 'text/html');
return doc.body.textContent ?? '';
}