Open History to see the last commit
1import * as Base64 from "effect/encoding/Base64";
2
3export const INLINE_SVG_DATA_URL = /^data:image\/svg\+xml(?=[;,])[^,]*,/i;
4export const SVG_BASE64_MARKER = /;base64[\t\n\f\r ]*$/i;
5
6export function decodeDataUriComponent(content: string): string {
7 const codePointEscapes =
8 /%[0-7][0-9a-f]|%[cd][0-9a-f]%[89ab][0-9a-f]|%e[0-9a-f](?:%[89ab][0-9a-f]){2}|%f[0-4](?:%[89ab][0-9a-f]){3}/gi;
9 return content.replace(codePointEscapes, (escapes) => {
10 try {
11 return decodeURIComponent(escapes);
12 } catch {
13 return escapes;
14 }
15 });
16}
17
18export function nativeSvgPreviewUri(uri: string): string {
19 const header = INLINE_SVG_DATA_URL.exec(uri)?.[0];
20 if (!header) return uri;
21 const content = uri.slice(header.length);
22 try {
23 const base64 = SVG_BASE64_MARKER.test(header.slice(0, -1))
24 ? decodeURIComponent(content.split("#", 1)[0]!)
25 : Base64.encode(decodeDataUriComponent(content));
26 return `data:image/svg+xml;base64,${base64}`;
27 } catch {
28 return uri;
29 }
30}