/
playground.ts
313 lines (276 loc) · 9.37 KB
/
playground.ts
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
/*!
* @license
* Copyright 2021 The Go Authors. All rights reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file.
*/
// This file implements the playground implementation of the documentation
// page. The playground involves a "play" button that allows you to open up
// a new link to play.golang.org using the example code.
// The CSS is in static/frontend/unit/main/_doc.css
/**
* CSS classes used by PlaygroundExampleController
*/
const PlayExampleClassName = {
PLAY_HREF: '.js-exampleHref',
PLAY_CONTAINER: '.js-exampleContainer',
EXAMPLE_INPUT: '.Documentation-exampleCode',
EXAMPLE_OUTPUT: '.Documentation-exampleOutput',
EXAMPLE_ERROR: '.Documentation-exampleError',
PLAY_BUTTON: '.Documentation-examplePlayButton',
SHARE_BUTTON: '.Documentation-exampleShareButton',
FORMAT_BUTTON: '.Documentation-exampleFormatButton',
RUN_BUTTON: '.Documentation-exampleRunButton',
};
/**
* This controller enables playground examples to expand their dropdown or
* generate shareable Go Playground URLs.
*/
export class PlaygroundExampleController {
/**
* The anchor tag used to identify the container with an example href.
* There is only one in an example container div.
*/
private readonly anchorEl: HTMLAnchorElement | null;
/**
* The error element
*/
private readonly errorEl: Element | null;
/**
* Buttons that redirect to an example's playground, this element
* only exists in executable examples.
*/
private readonly playButtonEl: Element | null;
private readonly shareButtonEl: Element | null;
/**
* Button that formats the code in an example's playground.
*/
private readonly formatButtonEl: Element | null;
/**
* Button that runs the code in an example's playground, this element
* only exists in executable examples.
*/
private readonly runButtonEl: Element | null;
/**
* The executable code of an example.
*/
private readonly inputEl: HTMLTextAreaElement | null;
/**
* The output of the given example code. This only exists if the
* author of the package provides an output for this example.
*/
private readonly outputEl: Element | null;
/**
* @param exampleEl The div that contains playground content for the given example.
*/
constructor(private readonly exampleEl: HTMLDetailsElement) {
this.exampleEl = exampleEl;
this.anchorEl = exampleEl.querySelector('a');
this.errorEl = exampleEl.querySelector(PlayExampleClassName.EXAMPLE_ERROR);
this.playButtonEl = exampleEl.querySelector(PlayExampleClassName.PLAY_BUTTON);
this.shareButtonEl = exampleEl.querySelector(PlayExampleClassName.SHARE_BUTTON);
this.formatButtonEl = exampleEl.querySelector(PlayExampleClassName.FORMAT_BUTTON);
this.runButtonEl = exampleEl.querySelector(PlayExampleClassName.RUN_BUTTON);
this.inputEl = this.makeTextArea(exampleEl.querySelector(PlayExampleClassName.EXAMPLE_INPUT));
this.outputEl = exampleEl.querySelector(PlayExampleClassName.EXAMPLE_OUTPUT);
// This is legacy listener to be replaced the listener for shareButtonEl.
this.playButtonEl?.addEventListener('click', () => this.handleShareButtonClick());
this.shareButtonEl?.addEventListener('click', () => this.handleShareButtonClick());
this.formatButtonEl?.addEventListener('click', () => this.handleFormatButtonClick());
this.runButtonEl?.addEventListener('click', () => this.handleRunButtonClick());
if (!this.inputEl) return;
this.resize();
this.inputEl.addEventListener('keyup', () => this.resize());
this.inputEl.addEventListener('keydown', e => this.onKeydown(e));
}
/**
* Replace the pre element with a textarea. The examples are initially rendered
* as pre elements so they're fully visible when JS is disabled.
*/
makeTextArea(el: Element | null): HTMLTextAreaElement {
const t = document.createElement('textarea');
t.classList.add('Documentation-exampleCode', 'code');
t.spellcheck = false;
t.value = el?.textContent ?? '';
el?.parentElement?.replaceChild(t, el);
return t;
}
/**
* Retrieve the hash value of the anchor element.
*/
getAnchorHash(): string | undefined {
return this.anchorEl?.hash;
}
/**
* Expands the current playground example.
*/
expand(): void {
this.exampleEl.open = true;
}
/**
* Resizes the input element to accommodate the amount of text present.
*/
private resize(): void {
if (this.inputEl?.value) {
const numLineBreaks = (this.inputEl.value.match(/\n/g) || []).length;
// min-height + lines x line-height + padding + border
this.inputEl.style.height = `${(20 + numLineBreaks * 20 + 12 + 2) / 16}rem`;
}
}
/**
* Handler to override keyboard behavior in the playground's
* textarea element.
*
* Tab key inserts tabs into the example playground instead of
* switching to the next interactive element.
* @param e input element keyboard event.
*/
private onKeydown(e: KeyboardEvent) {
if (e.key === 'Tab') {
document.execCommand('insertText', false, '\t');
e.preventDefault();
}
}
/**
* Changes the text of the example's input box.
*/
private setInputText(output: string) {
if (this.inputEl) {
this.inputEl.value = output;
}
}
/**
* Changes the text of the example's output box.
*/
private setOutputText(output: string) {
if (this.outputEl) {
this.outputEl.textContent = output;
}
}
private setOutputHTML(output: string) {
if (this.outputEl) {
this.outputEl.innerHTML = output;
}
}
/**
* Sets the error message text and overwrites
* output box to indicate a failed response.
*/
private setErrorText(err: string) {
if (this.errorEl) {
this.errorEl.textContent = err;
}
this.setOutputText('An error has occurred…');
}
private getCodeWithModFile(): string {
let codeWithModFile = this.inputEl?.value ?? '';
const moduleVars = document.querySelector<HTMLDivElement>('.js-playgroundVars')?.dataset ?? {};
if (moduleVars.modulepath !== 'std') {
codeWithModFile = codeWithModFile.concat(`
-- go.mod --
module play.ground
require ${moduleVars.modulepath} ${moduleVars.version}
`);
}
return codeWithModFile;
}
/**
* Opens a new window to play.golang.org using the
* example snippet's code in the playground.
*/
private handleShareButtonClick() {
const PLAYGROUND_BASE_URL = 'https://play.golang.org/p/';
this.setOutputText('Waiting for remote server…');
fetch('/play/share', {
method: 'POST',
body: this.getCodeWithModFile(),
})
.then(res => res.text())
.then(shareId => {
const href = PLAYGROUND_BASE_URL + shareId;
this.setOutputHTML(`<a href="${href}">${href}</a>`);
window.open(href);
})
.catch(err => {
this.setErrorText(err);
});
}
/**
* Runs gofmt on the example snippet in the playground.
*/
private handleFormatButtonClick() {
this.setOutputText('Waiting for remote server…');
const body = new FormData();
body.append('body', this.inputEl?.value ?? '');
fetch('/play/fmt', {
method: 'POST',
body: body,
})
.then(res => res.json())
.then(({ Body, Error }) => {
this.setOutputText(Error || 'Done.');
if (Body) {
this.setInputText(Body);
this.resize();
}
})
.catch(err => {
this.setErrorText(err);
});
}
/**
* Runs the code snippet in the example playground.
*/
private handleRunButtonClick() {
this.setOutputText('Waiting for remote server…');
fetch('/play/compile', {
method: 'POST',
body: JSON.stringify({ body: this.getCodeWithModFile(), version: 2 }),
})
.then(res => res.json())
.then(async ({ Events, Errors }) => {
this.setOutputText(Errors || '');
for (const e of Events || []) {
this.setOutputText(e.Message);
await new Promise(resolve => setTimeout(resolve, e.Delay / 1000000));
}
})
.catch(err => {
this.setErrorText(err);
});
}
}
export function initPlaygrounds(): void {
const exampleHashRegex = location.hash.match(/^#(example-.*)$/);
if (exampleHashRegex) {
const exampleHashEl = document.getElementById(exampleHashRegex[1]) as HTMLDetailsElement;
if (exampleHashEl) {
exampleHashEl.open = true;
}
}
// We use a spread operator to convert a nodelist into an array of elements.
const exampleHrefs = [
...document.querySelectorAll<HTMLAnchorElement>(PlayExampleClassName.PLAY_HREF),
];
/**
* Sometimes exampleHrefs and playContainers are in different order, so we
* find an exampleHref from a common hash.
* @param playContainer - playground container
*/
const findExampleHash = (playContainer: PlaygroundExampleController) =>
exampleHrefs.find(ex => {
return ex.hash === playContainer.getAnchorHash();
});
for (const el of document.querySelectorAll(PlayExampleClassName.PLAY_CONTAINER)) {
// There should be the same amount of hrefs referencing examples as example containers.
const playContainer = new PlaygroundExampleController(el as HTMLDetailsElement);
const exampleHref = findExampleHash(playContainer);
if (exampleHref) {
exampleHref.addEventListener('click', () => {
playContainer.expand();
});
} else {
console.warn('example href not found');
}
}
}