-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathindex.ts
More file actions
784 lines (662 loc) · 27.5 KB
/
index.ts
File metadata and controls
784 lines (662 loc) · 27.5 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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
type Sandbox = import("@typescript/sandbox").Sandbox
type Monaco = typeof import("monaco-editor")
declare const window: any
import {
createSidebar,
createTabForPlugin,
createTabBar,
createPluginContainer,
activatePlugin,
createDragBar,
setupSidebarToggle,
createNavigationSection,
} from "./createElements"
import { runWithCustomLogs } from "./sidebar/runtime"
import { createExporter } from "./exporter"
import { createUI } from "./createUI"
import { getExampleSourceCode } from "./getExample"
import { ExampleHighlighter } from "./monaco/ExampleHighlight"
import { createConfigDropdown, updateConfigDropdownForCompilerOptions } from "./createConfigDropdown"
import { allowConnectingToLocalhost, activePlugins, addCustomPlugin } from "./sidebar/plugins"
import { createUtils, PluginUtils } from "./pluginUtils"
import type React from "react"
import { settingsPlugin, getPlaygroundPlugins } from "./sidebar/settings"
import { hideNavForHandbook, showNavForHandbook } from "./navigation"
import { createTwoslashInlayProvider } from "./twoslashInlays"
export { PluginUtils } from "./pluginUtils"
export type PluginFactory = {
(i: (key: string, components?: any) => string, utils: PluginUtils): PlaygroundPlugin
}
/** The interface of all sidebar plugins */
export interface PlaygroundPlugin {
/** Not public facing, but used by the playground to uniquely identify plugins */
id: string
/** To show in the tabs */
displayName: string
/** Should this plugin be selected when the plugin is first loaded? Lets you check for query vars etc to load a particular plugin */
shouldBeSelected?: () => boolean
/** Before we show the tab, use this to set up your HTML - it will all be removed by the playground when someone navigates off the tab */
willMount?: (sandbox: Sandbox, container: HTMLDivElement) => void
/** After we show the tab */
didMount?: (sandbox: Sandbox, container: HTMLDivElement) => void
/** Model changes while this plugin is actively selected */
modelChanged?: (sandbox: Sandbox, model: import("monaco-editor").editor.ITextModel, container: HTMLDivElement) => void
/** Delayed model changes while this plugin is actively selected, useful when you are working with the TS API because it won't run on every keypress */
modelChangedDebounce?: (
sandbox: Sandbox,
model: import("monaco-editor").editor.ITextModel,
container: HTMLDivElement
) => void
/** Before we remove the tab */
willUnmount?: (sandbox: Sandbox, container: HTMLDivElement) => void
/** After we remove the tab */
didUnmount?: (sandbox: Sandbox, container: HTMLDivElement) => void
/** An object you can use to keep data around in the scope of your plugin object */
data?: any
}
interface PlaygroundConfig {
/** Language like "en" / "ja" etc */
lang: string
/** Site prefix, like "v2" during the pre-release */
prefix: string
/** Optional plugins so that we can re-use the playground with different sidebars */
plugins?: PluginFactory[]
/** Should this playground load up custom plugins from localStorage? */
supportCustomPlugins: boolean
}
export const setupPlayground = (
sandbox: Sandbox,
monaco: Monaco,
config: PlaygroundConfig,
i: (key: string) => string,
react: typeof React
) => {
const playgroundParent = sandbox.getDomNode().parentElement!.parentElement!.parentElement!
// UI to the left
const leftNav = createNavigationSection()
playgroundParent.insertBefore(leftNav, sandbox.getDomNode().parentElement!.parentElement!)
const dragBarLeft = createDragBar("left")
playgroundParent.insertBefore(dragBarLeft, sandbox.getDomNode().parentElement!.parentElement!)
const showNav = () => {
const right = document.getElementsByClassName("playground-sidebar").item(0)!
const middle = document.getElementById("editor-container")!
middle.style.width = `calc(100% - ${right.clientWidth + 210}px)`
leftNav.style.display = "block"
leftNav.style.width = "210px"
leftNav.style.minWidth = "210px"
leftNav.style.maxWidth = "210px"
dragBarLeft.style.display = "block"
}
const hideNav = () => {
leftNav.style.display = "none"
dragBarLeft.style.display = "none"
}
hideNav()
// UI to the right
const dragBar = createDragBar("right")
playgroundParent.appendChild(dragBar)
const sidebar = createSidebar()
playgroundParent.appendChild(sidebar)
const tabBar = createTabBar()
sidebar.appendChild(tabBar)
const container = createPluginContainer()
sidebar.appendChild(container)
const plugins = [] as PlaygroundPlugin[]
const tabs = [] as HTMLButtonElement[]
// Let's things like the workbench hook into tab changes
let didUpdateTab: (newPlugin: PlaygroundPlugin, previousPlugin: PlaygroundPlugin) => void | undefined
const registerPlugin = (plugin: PlaygroundPlugin) => {
plugins.push(plugin)
const tab = createTabForPlugin(plugin)
tabs.push(tab)
const tabClicked: HTMLElement["onclick"] = e => {
const previousPlugin = getCurrentPlugin()
let newTab = e.target as HTMLElement
// It could be a notification you clicked on
if (newTab.tagName === "DIV") newTab = newTab.parentElement!
const newPlugin = plugins.find(p => `playground-plugin-tab-${p.id}` == newTab.id)!
activatePlugin(newPlugin, previousPlugin, sandbox, tabBar, container)
didUpdateTab && didUpdateTab(newPlugin, previousPlugin)
}
tabBar.appendChild(tab)
tab.onclick = tabClicked
}
const setDidUpdateTab = (func: (newPlugin: PlaygroundPlugin, previousPlugin: PlaygroundPlugin) => void) => {
didUpdateTab = func
}
const getCurrentPlugin = () => {
const selectedTab = tabs.find(t => t.classList.contains("active"))!
return plugins[tabs.indexOf(selectedTab)]
}
const defaultPlugins = config.plugins || getPlaygroundPlugins()
const utils = createUtils(sandbox, react)
const initialPlugins = defaultPlugins.map(f => f(i, utils))
initialPlugins.forEach(p => registerPlugin(p))
// Choose which should be selected
const priorityPlugin = plugins.find(plugin => plugin.shouldBeSelected && plugin.shouldBeSelected())
const selectedPlugin = priorityPlugin || plugins[0]
const selectedTab = tabs[plugins.indexOf(selectedPlugin)]!
selectedTab.onclick!({ target: selectedTab } as any)
let debouncingTimer = false
sandbox.editor.onDidChangeModelContent(_event => {
const plugin = getCurrentPlugin()
if (plugin.modelChanged) plugin.modelChanged(sandbox, sandbox.getModel(), container)
// This needs to be last in the function
if (debouncingTimer) return
debouncingTimer = true
setTimeout(() => {
debouncingTimer = false
playgroundDebouncedMainFunction()
// Only call the plugin function once every 0.3s
if (plugin.modelChangedDebounce && plugin.id === getCurrentPlugin().id) {
plugin.modelChangedDebounce(sandbox, sandbox.getModel(), container)
}
}, 300)
})
// When there are multi-file playgrounds, we should show the implicit filename, ideally this would be
// something more inline, but we can abuse the code lenses for now because they get their own line!
sandbox.monaco.languages.registerCodeLensProvider(sandbox.language, {
provideCodeLenses: function (model, token) {
// If you have @filename on the first line, don't show the implicit filename
const lenses =
!showFileCodeLens && !model.getLineContent(1).startsWith("// @filename")
? []
: [
{
range: {
startLineNumber: 1,
startColumn: 1,
endLineNumber: 2,
endColumn: 1,
},
id: "implicit-filename-first",
command: {
id: "noop",
title: `// @filename: ${sandbox.filepath}`,
},
},
]
return { lenses, dispose: () => {} }
},
})
let showFileCodeLens = false
// If you set this to true, then the next time the playground would
// have set the user's hash it would be skipped - used for setting
// the text in examples
let suppressNextTextChangeForHashChange = false
// Sets the URL and storage of the sandbox string
const playgroundDebouncedMainFunction = () => {
showFileCodeLens = sandbox.getText().includes("// @filename")
localStorage.setItem("sandbox-history", sandbox.getText())
}
sandbox.editor.onDidBlurEditorText(() => {
const alwaysUpdateURL = !localStorage.getItem("disable-save-on-type")
if (alwaysUpdateURL) {
if (suppressNextTextChangeForHashChange) {
suppressNextTextChangeForHashChange = false
return
}
const newURL = sandbox.createURLQueryWithCompilerOptions(sandbox)
window.history.replaceState({}, "", newURL)
}
})
// Keeps track of whether the project has been set up as an ESM module via a package.json
let isESMMode = false
// When any compiler flags are changed, trigger a potential change to the URL
sandbox.setDidUpdateCompilerSettings(async () => {
playgroundDebouncedMainFunction()
const model = sandbox.editor.getModel()
const plugin = getCurrentPlugin()
if (model && plugin.modelChanged) plugin.modelChanged(sandbox, model, container)
if (model && plugin.modelChangedDebounce) plugin.modelChangedDebounce(sandbox, model, container)
const alwaysUpdateURL = !localStorage.getItem("disable-save-on-type")
if (alwaysUpdateURL) {
const newURL = sandbox.createURLQueryWithCompilerOptions(sandbox)
window.history.replaceState({}, "", newURL)
}
// Add an outer package.json with 'module: type' and ensures all the
// other settings are inline for ESM mode
const moduleNumber = (sandbox.getCompilerOptions().module as number) || 0
const isESMviaModule = moduleNumber > 99 && moduleNumber < 200
const moduleResNumber = sandbox.getCompilerOptions().moduleResolution || 0
const isESMviaModuleRes = moduleResNumber > 2 && moduleResNumber < 100
if (isESMviaModule || isESMviaModuleRes) {
if (isESMMode) return
isESMMode = true
setTimeout(() => {
ui.flashInfo(i("play_esm_mode"))
}, 300)
const nextRes = (
moduleNumber === 199 || moduleNumber === 100 ? 99 : 2
) as import("monaco-editor").languages.typescript.ModuleResolutionKind
sandbox.setCompilerSettings({ target: 99, moduleResolution: nextRes, module: moduleNumber })
sandbox.addLibraryToRuntime(JSON.stringify({ name: "playground", type: "module" }), "/package.json")
}
})
const skipInitiallySettingHash = document.location.hash && document.location.hash.includes("example/")
if (!skipInitiallySettingHash) playgroundDebouncedMainFunction()
// Setup working with the existing UI, once it's loaded
// Versions of TypeScript
// Set up the label for the dropdown
const versionButton = document.querySelectorAll("#versions > a").item(0)
versionButton.textContent = "v" + sandbox.ts.version + " "
const caret = document.createElement("spam")
caret.classList.add("caret")
versionButton.appendChild(caret)
versionButton.setAttribute("aria-label", `Select version of TypeScript, currently ${sandbox.ts.version}`)
// Add the versions to the dropdown
const versionsMenu = document.querySelectorAll("#versions > ul").item(0)
// Enable all submenus
document.querySelectorAll("nav ul li").forEach(e => e.classList.add("active"))
const notWorkingInPlayground = ["3.1.6", "3.0.1", "2.8.1", "2.7.2", "2.4.1"]
const allVersions = ["Nightly", ...sandbox.supportedVersions.filter(f => !notWorkingInPlayground.includes(f))]
allVersions.forEach((v: string) => {
const li = document.createElement("li")
const a = document.createElement("a")
let display = v
if (v.includes("-dev.")) {
const match = v.match(/-dev\.(\d{4})(\d{2})(\d{2})$/)
if (match) {
const date = `${match[1]}-${match[2]}-${match[3]}`
display = v + " (" + date + ")"
}
}
a.textContent = display
a.href = "#"
if (v === "Nightly") {
li.classList.add("nightly")
}
if (v.toLowerCase().includes("beta")) {
li.classList.add("beta")
}
li.onclick = () => {
const currentURL = sandbox.createURLQueryWithCompilerOptions(sandbox)
const params = new URLSearchParams(currentURL.split("#")[0])
const version = v === "Nightly" ? "next" : v
params.set("ts", version)
const hash = document.location.hash.length ? document.location.hash : ""
const newURL = `${document.location.protocol}//${document.location.host}${document.location.pathname}?${params}${hash}`
// @ts-ignore - it is allowed
document.location = newURL
}
li.appendChild(a)
versionsMenu.appendChild(li)
})
// Support dropdowns
document.querySelectorAll(".navbar-sub li.dropdown > a").forEach(link => {
const a = link as HTMLAnchorElement
a.onclick = _e => {
if (a.parentElement!.classList.contains("open")) {
escapePressed()
} else {
escapePressed()
a.parentElement!.classList.toggle("open")
a.setAttribute("aria-expanded", "true")
const exampleContainer = a.closest("li")!.getElementsByClassName("dropdown-dialog").item(0) as HTMLElement
if (!exampleContainer) return
const firstLabel = exampleContainer.querySelector("label") as HTMLElement
if (firstLabel) firstLabel.focus()
// Set exact height and widths for the popovers for the main playground navigation
const isPlaygroundSubmenu = !!a.closest("nav")
if (isPlaygroundSubmenu) {
const playgroundContainer = document.getElementById("playground-container")!
exampleContainer.style.height = `calc(${playgroundContainer.getBoundingClientRect().height + 26}px - 4rem)`
const sideBarWidth = (document.querySelector(".playground-sidebar") as any).offsetWidth
exampleContainer.style.width = `calc(100% - ${sideBarWidth}px - 71px)`
// All this is to make sure that tabbing stays inside the dropdown for tsconfig/examples
const buttons = exampleContainer.querySelectorAll("input")
const lastButton = buttons.item(buttons.length - 1) as HTMLElement
if (lastButton) {
redirectTabPressTo(lastButton, exampleContainer, ".examples-close")
} else {
const sections = document.querySelectorAll(".dropdown-dialog .section-content")
sections.forEach(s => {
const buttons = s.querySelectorAll("a.example-link")
const lastButton = buttons.item(buttons.length - 1) as HTMLElement
if (lastButton) {
redirectTabPressTo(lastButton, exampleContainer, ".examples-close")
}
})
}
}
}
return false
}
})
/** Handles removing the dropdowns like tsconfig/examples/handbook */
const escapePressed = () => {
document.querySelectorAll(".navbar-sub li.open").forEach(i => i.classList.remove("open"))
document.querySelectorAll(".navbar-sub li").forEach(i => i.setAttribute("aria-expanded", "false"))
hideNavForHandbook(sandbox)
}
// Handle escape closing dropdowns etc
document.onkeydown = function (evt) {
evt = evt || window.event
var isEscape = false
if ("key" in evt) {
isEscape = evt.key === "Escape" || evt.key === "Esc"
} else {
// @ts-ignore - this used to be the case
isEscape = evt.keyCode === 27
}
if (isEscape) escapePressed()
}
const shareAction = {
id: "copy-clipboard",
label: "Save to clipboard",
keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyS],
contextMenuGroupId: "run",
contextMenuOrder: 1.5,
run: function () {
// Update the URL, then write that to the clipboard
const newURL = sandbox.createURLQueryWithCompilerOptions(sandbox)
window.history.replaceState({}, "", newURL)
window.navigator.clipboard.writeText(location.href.toString()).then(
() => ui.flashInfo(i("play_export_clipboard")),
(e: any) => alert(e)
)
},
}
const shareButton = document.getElementById("share-button")
if (shareButton) {
shareButton.onclick = e => {
e.preventDefault()
shareAction.run()
return false
}
// Set up some key commands
sandbox.editor.addAction(shareAction)
sandbox.editor.addAction({
id: "run-js",
label: "Run the evaluated JavaScript for your TypeScript file",
keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyCode.Enter],
contextMenuGroupId: "run",
contextMenuOrder: 1.5,
run: function (ed) {
const runButton = document.getElementById("run-button")
runButton && runButton.onclick && runButton.onclick({} as any)
},
})
}
const runButton = document.getElementById("run-button")
if (runButton) {
runButton.onclick = () => {
const run = sandbox.getRunnableJS()
const runPlugin = plugins.find(p => p.id === "logs")!
activatePlugin(runPlugin, getCurrentPlugin(), sandbox, tabBar, container)
runWithCustomLogs(run, i)
const isJS = sandbox.config.filetype === "js"
ui.flashInfo(i(isJS ? "play_run_js" : "play_run_ts"))
return false
}
}
// Handle the close buttons on the examples
document.querySelectorAll("button.examples-close").forEach(b => {
const button = b as HTMLButtonElement
button.onclick = escapePressed
})
// Support clicking the handbook button on the top nav
const handbookButton = document.getElementById("handbook-button")
if (handbookButton) {
handbookButton.onclick = () => {
// Two potentially concurrent sidebar navs is just a bit too much
// state to keep track of ATM
if (!handbookButton.parentElement!.classList.contains("active")) {
ui.flashInfo("Cannot open the Playground handbook when in a Gist")
return
}
const showingHandbook = handbookButton.parentElement!.classList.contains("open")
if (!showingHandbook) {
escapePressed()
showNav()
handbookButton.parentElement!.classList.add("open")
showNavForHandbook(sandbox, escapePressed)
} else {
escapePressed()
}
return false
}
}
setupSidebarToggle()
if (document.getElementById("config-container")) {
createConfigDropdown(sandbox, monaco)
updateConfigDropdownForCompilerOptions(sandbox, monaco)
}
if (document.getElementById("playground-settings")) {
const settingsToggle = document.getElementById("playground-settings")!
settingsToggle.onclick = () => {
const open = settingsToggle.parentElement!.classList.contains("open")
const sidebarTabs = document.querySelector(".playground-plugin-tabview") as HTMLDivElement
const sidebarContent = document.querySelector(".playground-plugin-container") as HTMLDivElement
let settingsContent = document.querySelector(".playground-settings-container") as HTMLDivElement
if (!settingsContent) {
settingsContent = document.createElement("div")
settingsContent.className = "playground-settings-container playground-plugin-container"
const settings = settingsPlugin(i, utils)
settings.didMount && settings.didMount(sandbox, settingsContent)
document.querySelector(".playground-sidebar")!.appendChild(settingsContent)
// When the last tab item is hit, go back to the settings button
const labels = document.querySelectorAll(".playground-sidebar input")
const lastLabel = labels.item(labels.length - 1) as HTMLElement
if (lastLabel) {
redirectTabPressTo(lastLabel, undefined, "#playground-settings")
}
}
if (open) {
sidebarTabs.style.display = "flex"
sidebarContent.style.display = "block"
settingsContent.style.display = "none"
} else {
sidebarTabs.style.display = "none"
sidebarContent.style.display = "none"
settingsContent.style.display = "block"
document.querySelector<HTMLElement>(".playground-sidebar label")!.focus()
}
settingsToggle.parentElement!.classList.toggle("open")
}
settingsToggle.addEventListener("keydown", e => {
const isOpen = settingsToggle.parentElement!.classList.contains("open")
if (e.key === "Tab" && isOpen) {
const result = document.querySelector(".playground-options li input") as any
result.focus()
e.preventDefault()
}
})
}
// Support grabbing examples from the location hash
if (location.hash.startsWith("#example")) {
const exampleName = location.hash.replace("#example/", "").trim()
sandbox.config.logger.log("Loading example:", exampleName)
getExampleSourceCode(config.prefix, config.lang, exampleName).then(ex => {
if (ex.example && ex.code) {
const { example, code } = ex
// Update the localstorage showing that you've seen this page
if (localStorage) {
const seenText = localStorage.getItem("examples-seen") || "{}"
const seen = JSON.parse(seenText)
seen[example.id] = example.hash
localStorage.setItem("examples-seen", JSON.stringify(seen))
}
const allLinks = document.querySelectorAll("example-link")
// @ts-ignore
for (const link of allLinks) {
if (link.textContent === example.title) {
link.classList.add("highlight")
}
}
document.title = "TypeScript Playground - " + example.title
suppressNextTextChangeForHashChange = true
sandbox.setText(code)
} else {
suppressNextTextChangeForHashChange = true
sandbox.setText("// There was an issue getting the example, bad URL? Check the console in the developer tools")
}
})
}
// Set the errors number in the sidebar tabs
const model = sandbox.getModel()
model.onDidChangeDecorations(() => {
const markers = sandbox.monaco.editor.getModelMarkers({ resource: model.uri }).filter(m => m.severity !== 1)
utils.setNotifications("errors", markers.length)
})
// Sets up a way to click between examples
monaco.languages.registerLinkProvider(sandbox.language, new ExampleHighlighter())
const languageSelector = document.getElementById("language-selector") as HTMLSelectElement
if (languageSelector) {
const params = new URLSearchParams(location.search)
const options = ["ts", "d.ts", "js"]
languageSelector.options.selectedIndex = options.indexOf(params.get("filetype") || "ts")
languageSelector.onchange = () => {
const filetype = options[Number(languageSelector.selectedIndex || 0)]
const query = sandbox.createURLQueryWithCompilerOptions(sandbox, { filetype })
const fullURL = `${document.location.protocol}//${document.location.host}${document.location.pathname}${query}`
// @ts-ignore
document.location = fullURL
}
}
// Ensure that the editor is full-width when the screen resizes
window.addEventListener("resize", () => {
sandbox.editor.layout()
})
// Tells monaco to check out the font sizes in order to make
// sure that selecting text in the editor provides the same
// length as unselected text - otherwise space for a selection
// will be a little bit wider than it should be. s
setTimeout(() => {
monaco.editor.remeasureFonts()
}, 5000)
const ui = createUI()
const exporter = createExporter(sandbox, monaco, ui)
const playground = {
exporter,
ui,
registerPlugin,
plugins,
getCurrentPlugin,
tabs,
setDidUpdateTab,
createUtils,
}
window.ts = sandbox.ts
window.sandbox = sandbox
window.playground = playground
console.log(`Using TypeScript ${window.ts.version}`)
console.log("Available globals:")
console.log("\twindow.ts", window.ts)
console.log("\twindow.sandbox", window.sandbox)
console.log("\twindow.playground", window.playground)
console.log("\twindow.react", window.react)
console.log("\twindow.reactDOM", window.reactDOM)
/** The plugin system */
const activateExternalPlugin = (
plugin: PlaygroundPlugin | ((utils: PluginUtils) => PlaygroundPlugin),
autoActivate: boolean
) => {
let readyPlugin: PlaygroundPlugin
// Can either be a factory, or object
if (typeof plugin === "function") {
const utils = createUtils(sandbox, react)
readyPlugin = plugin(utils)
} else {
readyPlugin = plugin
}
if (autoActivate) {
console.log(readyPlugin)
}
playground.registerPlugin(readyPlugin)
// Auto-select the dev plugin
const pluginWantsFront = readyPlugin.shouldBeSelected && readyPlugin.shouldBeSelected()
if (pluginWantsFront || autoActivate) {
// Auto-select the dev plugin
activatePlugin(readyPlugin, getCurrentPlugin(), sandbox, tabBar, container)
}
}
// Dev mode plugin
if (config.supportCustomPlugins && allowConnectingToLocalhost()) {
window.exports = {}
console.log("Connecting to dev plugin")
try {
// @ts-ignore
const re = window.require
re(["local/index"], (devPlugin: any) => {
console.log("Set up dev plugin from localhost:5000")
try {
activateExternalPlugin(devPlugin, true)
} catch (error) {
console.error(error)
setTimeout(() => {
ui.flashInfo("Error: Could not load dev plugin from localhost:5000")
}, 700)
}
})
} catch (error) {
console.error("Problem loading up the dev plugin")
console.error(error)
}
}
const downloadPlugin = (plugin: string, autoEnable: boolean) => {
try {
// @ts-ignore
const re = window.require
re([`unpkg/${plugin}@latest/dist/index`], (devPlugin: PlaygroundPlugin) => {
activateExternalPlugin(devPlugin, autoEnable)
})
} catch (error) {
console.error("Problem loading up the plugin:", plugin)
console.error(error)
}
}
if (config.supportCustomPlugins) {
// Grab ones from localstorage
activePlugins().forEach(p => downloadPlugin(p.id, false))
// Offer to install one if 'install-plugin' is a query param
const params = new URLSearchParams(location.search)
const pluginToInstall = params.get("install-plugin")
if (pluginToInstall) {
const alreadyInstalled = activePlugins().find(p => p.id === pluginToInstall)
if (!alreadyInstalled) {
const shouldDoIt = confirm("Would you like to install the third party plugin?\n\n" + pluginToInstall)
if (shouldDoIt) {
addCustomPlugin(pluginToInstall)
downloadPlugin(pluginToInstall, true)
}
}
}
}
const [tsMajor, tsMinor] = sandbox.ts.version.split(".")
if (
(parseInt(tsMajor) > 4 || (parseInt(tsMajor) == 4 && parseInt(tsMinor) >= 6)) &&
monaco.languages.registerInlayHintsProvider
) {
monaco.languages.registerInlayHintsProvider(sandbox.language, createTwoslashInlayProvider(sandbox))
}
if (location.hash.startsWith("#show-examples")) {
setTimeout(() => {
document.getElementById("examples-button")?.click()
}, 100)
}
if (location.hash.startsWith("#show-whatisnew")) {
setTimeout(() => {
document.getElementById("whatisnew-button")?.click()
}, 100)
}
// Auto-load into the playground
if (location.hash.startsWith("#handbook")) {
setTimeout(() => {
document.getElementById("handbook-button")?.click()
}, 100)
}
return playground
}
export type Playground = ReturnType<typeof setupPlayground>
const redirectTabPressTo = (element: HTMLElement, container: HTMLElement | undefined, query: string) => {
element.addEventListener("keydown", e => {
if (e.key === "Tab") {
const host = container || document
const result = host.querySelector(query) as any
if (!result) throw new Error(`Expected to find a result for keydown`)
result.focus()
e.preventDefault()
}
})
}