CodeBlock.svelte 6.29 KB
Newer Older
Timothy J. Baek's avatar
Timothy J. Baek committed
1
<script lang="ts">
2
	import Spinner from '$lib/components/common/Spinner.svelte';
Timothy J. Baek's avatar
Timothy J. Baek committed
3
4
5
	import { copyToClipboard } from '$lib/utils';
	import hljs from 'highlight.js';
	import 'highlight.js/styles/github-dark.min.css';
6
	import { loadPyodide } from 'pyodide';
Timothy J. Baek's avatar
Timothy J. Baek committed
7
	import { tick } from 'svelte';
8
	import PyodideWorker from '$lib/workers/pyodide.worker?worker';
Timothy J. Baek's avatar
Timothy J. Baek committed
9
10

	export let id = '';
Timothy J. Baek's avatar
Timothy J. Baek committed
11
12
13
14

	export let lang = '';
	export let code = '';

15
	let executing = false;
16
17
18
19
20

	let stdout = null;
	let stderr = null;
	let result = null;

Timothy J. Baek's avatar
Timothy J. Baek committed
21
22
23
24
25
26
27
28
29
30
31
	let copied = false;

	const copyCode = async () => {
		copied = true;
		await copyToClipboard(code);

		setTimeout(() => {
			copied = false;
		}, 1000);
	};

Timothy J. Baek's avatar
Timothy J. Baek committed
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
	const checkPythonCode = (str) => {
		// Check if the string contains typical Python syntax characters
		const pythonSyntax = [
			'def ',
			'else:',
			'elif ',
			'try:',
			'except:',
			'finally:',
			'yield ',
			'lambda ',
			'assert ',
			'nonlocal ',
			'del ',
			'True',
			'False',
			'None',
			' and ',
			' or ',
			' not ',
			' in ',
			' is ',
Timothy J. Baek's avatar
Timothy J. Baek committed
54
			' with '
Timothy J. Baek's avatar
Timothy J. Baek committed
55
56
57
58
59
60
61
62
63
64
65
66
		];

		for (let syntax of pythonSyntax) {
			if (str.includes(syntax)) {
				return true;
			}
		}

		// If none of the above conditions met, it's probably not Python code
		return false;
	};

67
	const executePython = async (code) => {
Timothy J. Baek's avatar
Timothy J. Baek committed
68
		if (!code.includes('input') && !code.includes('matplotlib')) {
69
70
71
72
73
			executePythonAsWorker(code);
		} else {
			result = null;
			stdout = null;
			stderr = null;
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
74

75
			executing = true;
Timothy J. Baek's avatar
Timothy J. Baek committed
76

Timothy J. Baek's avatar
Timothy J. Baek committed
77
			document.pyodideMplTarget = document.getElementById(`plt-canvas-${id}`);
Timothy J. Baek's avatar
Timothy J. Baek committed
78

79
80
81
82
			let pyodide = await loadPyodide({
				indexURL: '/pyodide/',
				stdout: (text) => {
					console.log('Python output:', text);
83

84
85
86
87
88
89
90
91
92
93
94
95
96
					if (stdout) {
						stdout += `${text}\n`;
					} else {
						stdout = `${text}\n`;
					}
				},
				stderr: (text) => {
					console.log('An error occured:', text);
					if (stderr) {
						stderr += `${text}\n`;
					} else {
						stderr = `${text}\n`;
					}
97
98
				},
				packages: ['micropip']
99
			});
Timothy J. Baek's avatar
Timothy J. Baek committed
100

101
102
			try {
				const micropip = pyodide.pyimport('micropip');
Timothy J. Baek's avatar
Timothy J. Baek committed
103

Timothy J. Baek's avatar
Timothy J. Baek committed
104
				// await micropip.set_index_urls('https://pypi.org/pypi/{package_name}/json');
Timothy J. Baek's avatar
Timothy J. Baek committed
105

106
107
108
109
				let packages = [
					code.includes('requests') ? 'requests' : null,
					code.includes('bs4') ? 'beautifulsoup4' : null,
					code.includes('numpy') ? 'numpy' : null,
Timothy J. Baek's avatar
Timothy J. Baek committed
110
					code.includes('pandas') ? 'pandas' : null,
Timothy J. Baek's avatar
Timothy J. Baek committed
111
					code.includes('matplotlib') ? 'matplotlib' : null,
Timothy J. Baek's avatar
fix  
Timothy J. Baek committed
112
					code.includes('sklearn') ? 'scikit-learn' : null,
Timothy J. Baek's avatar
Timothy J. Baek committed
113
					code.includes('scipy') ? 'scipy' : null,
114
115
					code.includes('re') ? 'regex' : null,
					code.includes('seaborn') ? 'seaborn' : null
116
				].filter(Boolean);
Timothy J. Baek's avatar
Timothy J. Baek committed
117

118
119
				console.log(packages);
				await micropip.install(packages);
Timothy J. Baek's avatar
Timothy J. Baek committed
120

121
				result = await pyodide.runPythonAsync(`from js import prompt
Timothy J. Baek's avatar
Timothy J. Baek committed
122
123
124
125
def input(p):
    return prompt(p)
__builtins__.input = input`);

126
127
128
129
130
				result = await pyodide.runPython(code);

				if (!result) {
					result = '[NO OUTPUT]';
				}
131

132
133
134
				console.log(result);
				console.log(stdout);
				console.log(stderr);
Timothy J. Baek's avatar
Timothy J. Baek committed
135
136
137
138

				const pltCanvasElement = document.getElementById(`plt-canvas-${id}`);

				if (pltCanvasElement?.innerHTML !== '') {
Timothy J. Baek's avatar
Timothy J. Baek committed
139
					pltCanvasElement.classList.add('pt-4');
Timothy J. Baek's avatar
Timothy J. Baek committed
140
				}
141
142
143
			} catch (error) {
				console.error('Error:', error);
				stderr = error;
Timothy J. Baek's avatar
Timothy J. Baek committed
144
145
			}

146
			executing = false;
147
		}
148
149
150
151
152
153
154
155
156
157
158
159
160
	};

	const executePythonAsWorker = async (code) => {
		result = null;
		stdout = null;
		stderr = null;

		executing = true;

		let packages = [
			code.includes('requests') ? 'requests' : null,
			code.includes('bs4') ? 'beautifulsoup4' : null,
			code.includes('numpy') ? 'numpy' : null,
Timothy J. Baek's avatar
Timothy J. Baek committed
161
			code.includes('pandas') ? 'pandas' : null,
Timothy J. Baek's avatar
fix  
Timothy J. Baek committed
162
			code.includes('sklearn') ? 'scikit-learn' : null,
Timothy J. Baek's avatar
Timothy J. Baek committed
163
			code.includes('scipy') ? 'scipy' : null,
164
165
			code.includes('re') ? 'regex' : null,
			code.includes('seaborn') ? 'seaborn' : null
166
167
		].filter(Boolean);

Timothy J. Baek's avatar
fix  
Timothy J. Baek committed
168
169
		console.log(packages);

170
		const pyodideWorker = new PyodideWorker();
171
172
173
174
175
176
177
178
179
180
181
182
183

		pyodideWorker.postMessage({
			id: id,
			code: code,
			packages: packages
		});

		setTimeout(() => {
			if (executing) {
				executing = false;
				stderr = 'Execution Time Limit Exceeded';
				pyodideWorker.terminate();
			}
Timothy J. Baek's avatar
Timothy J. Baek committed
184
		}, 60000);
185
186
187
188
189
190
191
192
193
194
195
196
197

		pyodideWorker.onmessage = (event) => {
			console.log('pyodideWorker.onmessage', event);
			const { id, ...data } = event.data;

			console.log(id, data);

			data['stdout'] && (stdout = data['stdout']);
			data['stderr'] && (stderr = data['stderr']);
			data['result'] && (result = data['result']);

			executing = false;
		};
198

199
200
201
202
		pyodideWorker.onerror = (event) => {
			console.log('pyodideWorker.onerror', event);
			executing = false;
		};
Timothy J. Baek's avatar
Timothy J. Baek committed
203
204
	};

Timothy J. Baek's avatar
Timothy J. Baek committed
205
206
207
	$: highlightedCode = code ? hljs.highlightAuto(code, hljs.getLanguage(lang)?.aliases).value : '';
</script>

208
{#if code}
209
	<div class="mb-4" dir="ltr">
210
211
		<div
			class="flex justify-between bg-[#202123] text-white text-xs px-4 pt-1 pb-0.5 rounded-t-lg overflow-x-auto"
Timothy J. Baek's avatar
Timothy J. Baek committed
212
		>
213
			<div class="p-1">{@html lang}</div>
Timothy J. Baek's avatar
Timothy J. Baek committed
214
215

			<div class="flex items-center">
216
				{#if lang.toLowerCase() === 'python' || lang.toLowerCase() === 'py' || (lang === '' && checkPythonCode(code))}
217
218
219
220
221
222
223
224
225
226
					{#if executing}
						<div class="copy-code-button bg-none border-none p-1 cursor-not-allowed">Running</div>
					{:else}
						<button
							class="copy-code-button bg-none border-none p-1"
							on:click={() => {
								executePython(code);
							}}>Run</button
						>
					{/if}
Timothy J. Baek's avatar
Timothy J. Baek committed
227
228
229
230
231
				{/if}
				<button class="copy-code-button bg-none border-none p-1" on:click={copyCode}
					>{copied ? 'Copied' : 'Copy Code'}</button
				>
			</div>
232
		</div>
Timothy J. Baek's avatar
Timothy J. Baek committed
233

Timothy J. Baek's avatar
Timothy J. Baek committed
234
235
		<pre
			class=" hljs p-4 px-5 overflow-x-auto"
236
237
238
239
			style="border-top-left-radius: 0px; border-top-right-radius: 0px; {(executing ||
				stdout ||
				stderr ||
				result) &&
Timothy J. Baek's avatar
Timothy J. Baek committed
240
				'border-bottom-left-radius: 0px; border-bottom-right-radius: 0px;'}"><code
241
242
				class="language-{lang} rounded-t-none whitespace-pre">{@html highlightedCode || code}</code
			></pre>
Timothy J. Baek's avatar
Timothy J. Baek committed
243

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
244
245
246
247
		<div
			id="plt-canvas-{id}"
			class="bg-[#202123] text-white max-w-full overflow-x-auto scrollbar-hidden"
		/>
Timothy J. Baek's avatar
Timothy J. Baek committed
248

249
		{#if executing}
Timothy J. Baek's avatar
Timothy J. Baek committed
250
			<div class="bg-[#202123] text-white px-4 py-4 rounded-b-lg">
Timothy J. Baek's avatar
Timothy J. Baek committed
251
				<div class=" text-gray-500 text-xs mb-1">STDOUT/STDERR</div>
252
253
				<div class="text-sm">Running...</div>
			</div>
Timothy J. Baek's avatar
Timothy J. Baek committed
254
		{:else if stdout || stderr || result}
255
256
			<div class="bg-[#202123] text-white px-4 py-4 rounded-b-lg">
				<div class=" text-gray-500 text-xs mb-1">STDOUT/STDERR</div>
Timothy J. Baek's avatar
Timothy J. Baek committed
257
				<div class="text-sm">{stdout || stderr || result}</div>
Timothy J. Baek's avatar
Timothy J. Baek committed
258
259
			</div>
		{/if}
260
261
	</div>
{/if}