Open History to see the last commit
1import {
2 COMPOSER_CONTEXT_CLIPBOARD_MIME,
3 ComposerContextClipboardFragment,
4} from "@t3tools/contracts";
5import * as Option from "effect/Option";
6import * as Schema from "effect/Schema";
7
8export { COMPOSER_CONTEXT_CLIPBOARD_MIME };
9
10const MAX_FRAGMENT_CHARS = 16_000_000;
11const decodeFragment = Schema.decodeUnknownOption(ComposerContextClipboardFragment);
12
13export function encodeComposerContextFragment(
14 fragment: ComposerContextClipboardFragment,
15): string | null {
16 const encoded = JSON.stringify(fragment);
17 return encoded.length <= MAX_FRAGMENT_CHARS ? encoded : null;
18}
19
20const HTML_WRAPPER_SLACK_CHARS = 4096;
21
22export function encodeComposerContextClipboardHtml(
23 text: string,
24 fragment: string,
25 html?: string,
26): string {
27 if (html !== undefined)
28 return `<div data-t3-context-fragment="${encodeURIComponent(fragment)}">${html}</div>`;
29 const escaped = text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
30 return `<pre data-t3-context-fragment="${encodeURIComponent(fragment)}">${escaped}</pre>`;
31}
32
33export function decodeComposerContextClipboardHtml(
34 html: string | null | undefined,
35): ComposerContextClipboardFragment | null {
36 // Percent encoding can expand each UTF-16 code unit to nine characters.
37 if (!html || html.length > MAX_FRAGMENT_CHARS * 9 + HTML_WRAPPER_SLACK_CHARS) return null;
38 const encoded = /data-t3-context-fragment=["']([^"']+)["']/.exec(html)?.[1];
39 if (!encoded) return null;
40 try {
41 return decodeComposerContextFragment(decodeURIComponent(encoded));
42 } catch {
43 return null;
44 }
45}
46
47export function decodeComposerContextFragment(
48 raw: string | null | undefined,
49): ComposerContextClipboardFragment | null {
50 if (!raw || raw.length > MAX_FRAGMENT_CHARS) return null;
51 try {
52 return Option.getOrNull(decodeFragment(JSON.parse(raw)));
53 } catch {
54 return null;
55 }
56}