From 2c462247786cdd6fe65ab918922bf9deb4d94cf8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20H=C3=A4drich?= <11225821+shaedrich@users.noreply.github.com> Date: Wed, 29 May 2024 01:42:13 +0200 Subject: [PATCH] Add ability to run code examples in the playground: Fetch tutorial snippet from URL by file name (#205) See https://github.com/ponylang/pony-tutorial/issues/340 > [!WARNING] Will only work, after #222 has been merged. Example: https://playground.ponylang.io/?snippet=hello-world-main.pony Co-authored-by: Joe Eli McIlvain --------- Co-authored-by: Matthias Wahl Co-authored-by: Joe Eli McIlvain --- static/web.js | 33 ++++++++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/static/web.js b/static/web.js index 8b36e7f..ec28e27 100644 --- a/static/web.js +++ b/static/web.js @@ -320,7 +320,7 @@ } /** - * + * Fetches a gist from the [gist.github.com](https://gist.github.com/) and loads it into the code editor * @param {Ace.EditSession} session (see [ace.Ace.Editor::getSession](https://ajaxorg.github.io/ace-api-docs/interfaces/ace.Ace.Editor.html#getSession)) * @param {HTMLDivElement} result * @param {String} gist_id @@ -358,6 +358,33 @@ ); } + /** + * Fetches a code snippet from the [`ponylang/pony-tutorial`](https://github.com/ponylang/pony-tutorial) repository on GitHub + * and loads it into the code editor + * @param {Ace.EditSession} session (see [ace.Ace.Editor::getSession](https://ajaxorg.github.io/ace-api-docs/interfaces/ace.Ace.Editor.html#getSession)) + * @param {HTMLDivElement} result + * @param {String} gist_id + * @param {bool} do_evaluate + * @param {HTMLButtonElement} evaluateButton + * @return {void} + */ + function fetchSnippet(session, result, snippet_file_name, do_evaluate, evaluateButton) { + session.setValue("// Loading snippet: https://github.com/ponylang/pony-tutorial/blob/main/code-samples/" + snippet_file_name + " ..."); + httpRequest("GET", "https://raw.githubusercontent.com/ponylang/pony-tutorial/main/code-samples/" + snippet_file_name, null, 200, + function (response) { + session.setValue(response); + + if (do_evaluate) { + doEvaluate(); + } + }, + function (status, response) { + set_result(result, "

Failed to fetch snippet" + + "

Are you connected to the Internet?"); + } + ); + } + /** * Get URL query parameters as Object * @returns {URLSearchParams} @@ -620,6 +647,10 @@ // fetchGist() must defer evaluation until after the content has been loaded fetchGist(session, result, query.get("gist"), query.get("run") === "1", evaluateButton); query.set("run", 0); + } else if (query.has("snippet")) { + // fetchSnippet() must defer evaluation until after the content has been loaded + fetchSnippet(session, result, query.get("snippet"), query.get("run") === "1", evaluateButton); + query.set("run", 0); } else { var code = optionalLocalStorageGetItem("code"); if (code !== null) {