-
Notifications
You must be signed in to change notification settings - Fork 67
Expand file tree
/
Copy pathrepl.tsx
More file actions
398 lines (356 loc) · 13.2 KB
/
repl.tsx
File metadata and controls
398 lines (356 loc) · 13.2 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
import { Show, For, createSignal, createEffect, batch, Match, Switch, onCleanup } from 'solid-js';
import { Icon } from 'solid-heroicons';
import { arrowPath, commandLine } 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 MonacoTabs from './editor/monacoTabs';
import Editor from './editor';
import type { Repl as ReplProps } from 'solid-repl/lib/repl';
const compileMode = {
SSR: { generate: 'ssr', hydratable: true },
DOM: { generate: 'dom', hydratable: false },
HYDRATABLE: { generate: 'dom', hydratable: true },
} as const;
const Repl: ReplProps = (props) => {
const { compiler, formatter, linter } = props;
let now: number;
const tabRefs : HTMLDivElement[] = [];
const [error, setError] = createSignal('');
const [compiled, setCompiled] = createSignal('');
const [mode, setMode] = createSignal<typeof compileMode[keyof typeof compileMode]>(compileMode.DOM);
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${props.tabs.length}.tsx`,
source: '',
};
batch(() => {
props.setTabs(props.tabs.concat(newTab));
props.setCurrent(newTab.name);
});
}
const [edit, setEdit] = createSignal(-1);
const [outputTab, setOutputTab] = createSignal(0);
let model: editor.ITextModel;
createEffect(() => {
const uri = Uri.parse(`file:///${props.id}/output_dont_import.tsx`);
model = editor.createModel('', 'typescript', uri);
onCleanup(() => model.dispose());
});
compiler.addEventListener('message', ({ data }) => {
const { event, compiled, error } = data;
if (event === 'ERROR') return setError(error);
else setError('');
if (event === 'ROLLUP') {
setCompiled(compiled);
} else if (event === 'BABEL') {
model.setValue(compiled);
}
console.log(`Compilation took: ${performance.now() - now}ms`);
});
/**
* 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 = () => {
applyCompilation(
outputTab() == 0
? {
event: 'ROLLUP',
tabs: unwrap(props.tabs),
}
: {
event: 'BABEL',
tab: unwrap(props.tabs.find((tab) => tab.name == props.current)),
compileOpts: mode(),
},
);
};
/**
* The heart of the playground. This recompile on
* every tab source changes.
*/
createEffect(() => {
if (!props.tabs.length) return;
compile();
});
const clampPercentage = (percentage: number, lowerBound: number, upperBound: number) => {
return Math.min(Math.max(percentage, lowerBound), upperBound);
};
let grid!: HTMLDivElement;
let resizer!: HTMLDivElement;
const [left, setLeft] = createSignal(1.25);
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 = clampPercentage(percentage * 2, 0.5, 1.5);
setLeft(percentageAdjusted);
};
const [reloadSignal, reload] = createSignal(false, { equals: false });
const [devtoolsOpen, setDevtoolsOpen] = createSignal(true);
const [displayErrors, setDisplayErrors] = createSignal(true);
return (
<div
ref={grid}
class="dark:bg-solid-darkbg grid h-full min-h-0 bg-white font-sans text-black dark:text-white"
classList={{
'wrapper--forced': props.isHorizontal,
'wrapper': !props.isHorizontal,
'dark': props.dark,
}}
style={{
'--left': `${left()}fr`,
'--right': `${2 - left()}fr`,
}}
>
<div class="flex h-full flex-col">
<TabList>
<For each={props.tabs}>
{(tab, index) => (
<TabItem active={props.current === tab.name} class="mr-2">
<div
ref={(el) => tabRefs[index()] = el}
class="cursor-pointer select-none rounded border border-solid border-transparent py-2 px-3 transition focus:border-blue-600 focus:outline-none"
contentEditable={edit() == index()}
onBlur={(e) => {
setEdit(-1);
if (e.currentTarget.textContent) {
setCurrentName(e.currentTarget.textContent);
} else {
e.currentTarget.textContent = tab.name;
}
}}
onKeyDown={(e) => {
if (e.code === 'Space') e.preventDefault();
if (e.code !== 'Enter' && e.code !== 'Escape') return;
e.currentTarget.blur();
}}
onClick={() => setCurrentTab(tab.name)}
onDblClick={(e) => {
e.preventDefault();
setEdit(index());
tabRefs[index()]?.focus();
// Fix for FireFox when editing the same tab twice
window.getSelection()?.setPosition(e.target, 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>
<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">
<label class="cursor-pointer space-x-2 px-3 py-2">
<input
type="checkbox"
name="display-errors"
checked={displayErrors()}
onChange={(event) => setDisplayErrors(event.currentTarget.checked)}
/>
<span>Display Errors</span>
</label>
</TabItem>
</TabList>
<MonacoTabs tabs={props.tabs} folder={props.id} />
<Show when={props.current}>
<Editor
url={`file:///${props.id}/${props.current}`}
onDocChange={() => 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 h-full flex-col">
<TabList>
<TabItem>
<button
type="button"
title="Refresh the page"
class="py-2 px-3 active:animate-spin 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="Open the devtools"
class="py-2 px-3 disabled:cursor-not-allowed disabled:opacity-25"
onClick={() => setDevtoolsOpen(!devtoolsOpen())}
disabled={outputTab() != 0}
>
<span class="sr-only">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);
setMode(compileMode.DOM);
}}
>
Output
</button>
</TabItem>
</TabList>
<Switch>
<Match when={outputTab() == 0}>
<Preview
reloadSignal={reloadSignal()}
devtools={devtoolsOpen()}
isDark={props.dark}
code={compiled()}
classList={{
'md:row-start-2': !props.isHorizontal,
}}
/>
</Match>
<Match when={outputTab() == 1}>
<section class="relative flex h-full flex-col divide-y-2 divide-slate-200 dark:divide-neutral-800">
<Editor
url={`file:///${props.id}/output_dont_import.tsx`}
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>
</div>
</div>
</section>
</Match>
</Switch>
</div>
</div>
);
};
export default Repl;