CodeBlock.svelte 4.54 KB
Newer Older
Timothy J. Baek's avatar
Timothy J. Baek committed
1
2
3
4
<script lang="ts">
	import { copyToClipboard } from '$lib/utils';
	import hljs from 'highlight.js';
	import 'highlight.js/styles/github-dark.min.css';
Timothy J. Baek's avatar
Timothy J. Baek committed
5
6
7
	import { tick } from 'svelte';

	export let id = '';
Timothy J. Baek's avatar
Timothy J. Baek committed
8
9
10
11

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

Timothy J. Baek's avatar
Timothy J. Baek committed
12
	let executed = false;
Timothy J. Baek's avatar
Timothy J. Baek committed
13
14
15
16
17
18
19
20
21
22
23
	let copied = false;

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

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

Timothy J. Baek's avatar
Timothy J. Baek committed
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
	const checkPythonCode = (str) => {
		// Check if the string contains typical Python keywords, syntax, or functions
		const pythonKeywords = [
			'def',
			'class',
			'import',
			'from',
			'if',
			'else',
			'elif',
			'for',
			'while',
			'try',
			'except',
			'finally',
			'return',
			'yield',
			'lambda',
			'assert',
			'pass',
			'break',
			'continue',
			'global',
			'nonlocal',
			'del',
			'True',
			'False',
			'None',
			'and',
			'or',
			'not',
			'in',
			'is',
			'as',
			'with'
		];

		for (let keyword of pythonKeywords) {
			if (str.includes(keyword)) {
				return true;
			}
		}

		// Check if the string contains typical Python syntax characters
		const pythonSyntax = [
			'def ',
			'class ',
			'import ',
			'from ',
			'if ',
			'else:',
			'elif ',
			'for ',
			'while ',
			'try:',
			'except:',
			'finally:',
			'return ',
			'yield ',
			'lambda ',
			'assert ',
			'pass',
			'break',
			'continue',
			'global ',
			'nonlocal ',
			'del ',
			'True',
			'False',
			'None',
			' and ',
			' or ',
			' not ',
			' in ',
			' is ',
			' as ',
			' with ',
			':',
			'=',
			'==',
			'!=',
			'>',
			'<',
			'>=',
			'<=',
			'+',
			'-',
			'*',
			'/',
			'%',
			'**',
			'//',
			'(',
			')',
			'[',
			']',
			'{',
			'}'
		];

		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;
	};

Timothy J. Baek's avatar
Timothy J. Baek committed
134
135
136
137
138
139
140
141
142
143
	const executePython = async (text) => {
		executed = true;

		await tick();
		const outputDiv = document.getElementById(`code-output-${id}`);

		if (outputDiv) {
			outputDiv.innerText = 'Running...';
		}

Timothy J. Baek's avatar
Timothy J. Baek committed
144
145
146
147
148
		text = text
			.split('\n')
			.map((line, index) => (index === 0 ? line : '    ' + line))
			.join('\n');

Timothy J. Baek's avatar
Timothy J. Baek committed
149
150
		// pyscript
		let div = document.createElement('div');
Timothy J. Baek's avatar
Timothy J. Baek committed
151
152
		let html = `
<py-script type="py" worker>
Timothy J. Baek's avatar
Timothy J. Baek committed
153
154
155
156
157
158
159
160
161
162
163
164
165
import js
import sys
import io

# Create a StringIO object to capture the output
output_capture = io.StringIO()

# Save the current standard output
original_stdout = sys.stdout

# Replace the standard output with the StringIO object
sys.stdout = output_capture

Timothy J. Baek's avatar
Timothy J. Baek committed
166
try:
Timothy J. Baek's avatar
Timothy J. Baek committed
167
    ${text}
Timothy J. Baek's avatar
Timothy J. Baek committed
168
169
170
except Exception as e:
    # Capture any errors and write them to the output capture
    print(f"Error: {e}", file=output_capture)
Timothy J. Baek's avatar
Timothy J. Baek committed
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186

# Restore the original standard output
sys.stdout = original_stdout

# Retrieve the captured output
captured_output = "[NO OUTPUT]"
captured_output = output_capture.getvalue()

# Print the captured output
print(captured_output)

def display_message():
    output_div = js.document.getElementById("code-output-${id}")
    output_div.innerText = captured_output

display_message()
Timothy J. Baek's avatar
Timothy J. Baek committed
187
</py-script>`;
Timothy J. Baek's avatar
Timothy J. Baek committed
188
189
190
191
192
193
194
195
196
197
198
199
200
201

		div.innerHTML = html;
		const pyScript = div.firstElementChild;
		try {
			document.body.appendChild(pyScript);
			setTimeout(() => {
				document.body.removeChild(pyScript);
			}, 0);
		} catch (error) {
			console.error('Python error:');
			console.error(error);
		}
	};

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

205
206
207
208
{#if code}
	<div class="mb-4">
		<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
209
		>
210
			<div class="p-1">{@html lang}</div>
Timothy J. Baek's avatar
Timothy J. Baek committed
211
212

			<div class="flex items-center">
Timothy J. Baek's avatar
Timothy J. Baek committed
213
				{#if lang === 'python' || checkPythonCode(code)}
Timothy J. Baek's avatar
Timothy J. Baek committed
214
215
216
217
218
219
220
221
222
223
224
					<button
						class="copy-code-button bg-none border-none p-1"
						on:click={() => {
							executePython(code);
						}}>Run</button
					>
				{/if}
				<button class="copy-code-button bg-none border-none p-1" on:click={copyCode}
					>{copied ? 'Copied' : 'Copy Code'}</button
				>
			</div>
225
		</div>
Timothy J. Baek's avatar
Timothy J. Baek committed
226

Timothy J. Baek's avatar
Timothy J. Baek committed
227
228
		<pre
			class=" hljs p-4 px-5 overflow-x-auto"
Timothy J. Baek's avatar
Timothy J. Baek committed
229
230
			style="border-top-left-radius: 0px; border-top-right-radius: 0px; {executed &&
				'border-bottom-left-radius: 0px; border-bottom-right-radius: 0px;'}"><code
231
232
				class="language-{lang} rounded-t-none whitespace-pre">{@html highlightedCode || code}</code
			></pre>
Timothy J. Baek's avatar
Timothy J. Baek committed
233
234
235

		{#if executed}
			<div class="bg-[#202123] text-white px-4 py-4 rounded-b-lg">
Timothy J. Baek's avatar
Timothy J. Baek committed
236
				<div class=" text-gray-500 text-xs mb-1">STDOUT/STDERR</div>
Timothy J. Baek's avatar
Timothy J. Baek committed
237
238
239
				<div id="code-output-{id}" class="text-sm" />
			</div>
		{/if}
240
241
	</div>
{/if}