forked from solidjs/solid-playground
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrepl.tsx
More file actions
509 lines (465 loc) · 18.1 KB
/
repl.tsx
File metadata and controls
509 lines (465 loc) · 18.1 KB
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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
import { Show, For, createSignal, createEffect, batch, Match, Switch, onCleanup, createMemo } from 'solid-js';
import { Icon } from 'solid-heroicons';
import { arrowPath, commandLine, trash, inboxStack, bell, bellSlash } from 'solid-heroicons/outline';
import { unwrap } from 'solid-js/store';
import { Preview } from './preview';
import { TabItem, TabList } from './tabs';
import { GridResizer } from './gridResizer';
import { Error } from './error';
import { throttle } from '@solid-primitives/scheduled';
import { createMediaQuery } from '@solid-primitives/media';
import { editor, Uri } from 'monaco-editor';
import { createMonacoTabs } from './editor/monacoTabs';
import Editor from './editor';
import type { Repl as ReplProps } from 'solid-repl/dist/repl';
import type { Tab } from 'solid-repl';
const compileMode = {
SSR: { generate: 'ssr', hydratable: true },
DOM: { generate: 'dom', hydratable: false },
HYDRATABLE: { generate: 'dom', hydratable: true },
UNIVERSAL: { generate: 'universal', hydratable: false, moduleName: 'solid-universal-module' as string },
} as const;
const findExtension = (str: string): '.tsx' | '.jsx' => {
for (const ext of ['.tsx', '.jsx'] as const) {
if (str.endsWith(ext)) return ext;
}
return '.jsx';
};
const getImportMap = (tabs: Tab[]): Record<string, string> => {
try {
const rawImportMap = tabs.find((tab) => tab.name === 'import_map.json');
return JSON.parse(rawImportMap?.source ?? '{}');
} catch (e) {
return {};
}
};
export const Repl: ReplProps = (props) => {
const { compiler, formatter, linter } = props;
let now: number;
const tabRefs = new Map<number, HTMLSpanElement>();
const [error, setError] = createSignal('');
const [output, setOutput] = createSignal('');
const [universalModuleName, setUniversalModuleName] = createSignal('solid-universal-module');
const [mode, setMode] = createSignal<(typeof compileMode)[keyof typeof compileMode]>(compileMode.DOM);
const userTabs = () => props.tabs.filter((tab) => tab.name != 'import_map.json');
const tabExtension = findExtension(props.tabs[0].name);
function setCurrentTab(current: string) {
const idx = props.tabs.findIndex((tab) => tab.name === current);
if (idx < 0) return;
props.setCurrent(current);
}
function setCurrentName(newName: string) {
const tabs = props.tabs;
tabs.find((tab) => tab.name === props.current).name = newName;
batch(() => {
props.setTabs([...tabs]);
props.setCurrent(newName);
});
}
function removeTab(name: string) {
const tabs = props.tabs;
const idx = tabs.findIndex((tab) => tab.name === name);
const tab = tabs[idx];
if (!tab) return;
const confirmDeletion = confirm(`Are you sure you want to delete ${tab.name}?`);
if (!confirmDeletion) return;
batch(() => {
props.setTabs([...tabs.slice(0, idx), ...tabs.slice(idx + 1)]);
// We want to redirect to another tab if we are deleting the current one
if (props.current === name) {
props.setCurrent(tabs[idx - 1].name);
}
});
}
function addTab() {
const newTab = {
name: `tab${userTabs().length}${tabExtension}`,
source: '',
};
batch(() => {
props.setTabs(props.tabs.concat(newTab));
props.setCurrent(newTab.name);
});
}
function resetTabs() {
const confirmReset = confirm('Are you sure you want to reset the editor?');
if (!confirmReset) return;
props.reset();
}
const [edit, setEdit] = createSignal(-1);
const [outputTab, setOutputTab] = createSignal(0);
const [importMap, setImportMap] = createSignal(getImportMap(props.tabs), {
equals: (a, b) => JSON.stringify(a) === JSON.stringify(b),
});
const outputUri = Uri.parse(`file:///${props.id}/output_dont_import.ts`);
const outputModel = editor.createModel('', 'typescript', outputUri);
onCleanup(() => outputModel.dispose());
const onCompilerMessage = ({ data }: any) => {
const { event, compiled, error } = data;
if (event === 'ERROR') {
console.error(error);
return setError(error.message);
} else setError('');
if (event === 'BABEL') {
outputModel.setValue(compiled);
setOutput('');
}
if (event === 'ROLLUP') {
const currentMap = { ...importMap() };
for (const file in currentMap) {
// Catch any `jspm.dev` URLs and migrate them to `esm.sh`
if (currentMap[file] === `https://jspm.dev/${file}`) {
currentMap[file] = `https://esm.sh/${file}`;
}
if (!(file in compiled) && currentMap[file] === `https://esm.sh/${file}`) {
delete currentMap[file];
}
if (file.split('/')[0] !== 'solid-js' && currentMap[file] === `https://esm.sh/${file}`) {
currentMap[file] = `https://esm.sh/${file}?external=solid-js`;
}
}
for (const file in compiled) {
if (!(file in currentMap) && !file.startsWith('./')) {
currentMap[file] = compiled[file];
}
}
console.log(`Compilation took: ${performance.now() - now}ms`);
batch(() => {
let tab = props.tabs.find((tab) => tab.name === 'import_map.json');
if (!tab) {
tab = {
name: 'import_map.json',
source: JSON.stringify(currentMap, null, 2),
};
props.setTabs(props.tabs.concat(tab));
} else {
tab.source = JSON.stringify(currentMap, null, 2);
const { model } = monacoTabs().get(`file:///${props.id}/import_map.json`)!;
model.setValue(tab.source);
}
setOutput(compiled['./main']);
setImportMap(currentMap);
});
}
};
compiler.addEventListener('message', onCompilerMessage);
onCleanup(() => compiler.removeEventListener('message', onCompilerMessage));
/**
* We need to debounce a bit the compilation because
* it takes ~15ms to compile with the web worker...
* Also, real time feedback can be stressful
*/
const applyCompilation = throttle((message: any) => {
now = performance.now();
compiler.postMessage(message);
}, 250);
const compile = () => {
let compileOpts = mode();
if (compileOpts === compileMode.UNIVERSAL) {
compileOpts = { generate: 'universal', hydratable: false, moduleName: universalModuleName() };
}
applyCompilation(
outputTab() == 0
? {
event: 'ROLLUP',
tabs: unwrap(userTabs()),
}
: {
event: 'BABEL',
tab: unwrap(props.tabs.find((tab) => tab.name == props.current)),
compileOpts,
},
);
};
/**
* The heart of the playground. This recompile on
* every tab source changes.
*/
createEffect(() => {
if (!props.tabs.length) return;
compile();
});
const monacoTabs = createMonacoTabs(props.id, () => props.tabs);
const currentModel = createMemo(() => monacoTabs().get(`file:///${props.id}/${props.current}`)!.model);
let grid!: HTMLDivElement;
let resizer!: HTMLDivElement;
const [left, setLeft] = createSignal(0.625);
const isLarge = createMediaQuery('(min-width: 768px)');
const isHorizontal = () => props.isHorizontal || !isLarge();
const changeLeft = (clientX: number, clientY: number) => {
let position: number;
let size: number;
const rect = grid.getBoundingClientRect();
if (isHorizontal()) {
position = clientY - rect.top - resizer.offsetHeight / 2;
size = grid.offsetHeight - resizer.offsetHeight;
} else {
position = clientX - rect.left - resizer.offsetWidth / 2;
size = grid.offsetWidth - resizer.offsetWidth;
}
const percentage = position / size;
const percentageAdjusted = Math.min(Math.max(percentage, 0.25), 0.75);
setLeft(percentageAdjusted);
};
const [reloadSignal, reload] = createSignal(false, { equals: false });
const [devtoolsOpen, setDevtoolsOpen] = createSignal(!props.hideDevtools);
const [displayErrors, setDisplayErrors] = createSignal(true);
return (
<div
ref={grid}
class="dark:bg-solid-darkbg flex h-full min-h-0 flex-1 flex-col bg-white font-sans text-black dark:text-white"
classList={{
'md:flex-row': !props.isHorizontal,
'dark': props.dark,
}}
>
<div class="flex min-h-0 min-w-0 flex-col" style={`flex: ${left()}`}>
<TabList>
<For each={userTabs()}>
{(tab, index) => (
<TabItem active={props.current === tab.name} class="mr-2">
<div
ref={(el) => tabRefs.set(index(), el)}
class="cursor-pointer select-none rounded border border-solid border-transparent px-3 py-2 transition"
classList={{
'border-transparent': edit() !== index(),
'border-blue-600 outline-none': edit() === index(),
}}
contentEditable={edit() == index()}
onBlur={(e) => {
if (edit() !== index()) return;
setEdit(-1);
setCurrentName(e.currentTarget.textContent!);
}}
onKeyDown={(e) => {
if (e.code === 'Space') e.preventDefault();
if (e.code !== 'Enter') return;
if (edit() === index()) {
setEdit(-1);
setCurrentName(e.currentTarget.textContent!);
e.currentTarget.blur();
} else {
setCurrentTab(tab.name);
}
}}
onClick={() => setCurrentTab(tab.name)}
onDblClick={(e) => {
e.preventDefault();
setEdit(index());
tabRefs.get(index())?.focus();
}}
title={tab.name}
role="button"
tabindex="0"
>
{tab.name}
</div>
<Show when={index() > 0}>
<button
type="button"
class="cursor-pointer"
onClick={() => {
removeTab(tab.name);
}}
>
<span class="sr-only">Delete this tab</span>
<svg style="stroke: currentColor; fill: none;" class="h-4 opacity-60" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</Show>
</TabItem>
)}
</For>
<TabItem class="select-none" active={props.current === 'import_map.json'}>
<label
class="cursor-pointer space-x-2 px-3 py-2"
onclick={() => props.setCurrent('import_map.json')}
onKeyDown={(e) => {
if (e.code === 'Enter') props.setCurrent('import_map.json');
}}
title="Import Map"
role="button"
tabindex="0"
>
<Icon path={inboxStack} class="h-5" />
<span class="sr-only">Import Map</span>
</label>
</TabItem>
<li class="m-0 inline-flex items-center border-b-2 border-transparent">
<button type="button" onClick={addTab} title="Add a new tab">
<span class="sr-only">Add a new tab</span>
<svg
viewBox="0 0 24 24"
style="stroke: currentColor; fill: none;"
class="text-brand-default h-5 dark:text-slate-50"
>
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
</svg>
</button>
</li>
<TabItem class="ml-auto justify-self-end">
<button class="cursor-pointer space-x-2 px-2 py-2" onclick={resetTabs} title="Reset Editor">
<Icon path={trash} class="h-5" />
<span class="sr-only">Reset Editor</span>
</button>
</TabItem>
<TabItem class="select-none justify-self-end">
<label class="cursor-pointer px-3 py-2" title="Display Errors">
<input
type="checkbox"
hidden
checked={displayErrors()}
onChange={(event) => setDisplayErrors(event.currentTarget.checked)}
/>
<Icon path={displayErrors() ? bell : bellSlash} class="h-5" />
<span class="sr-only">Display Errors</span>
</label>
</TabItem>
</TabList>
<Show when={props.current}>
<Editor
model={currentModel()}
onDocChange={(code: string) => {
if (props.current == 'import_map.json') {
const newImportMap = JSON.parse(code);
setImportMap(newImportMap);
} else {
compile();
}
}}
formatter={formatter}
linter={linter}
isDark={props.dark}
withMinimap={false}
onEditorReady={props.onEditorReady}
displayErrors={displayErrors()}
/>
</Show>
<Show when={displayErrors() && error()}>
<Error onDismiss={() => setError('')} message={error()} />
</Show>
</div>
<GridResizer ref={resizer} isHorizontal={isHorizontal()} onResize={changeLeft} />
<div class="flex min-h-0 min-w-0 flex-col" style={`flex: ${1 - left()}`}>
<TabList>
<TabItem>
<button
type="button"
title="Refresh the page"
class="px-3 py-2 active:animate-spin disabled:animate-none disabled:cursor-not-allowed disabled:opacity-25"
onClick={[reload, true]}
disabled={outputTab() != 0}
>
<span class="sr-only">Refresh the page</span>
<Icon path={arrowPath} class="h-5" />
</button>
</TabItem>
<TabItem>
<button
type="button"
title={`${devtoolsOpen() ? 'Close' : 'Open'} the devtools`}
class="px-3 py-2 disabled:cursor-not-allowed disabled:opacity-25"
onClick={() => setDevtoolsOpen(!devtoolsOpen())}
disabled={outputTab() != 0}
>
<span class="sr-only">{devtoolsOpen() ? 'Close' : 'Open'} the devtools</span>
<Icon path={commandLine} class="h-5" />
</button>
</TabItem>
<TabItem class="flex-1" active={outputTab() == 0}>
<button type="button" class="-mb-0.5 w-full py-2" onClick={[setOutputTab, 0]}>
Result
</button>
</TabItem>
<TabItem class="flex-1" active={outputTab() == 1}>
<button
type="button"
class="-mb-0.5 w-full py-2"
onClick={() => {
setOutputTab(1);
}}
>
Output
</button>
</TabItem>
</TabList>
<Switch>
<Match when={outputTab() == 0}>
<Preview
importMap={importMap()}
code={output()}
reloadSignal={reloadSignal()}
devtools={devtoolsOpen()}
isDark={props.dark}
/>
</Match>
<Match when={outputTab() == 1}>
<section class="relative flex min-h-0 min-w-0 flex-1 flex-col divide-y-2 divide-slate-200 dark:divide-neutral-800">
<Editor model={outputModel} isDark={props.dark} disabled withMinimap={false} />
<div class="p-5">
<label class="text-sm font-semibold uppercase">Compile mode</label>
<div class="mt-1 space-y-1 text-sm">
<label class="mr-auto block cursor-pointer space-x-2">
<input
checked={mode() === compileMode.DOM}
value="DOM"
class="text-brand-default"
onChange={[setMode, compileMode.DOM]}
type="radio"
name="dom"
/>
<span>Client side rendering</span>
</label>
<label class="mr-auto block cursor-pointer space-x-2">
<input
checked={mode() === compileMode.SSR}
value="SSR"
class="text-brand-default"
onChange={[setMode, compileMode.SSR]}
type="radio"
name="dom"
/>
<span>Server side rendering</span>
</label>
<label class="mr-auto block cursor-pointer space-x-2">
<input
checked={mode() === compileMode.HYDRATABLE}
value="HYDRATABLE"
class="text-brand-default"
onChange={[setMode, compileMode.HYDRATABLE]}
type="radio"
name="dom"
/>
<span>Client side rendering with hydration</span>
</label>
<label class="mr-auto block cursor-pointer space-x-2">
<input
checked={mode() === compileMode.UNIVERSAL}
value="UNIVERSAL"
class="text-brand-default"
onChange={[setMode, compileMode.UNIVERSAL]}
type="radio"
name="dom"
/>
<span>Universal Rendering & moduleName:</span>
<input
onFocus={[setMode, compileMode.UNIVERSAL]}
onInput={(e) => {
setUniversalModuleName(e.target.value);
}}
class="p-2.5"
type="text"
value={universalModuleName()}
name="moduleName"
/>
</label>
</div>
</div>
</section>
</Match>
</Switch>
</div>
</div>
);
};