-
-
Notifications
You must be signed in to change notification settings - Fork 144
/
Copy pathsvelte.ts
34 lines (30 loc) · 1.07 KB
/
svelte.ts
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
import type { Compiler } from './types'
let svelteRunes: boolean | null
export const SvelteCompiler = (async (svg: string) => {
if (svelteRunes == null) {
try {
const { VERSION } = await import('svelte/compiler')
svelteRunes = Number(VERSION.split('.')[0]) >= 5
}
catch {
svelteRunes = false
}
}
const openTagEnd = svg.indexOf('>', svg.indexOf('<svg '))
const closeTagStart = svg.lastIndexOf('</svg')
let sfc = `${svg.slice(0, openTagEnd)} {...${svelteRunes ? 'p' : '$$props'}}>`
if (svelteRunes)
sfc += svg.slice(openTagEnd + 1, closeTagStart)
else
sfc += `{@html \`${escapeSvelte(svg.slice(openTagEnd + 1, closeTagStart))}\`}`
sfc += svg.slice(closeTagStart)
return svelteRunes ? `<script>const{...p}=$props()</script>${sfc}` : sfc
}) as Compiler
// escape curlies, backtick, \t, \r, \n to avoid breaking output of {@html `here`} in .svelte
export function escapeSvelte(str: string): string {
return str
.replace(/\{/g, '{')
.replace(/\}/g, '}')
.replace(/`/g, '`')
.replace(/\\([trn])/g, ' ')
}