Debian Codegraph @

test/contrib/emscripten/templates/pyodide-console.html

raw
1 <!-- taken from https://github.com/pyodide/pyodide/blob/main/src/templates/console.html -->
2 <!-- Copyright (C) 2019-2022, Pyodide contributors and Mozilla -->
3 <!-- SPDX-FileCopyrightText: 2019-2022, Pyodide contributors and Mozilla -->
4 <!-- SPDX-License-Identifier: MPL-2.0 -->
5 <!doctype html>
6 <html>
7 <head>
8 <meta charset="UTF-8" />
9 <title>Pyodide — urllib3</title>
10 <script src="https://cdn.jsdelivr.net/npm/jquery"></script>
11 <script src="https://cdn.jsdelivr.net/npm/[email protected]/js/jquery.terminal.min.js"></script>
12 <script src="https://cdn.jsdelivr.net/npm/[email protected]/js/unix_formatting.min.js"></script>
13 <link
14 href="https://cdn.jsdelivr.net/npm/[email protected]/css/jquery.terminal.min.css"
15 rel="stylesheet"
16 />
17 <style>
18 .terminal {
19 --size: 1.5;
20 --color: rgba(255, 255, 255, 0.8);
21 }
22 .noblink {
23 --animation: terminal-none;
24 }
25 body {
26 background-color: black;
27 }
28 #jquery-terminal-logo {
29 color: white;
30 border-color: white;
31 position: absolute;
32 top: 7px;
33 right: 18px;
34 z-index: 2;
35 }
36 #jquery-terminal-logo a {
37 color: gray;
38 text-decoration: none;
39 font-size: 0.7em;
40 }
41 #loading {
42 display: inline-block;
43 width: 50px;
44 height: 50px;
45 position: fixed;
46 top: 50%;
47 left: 50%;
48 border: 3px solid rgba(172, 237, 255, 0.5);
49 border-radius: 50%;
50 border-top-color: #fff;
51 animation: spin 1s ease-in-out infinite;
52 -webkit-animation: spin 1s ease-in-out infinite;
53 }
54
55 @keyframes spin {
56 to {
57 -webkit-transform: rotate(360deg);
58 }
59 }
60 @-webkit-keyframes spin {
61 to {
62 -webkit-transform: rotate(360deg);
63 }
64 }
65 </style>
66 </head>
67 <body>
68 <div id="jquery-terminal-logo">
69 <a href="https://terminal.jcubic.pl/">jQuery Terminal</a>
70 </div>
71 <div id="loading"></div>
72 <script>
73 "use strict";
74
75 function sleep(s) {
76 return new Promise((resolve) => setTimeout(resolve, s));
77 }
78
79 async function main() {
80 let indexURL = "https://cdn.jsdelivr.net/pyodide/v0.27.1/full/";
81 const urlParams = new URLSearchParams(window.location.search);
82 const buildParam = urlParams.get("build");
83 if (buildParam) {
84 if (["full", "debug", "pyc"].includes(buildParam)) {
85 indexURL = indexURL.replace(
86 "/full/",
87 "/" + urlParams.get("build") + "/",
88 );
89 } else {
90 console.warn(
91 'Invalid URL parameter: build="' +
92 buildParam +
93 '". Using default "full".',
94 );
95 }
96 }
97 const { loadPyodide } = await import(indexURL + "pyodide.mjs");
98 // to facilitate debugging
99 globalThis.loadPyodide = loadPyodide;
100
101 let term;
102 globalThis.pyodide = await loadPyodide({
103 stdin: () => {
104 let result = prompt();
105 echo(result);
106 return result;
107 },
108 });
109 let { repr_shorten, BANNER, PyodideConsole } =
110 pyodide.pyimport("pyodide.console");
111 BANNER =
112 `Welcome to the Pyodide ${pyodide.version} terminal emulator 🐍\n` +
113 BANNER;
114 const pyconsole = PyodideConsole(pyodide.globals);
115
116 const namespace = pyodide.globals.get("dict")();
117 const await_fut = pyodide.runPython(
118 `
119 import builtins
120 from pyodide.ffi import to_js
121
122 async def await_fut(fut):
123 res = await fut
124 if res is not None:
125 builtins._ = res
126 return to_js([res], depth=1)
127
128 await_fut
129 `,
130 { globals: namespace },
131 );
132 namespace.destroy();
133
134 const echo = (msg, ...opts) =>
135 term.echo(
136 msg
137 .replaceAll("]]", "&rsqb;&rsqb;")
138 .replaceAll("[[", "&lsqb;&lsqb;"),
139 ...opts,
140 );
141
142 const ps1 = ">>> ";
143 const ps2 = "... ";
144
145 async function lock() {
146 let resolve;
147 const ready = term.ready;
148 term.ready = new Promise((res) => (resolve = res));
149 await ready;
150 return resolve;
151 }
152
153 async function interpreter(command) {
154 const unlock = await lock();
155 term.pause();
156 // multiline should be split (useful when pasting)
157 for (const c of command.split("\n")) {
158 const escaped = c.replaceAll(/\u00a0/g, " ");
159 const fut = pyconsole.push(escaped);
160 term.set_prompt(fut.syntax_check === "incomplete" ? ps2 : ps1);
161 switch (fut.syntax_check) {
162 case "syntax-error":
163 term.error(fut.formatted_error.trimEnd());
164 continue;
165 case "incomplete":
166 continue;
167 case "complete":
168 break;
169 default:
170 throw new Error(`Unexpected type ${ty}`);
171 }
172 // In JavaScript, await automatically also awaits any results of
173 // awaits, so if an async function returns a future, it will await
174 // the inner future too. This is not what we want so we
175 // temporarily put it into a list to protect it.
176 const wrapped = await_fut(fut);
177 // complete case, get result / error and print it.
178 try {
179 const [value] = await wrapped;
180 if (value !== undefined) {
181 echo(
182 repr_shorten.callKwargs(value, {
183 separator: "\n<long output truncated>\n",
184 }),
185 );
186 }
187 if (value instanceof pyodide.ffi.PyProxy) {
188 value.destroy();
189 }
190 } catch (e) {
191 if (e.constructor.name === "PythonError") {
192 const message = fut.formatted_error || e.message;
193 term.error(message.trimEnd());
194 } else {
195 throw e;
196 }
197 } finally {
198 fut.destroy();
199 wrapped.destroy();
200 }
201 }
202 term.resume();
203 await sleep(10);
204 unlock();
205 }
206
207 term = $("body").terminal(interpreter, {
208 greetings: BANNER,
209 prompt: ps1,
210 completionEscape: false,
211 completion: function (command, callback) {
212 callback(pyconsole.complete(command).toJs()[0]);
213 },
214 keymap: {
215 "CTRL+C": async function (event, original) {
216 pyconsole.buffer.clear();
217 term.enter();
218 echo("KeyboardInterrupt");
219 term.set_command("");
220 term.set_prompt(ps1);
221 },
222 TAB: (event, original) => {
223 const command = term.before_cursor();
224 // Disable completion for whitespaces.
225 if (command.trim() === "") {
226 term.insert("\t");
227 return false;
228 }
229 return original(event);
230 },
231 },
232 });
233 window.term = term;
234 pyconsole.stdout_callback = (s) => echo(s, { newline: false });
235 pyconsole.stderr_callback = (s) => {
236 term.error(s.trimEnd());
237 };
238 term.ready = Promise.resolve();
239 pyodide._api.on_fatal = async (e) => {
240 if (e.name === "Exit") {
241 term.error(e);
242 term.error("Pyodide exited and can no longer be used.");
243 } else {
244 term.error(
245 "Pyodide has suffered a fatal error. Please report this to the Pyodide maintainers.",
246 );
247 term.error("The cause of the fatal error was:");
248 term.error(e);
249 term.error("Look in the browser console for more details.");
250 }
251 await term.ready;
252 term.pause();
253 await sleep(15);
254 term.pause();
255 };
256
257 const searchParams = new URLSearchParams(window.location.search);
258 if (searchParams.has("noblink")) {
259 $(".cmd-cursor").addClass("noblink");
260 }
261 await term.ready;
262 await term.exec("import micropip\n");
263 await term.exec("micropip.list()\n");
264 await term.exec('await micropip.install("http://localhost:8000/{urllib3_wheel_name}.whl")')
265 await term.exec("micropip.list()");
266 await term.exec("import urllib3");
267 await term.exec("urllib3.__version__");
268 }
269 window.console_ready = main();
270 </script>
271 </body>
272 </html>