|
| 1 | +import { csvFormat } from 'd3-dsv'; |
| 2 | + |
| 3 | +const uiComponents = Object.fromEntries( |
| 4 | + Object.entries( |
| 5 | + import.meta.glob('../../../../shared/ui/*.svelte', { |
| 6 | + eager: true, |
| 7 | + query: '?raw', |
| 8 | + import: 'default' |
| 9 | + }) as Record<string, string> |
| 10 | + ).map(([path, src]) => [path.split('/').at(-1), src]) |
| 11 | +); |
| 12 | + |
| 13 | +export type REPLState = { |
| 14 | + name: string; |
| 15 | + tailwind: boolean; |
| 16 | + files: { |
| 17 | + type: 'file'; |
| 18 | + name: string; |
| 19 | + basename: string; |
| 20 | + text: true; |
| 21 | + contents: string; |
| 22 | + }[]; |
| 23 | +}; |
| 24 | + |
| 25 | +function bytesToBase64url(bytes: Uint8Array<ArrayBuffer>) { |
| 26 | + let bin = ''; |
| 27 | + for (const b of bytes) bin += String.fromCharCode(b); |
| 28 | + const b64 = btoa(bin); |
| 29 | + return b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/g, ''); |
| 30 | +} |
| 31 | + |
| 32 | +async function gzipStringToBytes(text: string) { |
| 33 | + const cs = new CompressionStream('gzip'); |
| 34 | + const stream = new Blob([new TextEncoder().encode(text)]).stream().pipeThrough(cs); |
| 35 | + const out = await new Response(stream).arrayBuffer(); |
| 36 | + return new Uint8Array(out); |
| 37 | +} |
| 38 | + |
| 39 | +export async function encodePlaygroundState(state: REPLState) { |
| 40 | + // state is whatever the playground expects (see “reverse-engineer” tip below) |
| 41 | + const jsonText = JSON.stringify(state); |
| 42 | + const gzBytes = await gzipStringToBytes(jsonText); |
| 43 | + return '#' + bytesToBase64url(gzBytes); |
| 44 | +} |
| 45 | + |
| 46 | +function firstPositive(a: number, b: number) { |
| 47 | + return a > -1 ? a : b; |
| 48 | +} |
| 49 | + |
| 50 | +const UI_REGEX = /import \{\s*([a-z]+)(?:,\s*([a-z]+))*\s*\} from '\$shared\/ui'/i; |
| 51 | + |
| 52 | +export function createREPLState( |
| 53 | + title: string, |
| 54 | + url: string, |
| 55 | + source: string, |
| 56 | + data: Record<string, string>, |
| 57 | + datasets: Record<string, object[]> |
| 58 | +): REPLState { |
| 59 | + const needSharedUIs: string[] = []; |
| 60 | + |
| 61 | + const appCode = source |
| 62 | + .substring(firstPositive(source.indexOf('<script lang="ts">'), source.indexOf('<script>'))) |
| 63 | + // add import statements for each dataset |
| 64 | + .replace( |
| 65 | + 'import ', |
| 66 | + Object.keys(data ?? {}).length |
| 67 | + ? `${Object.entries(data ?? {}) |
| 68 | + .map(([key, url]) => `import ${key} from './${url.split('/').at(-1)}';`) |
| 69 | + .join('\n ')}\n import ` |
| 70 | + : 'import ' |
| 71 | + ) |
| 72 | + .split(';') |
| 73 | + // remove data type imports for now |
| 74 | + .filter((line) => !line.trim().startsWith('import type')) |
| 75 | + // remove props since we're importing data |
| 76 | + .filter((line) => !line.trim().includes('$props')) |
| 77 | + // replace shared/ui imports |
| 78 | + .map((line) => { |
| 79 | + if (line.includes('$shared/ui')) { |
| 80 | + const m = line.match(UI_REGEX); |
| 81 | + if (!m) return ''; |
| 82 | + const modules = m?.slice(1); |
| 83 | + return modules |
| 84 | + ?.filter((d) => d) |
| 85 | + ?.map((mod) => { |
| 86 | + needSharedUIs.push(mod); |
| 87 | + return `\n import ${mod} from './${mod}.svelte'`; |
| 88 | + }) |
| 89 | + .join(';'); |
| 90 | + } |
| 91 | + return line; |
| 92 | + }) |
| 93 | + .join(';') |
| 94 | + .split('\n') |
| 95 | + .map((line) => { |
| 96 | + // convert from 4-spaces to 2-spaces |
| 97 | + const leadingSpaces = line?.match(/^ +/)?.[0]?.length ?? -1; |
| 98 | + if (leadingSpaces % 4 === 0) { |
| 99 | + const indent = leadingSpaces / 4; |
| 100 | + return `${Array.from({ length: indent }, () => ' ').join('')}${line.trim()}`; |
| 101 | + } |
| 102 | + return line; |
| 103 | + }) |
| 104 | + .join('\n'); |
| 105 | + return { |
| 106 | + name: title, |
| 107 | + tailwind: false, |
| 108 | + files: [ |
| 109 | + { |
| 110 | + type: 'file', |
| 111 | + name: 'App.svelte', |
| 112 | + basename: 'App.svelte', |
| 113 | + text: true, |
| 114 | + contents: `<!--\n This is a SveltePlot example created from\n https://svelteplot.dev/examples/${url}\n-->\n${appCode}` |
| 115 | + }, |
| 116 | + // add dataset files |
| 117 | + ...Object.entries(data ?? {}).map(([key, url]) => ({ |
| 118 | + type: 'file', |
| 119 | + text: true, |
| 120 | + name: `${url.split('/').at(-1)}.js`, |
| 121 | + basename: `${url.split('/').at(-1)}.js`, |
| 122 | + contents: url.endsWith('.csv') |
| 123 | + ? `import { csvParse, autoType } from 'd3-dsv';\n\nexport default csvParse(\`${csvFormat(datasets[key])}\`, autoType);` |
| 124 | + : `export default ${JSON.stringify(datasets[key], null, 4)};` |
| 125 | + })), |
| 126 | + ...needSharedUIs.map((mod) => ({ |
| 127 | + type: 'file', |
| 128 | + text: true, |
| 129 | + name: `${mod}.svelte`, |
| 130 | + basename: `${mod}.svelte`, |
| 131 | + contents: uiComponents[`${mod}.svelte`] |
| 132 | + })) |
| 133 | + ] |
| 134 | + } as REPLState; |
| 135 | +} |
0 commit comments