-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpyprez.js
1818 lines (1655 loc) · 72.2 KB
/
pyprez.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*Sun Nov 06 2022 15:53:57 GMT -0800 (Pacific Standard Time)*/
if (!window.pyprezUpdateDate){
/* github pages can only serve one branch and takes a few minutes to update, this will help identify which version
of code we are on */
var pyprezUpdateDate = new Date("Sun Nov 06 2022 15:53:57 GMT -0800 (Pacific Standard Time)");
var pyprezCommitMessage = "fix imports";
var pyprezPrevCommit = "development:commit b49c434f40e62e250ff08c4266e3fb9778947c0d";
}
/*
Pyodide is undeniably cool, and useful in niche cases. Pyscript is easy to use, but is bulky, slow, not especially
easy to develop on, and is not really necessary seeing as 95+% of its utility comes from Pyodide. With Pyprez,
99.9+% of utility comes from Pyodide. We're not claiming to do anything better, its just a simple script to get you
started with exploring Pyodide's capabilities.
This js file will import pyodide and codemirror dependencies for you, so all you need to do is import this
<script src="https://modularizer.github.io/pyprez/pyprez.js" mode="editor">
import numpy as np
print("testing")
np.random.rand(5)
</script>
*/
if (!window.pyprezInitStarted){// allow importing this script multiple times without raising an error
console.log("loaded pyprez.js from", location.href);
/* ___________________________________________ CONSTANTS _________________________________________________ */
var pyprezInitStarted = true;// signal to duplicate imports not to try again
var preferredPyPrezImportSrc = "https://modularizer.github.io/pyprez/pyprz.min.js";
var githublinkImage = '<a href="https://modularizer.github.io/pyprez"><img src="https://github.com/favicon.ico" height="15px"/></a>';
var stackMode = false;
var pyprezScript = document.currentScript; // get the HTML <script> element running this code
/* ___________________________________________ CONFIG _________________________________________________ */
// set default configuration settings
//first separate config defaults by type to make validation easier
let boolConfig = {
help: true,
useWorker: false,
convert: true,
includeGithubLink: true,
showThemeSelect: true,
showNamespaceSelect: false,
patch: true,
lint: true
}
let strConfig = {
patchSrc: "https://modularizer.github.io/pyprez/patches.py",
codemirrorCDN: "https://cdnjs.cloudflare.com/ajax/libs/codemirror/6.65.7/",
pyodideCDN: "https://cdn.jsdelivr.net/pyodide/v0.21.3/full/pyodide.js",
consolePrompt: ">>> ",
consoleOut: "[Out] ",
consoleEscape: "...",
}
// construct default config
var pyprezConfig = {
...boolConfig ,
...strConfig,
}
// if there are globally defined config values in window, use those as default config
for (let k of Object.keys(pyprezConfig)){
if (window[k] !== undefined){
pyprezConfig[k] = window[k]
}
}
// if any config values are defined as attributes by the script doing the import, make that override defaults
for (let k of Object.keys(pyprezConfig)){
if (pyprezScript.hasAttribute(k)){
let v = pyprezScript.getAttribute(k).toLowerCase();
if (Object.keys(boolConfig).includes(k)){
if (["true", "1", ""].includes(v)){
pyprezConfig[k] = true
}else if (["false", "0"].includes(v)){
pyprezConfig[k] = false
}else{
console.error(`Invalid value '${v}' for attribute '${k}'. Value must be "true", "false", "1", "0", or ""`)
}
}else{
pyprezConfig[k] = v
}
}
}
Object.assign(window, pyprezConfig);
/* ___________________________________________ DEFERRED PROMISE _________________________________________________ */
class DeferredPromise{
/* this is an object which creates a promise in a different spot from where it will be resolve. It allows you
to say wait on athe completion of a task that you have not yet started. The interface is similar to
that of a promise (supports `then`, `catch` and if you wish you can access the true promise with
the `promise` attribute.*/
constructor(){
this.promise = new Promise((resolve, reject)=>{
this.resolve = resolve.bind()
this.reject = reject.bind()
})
this.then = this.promise.then.bind(this.promise)
this.catch = this.promise.catch.bind(this.promise)
}
}
window.DeferredPromise = DeferredPromise;
/* ________________________________________ DEFINE STATE VARIABLES ______________________________________________ */
// define steps of the load that different tasks may depend on
var domContentLoaded = new DeferredPromise();
var pyodideImported = new DeferredPromise();
var codemirrorImported = new DeferredPromise();
var workerReady = new DeferredPromise();
var pyodidePromise = new DeferredPromise("pyodidePromise");
var micropipPromise = new DeferredPromise("micropipPromise");
var patches = new DeferredPromise();
var linterPromise = new DeferredPromise();
if (patch){
patches = get(patchSrc);
}
var loadedCodeMirrorStyles = ["default"];
/* ___________________________________________ INTERPRET SCRIPT TAG _________________________________________________ */
// check if document is ready to go
if (document.readyState === "complete" || document.readyState === "loaded") {
// document is already ready to go
domContentLoaded.resolve()
}else{
// document is not ready, resolve deferred promise when it is
document.addEventListener('DOMContentLoaded', domContentLoaded.resolve)
}
// if the user is using the script tag as a code block, add a real code block to the document
function pyprezConvert(){
if (pyprezScript.innerHTML){
if (convert){
let script = pyprezScript;
// read script innerHTML then remove it
let ih = script.innerHTML;
script.innerHTML = "";
// make a real pyprez custom-element with the same attributes
let mode = "editor"
if (script.hasAttribute("mode")){
mode = script.getAttribute("mode")
}
let el = document.createElement("pyprez-" + mode);
el.innerHTML = ih;
for (let k of script.getAttributeNames()){
if (!["src"].includes(k)){
el.setAttribute(k, script.getAttribute(k))
}
}
// add to container and insert into document after script element
let div = document.createElement("div");
div.append(el);
script.after(div);
}
}else{
domContentLoaded.then(()=>{
console.log("DOMContentLoaded")
// try to identify if this script is running in a stack overflow demo (or other similar environment)
// if it is we will make a pyprez-editor which runs the code in the last script element
let isFirstScript = pyprezScript === document.scripts[0]
let numBodyEls = document.body.children.length
let singleBodyChild = numBodyEls === 1 && (document.body.children[0].tagName === "SCRIPT")
let twoDirectBodyChildren = (numBodyEls === 2) && (pyprezScript.parentElement === document.body)
let solo = isFirstScript && (twoDirectBodyChildren || singleBodyChild)
let convertScript = pyprezScript.hasAttribute("convert")?pyprezScript.getAttribute("convert")==="true":convert
if (solo && convertScript){
window.stackMode = true;
// use special attribute defaults in stack overflow
let mode = pyprezScript.hasAttribute("mode")?pyprezScript.getAttribute("mode"):"editor"
let specialAttributes = {
runonload: "true",
theme: "darcula",
githublink: "true"
}
let a = ""
for (let [k, defaultValue] of Object.entries(specialAttributes)){
let v = pyprezScript.hasAttribute(k)?pyprezScript.getAttribute(k):defaultValue;
a += ` ${k}="${v}"`
}
// get the code from the last script in the code demo
let lastScript = document.scripts[document.scripts.length - 1]
let demoCode = lastScript.innerHTML.trim()
// add an element to hold the pyprez-editor
let stackEditor = document.createElement("div");
document.body.appendChild(stackEditor);
// convert added element into pyprez-editor
stackEditor.innerHTML = `
<pyprez-${mode} ${a}>${demoCode}</pyprez-${mode}>
`;
}
})
}
}
pyprezConvert();
/* _______________________________ SETUP TO LOAD DEPENDENCIES ____________________________________________________ */
// allow disabling dependency import if desired (people may want to do their own imports for clarity, speed, or to
// tool to add css to document
function addStyle(s){
let style = document.createElement("style");
style.innerHTML = s;
document.head.appendChild(style);
}
// tools to import js dependencies
function importScript(url){
let el = document.createElement("script");
el.src = url;
return new Promise((resolve, reject)=>{
domContentLoaded.then(()=>{
console.log("attempting to import ", url)
document.body.appendChild(el)
el.addEventListener("load", ()=>resolve(url))
})
})
}
// function to get the text of css dependencies
function get(src){return fetch(src).then(r=>r.text())}
// function to load an external .css document into the page
function importStyle(url){
console.log("importing", url)
return get(url).then(addStyle)
}
// make functions to import dependencies
function importPyodide(){
if (pyodideCDN && !useWorker && window.importPyodide && !window.pyodide){
importScript(pyodideCDN).then(()=>{pyodideImported.resolve(true)})
}
}
function importCodeMirror(){
if (codemirrorCDN && !window.CodeMirror){
importScript(codemirrorCDN + "codemirror.min.js").then(()=>{
importScript(codemirrorCDN + "mode/python/python.min.js").then(()=>{
importStyle(codemirrorCDN + "codemirror.min.css").then(()=>{
addStyle('.CodeMirror { border: 1px solid #eee !important; height: auto !important;}');
codemirrorImported.resolve(CodeMirror)
})
})
})
}
}
/* _______________________________ ACTUALLY LOAD DEPENDENCIES ____________________________________________________ */
importPyodide();
importCodeMirror();
/* _______________________________________ LOAD AND EXTEND PYODIDE FUNCTIONALITY ____________________________________ */
class PyodideWorker extends Worker{
constructor(src){
super(src);
this.parent = window;
// bind methods to scope, may be unnecessary
this.getMethod = this.getMethod.bind(this);
this.postResponse = this.postResponse.bind(this);
this.postError = this.postError.bind(this);
this.postRequest = this.postRequest.bind(this);
this.postCall = this.postCall.bind(this);
this.receiveResponse = this.receiveResponse.bind(this);
this.receiveCallRequest = this.receiveCallRequest.bind(this);
this.receiveRequest = this.receiveRequest.bind(this);
this.stdout = this.stdout.bind(this);
this.stderr = this.stderr.bind(this);
this.worker = this;
this.proxy = new Proxy(this, {
get(target, prop, receiver) {
if (target[prop] !== undefined){return target[prop]}
function callMethod(){
return target.postRequest(prop, Array.from(arguments))
}
return callMethod
}
});
return this.proxy
}
_id = 0
get id(){
let id = this._id
this._id = (id + 1) % Number.MAX_SAFE_INTEGER;
return id
}
pendingRequests = {}
receivemessage(event){
let data = event.data
let type = data.type
if (type === "response"){this.receiveResponse(data)}
else if (type === "call"){this.receiveCallRequest(data)}
else if (type === "request"){this.receiveRequest(data)}
else{this.postError(data, "unrecognized type")}
}
getMethod(methodName, scopes){
if (!scopes){scopes = [this.parent, this]}
for (let scope of scopes){
if (scope[methodName]){return scope[methodName]}
else if (methodName.includes(".")){
let methodNames = methodName.split(".")
for (let mn of methodNames){
scope = scope[mn]
if (!scope){return scope}
}
return scope
}
}
}
postResponse(data, results, error=null){
data.type = "response";
data.results = results;
data.error = error;
this.postMessage(data)
}
postError(data, error){this.postResponse(data, null, error)}
postRequest(method, args, type="request"){
let id = this.id;
let data = {id, type, method, args, results: null, error: null}
this.pendingRequests[id] = [new DeferredPromise(), data];
this.postMessage(data)
return this.pendingRequests[id][0]
}
postCall(method, args){this.postRequest(method, args, "call")}
receiveResponse(data){
if ( this.pendingRequests[data.id] === undefined){
console.error(data.id, data);
return
}
let [deferredPromise, sentData] = this.pendingRequests[data.id];
delete this.pendingRequests[data.id];
if (data.results){deferredPromise.resolve(data.results)}
else{ deferredPromise.reject(data.error)}
}
receiveCallRequest(data){
let f = this.getMethod(data.method);
if (f){ return f(...data.args)}
else{this.postError(data, "method not found")}
}
receiveRequest(data){
try{
let results = this.receiveCallRequest(data);
if (results.then){
results
.then(r=>this.postResponse(data, r))
.catch(e=>this.postError(data, e))
}
else{this.postResponse(data, results)}
}
catch(error){this.postError(data, error)}
}
stdout(...args){
console.log(args)
}
stderr(...args){
console.log(args)
}
stdin(){return ""}
}
function loadPyodideInterface(config){
if (useWorker){
window.pyodide = new PyodideWorker('./webworker.js');
pyodide.worker.onmessage = pyodide.worker.receivemessage
if (config.stdin){pyodide.stdin = config.stdin;}
if (config.stdout){pyodide.stdout = config.stdout;}
if (config.stderr){pyodide.stderr = config.stderr;}
pyodideImported.resolve(true)
workerReady.then(()=>{
pyodide.runPythonAsync("2+2").then(r=>{
if (r == 4){
window.pyodide = pyodide;
window.pyodidePromise.resolve(true);
}
})
})
}else{
pyodideImported.then(()=>{
loadPyodide(config).then(pyodide =>{
pyodide.runPythonAsync(`
from js import prompt
__builtins__.input = prompt
2+2
`).then(()=>{
if (patch){
patches.then(code =>{
console.warn("applying python patches", code)
pyodide.runPythonAsync(code).then(()=>{
console.log("patched")
window.pyodide = pyodide;
pyodidePromise.resolve(true);
pyodide.loadPackage("micropip").then(micropip =>{
window.micropip = pyodide.pyimport("micropip");
micropipPromise.resolve(true);
})
})
})
}else{
window.pyodide = pyodide;
pyodidePromise.resolve(true);
pyodide.loadPackage("micropip").then(micropip =>{
window.micropip = pyodide.pyimport("micropip");
micropipPromise.resolve(true);
})
}
})
})
})
}
return pyodidePromise
}
/* linter */
if (lint){
micropipPromise.then(()=>{
micropip.install("autopep8").then(()=>{
pyodide.loadPackagesFromImports("autopep8").then(()=>{
console.warn("autopep8_fix")
pyodide.runPythonAsync(`
def autopep8_fix(s, tmp_fn="autopep8_temp.py"):
# micropip install autopep8
import autopep8
import os
autopep8.detect_encoding = lambda *a, **kw: 'utf-8'
with open(tmp_fn,"w") as f:
f.write(s)
r = autopep8.fix_file(tmp_fn)
os.remove(tmp_fn)
return r
`).then(()=>{
window.autopep8Fix = pyodide.globals.get("autopep8_fix");
linterPromise.resolve(true);
})
})
})
})
}
/* _______________________________________ scopeEval ____________________________________ */
function scopeEval(script) {
return Function(( "with(this) { " + script + "}"))();
}
/* _______________________________________ LOAD AND EXTEND PYODIDE FUNCTIONALITY ____________________________________ */
class PyPrez{
/*class which loads pyoidide and provides utility to allow user to load packages and run code as soon as possible
examples:
var pyprez = new Pyprez();
// use pyodide as soon as it loads
let promiseToFour = pyprez.then(pyodide => {
console.log("pyodide has loaded");
return pyodide.runPython("2+2")
});
// load dependencies and run some code as soon as it loads
let promiseToRandom = pyprez.loadAndRunAsync(`
import numpy as np
np.random.rand(5)
`);
//reroute stdout to a new javascript function
pyprez.stdout = alert;
pyprez.loadAndRunAsync(`print("testing if this alerts on window")`);
*/
constructor(config={}, load=true){
// bind the class methods to this instance
this._stdout = this._stdout.bind(this);
this._stderr = this._stderr.bind(this);
this._stdin = this._stdin.bind(this);
this.load = this.load.bind(this);
this.loadPyodideInterface = this.loadPyodideInterface.bind(this);
this.load = this.load.bind(this);
this._runPythonAsync = this._runPythonAsync.bind(this);
this.loadAndRunAsync = this.loadAndRunAsync.bind(this);
this.recordNamespaceName = this.recordNamespaceName.bind(this);
this.register = this.register.bind(this);
// load pyodide or pyodide worker proxy
Object.assign(this, config);
this.config = {
stdout: this._stdout,
stderr: this._stderr,
stdin: this._stdin
};
if (load){
this.loadPyodideInterface();
}
}
loadPyodideInterface(){
loadPyodideInterface(this.config).then(()=>{
this.getNamespace("global")
})
}
pending = []
// allow pyprez object to act a bit like a the promise to the pyodide object
then(successCb, errorCb){
return pyodidePromise.then(successCb, errorCb)
}
catch(errorCb){return pyodidePromise.catch(errorCB)}
// set the functions that will handle stdout, stderr from the python interpreter
stdout = console.log
stderr = console.error
stdin = ()=>""
// set parent functions which will call wrap and call stdout, stderr, stdin from the python interpreter
_stdout(...args){return this.stdout(...args)}
_stderr(...args){return this.stderr(...args)}
_stdin(...args){return this.stdin(...args)}
// store elements
elements = {};
editors = {};
consoles = {};
scripts = {};
imports = {};
overflows = {};
register(el){
let mode = el.tagName.toLowerCase().split("-").pop();
let m = this[mode + "s"]
this.elements[Object.keys(this.elements).length] = el;
m[Object.keys(m).length] = el;
if (el.id){
this.elements[el.id] = el;
m[el.id] = el;
}
}
_runPythonAsync(code, namespace){
/* internal function which runs the code */
if (code){
console.debug("running code asynchronously:")
console.debug(code)
this.recordNamespaceName(namespace)
if (useWorker){
return pyodide.runPythonAsyncInNamespace(code, namespace).catch(this.stderr)
}else{
return pyodide.runPythonAsync(code, {globals: this.getNamespace(namespace)}).catch(this.stderr)
}
}
}
jsNamespaces = {}
getJSNamespace(name){
if (this.jsNamespaces[name] === undefined){
let scope = {}
Object.assign(scope, window, {console, })
this.jsNamespaces[name] = [scope, scopeEval.bind(scope)]
}
return this.jsNamespaces[name]
}
namespaceEval(code, name){
let [scope, scopedEval] = this.getJSNamespace(name);
return scopedEval(code)
}
namespaces = {}
namespaceNames = ['global']
recordNamespaceName(name){
if (!this.namespaceNames.includes(name)){
this.namespaceNames = this.namespaceNames.concat([name])
}
}
getNamespace(name){
pyodidePromise.then((()=>{
if (this.namespaces[name] === undefined){
if (!useWorker){
this.namespaces[name] = pyodide.globals.get("dict")();
}
}
return this.namespaces[name]
}).bind(this))
}
// utility methods used to load requirements and run code asynchronously as soon as pyodide is loaded
load(code, requirements="detect"){
/*load required packages as soon as pyodide is loaded*/
return this.then(() =>{
if (requirements === "detect"){
if (code){
console.debug("auto loading packages detected in code")
return this.installPackagesFromComments(code).then(()=>{
console.warn("installed it here")
return window.pyodide.loadPackagesFromImports(code)
})
}
}else{
console.debug("loading", requirements)
return this.installPackagesFromComments(code).then(()=>{
console.warn("installed it here2")
return window.pyodide.loadPackagesFromImports(code)
})
}
})
}
installPackagesFromComments(code){
// let m = code.match(/#\s*(micro)?pip\s*install\s*(\S*)/g);
// console.warn(m);
// let packageNames = m?m.map(s => s.match(/#\s*(micro)?pip\s*install\s*(\S*)/)[2]):[];
// if (packageNames.length){
// console.warn("preparing to micropip install", packageNames)
// return micropipPromise.then(()=>{console.warn('installing');return micropip.install(packageNames)})
// }else{
return new Promise((res, rej)=>{res(true)})
// }
}
loadAndRunAsync(code, namespace="global", requirements="detect"){
/* run a python script asynchronously as soon as pyodide is loaded and all required packages are imported*/
let p = this.then((() =>{
if (code){
return this.load(code, requirements)
.then((r => {console.warn('loaded', r);return this._runPythonAsync(code, namespace)}).bind(this))
.catch((e => {console.error(e); return this._runPythonAsync(code, namespace)}).bind(this))
}
}).bind(this))
return p
}
}
var pyprez = new PyPrez(load=true);
/* ___________________________________________________ EDITOR ___________________________________________________ */
class PyPrezEditor extends HTMLElement{
/*
custom element which allows editing a block of python code, then when you are ready, pressing run to
load required packages and run the block of python code in the pyodide interpreter and see the result
example:
<pyprez-editor>
import numpy as np
np.random.rand(5)
</pyprez-editor>
<pyprez-editor src="my-script.py"></pyprez-editor>
*/
constructor(){
super();
this.classList.add("pyprez");
// bind functions
this.loadEl = this.loadEl.bind(this);
this.loadEditor = this.loadEditor.bind(this);
this.keypressed = this.keypressed.bind(this);
this.run = this.run.bind(this);
this.copyRunnable = this.copyRunnable.bind(this);
this.getRunnable = this.getRunnable.bind(this);
this.autopep8Fix = this.autopep8Fix.bind(this);
// set language to python(default), javascript, or html
let language = this.hasAttribute("language")?this.getAttribute("language").toLowerCase():"python"
let aliases = {
"python": "python",
"javascript": "javascript",
"html": "html",
"py": "python",
"js": "javascript",
}
this.language = aliases[language]
// default is to print stdout into editor
if (!this.hasAttribute("stdout")){this.setAttribute("stdout", "true")}
// allow loading code from an external source
if (this.hasAttribute("src") && this.getAttribute("src") && (this.getAttribute("src") !== pyprezScript.src)){
let src = this.getAttribute("src")
console.debug("fetching script for pyprez-editor src", src)
if (src.endsWith('.js')){
this.language = "javascript"
}else if (src.endsWith('.py')){
this.language = "python"
}else if (src.endsWith('.html')){
this.language = "html"
}
fetch(src).then(r=>r.text()).then(code =>{
this.innerHTML = code;
this.loadEl();
})
}else{
this.loadEl();
}
this.namespace = this.hasAttribute("namespace")?this.getAttribute("namespace"):"global"
pyprez.recordNamespaceName(this.namespace)
// add listeners
this.addEventListener("keydown", this.keypressed.bind(this));
this.addEventListener("dblclick", this.dblclicked.bind(this))
// register
pyprez.register(this);
// runonload if told to
if (this.hasAttribute("runonload") & (this.getAttribute("runonload")==="true")){
this.run();
}
}
/* ________________________ LOAD _____________________________*/
unindent(code, minIndent=0){
// read innerHTML and remove extra leading spaces
let firstFound=false;
let lines = code.replaceAll("\t"," ").split("\n").filter((v,i)=>{
if (firstFound){return true}
firstFound = v.trim().length > 0;
return firstFound
}); // replace tabs with spaces
let nonemptylines = lines.filter(v=>v.trim().length)
let leadingSpacesPerLine = nonemptylines.filter(v=>!v.trim().startsWith('#')).map(v=>v.match(/\s*/)[0].length); // count leading spaces of each line which has code
let extraLeadingSpaces = Math.min(...leadingSpacesPerLine) - minIndent; // recognize if every line containing code starts with spaces
if ((extraLeadingSpaces > 0) && (extraLeadingSpaces < 1000)){
let extraIndent = " ".repeat(extraLeadingSpaces);// string representing extra indent to remove
code = lines.map(v=>v.startsWith(extraIndent)?v.replace(extraIndent, ""):v).join("\n") // remove extra space
}
return code
}
reformatIndentation(code){
// deal with weird edge case where python comments use html tags and get auto-closed
while(code.endsWith('>')){
let newCode = code.replace(/<\/[a-z-]*>$/,'')
if (newCode === code){
break
}
code = newCode;
}
code = this.unindent(code)
let inem = '\nif __name__=="__main__":';
let blocks = code.split(inem);
if (blocks.length == 2){
let [pre, post] = blocks
post = this.unindent(post, 4)
code = pre + inem + post
}
return code
}
loadEl(){
/* load and format the html element */
let code=this.innerHTML?this.reformatIndentation(this.innerHTML):"";
this.initialCode = code;
this.innerHTML = `<pre>${code}</pre>`// set innerHTML to the cleanest builtin HTML
// load the editor
this.loadEditor();
// set theme
if (this.hasAttribute("theme")){
this.theme = this.getAttribute("theme")
}
// now load packages detected in code imports
// pyprez.installPackagesFromComments(this.code);
}
loadEditor(){
/* first load the editor as though codemirror does not and will not exist, then load codemirror*/
this._loadEditor();
codemirrorImported.then(this._loadCodeMirror.bind(this));
}
helpInfo = `
<b>PyPrez</b> is powered by <i>Pyodide</i> and runs fully in your browser!<br/><br/>
<b>To run:</b>
<ul>
<li>Click green arrow</li>
<li>Shift + Enter</li>
<li>Double-Click</li>
</ul>
<b>To lint:</b>
<ul>
<li>Ctrl + K to reformat/li>
</ul>
<b>To re-run:</b>
<ul>
<li>Shift + Enter</li>
<li>Double-Click</li>
</ul>
<b>To reload:</b>
<ul>
<li>Click red reload</li>
<li>Shift + Backspace</li>
</ul>
<b>Post-Run Console</b>
After code executes, try the runnable console at the bottom!
<b>Add to StackOverflow:</b>
Click <b>M↓</b> to copy markdown, then paste into your answer.
`
_loadEditor(){
/* first load the editor as though codemirror does not and will not exist*/
// check whether to add github link to top based on attributes
let githublink = this.hasAttribute("githublink")?this.getAttribute("githublink")==="true":includeGithubLink
let gh = githublink?githublinkImage:"<div></div>"
// check whether to add a message bar to the top of the element
let help= this.hasAttribute("help")?this.getAttribute("help")==="true":window.help;
let snss = this.hasAttribute("showNamespaceSelect")?this.getAttribute("showNamespaceSelect"):window.showNamespaceSelect;
snss=snss?"block":"none";
let sts = this.hasAttribute("showThemeSelect")?this.getAttribute("showThemeSelect"):window.showThemeSelect;
sts = sts?"block":"none";
// make top bar above codemirror
let top = ""
if (help){
top = `<div style="background-color:#d3d3d3;border-color:#808080;border-radius:3px;display:flex">
${gh}
<div style="margin-left:10px;overflow:hidden;white-space: nowrap;"></div>
<div style="order:2;margin-left:auto;cursor:help;" clicktooltip="${this.helpInfo}#def">ⓘ</div>
<div style="background-color:#f0f0f0;border-radius:5px;margin:2px;order:2;margin-right:5px;cursor:help;" tooltip="copy iframe#def" onclick="this.parentElement.parentElement.copyEmbeddable()"></></div>
<div style="background-color:#f0f0f0;border-radius:5px;margin:2px;order:2;margin-right:5px;cursor:help;" tooltip="copy runnable markdown#def" onclick="this.parentElement.parentElement.copyRunnable()">M↓</div>
<select style="order:2;margin-right:4px;background-color:#f0f0f0;border-radius:3px;display:${snss};">
<option>global</option>
</select>
<select style="order:2;margin-right:5px;background-color:#f0f0f0;border-radius:3px;display:${sts};">
<option>default</option>
<option style="background-color:#2b2b2b;color:#a9b7c6;">darcula</option>
<option style="background-color:#d7d4f0;color:#30a;">eclipse</option>
<option style="background-color:rgba(37,59,118,.99);color:#ff6400;">blackboard</option>
<option style="background-color:#d7d4f0;color:#0080ff;">xq-light</option>
<option style="background-color:#0a001f;color:#f8f8f8;">xq-dark</option>
</select>
</div>`
}else{
top = `<div>
${gh}
<div style="display:none;margin-left:10px;overflow:hidden;white-space: nowrap;"></div>
<div style="order:2;margin-left:auto;cursor:help;" clicktooltip="${this.helpInfo}#def">ⓘ</div>
<div style="background-color:#f0f0f0;border-radius:5px;margin:2px;order:2;margin-right:5px;cursor:help;" tooltip="copy iframe#def" onclick="this.parentElement.parentElement.copyEmbeddable()"></></div>
<div style="background-color:#f0f0f0;border-radius:5px;margin:2px;order:2;margin-right:5px;cursor:help;" tooltip="copy runnable markdown#def" onclick="this.parentElement.parentElement.copyRunnable()">M↓</div>
<select style="order:2;margin-right:5px;background-color:#f0f0f0;border-radius:3px;display:${snss};">
<option>global</option>
</select>
<select style="order:2;margin-right:5px;background-color:#f0f0f0;border-radius:3px;display:${sts};">
<option>default</option>
<option style="background-color:#2b2b2b;color:#a9b7c6;">darcula</option>
<option style="background-color:#d7d4f0;color:#30a;">eclipse</option>
<option style="background-color:rgba(37,59,118,.99);color:#ff6400;">blackboard</option>
<option style="background-color:#d7d4f0;color:#0080ff;">xq-light</option>
<option style="background-color:#0a001f;color:#f8f8f8;">xq-dark</option>
</select>
</div>`
}
this.style.display="flex"
this.style["flex-direction"] = "column"
this.style.resize = "both"
this.style.overflow = "auto"
this.innerHTML = `
<div style="color:green">${this.startChar}</div>
${top}
<textarea style="height:auto;">${this.initialCode}</textarea>
<pre></pre>
`
this.start = this.children[0] // start button
this.messageBar = this.children[1].children[1] // top message bar to use to print status (Loading, Running, etc.)
this.copyEmbeddableLink = this.children[1].children[3]
this.copyRunnableLink = this.children[1].children[4]
this.namespaceSelect = this.children[1].children[5]
this.themeSelect = this.children[1].children[6]
this.textarea = this.children[2] // textarea in case codemirror does not load
this.endSpace = this.children[3]
// add click event to start button
this.start.addEventListener("click", this.startClicked.bind(this))
this.themeSelect.addEventListener("change", ((e)=>{
this.theme = this.themeSelect.value;
try{
localStorage.setItem("codemirrorTheme", this.themeSelect.value);
}catch{}
}).bind(this))
this.namespaceSelect.addEventListener("click", ()=>{
this.refreshNamespaces();
})
// size text area to fit initial code
this.textarea.style.height = this.textarea.scrollHeight +"px" // set text area to full height
let longestLine = this.initialCode.split("\n").map(v=>v.length).reduce((a,b)=>a>b?a:b)
let fontSize = 1 * window.getComputedStyle(this.textarea).fontSize.slice(0,-2)
let w = Math.min(window.innerWidth - 50, Math.ceil(longestLine * fontSize) + 200)
// this.children[1].style.width = w +"px"
// this.textarea.style.width = w + "px"
this.style.maxWidth = "100%"
this.style.width = stackMode?"100%":(w + "px")
// Set initial messages
if (!pyodideImported.promise.fullfilled){
this.message = "Loading pyodide"
pyodideImported.then((()=>{this.message = "Ready (Double-Click to Run)"}).bind(this))
}
}
_loadCodeMirror(){
// make codemirror editor from textarea
this.editor = CodeMirror.fromTextArea(this.textarea, {
lineNumbers: true,
mode: this.language,
viewportMargin: Infinity,
gutters: ["Codemirror-linenumbers", "start"],
});
// this.editor.setSize(1*this.textarea.style.width.slice(0,-2))
// add start button in gutter
this.editor.doc.setGutterMarker(0, "start", this.start);
// set double click listener on editor as well because otherwise outer element listener does not get triggered
this.editor.display.lineDiv.addEventListener("dblclick", this.dblclicked.bind(this))
try{
if (!this.hasAttribute("theme")){
this.themeSelect.value = this.theme;
let cmt = localStorage.getItem("codemirrorTheme");
cmt = cmt?cmt:this.theme;
localStorage.setItem("codemirrorTheme", cmt);
this.themeSelect.value = cmt;
this.theme = cmt;
}
}catch{}
}
get selectedNamespace(){return this.namespaceSelect.value}
set selectedNamespace(name){
this.namespaceSelect.value = name;
}
get namespaces(){return Array.from(this.namespaceSelect.children).map(el=>el.innerHTML)}
set namespaces(namespaces){
let sn = this.selectedNamespace;
this.namespaceSelect.innerHTML = namespaces.map(name=>`<option>${name}</option>`).join("")
this.namespaceSelect.value = sn;
}
refreshNamespaces(){
this.namespaces = pyprez.namespaceNames;
}
get namespace(){return this.selectedNamespace}
set namespace(name){
if (!this.namespaces.includes(name)){
this.namespaces = this.namespaces.concat([name]);
}
this.selectedNamespace = name
}
/* ________________________ EVENTS _____________________________*/
keypressed(e){
/* Shift + Enter to run, Shift + Backspace to reload */
if (e.ctrlKey && e.key == 'k'){this.autopep8Fix();e.preventDefault();}
if (e.shiftKey && e.key == "Backspace"){this.reload(); e.preventDefault();}
else if (e.key == "Enter"){
if (e.shiftKey && !this.done){this.run(); e.preventDefault();}
if (this.done){
if (!(e.shiftKey || this.code.endsWith(':'))){this.run(); e.preventDefault();}
else{
let s = "\n" + this.consoleEscape
this.code += s;
e.preventDefault();
let lines = this.code.split("\n")
this.editor.setCursor({line: lines.length, ch: lines[lines.length-1].length})
}
}
}
}
dblclicked(e){
/* always run or re-run on double click*/
if (this.done){
this.reload();
}
this.run();
e.stopPropagation();
}
startClicked(){
/* when the start button is clicked either run code or reload to the last code that was executed*/
if (!this.executed){
this.run();
}else{