Repository navigation
Demo improvements #1675
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Demo improvements #1675
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
73b363d
Add asyncbrowser demo snippet
coolreader18 96dfaa0
Combine index.js and main.js into one to improve UX while loading rus…
coolreader18 e01e711
Add the other rp.py* functions to the mini-doc
coolreader18 338ac4d
Update demo dependencies
coolreader18 53be1a0
Improve WASM testing and CI
coolreader18 22653ac
Add clean-webpack-plugin
coolreader18 6feb0d7
Fix contest
coolreader18 049df44
Fix default import from raw-loader
coolreader18 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,68 @@ | ||
| import browser | ||
| import functools | ||
|
|
||
|
|
||
| # just setting up the framework, skip to the bottom to see the real code | ||
|
|
||
| ready = object() | ||
| go = object() | ||
|
|
||
|
|
||
| def run(coro, *, payload=None, error=False): | ||
| send = coro.throw if error else coro.send | ||
| try: | ||
| cmd = send(payload) | ||
| except StopIteration: | ||
| return | ||
| if cmd is ready: | ||
| coro.send( | ||
| ( | ||
| lambda *args: run(coro, payload=args), | ||
| lambda *args: run(coro, payload=args, error=True), | ||
| ) | ||
| ) | ||
| elif cmd is go: | ||
| pass | ||
| else: | ||
| raise RuntimeError(f"expected cmd to be ready or go, got {cmd}") | ||
|
|
||
|
|
||
| class JSFuture: | ||
| def __init__(self, prom): | ||
| self._prom = prom | ||
|
|
||
| def __await__(self): | ||
| done, error = yield ready | ||
| self._prom.then(done, error) | ||
| res, = yield go | ||
| return res | ||
|
|
||
|
|
||
| def wrap_prom_func(func): | ||
| @functools.wraps(func) | ||
| async def wrapper(*args, **kwargs): | ||
| return await JSFuture(func(*args, **kwargs)) | ||
|
|
||
| return wrapper | ||
|
|
||
|
|
||
| fetch = wrap_prom_func(browser.fetch) | ||
|
|
||
| ################### | ||
| # Real code start # | ||
| ################### | ||
|
|
||
|
|
||
| async def main(delay): | ||
| url = f"https://httpbin.org/delay/{delay}" | ||
| print(f"fetching {url}...") | ||
| res = await fetch( | ||
| url, response_format="json", headers={"X-Header-Thing": "rustpython is neat!"} | ||
| ) | ||
| print(f"got res from {res['url']}:") | ||
| print(res, end="\n\n") | ||
|
|
||
|
|
||
| for delay in range(3): | ||
| run(main(delay)) | ||
| print() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,11 +1,158 @@ | ||
| import './style.css'; | ||
| import 'codemirror/lib/codemirror.css'; | ||
| import 'xterm/lib/xterm.css'; | ||
| import CodeMirror from 'codemirror'; | ||
| import 'codemirror/mode/python/python'; | ||
| import 'codemirror/addon/comment/comment'; | ||
| import 'codemirror/lib/codemirror.css'; | ||
| import { Terminal } from 'xterm'; | ||
| import LocalEchoController from 'local-echo'; | ||
|
|
||
| let rp; | ||
|
|
||
| // A dependency graph that contains any wasm must all be imported | ||
| // asynchronously. This `index.js` file does the single async import, so | ||
| // that no one else needs to worry about it again. | ||
| import('./main.js').catch(e => { | ||
| console.error('Error importing `main.js`:', e); | ||
| document.getElementById('error').textContent = e; | ||
| // A dependency graph that contains any wasm must be imported asynchronously. | ||
| import('rustpython') | ||
| .then(rustpy => { | ||
| rp = rustpy; | ||
| // so people can play around with it | ||
| window.rp = rustpy; | ||
| onReady(); | ||
| }) | ||
| .catch(e => { | ||
| console.error('Error importing `rustpython`:', e); | ||
| document.getElementById('error').textContent = e; | ||
| }); | ||
|
|
||
| const editor = CodeMirror.fromTextArea(document.getElementById('code'), { | ||
| extraKeys: { | ||
| 'Ctrl-Enter': runCodeFromTextarea, | ||
| 'Cmd-Enter': runCodeFromTextarea, | ||
| 'Shift-Tab': 'indentLess', | ||
| 'Ctrl-/': 'toggleComment', | ||
| 'Cmd-/': 'toggleComment', | ||
| Tab: editor => { | ||
| var spaces = Array(editor.getOption('indentUnit') + 1).join(' '); | ||
| editor.replaceSelection(spaces); | ||
| } | ||
| }, | ||
| lineNumbers: true, | ||
| mode: 'text/x-python', | ||
| indentUnit: 4, | ||
| autofocus: true | ||
| }); | ||
|
|
||
| const consoleElement = document.getElementById('console'); | ||
| const errorElement = document.getElementById('error'); | ||
|
|
||
| function runCodeFromTextarea() { | ||
| // Clean the console and errors | ||
| consoleElement.value = ''; | ||
| errorElement.textContent = ''; | ||
|
|
||
| const code = editor.getValue(); | ||
| try { | ||
| rp.pyExec(code, { | ||
| stdout: output => { | ||
| const shouldScroll = | ||
| consoleElement.scrollHeight - consoleElement.scrollTop === | ||
| consoleElement.clientHeight; | ||
| consoleElement.value += output; | ||
| if (shouldScroll) { | ||
| consoleElement.scrollTop = consoleElement.scrollHeight; | ||
| } | ||
| } | ||
| }); | ||
| } catch (err) { | ||
| if (err instanceof WebAssembly.RuntimeError) { | ||
| err = window.__RUSTPYTHON_ERROR || err; | ||
| } | ||
| errorElement.textContent = err; | ||
| console.error(err); | ||
| } | ||
| } | ||
|
|
||
| const snippets = document.getElementById('snippets'); | ||
|
|
||
| function updateSnippet() { | ||
| const selected = snippets.value; | ||
|
|
||
| // the require here creates a webpack context; it's fine to use it | ||
| // dynamically. | ||
| // https://webpack.js.org/guides/dependency-management/ | ||
| const { | ||
| default: snippet | ||
| } = require(`raw-loader!../snippets/${selected}.py`); | ||
|
|
||
| editor.setValue(snippet); | ||
| runCodeFromTextarea(); | ||
| } | ||
|
|
||
| const term = new Terminal(); | ||
| term.open(document.getElementById('terminal')); | ||
|
|
||
| const localEcho = new LocalEchoController(term); | ||
|
|
||
| let terminalVM; | ||
|
|
||
| function getPrompt(name) { | ||
| terminalVM.exec(` | ||
| try: | ||
| import sys as __sys | ||
| __prompt = __sys.${name} | ||
| except: | ||
| __prompt = '' | ||
| finally: | ||
| del __sys | ||
| `); | ||
| return String(terminalVM.eval('__prompt')); | ||
| } | ||
|
|
||
| async function readPrompts() { | ||
| let continuing = false; | ||
|
|
||
| while (true) { | ||
| const ps1 = getPrompt('ps1'); | ||
| const ps2 = getPrompt('ps2'); | ||
| let input; | ||
| if (continuing) { | ||
| const prom = localEcho.read(ps2, ps2); | ||
| localEcho._activePrompt.prompt = ps1; | ||
| localEcho._input = localEcho.history.entries.pop() + '\n'; | ||
| localEcho._cursor = localEcho._input.length; | ||
| localEcho._active = true; | ||
| input = await prom; | ||
| if (!input.endsWith('\n')) continue; | ||
| } else { | ||
| input = await localEcho.read(ps1, ps2); | ||
| } | ||
| try { | ||
| terminalVM.execSingle(input); | ||
| } catch (err) { | ||
| if (err instanceof SyntaxError && err.message.includes('EOF')) { | ||
| continuing = true; | ||
| continue; | ||
| } else if (err instanceof WebAssembly.RuntimeError) { | ||
| err = window.__RUSTPYTHON_ERROR || err; | ||
| } | ||
| localEcho.println(err); | ||
| } | ||
| continuing = false; | ||
| } | ||
| } | ||
|
|
||
| function onReady() { | ||
| snippets.addEventListener('change', updateSnippet); | ||
| document | ||
| .getElementById('run-btn') | ||
| .addEventListener('click', runCodeFromTextarea); | ||
| // Run once for demo | ||
| runCodeFromTextarea(); | ||
|
|
||
| terminalVM = rp.vmStore.init('term_vm'); | ||
| terminalVM.setStdout(data => localEcho.println(data)); | ||
| readPrompts().catch(err => console.error(err)); | ||
|
|
||
| // so that the test knows that we're ready | ||
| const readyElement = document.createElement('div'); | ||
| readyElement.id = 'rp_loaded'; | ||
| document.head.appendChild(readyElement); | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.