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 // `encodeURIComponent` expands one non-ASCII code unit to up to nine characters, so a
37 // fragment just under the limit must still survive the round trip through the attribute.
38 if (!html || html.length > MAX_FRAGMENT_CHARS * 9 + HTML_WRAPPER_SLACK_CHARS) return null;
39 const encoded = /data-t3-context-fragment=["']([^"']+)["']/.exec(html)?.[1];
40 if (!encoded) return null;
41 try {
42 return decodeComposerContextFragment(decodeURIComponent(encoded));
43 } catch {
44 return null;
45 }
46}
47
48export function decodeComposerContextFragment(
49 raw: string | null | undefined,
50): ComposerContextClipboardFragment | null {
51 if (!raw || raw.length > MAX_FRAGMENT_CHARS) return null;
52 try {
53 return Option.getOrNull(decodeFragment(JSON.parse(raw)));
54 } catch {
55 return null;
56 }
57}