@supatype/common 0.3.6 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.turbo/turbo-build.log +1 -1
- package/.turbo/turbo-test.log +14 -0
- package/.turbo/turbo-typecheck.log +2 -2
- package/LICENSE +1 -1
- package/dist/analytics.d.ts.map +1 -1
- package/dist/analytics.js.map +1 -1
- package/dist/auth.d.ts.map +1 -1
- package/dist/auth.js +11 -1
- package/dist/auth.js.map +1 -1
- package/dist/build-env.d.ts +7 -0
- package/dist/build-env.d.ts.map +1 -0
- package/dist/build-env.js +17 -0
- package/dist/build-env.js.map +1 -0
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +2 -6
- package/dist/config.js.map +1 -1
- package/dist/content.d.ts.map +1 -1
- package/dist/content.js +2 -6
- package/dist/content.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/richtext-tree.d.ts +55 -0
- package/dist/richtext-tree.d.ts.map +1 -0
- package/dist/richtext-tree.js +208 -0
- package/dist/richtext-tree.js.map +1 -0
- package/dist/richtext.d.ts +8 -67
- package/dist/richtext.d.ts.map +1 -1
- package/dist/richtext.js +59 -80
- package/dist/richtext.js.map +1 -1
- package/package.json +8 -4
- package/src/analytics.ts +3 -2
- package/src/auth.ts +10 -1
- package/src/build-env.ts +16 -0
- package/src/config.ts +3 -5
- package/src/content.ts +2 -5
- package/src/index.ts +1 -1
- package/src/posthog-js.d.ts +1 -1
- package/src/richtext-tree.ts +274 -0
- package/src/richtext.ts +67 -112
- package/tests/fixtures/lexical-code-block.json +92 -0
- package/tests/fixtures/lexical-documents.json +1345 -0
- package/tests/richtext-cases.ts +154 -0
- package/tests/richtext.test.ts +73 -0
- package/tests/tsconfig.json +10 -0
- package/tsconfig.json +3 -2
- package/tsconfig.tsbuildinfo +1 -1
package/dist/richtext.js
CHANGED
|
@@ -1,89 +1,68 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Rich text rendering:
|
|
2
|
+
* Rich text rendering: prints a saved Lexical document as an HTML string.
|
|
3
|
+
*
|
|
4
|
+
* The document is walked once by `richTextTree` (shared with the React renderer); this module only
|
|
5
|
+
* prints that tree, escaping every text run and attribute value.
|
|
3
6
|
*/
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
};
|
|
7
|
+
import { richTextTree } from "./richtext-tree.js";
|
|
8
|
+
export { richTextTree, safeHref, } from "./richtext-tree.js";
|
|
9
|
+
const VOID_TAGS = new Set(["br", "hr", "input"]);
|
|
10
|
+
const ESCAPES = { "&": "&", "<": "<", ">": ">", '"': """, "'": "'" };
|
|
9
11
|
function escapeHtml(text) {
|
|
10
|
-
return text
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
.replace(/
|
|
15
|
-
.
|
|
12
|
+
return text.replace(/[&<>"']/g, (char) => ESCAPES[char] ?? char);
|
|
13
|
+
}
|
|
14
|
+
function styleText(style) {
|
|
15
|
+
return Object.entries(style)
|
|
16
|
+
.map(([property, value]) => `${property.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`)}:${value}`)
|
|
17
|
+
.join(";");
|
|
16
18
|
}
|
|
17
|
-
|
|
18
|
-
|
|
19
|
+
/** Every attribute an element can carry: the compiler checks this names each one, and no other. */
|
|
20
|
+
const ATTRIBUTE_NAMES = {
|
|
21
|
+
href: true,
|
|
22
|
+
rel: true,
|
|
23
|
+
target: true,
|
|
24
|
+
title: true,
|
|
25
|
+
dir: true,
|
|
26
|
+
start: true,
|
|
27
|
+
value: true,
|
|
28
|
+
class: true,
|
|
29
|
+
type: true,
|
|
30
|
+
checked: true,
|
|
31
|
+
disabled: true,
|
|
32
|
+
style: true,
|
|
33
|
+
};
|
|
34
|
+
function isAttributeName(name) {
|
|
35
|
+
return Object.hasOwn(ATTRIBUTE_NAMES, name);
|
|
36
|
+
}
|
|
37
|
+
function attributeText(attributes) {
|
|
38
|
+
let out = "";
|
|
39
|
+
// `Object.entries` types an interface's values as `any`; read each through its own key instead.
|
|
40
|
+
for (const name of Object.keys(attributes).filter(isAttributeName)) {
|
|
41
|
+
const value = attributes[name];
|
|
42
|
+
if (value === undefined || value === false)
|
|
43
|
+
continue;
|
|
44
|
+
if (value === true)
|
|
45
|
+
out += ` ${name}`;
|
|
46
|
+
else if (typeof value === "object")
|
|
47
|
+
out += ` ${name}="${escapeHtml(styleText(value))}"`;
|
|
48
|
+
else
|
|
49
|
+
out += ` ${name}="${escapeHtml(String(value))}"`;
|
|
50
|
+
}
|
|
51
|
+
return out;
|
|
52
|
+
}
|
|
53
|
+
function printChild(child) {
|
|
54
|
+
if (typeof child === "string")
|
|
55
|
+
return escapeHtml(child);
|
|
56
|
+
const attributes = attributeText(child.attributes);
|
|
57
|
+
if (VOID_TAGS.has(child.tag))
|
|
58
|
+
return `<${child.tag}${attributes} />`;
|
|
59
|
+
return `<${child.tag}${attributes}>${child.children.map(printChild).join("")}</${child.tag}>`;
|
|
19
60
|
}
|
|
20
61
|
/**
|
|
21
|
-
*
|
|
62
|
+
* Print a saved Lexical document (the editor state, its root node, or a list of nodes) as HTML.
|
|
63
|
+
* Null, undefined and anything else that is not a document print as an empty string.
|
|
22
64
|
*/
|
|
23
|
-
export function renderRichText(
|
|
24
|
-
|
|
25
|
-
case "root":
|
|
26
|
-
return renderChildren(node.children);
|
|
27
|
-
case "heading":
|
|
28
|
-
return `<${node.tag}>${renderChildren(node.children)}</${node.tag}>`;
|
|
29
|
-
case "paragraph":
|
|
30
|
-
return `<p>${renderChildren(node.children)}</p>`;
|
|
31
|
-
case "text": {
|
|
32
|
-
let html = escapeHtml(node.text);
|
|
33
|
-
if (node.format?.code)
|
|
34
|
-
html = `<code>${html}</code>`;
|
|
35
|
-
if (node.format?.bold)
|
|
36
|
-
html = `<strong>${html}</strong>`;
|
|
37
|
-
if (node.format?.italic)
|
|
38
|
-
html = `<em>${html}</em>`;
|
|
39
|
-
return html;
|
|
40
|
-
}
|
|
41
|
-
case "link":
|
|
42
|
-
return `<a href="${escapeHtml(node.url)}">${renderChildren(node.children)}</a>`;
|
|
43
|
-
case "code":
|
|
44
|
-
return `<pre><code class="language-${escapeHtml(node.language)}">${escapeHtml(node.code)}</code></pre>`;
|
|
45
|
-
case "image": {
|
|
46
|
-
const attrs = [
|
|
47
|
-
`src="${escapeHtml(node.src)}"`,
|
|
48
|
-
`alt="${escapeHtml(node.alt)}"`,
|
|
49
|
-
...(node.width !== undefined ? [`width="${node.width}"`] : []),
|
|
50
|
-
...(node.height !== undefined ? [`height="${node.height}"`] : []),
|
|
51
|
-
];
|
|
52
|
-
return `<img ${attrs.join(" ")} />`;
|
|
53
|
-
}
|
|
54
|
-
case "blockquote":
|
|
55
|
-
return `<blockquote>${renderChildren(node.children)}</blockquote>`;
|
|
56
|
-
case "list": {
|
|
57
|
-
const tag = node.listType === "ordered" ? "ol" : "ul";
|
|
58
|
-
return `<${tag}>${renderChildren(node.children)}</${tag}>`;
|
|
59
|
-
}
|
|
60
|
-
case "listitem":
|
|
61
|
-
return `<li>${renderChildren(node.children)}</li>`;
|
|
62
|
-
case "horizontalrule":
|
|
63
|
-
return `<hr />`;
|
|
64
|
-
case "callout":
|
|
65
|
-
return `<div class="callout callout-${node.variant}">${CALLOUT_ICONS[node.variant]} ${renderChildren(node.children)}</div>`;
|
|
66
|
-
case "code-tabs": {
|
|
67
|
-
const buttons = node.tabs
|
|
68
|
-
.map((tab, i) => `<button class="code-tab-button${i === 0 ? " active" : ""}" data-tab="${i}">${escapeHtml(tab.label)}</button>`)
|
|
69
|
-
.join("");
|
|
70
|
-
const panels = node.tabs
|
|
71
|
-
.map((tab, i) => `<div class="code-tab-panel${i === 0 ? " active" : ""}" data-tab="${i}"><pre><code class="language-${escapeHtml(tab.language)}">${escapeHtml(tab.code)}</code></pre></div>`)
|
|
72
|
-
.join("");
|
|
73
|
-
return `<div class="code-tabs"><div class="code-tabs-buttons">${buttons}</div>${panels}</div>`;
|
|
74
|
-
}
|
|
75
|
-
case "cta":
|
|
76
|
-
return `<a class="cta-button" href="${escapeHtml(node.url)}">${escapeHtml(node.text)}</a>`;
|
|
77
|
-
case "embed": {
|
|
78
|
-
if (node.provider === "youtube") {
|
|
79
|
-
return `<iframe src="https://www.youtube-nocookie.com/embed/${escapeHtml(node.embedId)}" frameborder="0" allowfullscreen loading="lazy"></iframe>`;
|
|
80
|
-
}
|
|
81
|
-
return `<iframe src="https://codesandbox.io/embed/${escapeHtml(node.embedId)}" frameborder="0" allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking" sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts" loading="lazy"></iframe>`;
|
|
82
|
-
}
|
|
83
|
-
default: {
|
|
84
|
-
const _exhaustive = node;
|
|
85
|
-
return "";
|
|
86
|
-
}
|
|
87
|
-
}
|
|
65
|
+
export function renderRichText(content) {
|
|
66
|
+
return richTextTree(content).map(printChild).join("");
|
|
88
67
|
}
|
|
89
68
|
//# sourceMappingURL=richtext.js.map
|
package/dist/richtext.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"richtext.js","sourceRoot":"","sources":["../src/richtext.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"richtext.js","sourceRoot":"","sources":["../src/richtext.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,YAAY,EAAyF,MAAM,oBAAoB,CAAA;AAExI,OAAO,EACL,YAAY,EACZ,QAAQ,GAQT,MAAM,oBAAoB,CAAA;AAE3B,MAAM,SAAS,GAAwB,IAAI,GAAG,CAAC,CAAC,IAAI,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC,CAAA;AAErE,MAAM,OAAO,GAAqC,EAAE,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,EAA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"license": "MIT",
|
|
5
5
|
"description": "Shared auth, config, and analytics for Supatype web apps",
|
|
6
6
|
"type": "module",
|
|
@@ -29,14 +29,18 @@
|
|
|
29
29
|
}
|
|
30
30
|
},
|
|
31
31
|
"dependencies": {
|
|
32
|
-
"@supatype/client": "0.
|
|
32
|
+
"@supatype/client": "0.8.0",
|
|
33
|
+
"@supatype/types": "0.8.0"
|
|
33
34
|
},
|
|
34
35
|
"devDependencies": {
|
|
35
|
-
"
|
|
36
|
+
"@types/node": "^22",
|
|
37
|
+
"typescript": "^5",
|
|
38
|
+
"vitest": "^4.0.18"
|
|
36
39
|
},
|
|
37
40
|
"scripts": {
|
|
38
41
|
"build": "tsc --project tsconfig.json",
|
|
39
|
-
"typecheck": "tsc --project tsconfig.json --noEmit",
|
|
42
|
+
"typecheck": "tsc --project tsconfig.json --noEmit && tsc --project tests/tsconfig.json --noEmit",
|
|
43
|
+
"test": "vitest run",
|
|
40
44
|
"clean": "rm -rf dist *.tsbuildinfo"
|
|
41
45
|
}
|
|
42
46
|
}
|
package/src/analytics.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { PostHog } from "posthog-js"
|
|
1
2
|
import { config } from "./config.js"
|
|
2
3
|
|
|
3
4
|
interface AnalyticsClient {
|
|
@@ -9,7 +10,7 @@ interface AnalyticsClient {
|
|
|
9
10
|
}
|
|
10
11
|
|
|
11
12
|
class PostHogAnalytics implements AnalyticsClient {
|
|
12
|
-
private posthog:
|
|
13
|
+
private posthog: PostHog | null = null
|
|
13
14
|
private initialized = false
|
|
14
15
|
|
|
15
16
|
private async init(): Promise<void> {
|
|
@@ -25,7 +26,7 @@ class PostHogAnalytics implements AnalyticsClient {
|
|
|
25
26
|
persistence: "localStorage+cookie",
|
|
26
27
|
respect_dnt: true,
|
|
27
28
|
})
|
|
28
|
-
this.posthog = ph.default
|
|
29
|
+
this.posthog = ph.default
|
|
29
30
|
} catch {
|
|
30
31
|
// PostHog not available: analytics disabled
|
|
31
32
|
}
|
package/src/auth.ts
CHANGED
|
@@ -21,8 +21,17 @@ export function getPlatformUser(): PlatformUser | null {
|
|
|
21
21
|
.find((c) => c.startsWith("st-platform-user="))
|
|
22
22
|
if (!cookie) return null
|
|
23
23
|
try {
|
|
24
|
-
|
|
24
|
+
const user = JSON.parse(decodeURIComponent(cookie.split("=")[1]!))
|
|
25
|
+
return isPlatformUser(user) ? user : null
|
|
25
26
|
} catch {
|
|
26
27
|
return null
|
|
27
28
|
}
|
|
28
29
|
}
|
|
30
|
+
|
|
31
|
+
/** The cookie's value, when it has the name and email this reads, and an avatar only as text. */
|
|
32
|
+
function isPlatformUser(value: unknown): value is PlatformUser {
|
|
33
|
+
if (typeof value !== "object" || value === null) return false
|
|
34
|
+
if (!("name" in value) || !("email" in value)) return false
|
|
35
|
+
const avatarIsTextOrAbsent = !("avatar" in value) || value.avatar === undefined || typeof value.avatar === "string"
|
|
36
|
+
return typeof value.name === "string" && typeof value.email === "string" && avatarIsTextOrAbsent
|
|
37
|
+
}
|
package/src/build-env.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
2
|
+
return typeof value === "object" && value !== null
|
|
3
|
+
}
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* A variable a bundler put on `import.meta.env` (Vite and its kin), when there is one and it is a
|
|
7
|
+
* non-empty string. Read through checks rather than a declared type: `import.meta.env` exists only
|
|
8
|
+
* when a bundler made it, and holds whatever that bundler put there.
|
|
9
|
+
*/
|
|
10
|
+
export function importMetaEnv(name: string): string | undefined {
|
|
11
|
+
if (typeof import.meta === "undefined") return undefined
|
|
12
|
+
const meta: unknown = import.meta
|
|
13
|
+
const env = isRecord(meta) ? meta["env"] : undefined
|
|
14
|
+
const value = isRecord(env) ? env[name] : undefined
|
|
15
|
+
return typeof value === "string" && value !== "" ? value : undefined
|
|
16
|
+
}
|
package/src/config.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { importMetaEnv } from "./build-env.js"
|
|
2
|
+
|
|
1
3
|
export type AppEnvironment = "development" | "staging" | "production"
|
|
2
4
|
|
|
3
5
|
function detectEnvironment(): AppEnvironment {
|
|
@@ -10,11 +12,7 @@ function detectEnvironment(): AppEnvironment {
|
|
|
10
12
|
|
|
11
13
|
function getEnvVar(name: string, fallback: string): string {
|
|
12
14
|
// Vite-style env vars
|
|
13
|
-
|
|
14
|
-
const env = (import.meta as unknown as { env?: Record<string, string> }).env
|
|
15
|
-
if (env?.[name]) return env[name]
|
|
16
|
-
}
|
|
17
|
-
return fallback
|
|
15
|
+
return importMetaEnv(name) ?? fallback
|
|
18
16
|
}
|
|
19
17
|
|
|
20
18
|
export const config = {
|
package/src/content.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { createClient } from "@supatype/client"
|
|
2
|
+
import { importMetaEnv } from "./build-env.js"
|
|
2
3
|
|
|
3
4
|
declare const process: { env?: Record<string, string | undefined> } | undefined
|
|
4
5
|
|
|
@@ -7,11 +8,7 @@ function getContentEnv(name: string): string {
|
|
|
7
8
|
if (proc?.env?.[name]) {
|
|
8
9
|
return proc.env[name]!
|
|
9
10
|
}
|
|
10
|
-
|
|
11
|
-
const env = (import.meta as unknown as { env?: Record<string, string> }).env
|
|
12
|
-
if (env?.[name]) return env[name]
|
|
13
|
-
}
|
|
14
|
-
return ""
|
|
11
|
+
return importMetaEnv(name) ?? ""
|
|
15
12
|
}
|
|
16
13
|
|
|
17
14
|
/**
|
package/src/index.ts
CHANGED
|
@@ -2,4 +2,4 @@ export { platformClient, getPlatformUser, type PlatformUser } from "./auth.js"
|
|
|
2
2
|
export { config, type AppEnvironment } from "./config.js"
|
|
3
3
|
export { analytics } from "./analytics.js"
|
|
4
4
|
export { contentClient } from "./content.js"
|
|
5
|
-
export { renderRichText, type RichTextNode } from "./richtext.js"
|
|
5
|
+
export { renderRichText, richTextTree, type RichTextContent, type RichTextNode } from "./richtext.js"
|
package/src/posthog-js.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
declare module "posthog-js" {
|
|
2
|
-
interface PostHog {
|
|
2
|
+
export interface PostHog {
|
|
3
3
|
init(token: string, config?: Record<string, unknown>): void
|
|
4
4
|
capture(event: string, properties?: Record<string, unknown>): void
|
|
5
5
|
identify(userId: string, properties?: Record<string, unknown>): void
|
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The one walker over saved Lexical JSON. It turns a document into a small element tree that each
|
|
3
|
+
* renderer (the HTML string here, React elements in @supatype/react) prints without knowing
|
|
4
|
+
* anything about Lexical, so every renderer shows the same thing for the same document.
|
|
5
|
+
*
|
|
6
|
+
* Saved JSON is untrusted: it came out of a database column that any API client can write. Every
|
|
7
|
+
* field is read with a type check, a link's URL is only emitted for a safe scheme, and a node type
|
|
8
|
+
* this walker does not know still shows its words rather than vanishing.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import type {
|
|
12
|
+
ElementFormat,
|
|
13
|
+
SerializedEditorState,
|
|
14
|
+
SerializedHeadingNode,
|
|
15
|
+
SerializedLexicalNode,
|
|
16
|
+
SerializedListNode,
|
|
17
|
+
} from "@supatype/types/lexical"
|
|
18
|
+
|
|
19
|
+
export type RichTextNode = SerializedLexicalNode
|
|
20
|
+
|
|
21
|
+
/** Anything a `RichText` column holds: the editor state, its root node, or a list of nodes. */
|
|
22
|
+
export type RichTextContent = SerializedEditorState | RichTextNode | readonly RichTextNode[] | null | undefined
|
|
23
|
+
|
|
24
|
+
export type RichTextTag =
|
|
25
|
+
| "p" | "h1" | "h2" | "h3" | "h4" | "h5" | "h6" | "blockquote" | "ul" | "ol" | "li" | "a" | "br"
|
|
26
|
+
| "hr" | "pre" | "code" | "strong" | "em" | "s" | "u" | "sub" | "sup" | "mark" | "span" | "input"
|
|
27
|
+
|
|
28
|
+
export interface RichTextStyle {
|
|
29
|
+
textAlign?: string
|
|
30
|
+
paddingInlineStart?: string
|
|
31
|
+
textTransform?: string
|
|
32
|
+
listStyleType?: string
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface RichTextAttributes {
|
|
36
|
+
href?: string
|
|
37
|
+
rel?: string
|
|
38
|
+
target?: string
|
|
39
|
+
title?: string
|
|
40
|
+
dir?: "ltr" | "rtl"
|
|
41
|
+
start?: number
|
|
42
|
+
value?: number
|
|
43
|
+
class?: string
|
|
44
|
+
type?: "checkbox"
|
|
45
|
+
checked?: boolean
|
|
46
|
+
disabled?: boolean
|
|
47
|
+
style?: RichTextStyle
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export interface RichTextElement {
|
|
51
|
+
tag: RichTextTag
|
|
52
|
+
attributes: RichTextAttributes
|
|
53
|
+
children: RichTextChild[]
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export type RichTextChild = RichTextElement | string
|
|
57
|
+
|
|
58
|
+
type ListType = SerializedListNode["listType"]
|
|
59
|
+
|
|
60
|
+
interface WalkContext {
|
|
61
|
+
inCode: boolean
|
|
62
|
+
listType: ListType | null
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
type NodeRenderer = (node: RichTextNode, context: WalkContext) => RichTextChild[]
|
|
66
|
+
|
|
67
|
+
const TOP: WalkContext = { inCode: false, listType: null }
|
|
68
|
+
|
|
69
|
+
/** Text format bits, innermost wrapper first. */
|
|
70
|
+
const FORMAT_TAGS: ReadonlyArray<readonly [bit: number, tag: RichTextTag]> = [
|
|
71
|
+
[16, "code"], [32, "sub"], [64, "sup"], [128, "mark"], [8, "u"], [4, "s"], [2, "em"], [1, "strong"],
|
|
72
|
+
]
|
|
73
|
+
|
|
74
|
+
const TEXT_TRANSFORMS: ReadonlyArray<readonly [bit: number, value: string]> = [
|
|
75
|
+
[256, "lowercase"], [512, "uppercase"], [1024, "capitalize"],
|
|
76
|
+
]
|
|
77
|
+
|
|
78
|
+
type HeadingTag = SerializedHeadingNode["tag"]
|
|
79
|
+
|
|
80
|
+
const HEADING_TAGS: ReadonlySet<string> = new Set<HeadingTag>(["h1", "h2", "h3", "h4", "h5", "h6"])
|
|
81
|
+
const ALIGNMENTS: ReadonlySet<string> = new Set<ElementFormat>(["left", "start", "center", "right", "end", "justify"])
|
|
82
|
+
const LIST_TYPES: ReadonlySet<string> = new Set<ListType>(["bullet", "number", "check"])
|
|
83
|
+
const SAFE_PROTOCOLS: ReadonlySet<string> = new Set(["http", "https", "mailto", "tel", "sms"])
|
|
84
|
+
const LINK_TARGETS: ReadonlySet<string> = new Set(["_blank", "_self", "_parent", "_top"])
|
|
85
|
+
|
|
86
|
+
function isNode(value: unknown): value is RichTextNode {
|
|
87
|
+
return typeof value === "object" && value !== null && "type" in value && typeof value.type === "string"
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function isHeadingTag(value: string | undefined): value is HeadingTag {
|
|
91
|
+
return value !== undefined && HEADING_TAGS.has(value)
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function isListType(value: string | undefined): value is ListType {
|
|
95
|
+
return value !== undefined && LIST_TYPES.has(value)
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function stringField(node: RichTextNode, key: string): string | undefined {
|
|
99
|
+
const value = node[key]
|
|
100
|
+
return typeof value === "string" ? value : undefined
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function integerField(node: RichTextNode, key: string): number | undefined {
|
|
104
|
+
const value = node[key]
|
|
105
|
+
return typeof value === "number" && Number.isInteger(value) ? value : undefined
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function element(tag: RichTextTag, attributes: RichTextAttributes = {}, children: RichTextChild[] = []): RichTextElement {
|
|
109
|
+
return { tag, attributes, children }
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function walkChildren(node: RichTextNode, context: WalkContext): RichTextChild[] {
|
|
113
|
+
const children: unknown = node.children
|
|
114
|
+
if (!Array.isArray(children)) return []
|
|
115
|
+
return children.flatMap((child: unknown) => (isNode(child) ? walk(child, context) : []))
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Alignment, indent and direction: the attributes every block element shares. */
|
|
119
|
+
function blockAttributes(node: RichTextNode): RichTextAttributes {
|
|
120
|
+
const format = stringField(node, "format")
|
|
121
|
+
const indent = integerField(node, "indent")
|
|
122
|
+
const direction = stringField(node, "direction")
|
|
123
|
+
const style: RichTextStyle = {
|
|
124
|
+
...(format !== undefined && ALIGNMENTS.has(format) && { textAlign: format }),
|
|
125
|
+
...(indent !== undefined && indent > 0 && { paddingInlineStart: `calc(${indent} * 40px)` }),
|
|
126
|
+
}
|
|
127
|
+
return {
|
|
128
|
+
...((direction === "ltr" || direction === "rtl") && { dir: direction }),
|
|
129
|
+
...(Object.keys(style).length > 0 && { style }),
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function textRun(node: RichTextNode, context: WalkContext): RichTextChild[] {
|
|
134
|
+
const text = stringField(node, "text") ?? ""
|
|
135
|
+
if (text === "") return []
|
|
136
|
+
const format = context.inCode ? 0 : (integerField(node, "format") ?? 0)
|
|
137
|
+
let out: RichTextChild = text
|
|
138
|
+
for (const [bit, value] of TEXT_TRANSFORMS) {
|
|
139
|
+
if (format & bit) out = element("span", { style: { textTransform: value } }, [out])
|
|
140
|
+
}
|
|
141
|
+
for (const [bit, tag] of FORMAT_TAGS) {
|
|
142
|
+
if (format & bit) out = element(tag, {}, [out])
|
|
143
|
+
}
|
|
144
|
+
return [out]
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function paragraph(node: RichTextNode, context: WalkContext): RichTextChild[] {
|
|
148
|
+
const children = walkChildren(node, context)
|
|
149
|
+
// An empty paragraph keeps its line, as Lexical's own HTML export does.
|
|
150
|
+
return [element("p", blockAttributes(node), children.length > 0 ? children : [element("br")])]
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function heading(node: RichTextNode, context: WalkContext): RichTextChild[] {
|
|
154
|
+
const tag = stringField(node, "tag")
|
|
155
|
+
if (!isHeadingTag(tag)) return paragraph(node, context)
|
|
156
|
+
return [element(tag, blockAttributes(node), walkChildren(node, context))]
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function list(node: RichTextNode, context: WalkContext): RichTextChild[] {
|
|
160
|
+
const raw = stringField(node, "listType")
|
|
161
|
+
const listType: ListType = isListType(raw) ? raw : "bullet"
|
|
162
|
+
const start = integerField(node, "start")
|
|
163
|
+
const ordered = listType === "number"
|
|
164
|
+
const attributes: RichTextAttributes = ordered && start !== undefined && start !== 1 ? { start } : {}
|
|
165
|
+
return [element(ordered ? "ol" : "ul", attributes, walkChildren(node, { ...context, listType }))]
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** A nested list lives in a list item of its own, which carries no marker and no number. */
|
|
169
|
+
function holdsOnlyLists(node: RichTextNode): boolean {
|
|
170
|
+
const children: unknown = node.children
|
|
171
|
+
return Array.isArray(children) && children.length > 0 && children.every((c: unknown) => isNode(c) && c.type === "list")
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function listItem(node: RichTextNode, context: WalkContext): RichTextChild[] {
|
|
175
|
+
const children = walkChildren(node, context)
|
|
176
|
+
if (holdsOnlyLists(node)) return [element("li", { style: { listStyleType: "none" } }, children)]
|
|
177
|
+
const value = integerField(node, "value")
|
|
178
|
+
const attributes: RichTextAttributes = context.listType === "number" && value !== undefined ? { value } : {}
|
|
179
|
+
if (context.listType !== "check") return [element("li", attributes, children)]
|
|
180
|
+
const checkbox = element("input", { type: "checkbox", ...(node["checked"] === true && { checked: true }), disabled: true })
|
|
181
|
+
return [element("li", attributes, [checkbox, ...children])]
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* The URL a link may point at, or undefined when it must not be a link at all. Browsers drop tabs
|
|
186
|
+
* and newlines anywhere in a URL and control characters around it, so `java\tscript:` is checked
|
|
187
|
+
* the way a browser would read it. Anything with a scheme outside the allow list is refused;
|
|
188
|
+
* a URL with no scheme is relative and stays.
|
|
189
|
+
*/
|
|
190
|
+
export function safeHref(url: string | undefined): string | undefined {
|
|
191
|
+
if (url === undefined) return undefined
|
|
192
|
+
const normalized = url.replace(/[\t\n\r]/g, "").replace(/^[\x00-\x20]+|[\x00-\x20]+$/g, "")
|
|
193
|
+
if (normalized === "") return undefined
|
|
194
|
+
const scheme = /^([a-z][a-z0-9+.-]*):/i.exec(normalized)?.[1]
|
|
195
|
+
if (scheme !== undefined && !SAFE_PROTOCOLS.has(scheme.toLowerCase())) return undefined
|
|
196
|
+
return normalized
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
function relFor(rel: string | undefined, target: string | undefined): string | undefined {
|
|
200
|
+
const tokens = (rel ?? "").split(/\s+/).filter((token) => token !== "")
|
|
201
|
+
if (target === "_blank") {
|
|
202
|
+
for (const required of ["noopener", "noreferrer"]) if (!tokens.includes(required)) tokens.push(required)
|
|
203
|
+
}
|
|
204
|
+
return tokens.length > 0 ? tokens.join(" ") : undefined
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function link(node: RichTextNode, context: WalkContext): RichTextChild[] {
|
|
208
|
+
const children = walkChildren(node, context)
|
|
209
|
+
if (node.type === "autolink" && node["isUnlinked"] === true) return children
|
|
210
|
+
const href = safeHref(stringField(node, "url"))
|
|
211
|
+
if (href === undefined) return children
|
|
212
|
+
const requested = stringField(node, "target")
|
|
213
|
+
const target = requested !== undefined && LINK_TARGETS.has(requested) ? requested : undefined
|
|
214
|
+
const rel = relFor(stringField(node, "rel"), target)
|
|
215
|
+
const title = stringField(node, "title")
|
|
216
|
+
const attributes: RichTextAttributes = {
|
|
217
|
+
href,
|
|
218
|
+
...(rel !== undefined && { rel }),
|
|
219
|
+
...(target !== undefined && { target }),
|
|
220
|
+
...(title !== undefined && { title }),
|
|
221
|
+
}
|
|
222
|
+
return [element("a", attributes, children)]
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
function codeBlock(node: RichTextNode): RichTextChild[] {
|
|
226
|
+
const language = stringField(node, "language")
|
|
227
|
+
const attributes: RichTextAttributes = language !== undefined && language !== "" ? { class: `language-${language}` } : {}
|
|
228
|
+
const children = walkChildren(node, { inCode: true, listType: null })
|
|
229
|
+
return [element("pre", {}, [element("code", attributes, children)])]
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/** A node type this walker does not know: its words, so nothing written is lost. */
|
|
233
|
+
function unknownNode(node: RichTextNode, context: WalkContext): RichTextChild[] {
|
|
234
|
+
if (typeof node["text"] === "string") return textRun(node, context)
|
|
235
|
+
return walkChildren(node, context)
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
const RENDERERS: ReadonlyMap<string, NodeRenderer> = new Map<string, NodeRenderer>([
|
|
239
|
+
["root", walkChildren],
|
|
240
|
+
["paragraph", paragraph],
|
|
241
|
+
["heading", heading],
|
|
242
|
+
["quote", (node, context) => [element("blockquote", blockAttributes(node), walkChildren(node, context))]],
|
|
243
|
+
["list", list],
|
|
244
|
+
["listitem", listItem],
|
|
245
|
+
["link", link],
|
|
246
|
+
["autolink", link],
|
|
247
|
+
["code", codeBlock],
|
|
248
|
+
["text", textRun],
|
|
249
|
+
["tab", textRun],
|
|
250
|
+
["code-highlight", textRun],
|
|
251
|
+
["linebreak", (_node, context) => [context.inCode ? "\n" : element("br")]],
|
|
252
|
+
["horizontalrule", () => [element("hr")]],
|
|
253
|
+
])
|
|
254
|
+
|
|
255
|
+
function walk(node: RichTextNode, context: WalkContext): RichTextChild[] {
|
|
256
|
+
return (RENDERERS.get(node.type) ?? unknownNode)(node, context)
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
function topLevelNodes(content: unknown): readonly unknown[] {
|
|
260
|
+
if (typeof content !== "object" || content === null) return []
|
|
261
|
+
if (Array.isArray(content)) return content
|
|
262
|
+
if (isNode(content)) return [content]
|
|
263
|
+
return "root" in content ? [content.root] : []
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/**
|
|
267
|
+
* Walk a saved document into the element tree every renderer prints.
|
|
268
|
+
*
|
|
269
|
+
* Takes any value, not only a `RichTextContent`: a column holds whatever was written to it, and
|
|
270
|
+
* anything that is not a document prints as nothing.
|
|
271
|
+
*/
|
|
272
|
+
export function richTextTree(content: unknown): RichTextChild[] {
|
|
273
|
+
return topLevelNodes(content).flatMap((node) => (isNode(node) ? walk(node, TOP) : []))
|
|
274
|
+
}
|