Skip to content

Commit

Permalink
Add download button
Browse files Browse the repository at this point in the history
  • Loading branch information
rossant committed Mar 12, 2024
1 parent dd0253c commit 251532a
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 0 deletions.
1 change: 1 addition & 0 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@
<div class="subpanel control-panel">
<button id="run-button">&#9658;</button>
<button id="share-button">Share</button>
<button id="download-button">Download</button>
</div>

<!-- PANEL -->
Expand Down
12 changes: 12 additions & 0 deletions scripts/panel.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { downloadText } from "./utils.js";

export { Panel };


Expand All @@ -21,10 +23,12 @@ class Panel {

this.runButton = document.getElementById("run-button");
this.shareButton = document.getElementById("share-button");
this.downloadButton = document.getElementById("download-button");

this.setupDispatcher();
this.setupRunButton();
this.setupShareButton();
this.setupDownloadButton();
}


Expand Down Expand Up @@ -56,6 +60,14 @@ class Panel {
});
}

setupDownloadButton() {
this.downloadButton.addEventListener("click", (e) => {
const text = this.model.editor.getCode();
const filename = `${this.state.name}.py`;
downloadText(text, filename);
});
}

setIcon(isPlaying) {
this.runButton.innerHTML = isPlaying ? PLAY_ICON : STOP_ICON;
}
Expand Down
25 changes: 25 additions & 0 deletions scripts/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,28 @@ export function decode(encoded) {
const utf8Str = decodeURIComponent(escape(inflated)); // Convert from UTF-8
return JSON.parse(utf8Str);
}

export function downloadText(text, filename) {
// Create a Blob object from the text
const blob = new Blob([text], { type: 'text/plain' });

// Create a temporary link element
const link = document.createElement('a');
link.download = filename;

// Create a URL for the Blob
const url = URL.createObjectURL(blob);

// Set the link's href to the URL of the Blob
link.href = url;

// Append the link to the body
document.body.appendChild(link);

// Trigger the download
link.click();

// Clean up: remove the link and revoke the URL
document.body.removeChild(link);
URL.revokeObjectURL(url);
}

0 comments on commit 251532a

Please sign in to comment.