-
-
Notifications
You must be signed in to change notification settings - Fork 145
/
Copy pathViewer.svelte
368 lines (311 loc) · 9.13 KB
/
Viewer.svelte
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
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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
<script lang="ts">
import { get_repl_context } from '../context';
import { BROWSER } from 'esm-env';
import { onMount } from 'svelte';
import Message from '../Message.svelte';
import PaneWithPanel from './PaneWithPanel.svelte';
import ReplProxy from './ReplProxy.js';
import Console, { type Log } from './console/Console.svelte';
import getLocationFromStack from './get-location-from-stack';
import srcdoc from './srcdoc/index.html?raw';
import srcdoc_styles from './srcdoc/styles.css?raw';
import ErrorOverlay from './ErrorOverlay.svelte';
import type { CompileError } from 'svelte/compiler';
import type { Bundle } from '../types';
import type { Writable } from 'svelte/store';
export let error: Error | null;
/** status by Bundler class instance */
export let status: string | null;
/** sandbox allow-same-origin */
export let relaxed = false;
/** sandbox allow-popups-to-escape-sandbox (i.e. links within the REPL to other pages work) */
export let can_escape = false;
/** Any additional JS you may want to inject */
export let injectedJS = '';
/** Any additional CSS you may want to inject */
export let injectedCSS = '';
export let theme: 'light' | 'dark';
/** A store containing the current bundle result. Takes precedence over REPL context, if set */
export let bundle: Writable<Bundle | null> | undefined = undefined;
/** Called everytime a log is pushed. If this is set, the built-in console coming with the Viewer isn't shown */
export let onLog: ((logs: Log[]) => void) | undefined = undefined;
const context = get_repl_context();
bundle = bundle ?? context.bundle;
let logs: Log[] = [];
let log_group_stack: Log[][] = [];
let current_log_group = logs;
let iframe: HTMLIFrameElement;
let pending_imports = 0;
let pending = false;
let proxy: ReplProxy | null = null;
let ready = false;
let inited = false;
let log_height = 90;
let prev_height: number;
let last_console_event: Log;
onMount(() => {
proxy = new ReplProxy(iframe, {
on_fetch_progress: (progress) => {
pending_imports = progress;
},
on_error: (event) => {
push_logs({ command: 'error', args: [event.value] });
},
on_unhandled_rejection: (event) => {
let error = event.value;
if (typeof error === 'string') error = { message: error };
error.message = 'Uncaught (in promise): ' + error.message;
push_logs({ command: 'error', args: [error] });
},
on_console: (log) => {
switch (log.command) {
case 'clear':
clear_logs();
push_logs(log);
break;
case 'group':
group_logs(log);
break;
case 'groupEnd':
ungroup_logs();
break;
case 'duplicate':
increment_duplicate_log();
break;
default:
push_logs(log);
}
}
});
iframe.addEventListener('load', () => {
proxy?.handle_links();
ready = true;
});
return () => {
proxy?.destroy();
};
});
$: if (ready) proxy?.iframe_command('set_theme', { theme });
async function apply_bundle($bundle: Bundle | null | undefined) {
console.log({ $bundle });
if (!$bundle) return;
try {
clear_logs();
if (!$bundle.error) {
await proxy?.eval(
`
${injectedJS}
if (!window.__setup_focus_handling) {
let can_focus = false;
window.addEventListener('pointerdown', (e) => (can_focus = true));
window.addEventListener('pointerup', (e) => (can_focus = false));
window.addEventListener('keydown', (e) => (can_focus = true));
window.addEventListener('keyup', (e) => (can_focus = false));
/**
* The iframe sometimes takes focus control in ways we can't prevent
* while the editor is focused. Refocus the editor in these cases.
*/
window.addEventListener('focusin', (e) => {
// if focusin happened as a result of a mouse/keyboard event, allow it
if (can_focus) return;
// if \`e.target\` is the \`<body>\` and there's a \`relatedTarget\`,
// assume the focusin was the result of a user navigation — allow it
if (e.target.tagName === 'BODY' && e.relatedTarget) return;
// otherwise, broadcast an event that causes the editor to reclaim focus
parent.postMessage({ type: 'iframe_took_focus' }, '*');
});
window.__setup_focus_handling = true;
}
{
const styles = document.querySelectorAll('style[id^=svelte-]');
let i = styles.length;
while (i--) styles[i].parentNode.removeChild(styles[i]);
if (window.__unmount_previous) {
try {
window.__unmount_previous();
} catch (err) {
console.error(err);
}
}
document.body.innerHTML = '';
window._svelteTransitionManager = null;
}
const __repl_exports = ${$bundle.client?.code};
{
const { mount, unmount, App, untrack } = __repl_exports;
const console_methods = ['log', 'error', 'trace', 'assert', 'warn', 'table', 'group'];
// The REPL hooks up to the console to provide a virtual console. However, the implementation
// needs to stringify the console to pass over a MessageChannel, which means that the object
// can get deeply read and tracked by accident when using the console. We can avoid this by
// ensuring we untrack the main console methods.
const original = {};
for (const method of console_methods) {
original[method] = console[method];
console[method] = function (...v) {
return untrack(() => original[method].apply(this, v));
}
}
const component = mount(App, { target: document.body });
window.__unmount_previous = () => {
for (const method of console_methods) {
console[method] = original[method];
}
unmount(component);
}
}
//# sourceURL=playground:output
`,
$bundle?.tailwind ?? srcdoc_styles
);
error = null;
}
} catch (e) {
// @ts-ignore
show_error(e);
}
inited = true;
}
$: if (ready) apply_bundle($bundle);
$: if (injectedCSS && proxy && ready) {
proxy.eval(
`{
const style = document.createElement('style');
style.textContent = ${JSON.stringify(injectedCSS)};
document.head.appendChild(style);
}`
);
}
function show_error(e: CompileError & { loc: { line: number; column: number } }) {
const map = $bundle?.client?.map;
// @ts-ignore INVESTIGATE
const loc = map && getLocationFromStack(e.stack, map);
if (loc) {
e.filename = loc.source;
e.loc = { line: loc.line, column: loc.column ?? 0 };
}
// @ts-ignore name is there, just not part of public API
error = e;
}
function push_logs(log: Log) {
current_log_group.push((last_console_event = log));
logs = logs;
onLog?.(logs);
}
function group_logs(log: Log) {
log.logs = [];
current_log_group.push(log);
// TODO: Investigate
log_group_stack.push(current_log_group);
current_log_group = log.logs;
logs = logs;
onLog?.(logs);
}
function ungroup_logs() {
const last = log_group_stack.pop();
if (last) current_log_group = last;
}
function increment_duplicate_log() {
const last_log = current_log_group[current_log_group.length - 1];
if (last_log) {
last_log.count = (last_log.count || 1) + 1;
logs = logs;
onLog?.(logs);
} else {
last_console_event.count = 1;
push_logs(last_console_event);
}
}
function on_toggle_console() {
if (log_height < 90) {
prev_height = log_height;
log_height = 90;
} else {
log_height = prev_height || 45;
}
}
function clear_logs() {
current_log_group = logs = [];
onLog?.(logs);
}
</script>
{#snippet main()}
<iframe
title="Result"
class:inited
bind:this={iframe}
sandbox={[
'allow-scripts',
'allow-popups',
'allow-forms',
'allow-pointer-lock',
'allow-modals',
can_escape ? 'allow-popups-to-escape-sandbox' : '',
relaxed ? 'allow-same-origin' : ''
].join(' ')}
class={error || pending || pending_imports ? 'greyed-out' : ''}
srcdoc={BROWSER ? srcdoc : ''}
></iframe>
{#if $bundle?.error}
<ErrorOverlay error={$bundle.error} />
{/if}
{/snippet}
<div class="iframe-container">
{#if !onLog}
<PaneWithPanel pos="100%" panel="Console" {main}>
{#snippet header()}
<button class="raised" disabled={logs.length === 0} on:click|stopPropagation={clear_logs}>
{#if logs.length > 0}
({logs.length})
{/if}
Clear
</button>
{/snippet}
{#snippet body()}
<Console {logs} />
{/snippet}
</PaneWithPanel>
{:else}
{@render main()}
{/if}
<div class="overlay">
{#if error}
<Message kind="error" details={error} />
{:else if status || !$bundle}
<Message kind="info" truncate>{status || 'loading Svelte compiler...'}</Message>
{/if}
</div>
</div>
<style>
.iframe-container {
position: absolute;
background-color: var(--sk-bg-1, white);
border: none;
width: 100%;
height: 100%;
}
iframe {
width: 100%;
height: 100%;
border: none;
display: block;
}
.greyed-out {
filter: grayscale(50%) blur(1px);
opacity: 0.25;
}
/* TODO this stuff should live in global styles */
button {
font: var(--sk-font-ui-small);
text-transform: uppercase;
display: block;
padding: 0.3rem 0.8rem;
&:disabled {
color: var(--sk-fg-4);
}
}
.overlay {
position: absolute;
top: 0;
width: 100%;
}
</style>