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