@pyscript/core 0.6.30 → 0.6.31
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{core-DBBBvqAZ.js → core-DnOjzQS_.js} +3 -3
- package/dist/{core-DBBBvqAZ.js.map → core-DnOjzQS_.js.map} +1 -1
- package/dist/core.css +1 -1
- package/dist/core.js +1 -1
- package/dist/{deprecations-manager-C9bz-cCo.js → deprecations-manager-BKGF65fL.js} +2 -2
- package/dist/{deprecations-manager-C9bz-cCo.js.map → deprecations-manager-BKGF65fL.js.map} +1 -1
- package/dist/{donkey-CPfzNIKU.js → donkey-Oqo7W5b8.js} +2 -2
- package/dist/{donkey-CPfzNIKU.js.map → donkey-Oqo7W5b8.js.map} +1 -1
- package/dist/{error-CcoJNMra.js → error-Dr1sICUr.js} +2 -2
- package/dist/{error-CcoJNMra.js.map → error-Dr1sICUr.js.map} +1 -1
- package/dist/{mpy-kF1Vi-UZ.js → mpy-Bj7Nqy2i.js} +2 -2
- package/dist/{mpy-kF1Vi-UZ.js.map → mpy-Bj7Nqy2i.js.map} +1 -1
- package/dist/{py-DeKU8cUk.js → py-B2TFi7-Q.js} +2 -2
- package/dist/{py-DeKU8cUk.js.map → py-B2TFi7-Q.js.map} +1 -1
- package/dist/py-editor-CVOs6pzi.js +2 -0
- package/dist/py-editor-CVOs6pzi.js.map +1 -0
- package/dist/{py-game-DS6TwE2V.js → py-game-BJyQhVm5.js} +2 -2
- package/dist/{py-game-DS6TwE2V.js.map → py-game-BJyQhVm5.js.map} +1 -1
- package/dist/{py-terminal-D6e0p-Qg.js → py-terminal-CpQPAjog.js} +2 -2
- package/dist/{py-terminal-D6e0p-Qg.js.map → py-terminal-CpQPAjog.js.map} +1 -1
- package/package.json +2 -2
- package/src/core.css +8 -8
- package/src/plugins/py-editor.js +28 -4
- package/src/stdlib/pyscript/display.py +9 -8
- package/src/stdlib/pyscript/events.py +4 -2
- package/src/stdlib/pyscript/flatted.py +3 -3
- package/src/stdlib/pyscript/fs.py +1 -0
- package/src/stdlib/pyscript/magic_js.py +1 -0
- package/src/stdlib/pyscript/media.py +1 -2
- package/src/stdlib/pyscript/storage.py +6 -4
- package/src/stdlib/pyscript/util.py +1 -1
- package/src/stdlib/pyscript/web.py +27 -20
- package/src/stdlib/pyscript/websocket.py +1 -1
- package/src/stdlib/pyscript/workers.py +5 -3
- package/src/stdlib/pyscript.js +8 -8
- package/dist/py-editor-DnliBZkx.js +0 -2
- package/dist/py-editor-DnliBZkx.js.map +0 -1
@@ -73,14 +73,14 @@ def _eval_formatter(obj, print_method):
|
|
73
73
|
"""
|
74
74
|
if print_method == "__repr__":
|
75
75
|
return repr(obj)
|
76
|
-
|
76
|
+
if hasattr(obj, print_method):
|
77
77
|
if print_method == "savefig":
|
78
78
|
buf = io.BytesIO()
|
79
79
|
obj.savefig(buf, format="png")
|
80
80
|
buf.seek(0)
|
81
81
|
return base64.b64encode(buf.read()).decode("utf-8")
|
82
82
|
return getattr(obj, print_method)()
|
83
|
-
|
83
|
+
if print_method == "_repr_mimebundle_":
|
84
84
|
return {}, {}
|
85
85
|
return None
|
86
86
|
|
@@ -107,7 +107,7 @@ def _format_mime(obj):
|
|
107
107
|
|
108
108
|
if output is None:
|
109
109
|
continue
|
110
|
-
|
110
|
+
if mime_type not in _MIME_RENDERERS:
|
111
111
|
not_available.append(mime_type)
|
112
112
|
continue
|
113
113
|
break
|
@@ -149,9 +149,11 @@ def display(*values, target=None, append=True):
|
|
149
149
|
if target is None:
|
150
150
|
target = current_target()
|
151
151
|
elif not isinstance(target, str):
|
152
|
-
|
152
|
+
msg = f"target must be str or None, not {target.__class__.__name__}"
|
153
|
+
raise TypeError(msg)
|
153
154
|
elif target == "":
|
154
|
-
|
155
|
+
msg = "Cannot have an empty target"
|
156
|
+
raise ValueError(msg)
|
155
157
|
elif target.startswith("#"):
|
156
158
|
# note: here target is str and not None!
|
157
159
|
# align with @when behavior
|
@@ -161,9 +163,8 @@ def display(*values, target=None, append=True):
|
|
161
163
|
|
162
164
|
# If target cannot be found on the page, a ValueError is raised
|
163
165
|
if element is None:
|
164
|
-
|
165
|
-
|
166
|
-
)
|
166
|
+
msg = f"Invalid selector with id={target}. Cannot be found in the page."
|
167
|
+
raise ValueError(msg)
|
167
168
|
|
168
169
|
# if element is a <script type="py">, it has a 'target' attribute which
|
169
170
|
# points to the visual element holding the displayed values. In that case,
|
@@ -36,7 +36,8 @@ class Event:
|
|
36
36
|
if listener not in self._listeners:
|
37
37
|
self._listeners.append(listener)
|
38
38
|
else:
|
39
|
-
|
39
|
+
msg = "Listener must be callable or awaitable."
|
40
|
+
raise ValueError(msg)
|
40
41
|
|
41
42
|
def remove_listener(self, *args):
|
42
43
|
"""
|
@@ -76,7 +77,8 @@ def when(target, *args, **kwargs):
|
|
76
77
|
# Extract the selector from the arguments or keyword arguments.
|
77
78
|
selector = args[0] if args else kwargs.pop("selector")
|
78
79
|
if not selector:
|
79
|
-
|
80
|
+
msg = "No selector provided."
|
81
|
+
raise ValueError(msg)
|
80
82
|
# Grab the DOM elements to which the target event will be attached.
|
81
83
|
from pyscript.web import Element, ElementCollection
|
82
84
|
|
@@ -31,7 +31,7 @@ def _object_keys(value):
|
|
31
31
|
|
32
32
|
|
33
33
|
def _is_array(value):
|
34
|
-
return isinstance(value, list
|
34
|
+
return isinstance(value, (list, tuple))
|
35
35
|
|
36
36
|
|
37
37
|
def _is_object(value):
|
@@ -60,10 +60,10 @@ def _loop(keys, input, known, output):
|
|
60
60
|
|
61
61
|
|
62
62
|
def _ref(key, value, input, known, output):
|
63
|
-
if _is_array(value) and not
|
63
|
+
if _is_array(value) and value not in known:
|
64
64
|
known.append(value)
|
65
65
|
value = _loop(_array_keys(value), input, known, value)
|
66
|
-
elif _is_object(value) and not
|
66
|
+
elif _is_object(value) and value not in known:
|
67
67
|
known.append(value)
|
68
68
|
value = _loop(_object_keys(value), input, known, value)
|
69
69
|
|
@@ -44,8 +44,7 @@ class Device:
|
|
44
44
|
for k in video:
|
45
45
|
setattr(options.video, k, to_js(video[k]))
|
46
46
|
|
47
|
-
|
48
|
-
return stream
|
47
|
+
return await window.navigator.mediaDevices.getUserMedia(options)
|
49
48
|
|
50
49
|
async def get_stream(self):
|
51
50
|
key = self.kind.replace("input", "").replace("output", "")
|
@@ -10,10 +10,11 @@ def _to_idb(value):
|
|
10
10
|
if isinstance(value, (bool, float, int, str, list, dict, tuple)):
|
11
11
|
return _stringify(["generic", value])
|
12
12
|
if isinstance(value, bytearray):
|
13
|
-
return _stringify(["bytearray",
|
13
|
+
return _stringify(["bytearray", list(value)])
|
14
14
|
if isinstance(value, memoryview):
|
15
|
-
return _stringify(["memoryview",
|
16
|
-
|
15
|
+
return _stringify(["memoryview", list(value)])
|
16
|
+
msg = f"Unexpected value: {value}"
|
17
|
+
raise TypeError(msg)
|
17
18
|
|
18
19
|
|
19
20
|
# convert an IndexedDB compatible entry into a Python value
|
@@ -56,5 +57,6 @@ class Storage(dict):
|
|
56
57
|
|
57
58
|
async def storage(name="", storage_class=Storage):
|
58
59
|
if not name:
|
59
|
-
|
60
|
+
msg = "The storage name must be defined"
|
61
|
+
raise ValueError(msg)
|
60
62
|
return storage_class(await _storage(f"@pyscript/{name}"))
|
@@ -2,7 +2,10 @@
|
|
2
2
|
|
3
3
|
# `when` is not used in this module. It is imported here save the user an additional
|
4
4
|
# import (i.e. they can get what they need from `pyscript.web`).
|
5
|
-
|
5
|
+
|
6
|
+
# from __future__ import annotations # CAUTION: This is not supported in MicroPython.
|
7
|
+
|
8
|
+
from pyscript import document, when, Event # noqa: F401
|
6
9
|
from pyscript.ffi import create_proxy
|
7
10
|
|
8
11
|
|
@@ -100,7 +103,7 @@ class Element:
|
|
100
103
|
If `key` is an integer or a slice we use it to index/slice the element's
|
101
104
|
children. Otherwise, we use `key` as a query selector.
|
102
105
|
"""
|
103
|
-
if isinstance(key, int
|
106
|
+
if isinstance(key, (int, slice)):
|
104
107
|
return self.children[key]
|
105
108
|
|
106
109
|
return self.find(key)
|
@@ -120,7 +123,7 @@ class Element:
|
|
120
123
|
# attribute `for` which is a Python keyword, so you can access it on the
|
121
124
|
# Element instance via `for_`).
|
122
125
|
if name.endswith("_"):
|
123
|
-
name = name[:-1]
|
126
|
+
name = name[:-1] # noqa: FURB188 No str.removesuffix() in MicroPython.
|
124
127
|
return getattr(self._dom_element, name)
|
125
128
|
|
126
129
|
def __setattr__(self, name, value):
|
@@ -138,7 +141,7 @@ class Element:
|
|
138
141
|
# attribute `for` which is a Python keyword, so you can access it on the
|
139
142
|
# Element instance via `for_`).
|
140
143
|
if name.endswith("_"):
|
141
|
-
name = name[:-1]
|
144
|
+
name = name[:-1] # noqa: FURB188 No str.removesuffix() in MicroPython.
|
142
145
|
|
143
146
|
if name.startswith("on_"):
|
144
147
|
# Ensure on-events are cached in the _on_events dict if the
|
@@ -152,10 +155,12 @@ class Element:
|
|
152
155
|
Get an `Event` instance for the specified event name.
|
153
156
|
"""
|
154
157
|
if not name.startswith("on_"):
|
155
|
-
|
158
|
+
msg = "Event names must start with 'on_'."
|
159
|
+
raise ValueError(msg)
|
156
160
|
event_name = name[3:] # Remove the "on_" prefix.
|
157
161
|
if not hasattr(self._dom_element, event_name):
|
158
|
-
|
162
|
+
msg = f"Element has no '{event_name}' event."
|
163
|
+
raise ValueError(msg)
|
159
164
|
if name in self._on_events:
|
160
165
|
return self._on_events[name]
|
161
166
|
# Such an on-event exists in the DOM element, but we haven't yet
|
@@ -203,7 +208,7 @@ class Element:
|
|
203
208
|
# We check for list/tuple here and NOT for any iterable as it will match
|
204
209
|
# a JS Nodelist which is handled explicitly below.
|
205
210
|
# NodeList.
|
206
|
-
elif isinstance(item, list
|
211
|
+
elif isinstance(item, (list, tuple)):
|
207
212
|
for child in item:
|
208
213
|
self.append(child)
|
209
214
|
|
@@ -227,10 +232,11 @@ class Element:
|
|
227
232
|
|
228
233
|
except AttributeError:
|
229
234
|
# Nope! This is not an element or a NodeList.
|
230
|
-
|
235
|
+
msg = (
|
231
236
|
f'Element "{item}" is a proxy object, "'
|
232
237
|
f"but not a valid element or a NodeList."
|
233
238
|
)
|
239
|
+
raise TypeError(msg)
|
234
240
|
|
235
241
|
def clone(self, clone_id=None):
|
236
242
|
"""Make a clone of the element (clones the underlying DOM object too)."""
|
@@ -401,9 +407,8 @@ class Options:
|
|
401
407
|
|
402
408
|
new_option = option(**kwargs)
|
403
409
|
|
404
|
-
if before:
|
405
|
-
|
406
|
-
before = before._dom_element
|
410
|
+
if before and isinstance(before, Element):
|
411
|
+
before = before._dom_element
|
407
412
|
|
408
413
|
self._element._dom_element.add(new_option._dom_element, before)
|
409
414
|
|
@@ -463,7 +468,7 @@ class ContainerElement(Element):
|
|
463
468
|
)
|
464
469
|
|
465
470
|
for child in list(args) + (children or []):
|
466
|
-
if isinstance(child, Element
|
471
|
+
if isinstance(child, (Element, ElementCollection)):
|
467
472
|
self.append(child)
|
468
473
|
|
469
474
|
else:
|
@@ -493,14 +498,13 @@ class ClassesCollection:
|
|
493
498
|
)
|
494
499
|
|
495
500
|
def __iter__(self):
|
496
|
-
|
497
|
-
yield class_name
|
501
|
+
yield from self._all_class_names()
|
498
502
|
|
499
503
|
def __len__(self):
|
500
504
|
return len(self._all_class_names())
|
501
505
|
|
502
506
|
def __repr__(self):
|
503
|
-
return f"ClassesCollection({
|
507
|
+
return f"ClassesCollection({self._collection!r})"
|
504
508
|
|
505
509
|
def __str__(self):
|
506
510
|
return " ".join(self._all_class_names())
|
@@ -553,7 +557,7 @@ class StyleCollection:
|
|
553
557
|
element.style[key] = value
|
554
558
|
|
555
559
|
def __repr__(self):
|
556
|
-
return f"StyleCollection({
|
560
|
+
return f"StyleCollection({self._collection!r})"
|
557
561
|
|
558
562
|
def remove(self, key):
|
559
563
|
"""Remove a CSS property from the elements in the collection."""
|
@@ -588,7 +592,7 @@ class ElementCollection:
|
|
588
592
|
if isinstance(key, int):
|
589
593
|
return self._elements[key]
|
590
594
|
|
591
|
-
|
595
|
+
if isinstance(key, slice):
|
592
596
|
return ElementCollection(self._elements[key])
|
593
597
|
|
594
598
|
return self.find(key)
|
@@ -1125,7 +1129,8 @@ class video(ContainerElement):
|
|
1125
1129
|
|
1126
1130
|
elif isinstance(to, Element):
|
1127
1131
|
if to.tag != "canvas":
|
1128
|
-
|
1132
|
+
msg = "Element to snap to must be a canvas."
|
1133
|
+
raise TypeError(msg)
|
1129
1134
|
|
1130
1135
|
elif getattr(to, "tagName", "") == "CANVAS":
|
1131
1136
|
to = canvas(dom_element=to)
|
@@ -1134,10 +1139,12 @@ class video(ContainerElement):
|
|
1134
1139
|
elif isinstance(to, str):
|
1135
1140
|
nodelist = document.querySelectorAll(to) # NOQA
|
1136
1141
|
if nodelist.length == 0:
|
1137
|
-
|
1142
|
+
msg = "No element with selector {to} to snap to."
|
1143
|
+
raise TypeError(msg)
|
1138
1144
|
|
1139
1145
|
if nodelist[0].tagName != "CANVAS":
|
1140
|
-
|
1146
|
+
msg = "Element to snap to must be a canvas."
|
1147
|
+
raise TypeError(msg)
|
1141
1148
|
|
1142
1149
|
to = canvas(dom_element=nodelist[0])
|
1143
1150
|
|
@@ -25,10 +25,12 @@ async def create_named_worker(src="", name="", config=None, type="py"):
|
|
25
25
|
from json import dumps
|
26
26
|
|
27
27
|
if not src:
|
28
|
-
|
28
|
+
msg = "Named workers require src"
|
29
|
+
raise ValueError(msg)
|
29
30
|
|
30
31
|
if not name:
|
31
|
-
|
32
|
+
msg = "Named workers require a name"
|
33
|
+
raise ValueError(msg)
|
32
34
|
|
33
35
|
s = _js.document.createElement("script")
|
34
36
|
s.type = type
|
@@ -37,7 +39,7 @@ async def create_named_worker(src="", name="", config=None, type="py"):
|
|
37
39
|
_set(s, "name", name)
|
38
40
|
|
39
41
|
if config:
|
40
|
-
_set(s, "config", isinstance(config, str) and config or dumps(config))
|
42
|
+
_set(s, "config", (isinstance(config, str) and config) or dumps(config))
|
41
43
|
|
42
44
|
_js.document.body.append(s)
|
43
45
|
return await workers[name]
|
package/src/stdlib/pyscript.js
CHANGED
@@ -2,18 +2,18 @@
|
|
2
2
|
export default {
|
3
3
|
"pyscript": {
|
4
4
|
"__init__.py": "from polyscript import lazy_py_modules as py_import\nfrom pyscript.magic_js import RUNNING_IN_WORKER,PyWorker,config,current_target,document,js_import,js_modules,sync,window\nfrom pyscript.display import HTML,display\nfrom pyscript.fetch import fetch\nfrom pyscript.storage import Storage,storage\nfrom pyscript.websocket import WebSocket\nfrom pyscript.events import when,Event\nif not RUNNING_IN_WORKER:from pyscript.workers import create_named_worker,workers",
|
5
|
-
"display.py": "_L='_repr_mimebundle_'\n_K='image/svg+xml'\n_J='application/json'\n_I='__repr__'\n_H='savefig'\n_G='text/html'\n_F='image/jpeg'\n_E='application/javascript'\n_D='utf-8'\n_C='text/plain'\n_B='image/png'\n_A=None\nimport base64,html,io,re\nfrom pyscript.magic_js import current_target,document,window\n_MIME_METHODS={_H:_B,'_repr_javascript_':_E,'_repr_json_':_J,'_repr_latex':'text/latex','_repr_png_':_B,'_repr_jpeg_':_F,'_repr_pdf_':'application/pdf','_repr_svg_':_K,'_repr_markdown_':'text/markdown','_repr_html_':_G,_I:_C}\ndef _render_image(mime,value,meta):\n\tA=value\n\tif isinstance(A,bytes):A=base64.b64encode(A).decode(_D)\n\tB=re.compile('^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$')\n\tif len(A)>0 and not B.match(A):A=base64.b64encode(A.encode(_D)).decode(_D)\n\tC=f\"data:{mime};charset=utf-8;base64,{A}\";D=' '.join(['{k}=\"{v}\"'for(A,B)in meta.items()]);return f'<img src=\"{C}\" {D}></img>'\ndef _identity(value,meta):return value\n_MIME_RENDERERS={_C:html.escape,_G:_identity,_B:lambda value,meta:_render_image(_B,value,meta),_F:lambda value,meta:_render_image(_F,value,meta),_K:_identity,_J:_identity,_E:lambda value,meta:f\"<script>{value}<\\\\/script>\"}\nclass HTML:\n\tdef __init__(A,html):A._html=html\n\tdef _repr_html_(A):return A._html\ndef _eval_formatter(obj,print_method):\n\tB=obj;A=print_method\n\tif A==_I:return repr(B)\n\
|
6
|
-
"events.py": "import asyncio,inspect,sys\nfrom functools import wraps\nfrom pyscript.magic_js import document\nfrom pyscript.ffi import create_proxy\nfrom pyscript.util import is_awaitable\nfrom pyscript import config\nclass Event:\n\tdef __init__(A):A._listeners=[]\n\tdef trigger(C,result):\n\t\tB=result\n\t\tfor A in C._listeners:\n\t\t\tif is_awaitable(A):asyncio.create_task(A(B))\n\t\t\telse:A(B)\n\tdef add_listener(B,listener):\n\t\tA=listener\n\t\tif is_awaitable(A)or callable(A):\n\t\t\tif A not in B._listeners:B._listeners.append(A)\n\t\telse:
|
5
|
+
"display.py": "_L='_repr_mimebundle_'\n_K='image/svg+xml'\n_J='application/json'\n_I='__repr__'\n_H='savefig'\n_G='text/html'\n_F='image/jpeg'\n_E='application/javascript'\n_D='utf-8'\n_C='text/plain'\n_B='image/png'\n_A=None\nimport base64,html,io,re\nfrom pyscript.magic_js import current_target,document,window\n_MIME_METHODS={_H:_B,'_repr_javascript_':_E,'_repr_json_':_J,'_repr_latex':'text/latex','_repr_png_':_B,'_repr_jpeg_':_F,'_repr_pdf_':'application/pdf','_repr_svg_':_K,'_repr_markdown_':'text/markdown','_repr_html_':_G,_I:_C}\ndef _render_image(mime,value,meta):\n\tA=value\n\tif isinstance(A,bytes):A=base64.b64encode(A).decode(_D)\n\tB=re.compile('^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$')\n\tif len(A)>0 and not B.match(A):A=base64.b64encode(A.encode(_D)).decode(_D)\n\tC=f\"data:{mime};charset=utf-8;base64,{A}\";D=' '.join(['{k}=\"{v}\"'for(A,B)in meta.items()]);return f'<img src=\"{C}\" {D}></img>'\ndef _identity(value,meta):return value\n_MIME_RENDERERS={_C:html.escape,_G:_identity,_B:lambda value,meta:_render_image(_B,value,meta),_F:lambda value,meta:_render_image(_F,value,meta),_K:_identity,_J:_identity,_E:lambda value,meta:f\"<script>{value}<\\\\/script>\"}\nclass HTML:\n\tdef __init__(A,html):A._html=html\n\tdef _repr_html_(A):return A._html\ndef _eval_formatter(obj,print_method):\n\tB=obj;A=print_method\n\tif A==_I:return repr(B)\n\tif hasattr(B,A):\n\t\tif A==_H:C=io.BytesIO();B.savefig(C,format='png');C.seek(0);return base64.b64encode(C.read()).decode(_D)\n\t\treturn getattr(B,A)()\n\tif A==_L:return{},{}\ndef _format_mime(obj):\n\tC=obj\n\tif isinstance(C,str):return html.escape(C),_C\n\tD=_eval_formatter(C,_L)\n\tif isinstance(D,tuple):E,I=D\n\telse:E=D\n\tA,F=_A,[]\n\tfor(H,B)in _MIME_METHODS.items():\n\t\tif B in E:A=E[B]\n\t\telse:A=_eval_formatter(C,H)\n\t\tif A is _A:continue\n\t\tif B not in _MIME_RENDERERS:F.append(B);continue\n\t\tbreak\n\tif A is _A:\n\t\tif F:window.console.warn(f\"Rendered object requested unavailable MIME renderers: {F}\")\n\t\tA=repr(A);B=_C\n\telif isinstance(A,tuple):A,G=A\n\telse:G={}\n\treturn _MIME_RENDERERS[B](A,G),B\ndef _write(element,value,append=False):\n\tB=element;C,D=_format_mime(value)\n\tif C=='\\\\n':return\n\tif append:A=document.createElement('div');B.append(A)\n\telse:\n\t\tA=B.lastElementChild\n\t\tif A is _A:A=B\n\tif D in(_E,_G):E=document.createRange().createContextualFragment(C);A.append(E)\n\telse:A.innerHTML=C\ndef display(*E,target=_A,append=True):\n\tD=append;A=target\n\tif A is _A:A=current_target()\n\telif not isinstance(A,str):C=f\"target must be str or None, not {A.__class__.__name__}\";raise TypeError(C)\n\telif A=='':C='Cannot have an empty target';raise ValueError(C)\n\telif A.startswith('#'):A=A[1:]\n\tB=document.getElementById(A)\n\tif B is _A:C=f\"Invalid selector with id={A}. Cannot be found in the page.\";raise ValueError(C)\n\tif B.tagName=='SCRIPT'and hasattr(B,'target'):B=B.target\n\tfor F in E:\n\t\tif not D:B.replaceChildren()\n\t\t_write(B,F,append=D)",
|
6
|
+
"events.py": "import asyncio,inspect,sys\nfrom functools import wraps\nfrom pyscript.magic_js import document\nfrom pyscript.ffi import create_proxy\nfrom pyscript.util import is_awaitable\nfrom pyscript import config\nclass Event:\n\tdef __init__(A):A._listeners=[]\n\tdef trigger(C,result):\n\t\tB=result\n\t\tfor A in C._listeners:\n\t\t\tif is_awaitable(A):asyncio.create_task(A(B))\n\t\t\telse:A(B)\n\tdef add_listener(B,listener):\n\t\tA=listener\n\t\tif is_awaitable(A)or callable(A):\n\t\t\tif A not in B._listeners:B._listeners.append(A)\n\t\telse:C='Listener must be callable or awaitable.';raise ValueError(C)\n\tdef remove_listener(A,*B):\n\t\tif B:\n\t\t\tfor C in B:A._listeners.remove(C)\n\t\telse:A._listeners=[]\ndef when(target,*B,**D):\n\tG='handler';C=target;E=None\n\tif B and(callable(B[0])or is_awaitable(B[0])):E=B[0]\n\telif callable(D.get(G))or is_awaitable(D.get(G)):E=D.pop(G)\n\tif isinstance(C,str):\n\t\tA=B[0]if B else D.pop('selector')\n\t\tif not A:I='No selector provided.';raise ValueError(I)\n\t\tfrom pyscript.web import Element as J,ElementCollection as K\n\t\tif isinstance(A,str):F=document.querySelectorAll(A)\n\t\telif isinstance(A,J):F=[A._dom_element]\n\t\telif isinstance(A,K):F=[A._dom_element for A in A]\n\t\telse:F=A if isinstance(A,list)else[A]\n\tdef H(func):\n\t\tE='positional arguments';D='takes';A=func\n\t\tif config['type']=='mpy':\n\t\t\tif is_awaitable(A):\n\t\t\t\tasync def B(*C,**F):\n\t\t\t\t\ttry:return await A(*C,**F)\n\t\t\t\t\texcept TypeError as B:\n\t\t\t\t\t\tif D in str(B)and E in str(B):return await A()\n\t\t\t\t\t\traise\n\t\t\telse:\n\t\t\t\tdef B(*C,**F):\n\t\t\t\t\ttry:return A(*C,**F)\n\t\t\t\t\texcept TypeError as B:\n\t\t\t\t\t\tif D in str(B)and E in str(B):return A()\n\t\t\t\t\t\traise\n\t\telse:\n\t\t\tG=inspect.signature(A)\n\t\t\tif G.parameters:\n\t\t\t\tif is_awaitable(A):\n\t\t\t\t\tasync def B(event):return await A(event)\n\t\t\t\telse:B=A\n\t\t\telif is_awaitable(A):\n\t\t\t\tasync def B(*B,**C):return await A()\n\t\t\telse:\n\t\t\t\tdef B(*B,**C):return A()\n\t\tB=wraps(A)(B)\n\t\tif isinstance(C,Event):C.add_listener(B)\n\t\telif isinstance(C,list)and all(isinstance(A,Event)for A in C):\n\t\t\tfor H in C:H.add_listener(B)\n\t\telse:\n\t\t\tfor I in F:I.addEventListener(C,create_proxy(B))\n\t\treturn B\n\treturn H(E)if E else H",
|
7
7
|
"fetch.py": "import json,js\nfrom pyscript.util import as_bytearray\nclass _Response:\n\tdef __init__(A,response):A._response=response\n\tdef __getattr__(A,attr):return getattr(A._response,attr)\n\tasync def arrayBuffer(B):\n\t\tA=await B._response.arrayBuffer()\n\t\tif hasattr(A,'to_py'):return A.to_py()\n\t\treturn memoryview(as_bytearray(A))\n\tasync def blob(A):return await A._response.blob()\n\tasync def bytearray(A):B=await A._response.arrayBuffer();return as_bytearray(B)\n\tasync def json(A):return json.loads(await A.text())\n\tasync def text(A):return await A._response.text()\nclass _DirectResponse:\n\t@staticmethod\n\tdef setup(promise,response):A=promise;A._response=_Response(response);return A._response\n\tdef __init__(B,promise):A=promise;B._promise=A;A._response=None;A.arrayBuffer=B.arrayBuffer;A.blob=B.blob;A.bytearray=B.bytearray;A.json=B.json;A.text=B.text\n\tasync def _response(A):\n\t\tif not A._promise._response:await A._promise\n\t\treturn A._promise._response\n\tasync def arrayBuffer(A):B=await A._response();return await B.arrayBuffer()\n\tasync def blob(A):B=await A._response();return await B.blob()\n\tasync def bytearray(A):B=await A._response();return await B.bytearray()\n\tasync def json(A):B=await A._response();return await B.json()\n\tasync def text(A):B=await A._response();return await B.text()\ndef fetch(url,**B):C=js.JSON.parse(json.dumps(B));D=lambda response,*B:_DirectResponse.setup(A,response);A=js.fetch(url,C).then(D);_DirectResponse(A);return A",
|
8
8
|
"ffi.py": "try:\n\timport js;from pyodide.ffi import create_proxy as _cp,to_js as _py_tjs;from_entries=js.Object.fromEntries\n\tdef _tjs(value,**A):\n\t\tB='dict_converter'\n\t\tif not hasattr(A,B):A[B]=from_entries\n\t\treturn _py_tjs(value,**A)\nexcept:from jsffi import create_proxy as _cp;from jsffi import to_js as _tjs\ncreate_proxy=_cp\nto_js=_tjs",
|
9
|
-
"flatted.py": "import json as _json\nclass _Known:\n\tdef __init__(A):A.key=[];A.value=[]\nclass _String:\n\tdef __init__(A,value):A.value=value\ndef _array_keys(value):\n\tA=[];B=0\n\tfor C in value:A.append(B);B+=1\n\treturn A\ndef _object_keys(value):\n\tA=[]\n\tfor B in value:A.append(B)\n\treturn A\ndef _is_array(value):
|
9
|
+
"flatted.py": "import json as _json\nclass _Known:\n\tdef __init__(A):A.key=[];A.value=[]\nclass _String:\n\tdef __init__(A,value):A.value=value\ndef _array_keys(value):\n\tA=[];B=0\n\tfor C in value:A.append(B);B+=1\n\treturn A\ndef _object_keys(value):\n\tA=[]\n\tfor B in value:A.append(B)\n\treturn A\ndef _is_array(value):return isinstance(value,(list,tuple))\ndef _is_object(value):return isinstance(value,dict)\ndef _is_string(value):return isinstance(value,str)\ndef _index(known,input,value):B=value;A=known;input.append(B);C=str(len(input)-1);A.key.append(B);A.value.append(C);return C\ndef _loop(keys,input,known,output):\n\tA=output\n\tfor B in keys:\n\t\tC=A[B]\n\t\tif isinstance(C,_String):_ref(B,input[int(C.value)],input,known,A)\n\treturn A\ndef _ref(key,value,input,known,output):\n\tB=known;A=value\n\tif _is_array(A)and A not in B:B.append(A);A=_loop(_array_keys(A),input,B,A)\n\telif _is_object(A)and A not in B:B.append(A);A=_loop(_object_keys(A),input,B,A)\n\toutput[key]=A\ndef _relate(known,input,value):\n\tB=known;A=value\n\tif _is_string(A)or _is_array(A)or _is_object(A):\n\t\ttry:return B.value[B.key.index(A)]\n\t\texcept:return _index(B,input,A)\n\treturn A\ndef _transform(known,input,value):\n\tB=known;A=value\n\tif _is_array(A):\n\t\tC=[]\n\t\tfor F in A:C.append(_relate(B,input,F))\n\t\treturn C\n\tif _is_object(A):\n\t\tD={}\n\t\tfor E in A:D[E]=_relate(B,input,A[E])\n\t\treturn D\n\treturn A\ndef _wrap(value):\n\tA=value\n\tif _is_string(A):return _String(A)\n\tif _is_array(A):\n\t\tB=0\n\t\tfor D in A:A[B]=_wrap(D);B+=1\n\telif _is_object(A):\n\t\tfor C in A:A[C]=_wrap(A[C])\n\treturn A\ndef parse(value,*C,**D):\n\tA=value;E=_json.loads(A,*C,**D);B=[]\n\tfor A in E:B.append(_wrap(A))\n\tinput=[]\n\tfor A in B:\n\t\tif isinstance(A,_String):input.append(A.value)\n\t\telse:input.append(A)\n\tA=input[0]\n\tif _is_array(A):return _loop(_array_keys(A),input,[A],A)\n\tif _is_object(A):return _loop(_object_keys(A),input,[A],A)\n\treturn A\ndef stringify(value,*D,**E):\n\tB=_Known();input=[];C=[];A=int(_index(B,input,value))\n\twhile A<len(input):C.append(_transform(B,input,input[A]));A+=1\n\treturn _json.dumps(C,*D,**E)",
|
10
10
|
"fs.py": "mounted={}\nasync def mount(path,mode='readwrite',root='',id='pyscript'):\n\tE=path;import js;from _pyscript import fs as A,interpreter as I;from pyscript.ffi import to_js as H;from pyscript.magic_js import RUNNING_IN_WORKER as J,sync;js.console.warn('experimental pyscript.fs ⚠️');B=None;C=f\"{E}@{id}\";F={'id':id,'mode':mode}\n\tif root!='':F['startIn']=root\n\tif J:\n\t\tG=sync.storeFSHandler(C,H(F))\n\t\tif isinstance(G,bool):D=G\n\t\telse:D=await G\n\t\tif D:from polyscript import IDBMap as K;L=K.new(A.NAMESPACE);B=await L.get(C)\n\t\telse:raise RuntimeError(A.ERROR)\n\telse:\n\t\tD=await A.idb.has(C)\n\t\tif D:B=await A.idb.get(C)\n\t\telse:B=await A.getFileSystemDirectoryHandle(H(F));await A.idb.set(C,B)\n\tmounted[E]=await I.mountNativeFS(E,B)\nasync def sync(path):await mounted[path].syncfs()\nasync def unmount(path):from _pyscript import interpreter as A;await sync(path);A._module.FS.unmount(path)",
|
11
11
|
"magic_js.py": "import json,sys,js as globalThis\nfrom polyscript import config as _config,js_modules\nfrom pyscript.util import NotSupported\nRUNNING_IN_WORKER=not hasattr(globalThis,'document')\nconfig=json.loads(globalThis.JSON.stringify(_config))\nif'MicroPython'in sys.version:config['type']='mpy'\nelse:config['type']='py'\nclass JSModule:\n\tdef __init__(A,name):A.name=name\n\tdef __getattr__(B,field):\n\t\tA=field\n\t\tif not A.startswith('_'):return getattr(getattr(js_modules,B.name),A)\nfor name in globalThis.Reflect.ownKeys(js_modules):sys.modules[f\"pyscript.js_modules.{name}\"]=JSModule(name)\nsys.modules['pyscript.js_modules']=js_modules\nif RUNNING_IN_WORKER:\n\timport polyscript;PyWorker=NotSupported('pyscript.PyWorker','pyscript.PyWorker works only when running in the main thread')\n\ttry:import js;window=polyscript.xworker.window;document=window.document;js.document=document;js_import=window.Function('return (...urls) => Promise.all(urls.map((url) => import(url)))')()\n\texcept:message='Unable to use `window` or `document` -> https://docs.pyscript.net/latest/faq/#sharedarraybuffer';globalThis.console.warn(message);window=NotSupported('pyscript.window',message);document=NotSupported('pyscript.document',message);js_import=None\n\tsync=polyscript.xworker.sync\n\tdef current_target():return polyscript.target\nelse:\n\timport _pyscript;from _pyscript import PyWorker,js_import;window=globalThis;document=globalThis.document;sync=NotSupported('pyscript.sync','pyscript.sync works only when running in a worker')\n\tdef current_target():return _pyscript.target",
|
12
|
-
"media.py": "from pyscript import window\nfrom pyscript.ffi import to_js\nclass Device:\n\tdef __init__(A,device):A._dom_element=device\n\t@property\n\tdef id(self):return self._dom_element.deviceId\n\t@property\n\tdef group(self):return self._dom_element.groupId\n\t@property\n\tdef kind(self):return self._dom_element.kind\n\t@property\n\tdef label(self):return self._dom_element.label\n\tdef __getitem__(A,key):return getattr(A,key)\n\t@classmethod\n\tasync def load(
|
13
|
-
"storage.py": "_C='memoryview'\n_B='bytearray'\n_A='generic'\nfrom polyscript import storage as _storage\nfrom pyscript.flatted import parse as _parse\nfrom pyscript.flatted import stringify as _stringify\ndef _to_idb(value):\n\tA=value\n\tif A is None:return _stringify(['null',0])\n\tif isinstance(A,(bool,float,int,str,list,dict,tuple)):return _stringify([_A,A])\n\tif isinstance(A,bytearray):return _stringify([_B,
|
14
|
-
"util.py": "import js,sys,inspect\ndef as_bytearray(buffer):\n\tA=js.Uint8Array.new(buffer);B=A.length;C=bytearray(B)\n\tfor D in range(
|
15
|
-
"web.py": "_B='on_'\n_A=None\nfrom pyscript import document,when,Event\nfrom pyscript.ffi import create_proxy\ndef wrap_dom_element(dom_element):return Element.wrap_dom_element(dom_element)\nclass Element:\n\telement_classes_by_tag_name={}\n\t@classmethod\n\tdef get_tag_name(A):return A.__name__.replace('_','')\n\t@classmethod\n\tdef register_element_classes(B,element_classes):\n\t\tfor A in element_classes:C=A.get_tag_name();B.element_classes_by_tag_name[C]=A\n\t@classmethod\n\tdef unregister_element_classes(A,element_classes):\n\t\tfor B in element_classes:C=B.get_tag_name();A.element_classes_by_tag_name.pop(C,_A)\n\t@classmethod\n\tdef wrap_dom_element(A,dom_element):B=dom_element;C=A.element_classes_by_tag_name.get(B.tagName.lower(),A);return C(dom_element=B)\n\tdef __init__(A,dom_element=_A,classes=_A,style=_A,**E):\n\t\tA._dom_element=dom_element or document.createElement(type(A).get_tag_name());A._on_events={};C={}\n\t\tfor(B,D)in E.items():\n\t\t\tif B.startswith(_B):F=A.get_event(B);F.add_listener(D)\n\t\t\telse:C[B]=D\n\t\tA._classes=Classes(A);A._style=Style(A);A.update(classes=classes,style=style,**C)\n\tdef __eq__(A,obj):return isinstance(obj,Element)and obj._dom_element==A._dom_element\n\tdef __getitem__(B,key):\n\t\tA=key\n\t\tif isinstance(A,int)or isinstance(A,slice):return B.children[A]\n\t\treturn B.find(A)\n\tdef __getattr__(B,name):\n\t\tA=name\n\t\tif A.startswith(_B):return B.get_event(A)\n\t\tif A.endswith('_'):A=A[:-1]\n\t\treturn getattr(B._dom_element,A)\n\tdef __setattr__(C,name,value):\n\t\tB=value;A=name\n\t\tif A.startswith('_'):super().__setattr__(A,B)\n\t\telse:\n\t\t\tif A.endswith('_'):A=A[:-1]\n\t\t\tif A.startswith(_B):C._on_events[A]=B\n\t\t\tsetattr(C._dom_element,A,B)\n\tdef get_event(A,name):\n\t\tB=name\n\t\tif not B.startswith(_B):raise ValueError(\"Event names must start with 'on_'.\")\n\t\tC=B[3:]\n\t\tif not hasattr(A._dom_element,C):raise ValueError(f\"Element has no '{C}' event.\")\n\t\tif B in A._on_events:return A._on_events[B]\n\t\tD=Event();A._on_events[B]=D;A._dom_element.addEventListener(C,create_proxy(D.trigger));return D\n\t@property\n\tdef children(self):return ElementCollection.wrap_dom_elements(self._dom_element.children)\n\t@property\n\tdef classes(self):return self._classes\n\t@property\n\tdef parent(self):\n\t\tif self._dom_element.parentElement is _A:return\n\t\treturn Element.wrap_dom_element(self._dom_element.parentElement)\n\t@property\n\tdef style(self):return self._style\n\tdef append(B,*C):\n\t\tfor A in C:\n\t\t\tif isinstance(A,Element):B._dom_element.appendChild(A._dom_element)\n\t\t\telif isinstance(A,ElementCollection):\n\t\t\t\tfor D in A:B._dom_element.appendChild(D._dom_element)\n\t\t\telif isinstance(A,list)or isinstance(A,tuple):\n\t\t\t\tfor E in A:B.append(E)\n\t\t\telse:\n\t\t\t\ttry:A.tagName;B._dom_element.appendChild(A)\n\t\t\t\texcept AttributeError:\n\t\t\t\t\ttry:\n\t\t\t\t\t\tA.length\n\t\t\t\t\t\tfor F in A:B._dom_element.appendChild(F)\n\t\t\t\t\texcept AttributeError:raise TypeError(f'Element \"{A}\" is a proxy object, \"but not a valid element or a NodeList.')\n\tdef clone(B,clone_id=_A):A=Element.wrap_dom_element(B._dom_element.cloneNode(True));A.id=clone_id;return A\n\tdef find(A,selector):return ElementCollection.wrap_dom_elements(A._dom_element.querySelectorAll(selector))\n\tdef show_me(A):A._dom_element.scrollIntoView()\n\tdef update(A,classes=_A,style=_A,**D):\n\t\tC=style;B=classes\n\t\tif B:A.classes.add(B)\n\t\tif C:A.style.set(**C)\n\t\tfor(E,F)in D.items():setattr(A,E,F)\nclass Classes:\n\tdef __init__(A,element):A._element=element;A._class_list=A._element._dom_element.classList\n\tdef __contains__(A,item):return item in A._class_list\n\tdef __eq__(C,other):\n\t\tA=other\n\t\tif isinstance(A,Classes):B=list(A._class_list)\n\t\telse:\n\t\t\ttry:B=iter(A)\n\t\t\texcept TypeError:return False\n\t\treturn set(C._class_list)==set(B)\n\tdef __iter__(A):return iter(A._class_list)\n\tdef __len__(A):return A._class_list.length\n\tdef __repr__(A):return f\"Classes({\", \".join(A._class_list)})\"\n\tdef __str__(A):return' '.join(A._class_list)\n\tdef add(B,*C):\n\t\tfor A in C:\n\t\t\tif isinstance(A,list):\n\t\t\t\tfor D in A:B.add(D)\n\t\t\telse:B._class_list.add(A)\n\tdef contains(A,class_name):return class_name in A\n\tdef remove(B,*C):\n\t\tfor A in C:\n\t\t\tif isinstance(A,list):\n\t\t\t\tfor D in A:B.remove(D)\n\t\t\telse:B._class_list.remove(A)\n\tdef replace(A,old_class,new_class):A.remove(old_class);A.add(new_class)\n\tdef toggle(A,*C):\n\t\tfor B in C:\n\t\t\tif B in A:A.remove(B)\n\t\t\telse:A.add(B)\nclass HasOptions:\n\t@property\n\tdef options(self):\n\t\tA=self\n\t\tif not hasattr(A,'_options'):A._options=Options(A)\n\t\treturn A._options\nclass Options:\n\tdef __init__(A,element):A._element=element\n\tdef __getitem__(A,key):return A.options[key]\n\tdef __iter__(A):yield from A.options\n\tdef __len__(A):return len(A.options)\n\tdef __repr__(A):return f\"{A.__class__.__name__} (length: {len(A)}) {A.options}\"\n\t@property\n\tdef options(self):return[Element.wrap_dom_element(A)for A in self._element._dom_element.options]\n\t@property\n\tdef selected(self):return self.options[self._element._dom_element.selectedIndex]\n\tdef add(D,value=_A,html=_A,text=_A,before=_A,**B):\n\t\tC=value;A=before\n\t\tif C is not _A:B['value']=C\n\t\tif html is not _A:B['innerHTML']=html\n\t\tif text is not _A:B['text']=text\n\t\tE=option(**B)\n\t\tif A:\n\t\t\tif isinstance(A,Element):A=A._dom_element\n\t\tD._element._dom_element.add(E._dom_element,A)\n\tdef clear(A):\n\t\twhile len(A)>0:A.remove(0)\n\tdef remove(A,index):A._element._dom_element.remove(index)\nclass Style:\n\tdef __init__(A,element):A._element=element;A._style=A._element._dom_element.style\n\tdef __getitem__(A,key):return A._style.getPropertyValue(key)\n\tdef __setitem__(A,key,value):A._style.setProperty(key,value)\n\tdef remove(A,key):A._style.removeProperty(key)\n\tdef set(A,**B):\n\t\tfor(C,D)in B.items():A._element._dom_element.style.setProperty(C,D)\n\t@property\n\tdef visible(self):return self._element._dom_element.style.visibility\n\t@visible.setter\n\tdef visible(self,value):self._element._dom_element.style.visibility=value\nclass ContainerElement(Element):\n\tdef __init__(B,*C,children=_A,dom_element=_A,style=_A,classes=_A,**D):\n\t\tsuper().__init__(dom_element=dom_element,style=style,classes=classes,**D)\n\t\tfor A in list(C)+(children or[]):\n\t\t\tif isinstance(A,Element)or isinstance(A,ElementCollection):B.append(A)\n\t\t\telse:B._dom_element.insertAdjacentHTML('beforeend',A)\n\tdef __iter__(A):yield from A.children\nclass ClassesCollection:\n\tdef __init__(A,collection):A._collection=collection\n\tdef __contains__(A,class_name):\n\t\tfor B in A._collection:\n\t\t\tif class_name in B.classes:return True\n\t\treturn False\n\tdef __eq__(B,other):A=other;return isinstance(A,ClassesCollection)and B._collection==A._collection\n\tdef __iter__(A):\n\t\tfor B in A._all_class_names():yield B\n\tdef __len__(A):return len(A._all_class_names())\n\tdef __repr__(A):return f\"ClassesCollection({repr(A._collection)})\"\n\tdef __str__(A):return' '.join(A._all_class_names())\n\tdef add(A,*B):\n\t\tfor C in A._collection:C.classes.add(*B)\n\tdef contains(A,class_name):return class_name in A\n\tdef remove(A,*B):\n\t\tfor C in A._collection:C.classes.remove(*B)\n\tdef replace(A,old_class,new_class):\n\t\tfor B in A._collection:B.classes.replace(old_class,new_class)\n\tdef toggle(A,*B):\n\t\tfor C in A._collection:C.classes.toggle(*B)\n\tdef _all_class_names(B):\n\t\tA=set()\n\t\tfor C in B._collection:\n\t\t\tfor D in C.classes:A.add(D)\n\t\treturn A\nclass StyleCollection:\n\tdef __init__(A,collection):A._collection=collection\n\tdef __getitem__(A,key):return[A.style[key]for A in A._collection._elements]\n\tdef __setitem__(A,key,value):\n\t\tfor B in A._collection._elements:B.style[key]=value\n\tdef __repr__(A):return f\"StyleCollection({repr(A._collection)})\"\n\tdef remove(A,key):\n\t\tfor B in A._collection._elements:B.style.remove(key)\nclass ElementCollection:\n\t@classmethod\n\tdef wrap_dom_elements(A,dom_elements):return A([Element.wrap_dom_element(A)for A in dom_elements])\n\tdef __init__(A,elements):A._elements=elements;A._classes=ClassesCollection(A);A._style=StyleCollection(A)\n\tdef __eq__(A,obj):return isinstance(obj,ElementCollection)and obj._elements==A._elements\n\tdef __getitem__(B,key):\n\t\tA=key\n\t\tif isinstance(A,int):return B._elements[A]\n\t\telif isinstance(A,slice):return ElementCollection(B._elements[A])\n\t\treturn B.find(A)\n\tdef __iter__(A):yield from A._elements\n\tdef __len__(A):return len(A._elements)\n\tdef __repr__(A):return f\"{A.__class__.__name__} (length: {len(A._elements)}) {A._elements}\"\n\tdef __getattr__(A,name):return[getattr(A,name)for A in A._elements]\n\tdef __setattr__(C,name,value):\n\t\tB=value;A=name\n\t\tif A.startswith('_'):super().__setattr__(A,B)\n\t\telse:\n\t\t\tfor D in C._elements:setattr(D,A,B)\n\t@property\n\tdef classes(self):return self._classes\n\t@property\n\tdef elements(self):return self._elements\n\t@property\n\tdef style(self):return self._style\n\tdef find(B,selector):\n\t\tA=[]\n\t\tfor C in B._elements:A.extend(C.find(selector))\n\t\treturn ElementCollection(A)\nclass a(ContainerElement):0\nclass abbr(ContainerElement):0\nclass address(ContainerElement):0\nclass area(Element):0\nclass article(ContainerElement):0\nclass aside(ContainerElement):0\nclass audio(ContainerElement):0\nclass b(ContainerElement):0\nclass base(Element):0\nclass blockquote(ContainerElement):0\nclass body(ContainerElement):0\nclass br(Element):0\nclass button(ContainerElement):0\nclass canvas(ContainerElement):\n\tdef download(A,filename='snapped.png'):B=a(download=filename,href=A._dom_element.toDataURL());A.append(B);B._dom_element.click()\n\tdef draw(E,what,width=_A,height=_A):\n\t\tC=height;B=width;A=what\n\t\tif isinstance(A,Element):A=A._dom_element\n\t\tD=E._dom_element.getContext('2d')\n\t\tif B or C:D.drawImage(A,0,0,B,C)\n\t\telse:D.drawImage(A,0,0)\nclass caption(ContainerElement):0\nclass cite(ContainerElement):0\nclass code(ContainerElement):0\nclass col(Element):0\nclass colgroup(ContainerElement):0\nclass data(ContainerElement):0\nclass datalist(ContainerElement,HasOptions):0\nclass dd(ContainerElement):0\nclass del_(ContainerElement):0\nclass details(ContainerElement):0\nclass dialog(ContainerElement):0\nclass div(ContainerElement):0\nclass dl(ContainerElement):0\nclass dt(ContainerElement):0\nclass em(ContainerElement):0\nclass embed(Element):0\nclass fieldset(ContainerElement):0\nclass figcaption(ContainerElement):0\nclass figure(ContainerElement):0\nclass footer(ContainerElement):0\nclass form(ContainerElement):0\nclass h1(ContainerElement):0\nclass h2(ContainerElement):0\nclass h3(ContainerElement):0\nclass h4(ContainerElement):0\nclass h5(ContainerElement):0\nclass h6(ContainerElement):0\nclass head(ContainerElement):0\nclass header(ContainerElement):0\nclass hgroup(ContainerElement):0\nclass hr(Element):0\nclass html(ContainerElement):0\nclass i(ContainerElement):0\nclass iframe(ContainerElement):0\nclass img(Element):0\nclass input_(Element):0\nclass ins(ContainerElement):0\nclass kbd(ContainerElement):0\nclass label(ContainerElement):0\nclass legend(ContainerElement):0\nclass li(ContainerElement):0\nclass link(Element):0\nclass main(ContainerElement):0\nclass map_(ContainerElement):0\nclass mark(ContainerElement):0\nclass menu(ContainerElement):0\nclass meta(ContainerElement):0\nclass meter(ContainerElement):0\nclass nav(ContainerElement):0\nclass object_(ContainerElement):0\nclass ol(ContainerElement):0\nclass optgroup(ContainerElement,HasOptions):0\nclass option(ContainerElement):0\nclass output(ContainerElement):0\nclass p(ContainerElement):0\nclass param(ContainerElement):0\nclass picture(ContainerElement):0\nclass pre(ContainerElement):0\nclass progress(ContainerElement):0\nclass q(ContainerElement):0\nclass s(ContainerElement):0\nclass script(ContainerElement):0\nclass section(ContainerElement):0\nclass select(ContainerElement,HasOptions):0\nclass small(ContainerElement):0\nclass source(Element):0\nclass span(ContainerElement):0\nclass strong(ContainerElement):0\nclass style(ContainerElement):0\nclass sub(ContainerElement):0\nclass summary(ContainerElement):0\nclass sup(ContainerElement):0\nclass table(ContainerElement):0\nclass tbody(ContainerElement):0\nclass td(ContainerElement):0\nclass template(ContainerElement):0\nclass textarea(ContainerElement):0\nclass tfoot(ContainerElement):0\nclass th(ContainerElement):0\nclass thead(ContainerElement):0\nclass time(ContainerElement):0\nclass title(ContainerElement):0\nclass tr(ContainerElement):0\nclass track(Element):0\nclass u(ContainerElement):0\nclass ul(ContainerElement):0\nclass var(ContainerElement):0\nclass video(ContainerElement):\n\tdef snap(D,to=_A,width=_A,height=_A):\n\t\tG='CANVAS';F='Element to snap to must be a canvas.';C=height;B=width;A=to;B=B if B is not _A else D.videoWidth;C=C if C is not _A else D.videoHeight\n\t\tif A is _A:A=canvas(width=B,height=C)\n\t\telif isinstance(A,Element):\n\t\t\tif A.tag!='canvas':raise TypeError(F)\n\t\telif getattr(A,'tagName','')==G:A=canvas(dom_element=A)\n\t\telif isinstance(A,str):\n\t\t\tE=document.querySelectorAll(A)\n\t\t\tif E.length==0:raise TypeError('No element with selector {to} to snap to.')\n\t\t\tif E[0].tagName!=G:raise TypeError(F)\n\t\t\tA=canvas(dom_element=E[0])\n\t\tA.draw(D,B,C);return A\nclass wbr(Element):0\nELEMENT_CLASSES=[a,abbr,address,area,article,aside,audio,b,base,blockquote,body,br,button,canvas,caption,cite,code,col,colgroup,data,datalist,dd,del_,details,dialog,div,dl,dt,em,embed,fieldset,figcaption,figure,footer,form,h1,h2,h3,h4,h5,h6,head,header,hgroup,hr,html,i,iframe,img,input_,ins,kbd,label,legend,li,link,main,map_,mark,menu,meta,meter,nav,object_,ol,optgroup,option,output,p,param,picture,pre,progress,q,s,script,section,select,small,source,span,strong,style,sub,summary,sup,table,tbody,td,template,textarea,tfoot,th,thead,time,title,tr,track,u,ul,var,video,wbr]\nElement.register_element_classes(ELEMENT_CLASSES)\nclass Page:\n\tdef __init__(A):A.html=Element.wrap_dom_element(document.documentElement);A.body=Element.wrap_dom_element(document.body);A.head=Element.wrap_dom_element(document.head)\n\tdef __getitem__(A,selector):return A.find(selector)\n\t@property\n\tdef title(self):return document.title\n\t@title.setter\n\tdef title(self,value):document.title=value\n\tdef append(A,*B):A.body.append(*B)\n\tdef find(A,selector):return ElementCollection.wrap_dom_elements(document.querySelectorAll(selector))\npage=Page()",
|
12
|
+
"media.py": "from pyscript import window\nfrom pyscript.ffi import to_js\nclass Device:\n\tdef __init__(A,device):A._dom_element=device\n\t@property\n\tdef id(self):return self._dom_element.deviceId\n\t@property\n\tdef group(self):return self._dom_element.groupId\n\t@property\n\tdef kind(self):return self._dom_element.kind\n\t@property\n\tdef label(self):return self._dom_element.label\n\tdef __getitem__(A,key):return getattr(A,key)\n\t@classmethod\n\tasync def load(D,audio=False,video=True):\n\t\tB=video;A=window.Object.new();A.audio=audio\n\t\tif isinstance(B,bool):A.video=B\n\t\telse:\n\t\t\tA.video=window.Object.new()\n\t\t\tfor C in B:setattr(A.video,C,to_js(B[C]))\n\t\treturn await window.navigator.mediaDevices.getUserMedia(A)\n\tasync def get_stream(A):B=A.kind.replace('input','').replace('output','');C={B:{'deviceId':{'exact':A.id}}};return await A.load(**C)\nasync def list_devices():return[Device(A)for A in await window.navigator.mediaDevices.enumerateDevices()]",
|
13
|
+
"storage.py": "_C='memoryview'\n_B='bytearray'\n_A='generic'\nfrom polyscript import storage as _storage\nfrom pyscript.flatted import parse as _parse\nfrom pyscript.flatted import stringify as _stringify\ndef _to_idb(value):\n\tA=value\n\tif A is None:return _stringify(['null',0])\n\tif isinstance(A,(bool,float,int,str,list,dict,tuple)):return _stringify([_A,A])\n\tif isinstance(A,bytearray):return _stringify([_B,list(A)])\n\tif isinstance(A,memoryview):return _stringify([_C,list(A)])\n\tB=f\"Unexpected value: {A}\";raise TypeError(B)\ndef _from_idb(value):\n\tC=value;A,B=_parse(C)\n\tif A=='null':return\n\tif A==_A:return B\n\tif A==_B:return bytearray(B)\n\tif A==_C:return memoryview(bytearray(B))\n\treturn C\nclass Storage(dict):\n\tdef __init__(B,store):A=store;super().__init__({A:_from_idb(B)for(A,B)in A.entries()});B.__store__=A\n\tdef __delitem__(A,attr):A.__store__.delete(attr);super().__delitem__(attr)\n\tdef __setitem__(B,attr,value):A=value;B.__store__.set(attr,_to_idb(A));super().__setitem__(attr,A)\n\tdef clear(A):A.__store__.clear();super().clear()\n\tasync def sync(A):await A.__store__.sync()\nasync def storage(name='',storage_class=Storage):\n\tif not name:A='The storage name must be defined';raise ValueError(A)\n\treturn storage_class(await _storage(f\"@pyscript/{name}\"))",
|
14
|
+
"util.py": "import js,sys,inspect\ndef as_bytearray(buffer):\n\tA=js.Uint8Array.new(buffer);B=A.length;C=bytearray(B)\n\tfor D in range(B):C[D]=A[D]\n\treturn C\nclass NotSupported:\n\tdef __init__(A,name,error):object.__setattr__(A,'name',name);object.__setattr__(A,'error',error)\n\tdef __repr__(A):return f\"<NotSupported {A.name} [{A.error}]>\"\n\tdef __getattr__(A,attr):raise AttributeError(A.error)\n\tdef __setattr__(A,attr,value):raise AttributeError(A.error)\n\tdef __call__(A,*B):raise TypeError(A.error)\ndef is_awaitable(obj):\n\tA=obj;from pyscript import config as B\n\tif B['type']=='mpy':\n\t\tif'<closure <generator>'in repr(A):return True\n\t\treturn inspect.isgeneratorfunction(A)\n\treturn inspect.iscoroutinefunction(A)",
|
15
|
+
"web.py": "_B='on_'\n_A=None\nfrom pyscript import document,when,Event\nfrom pyscript.ffi import create_proxy\ndef wrap_dom_element(dom_element):return Element.wrap_dom_element(dom_element)\nclass Element:\n\telement_classes_by_tag_name={}\n\t@classmethod\n\tdef get_tag_name(A):return A.__name__.replace('_','')\n\t@classmethod\n\tdef register_element_classes(B,element_classes):\n\t\tfor A in element_classes:C=A.get_tag_name();B.element_classes_by_tag_name[C]=A\n\t@classmethod\n\tdef unregister_element_classes(A,element_classes):\n\t\tfor B in element_classes:C=B.get_tag_name();A.element_classes_by_tag_name.pop(C,_A)\n\t@classmethod\n\tdef wrap_dom_element(A,dom_element):B=dom_element;C=A.element_classes_by_tag_name.get(B.tagName.lower(),A);return C(dom_element=B)\n\tdef __init__(A,dom_element=_A,classes=_A,style=_A,**E):\n\t\tA._dom_element=dom_element or document.createElement(type(A).get_tag_name());A._on_events={};C={}\n\t\tfor(B,D)in E.items():\n\t\t\tif B.startswith(_B):F=A.get_event(B);F.add_listener(D)\n\t\t\telse:C[B]=D\n\t\tA._classes=Classes(A);A._style=Style(A);A.update(classes=classes,style=style,**C)\n\tdef __eq__(A,obj):return isinstance(obj,Element)and obj._dom_element==A._dom_element\n\tdef __getitem__(B,key):\n\t\tA=key\n\t\tif isinstance(A,(int,slice)):return B.children[A]\n\t\treturn B.find(A)\n\tdef __getattr__(B,name):\n\t\tA=name\n\t\tif A.startswith(_B):return B.get_event(A)\n\t\tif A.endswith('_'):A=A[:-1]\n\t\treturn getattr(B._dom_element,A)\n\tdef __setattr__(C,name,value):\n\t\tB=value;A=name\n\t\tif A.startswith('_'):super().__setattr__(A,B)\n\t\telse:\n\t\t\tif A.endswith('_'):A=A[:-1]\n\t\t\tif A.startswith(_B):C._on_events[A]=B\n\t\t\tsetattr(C._dom_element,A,B)\n\tdef get_event(A,name):\n\t\tB=name\n\t\tif not B.startswith(_B):C=\"Event names must start with 'on_'.\";raise ValueError(C)\n\t\tD=B[3:]\n\t\tif not hasattr(A._dom_element,D):C=f\"Element has no '{D}' event.\";raise ValueError(C)\n\t\tif B in A._on_events:return A._on_events[B]\n\t\tE=Event();A._on_events[B]=E;A._dom_element.addEventListener(D,create_proxy(E.trigger));return E\n\t@property\n\tdef children(self):return ElementCollection.wrap_dom_elements(self._dom_element.children)\n\t@property\n\tdef classes(self):return self._classes\n\t@property\n\tdef parent(self):\n\t\tif self._dom_element.parentElement is _A:return\n\t\treturn Element.wrap_dom_element(self._dom_element.parentElement)\n\t@property\n\tdef style(self):return self._style\n\tdef append(B,*C):\n\t\tfor A in C:\n\t\t\tif isinstance(A,Element):B._dom_element.appendChild(A._dom_element)\n\t\t\telif isinstance(A,ElementCollection):\n\t\t\t\tfor D in A:B._dom_element.appendChild(D._dom_element)\n\t\t\telif isinstance(A,(list,tuple)):\n\t\t\t\tfor E in A:B.append(E)\n\t\t\telse:\n\t\t\t\ttry:A.tagName;B._dom_element.appendChild(A)\n\t\t\t\texcept AttributeError:\n\t\t\t\t\ttry:\n\t\t\t\t\t\tA.length\n\t\t\t\t\t\tfor F in A:B._dom_element.appendChild(F)\n\t\t\t\t\texcept AttributeError:G=f'Element \"{A}\" is a proxy object, \"but not a valid element or a NodeList.';raise TypeError(G)\n\tdef clone(B,clone_id=_A):A=Element.wrap_dom_element(B._dom_element.cloneNode(True));A.id=clone_id;return A\n\tdef find(A,selector):return ElementCollection.wrap_dom_elements(A._dom_element.querySelectorAll(selector))\n\tdef show_me(A):A._dom_element.scrollIntoView()\n\tdef update(A,classes=_A,style=_A,**D):\n\t\tC=style;B=classes\n\t\tif B:A.classes.add(B)\n\t\tif C:A.style.set(**C)\n\t\tfor(E,F)in D.items():setattr(A,E,F)\nclass Classes:\n\tdef __init__(A,element):A._element=element;A._class_list=A._element._dom_element.classList\n\tdef __contains__(A,item):return item in A._class_list\n\tdef __eq__(C,other):\n\t\tA=other\n\t\tif isinstance(A,Classes):B=list(A._class_list)\n\t\telse:\n\t\t\ttry:B=iter(A)\n\t\t\texcept TypeError:return False\n\t\treturn set(C._class_list)==set(B)\n\tdef __iter__(A):return iter(A._class_list)\n\tdef __len__(A):return A._class_list.length\n\tdef __repr__(A):return f\"Classes({\", \".join(A._class_list)})\"\n\tdef __str__(A):return' '.join(A._class_list)\n\tdef add(B,*C):\n\t\tfor A in C:\n\t\t\tif isinstance(A,list):\n\t\t\t\tfor D in A:B.add(D)\n\t\t\telse:B._class_list.add(A)\n\tdef contains(A,class_name):return class_name in A\n\tdef remove(B,*C):\n\t\tfor A in C:\n\t\t\tif isinstance(A,list):\n\t\t\t\tfor D in A:B.remove(D)\n\t\t\telse:B._class_list.remove(A)\n\tdef replace(A,old_class,new_class):A.remove(old_class);A.add(new_class)\n\tdef toggle(A,*C):\n\t\tfor B in C:\n\t\t\tif B in A:A.remove(B)\n\t\t\telse:A.add(B)\nclass HasOptions:\n\t@property\n\tdef options(self):\n\t\tA=self\n\t\tif not hasattr(A,'_options'):A._options=Options(A)\n\t\treturn A._options\nclass Options:\n\tdef __init__(A,element):A._element=element\n\tdef __getitem__(A,key):return A.options[key]\n\tdef __iter__(A):yield from A.options\n\tdef __len__(A):return len(A.options)\n\tdef __repr__(A):return f\"{A.__class__.__name__} (length: {len(A)}) {A.options}\"\n\t@property\n\tdef options(self):return[Element.wrap_dom_element(A)for A in self._element._dom_element.options]\n\t@property\n\tdef selected(self):return self.options[self._element._dom_element.selectedIndex]\n\tdef add(D,value=_A,html=_A,text=_A,before=_A,**B):\n\t\tC=value;A=before\n\t\tif C is not _A:B['value']=C\n\t\tif html is not _A:B['innerHTML']=html\n\t\tif text is not _A:B['text']=text\n\t\tE=option(**B)\n\t\tif A and isinstance(A,Element):A=A._dom_element\n\t\tD._element._dom_element.add(E._dom_element,A)\n\tdef clear(A):\n\t\twhile len(A)>0:A.remove(0)\n\tdef remove(A,index):A._element._dom_element.remove(index)\nclass Style:\n\tdef __init__(A,element):A._element=element;A._style=A._element._dom_element.style\n\tdef __getitem__(A,key):return A._style.getPropertyValue(key)\n\tdef __setitem__(A,key,value):A._style.setProperty(key,value)\n\tdef remove(A,key):A._style.removeProperty(key)\n\tdef set(A,**B):\n\t\tfor(C,D)in B.items():A._element._dom_element.style.setProperty(C,D)\n\t@property\n\tdef visible(self):return self._element._dom_element.style.visibility\n\t@visible.setter\n\tdef visible(self,value):self._element._dom_element.style.visibility=value\nclass ContainerElement(Element):\n\tdef __init__(B,*C,children=_A,dom_element=_A,style=_A,classes=_A,**D):\n\t\tsuper().__init__(dom_element=dom_element,style=style,classes=classes,**D)\n\t\tfor A in list(C)+(children or[]):\n\t\t\tif isinstance(A,(Element,ElementCollection)):B.append(A)\n\t\t\telse:B._dom_element.insertAdjacentHTML('beforeend',A)\n\tdef __iter__(A):yield from A.children\nclass ClassesCollection:\n\tdef __init__(A,collection):A._collection=collection\n\tdef __contains__(A,class_name):\n\t\tfor B in A._collection:\n\t\t\tif class_name in B.classes:return True\n\t\treturn False\n\tdef __eq__(B,other):A=other;return isinstance(A,ClassesCollection)and B._collection==A._collection\n\tdef __iter__(A):yield from A._all_class_names()\n\tdef __len__(A):return len(A._all_class_names())\n\tdef __repr__(A):return f\"ClassesCollection({A._collection!r})\"\n\tdef __str__(A):return' '.join(A._all_class_names())\n\tdef add(A,*B):\n\t\tfor C in A._collection:C.classes.add(*B)\n\tdef contains(A,class_name):return class_name in A\n\tdef remove(A,*B):\n\t\tfor C in A._collection:C.classes.remove(*B)\n\tdef replace(A,old_class,new_class):\n\t\tfor B in A._collection:B.classes.replace(old_class,new_class)\n\tdef toggle(A,*B):\n\t\tfor C in A._collection:C.classes.toggle(*B)\n\tdef _all_class_names(B):\n\t\tA=set()\n\t\tfor C in B._collection:\n\t\t\tfor D in C.classes:A.add(D)\n\t\treturn A\nclass StyleCollection:\n\tdef __init__(A,collection):A._collection=collection\n\tdef __getitem__(A,key):return[A.style[key]for A in A._collection._elements]\n\tdef __setitem__(A,key,value):\n\t\tfor B in A._collection._elements:B.style[key]=value\n\tdef __repr__(A):return f\"StyleCollection({A._collection!r})\"\n\tdef remove(A,key):\n\t\tfor B in A._collection._elements:B.style.remove(key)\nclass ElementCollection:\n\t@classmethod\n\tdef wrap_dom_elements(A,dom_elements):return A([Element.wrap_dom_element(A)for A in dom_elements])\n\tdef __init__(A,elements):A._elements=elements;A._classes=ClassesCollection(A);A._style=StyleCollection(A)\n\tdef __eq__(A,obj):return isinstance(obj,ElementCollection)and obj._elements==A._elements\n\tdef __getitem__(B,key):\n\t\tA=key\n\t\tif isinstance(A,int):return B._elements[A]\n\t\tif isinstance(A,slice):return ElementCollection(B._elements[A])\n\t\treturn B.find(A)\n\tdef __iter__(A):yield from A._elements\n\tdef __len__(A):return len(A._elements)\n\tdef __repr__(A):return f\"{A.__class__.__name__} (length: {len(A._elements)}) {A._elements}\"\n\tdef __getattr__(A,name):return[getattr(A,name)for A in A._elements]\n\tdef __setattr__(C,name,value):\n\t\tB=value;A=name\n\t\tif A.startswith('_'):super().__setattr__(A,B)\n\t\telse:\n\t\t\tfor D in C._elements:setattr(D,A,B)\n\t@property\n\tdef classes(self):return self._classes\n\t@property\n\tdef elements(self):return self._elements\n\t@property\n\tdef style(self):return self._style\n\tdef find(B,selector):\n\t\tA=[]\n\t\tfor C in B._elements:A.extend(C.find(selector))\n\t\treturn ElementCollection(A)\nclass a(ContainerElement):0\nclass abbr(ContainerElement):0\nclass address(ContainerElement):0\nclass area(Element):0\nclass article(ContainerElement):0\nclass aside(ContainerElement):0\nclass audio(ContainerElement):0\nclass b(ContainerElement):0\nclass base(Element):0\nclass blockquote(ContainerElement):0\nclass body(ContainerElement):0\nclass br(Element):0\nclass button(ContainerElement):0\nclass canvas(ContainerElement):\n\tdef download(A,filename='snapped.png'):B=a(download=filename,href=A._dom_element.toDataURL());A.append(B);B._dom_element.click()\n\tdef draw(E,what,width=_A,height=_A):\n\t\tC=height;B=width;A=what\n\t\tif isinstance(A,Element):A=A._dom_element\n\t\tD=E._dom_element.getContext('2d')\n\t\tif B or C:D.drawImage(A,0,0,B,C)\n\t\telse:D.drawImage(A,0,0)\nclass caption(ContainerElement):0\nclass cite(ContainerElement):0\nclass code(ContainerElement):0\nclass col(Element):0\nclass colgroup(ContainerElement):0\nclass data(ContainerElement):0\nclass datalist(ContainerElement,HasOptions):0\nclass dd(ContainerElement):0\nclass del_(ContainerElement):0\nclass details(ContainerElement):0\nclass dialog(ContainerElement):0\nclass div(ContainerElement):0\nclass dl(ContainerElement):0\nclass dt(ContainerElement):0\nclass em(ContainerElement):0\nclass embed(Element):0\nclass fieldset(ContainerElement):0\nclass figcaption(ContainerElement):0\nclass figure(ContainerElement):0\nclass footer(ContainerElement):0\nclass form(ContainerElement):0\nclass h1(ContainerElement):0\nclass h2(ContainerElement):0\nclass h3(ContainerElement):0\nclass h4(ContainerElement):0\nclass h5(ContainerElement):0\nclass h6(ContainerElement):0\nclass head(ContainerElement):0\nclass header(ContainerElement):0\nclass hgroup(ContainerElement):0\nclass hr(Element):0\nclass html(ContainerElement):0\nclass i(ContainerElement):0\nclass iframe(ContainerElement):0\nclass img(Element):0\nclass input_(Element):0\nclass ins(ContainerElement):0\nclass kbd(ContainerElement):0\nclass label(ContainerElement):0\nclass legend(ContainerElement):0\nclass li(ContainerElement):0\nclass link(Element):0\nclass main(ContainerElement):0\nclass map_(ContainerElement):0\nclass mark(ContainerElement):0\nclass menu(ContainerElement):0\nclass meta(ContainerElement):0\nclass meter(ContainerElement):0\nclass nav(ContainerElement):0\nclass object_(ContainerElement):0\nclass ol(ContainerElement):0\nclass optgroup(ContainerElement,HasOptions):0\nclass option(ContainerElement):0\nclass output(ContainerElement):0\nclass p(ContainerElement):0\nclass param(ContainerElement):0\nclass picture(ContainerElement):0\nclass pre(ContainerElement):0\nclass progress(ContainerElement):0\nclass q(ContainerElement):0\nclass s(ContainerElement):0\nclass script(ContainerElement):0\nclass section(ContainerElement):0\nclass select(ContainerElement,HasOptions):0\nclass small(ContainerElement):0\nclass source(Element):0\nclass span(ContainerElement):0\nclass strong(ContainerElement):0\nclass style(ContainerElement):0\nclass sub(ContainerElement):0\nclass summary(ContainerElement):0\nclass sup(ContainerElement):0\nclass table(ContainerElement):0\nclass tbody(ContainerElement):0\nclass td(ContainerElement):0\nclass template(ContainerElement):0\nclass textarea(ContainerElement):0\nclass tfoot(ContainerElement):0\nclass th(ContainerElement):0\nclass thead(ContainerElement):0\nclass time(ContainerElement):0\nclass title(ContainerElement):0\nclass tr(ContainerElement):0\nclass track(Element):0\nclass u(ContainerElement):0\nclass ul(ContainerElement):0\nclass var(ContainerElement):0\nclass video(ContainerElement):\n\tdef snap(E,to=_A,width=_A,height=_A):\n\t\tH='CANVAS';G='Element to snap to must be a canvas.';C=height;B=width;A=to;B=B if B is not _A else E.videoWidth;C=C if C is not _A else E.videoHeight\n\t\tif A is _A:A=canvas(width=B,height=C)\n\t\telif isinstance(A,Element):\n\t\t\tif A.tag!='canvas':D=G;raise TypeError(D)\n\t\telif getattr(A,'tagName','')==H:A=canvas(dom_element=A)\n\t\telif isinstance(A,str):\n\t\t\tF=document.querySelectorAll(A)\n\t\t\tif F.length==0:D='No element with selector {to} to snap to.';raise TypeError(D)\n\t\t\tif F[0].tagName!=H:D=G;raise TypeError(D)\n\t\t\tA=canvas(dom_element=F[0])\n\t\tA.draw(E,B,C);return A\nclass wbr(Element):0\nELEMENT_CLASSES=[a,abbr,address,area,article,aside,audio,b,base,blockquote,body,br,button,canvas,caption,cite,code,col,colgroup,data,datalist,dd,del_,details,dialog,div,dl,dt,em,embed,fieldset,figcaption,figure,footer,form,h1,h2,h3,h4,h5,h6,head,header,hgroup,hr,html,i,iframe,img,input_,ins,kbd,label,legend,li,link,main,map_,mark,menu,meta,meter,nav,object_,ol,optgroup,option,output,p,param,picture,pre,progress,q,s,script,section,select,small,source,span,strong,style,sub,summary,sup,table,tbody,td,template,textarea,tfoot,th,thead,time,title,tr,track,u,ul,var,video,wbr]\nElement.register_element_classes(ELEMENT_CLASSES)\nclass Page:\n\tdef __init__(A):A.html=Element.wrap_dom_element(document.documentElement);A.body=Element.wrap_dom_element(document.body);A.head=Element.wrap_dom_element(document.head)\n\tdef __getitem__(A,selector):return A.find(selector)\n\t@property\n\tdef title(self):return document.title\n\t@title.setter\n\tdef title(self,value):document.title=value\n\tdef append(A,*B):A.body.append(*B)\n\tdef find(A,selector):return ElementCollection.wrap_dom_elements(document.querySelectorAll(selector))\npage=Page()",
|
16
16
|
"websocket.py": "import js\nfrom pyscript.ffi import create_proxy\nfrom pyscript.util import as_bytearray\ncode='code'\nprotocols='protocols'\nreason='reason'\nmethods=['onclose','onerror','onmessage','onopen']\nclass EventMessage:\n\tdef __init__(A,event):A._event=event\n\tdef __getattr__(B,attr):\n\t\tA=getattr(B._event,attr)\n\t\tif attr=='data'and not isinstance(A,str):\n\t\t\tif hasattr(A,'to_py'):return A.to_py()\n\t\t\treturn memoryview(as_bytearray(A))\n\t\treturn A\nclass WebSocket:\n\tCONNECTING=0;OPEN=1;CLOSING=2;CLOSED=3\n\tdef __init__(E,**A):\n\t\tD=A['url']\n\t\tif protocols in A:B=js.WebSocket.new(D,A[protocols])\n\t\telse:B=js.WebSocket.new(D)\n\t\tobject.__setattr__(E,'_ws',B)\n\t\tfor C in methods:\n\t\t\tif C in A:setattr(B,C,create_proxy(A[C]))\n\tdef __getattr__(A,attr):return getattr(A._ws,attr)\n\tdef __setattr__(B,attr,value):\n\t\tC=value;A=attr\n\t\tif A in methods:D=lambda e:C(EventMessage(e));setattr(B._ws,A,create_proxy(D))\n\t\telse:setattr(B._ws,A,C)\n\tdef close(B,**A):\n\t\tif code in A and reason in A:B._ws.close(A[code],A[reason])\n\t\telif code in A:B._ws.close(A[code])\n\t\telse:B._ws.close()\n\tdef send(B,data):\n\t\tA=data\n\t\tif isinstance(A,str):B._ws.send(A)\n\t\telse:\n\t\t\tC=js.Uint8Array.new(len(A))\n\t\t\tfor(D,E)in enumerate(A):C[D]=E\n\t\t\tB._ws.send(C)",
|
17
|
-
"workers.py": "import js as _js\nfrom polyscript import workers as _workers\n_get=_js.Reflect.get\ndef _set(script,name,value=''):script.setAttribute(name,value)\nclass _ReadOnlyProxy:\n\tdef __getitem__(A,name):return _get(_workers,name)\n\tdef __getattr__(A,name):return _get(_workers,name)\nworkers=_ReadOnlyProxy()\nasync def create_named_worker(src='',name='',config=None,type='py'):\n\tC=name;B=config;from json import dumps\n\tif not src:
|
17
|
+
"workers.py": "import js as _js\nfrom polyscript import workers as _workers\n_get=_js.Reflect.get\ndef _set(script,name,value=''):script.setAttribute(name,value)\nclass _ReadOnlyProxy:\n\tdef __getitem__(A,name):return _get(_workers,name)\n\tdef __getattr__(A,name):return _get(_workers,name)\nworkers=_ReadOnlyProxy()\nasync def create_named_worker(src='',name='',config=None,type='py'):\n\tC=name;B=config;from json import dumps\n\tif not src:D='Named workers require src';raise ValueError(D)\n\tif not C:D='Named workers require a name';raise ValueError(D)\n\tA=_js.document.createElement('script');A.type=type;A.src=src;_set(A,'worker');_set(A,'name',C)\n\tif B:_set(A,'config',isinstance(B,str)and B or dumps(B))\n\t_js.document.body.append(A);return await workers[C]"
|
18
18
|
}
|
19
19
|
};
|
@@ -1,2 +0,0 @@
|
|
1
|
-
import{T as e,c as t,X as r,d as n,a as o,r as s,o as a,H as i,s as c}from"./core-DBBBvqAZ.js";import{notify as l}from"./error-CcoJNMra.js";let d=0;const u=e=>`${e}-editor-${d++}`,f=new Map,p=new Map,g={worker:{codeBeforeRun:()=>c,onReady:({runAsync:e,io:t},{sync:r})=>{t.stdout=t.buffered(r.write),t.stderr=t.buffered(r.writeErr),r.revoke(),r.runAsync=e}}},v=(e,t)=>{if("boolean"==typeof t)throw`Invalid source: ${e}`;return t};async function m({currentTarget:t}){const{env:o,pySrc:c,outDiv:d}=this,u=!!t;if(u&&(t.disabled=!0,d.innerHTML=""),!f.has(o)){const c=URL.createObjectURL(new Blob([""])),d={type:this.interpreter,serviceWorker:this.serviceWorker},{config:p}=this;if(p)try{if(d.configURL=s(p),p.endsWith(".toml")){const[{parse:e},t]=await Promise.all([import("./toml-BLBSZ43A.js"),fetch(p).then((e=>e.ok&&e.text()))]);d.config=e(v(p,t))}else if(p.endsWith(".json")){const e=await fetch(p).then((e=>e.ok&&e.json()));d.config=v(p,e)}else d.configURL=s("./config.txt"),d.config=JSON.parse(p);d.version=a(d.config)}catch(e){return void l(e)}else d.config={};const m=r.call(new i(null,g),c,d);if(u)for(const r of e.keys()){const e=t.closest(`.${r}-editor-box`),o=e?.parentNode?.previousElementSibling;if(o){n(o,{xworker:{value:m}});break}}const{sync:h}=m,{promise:y,resolve:b}=Promise.withResolvers();f.set(o,y),h.revoke=()=>{URL.revokeObjectURL(c),b(m)}}return f.get(o).then((e=>{e.onerror=({error:e})=>{u&&d.insertAdjacentHTML("beforeend",`<span style='color:red'>${e.message||e}</span>\n`),console.error(e)};const r=()=>{u&&(t.disabled=!1)},{sync:n}=e;n.write=e=>{u?d.innerText+=`${e}\n`:console.log(e)},n.writeErr=e=>{u?d.insertAdjacentHTML("beforeend",`<span style='color:red'>${e}</span>\n`):(l(e),console.error(e))},n.runAsync(c).then(r,r)}))}const h=(e,t)=>{const r=document.createElement("div");r.className=`${t}-editor-input`,r.setAttribute("aria-label","Python Script Area");const n=((e,t)=>{const r=document.createElement("button");return r.className=`absolute ${t}-editor-run-button`,r.innerHTML='<svg style="height:20px;width:20px;vertical-align:-.125em;transform-origin:center;overflow:visible;color:green" viewBox="0 0 384 512" aria-hidden="true" role="img" xmlns="http://www.w3.org/2000/svg"><g transform="translate(192 256)" transform-origin="96 0"><g transform="translate(0,0) scale(1,1)"><path d="M361 215C375.3 223.8 384 239.3 384 256C384 272.7 375.3 288.2 361 296.1L73.03 472.1C58.21 482 39.66 482.4 24.52 473.9C9.377 465.4 0 449.4 0 432V80C0 62.64 9.377 46.63 24.52 38.13C39.66 29.64 58.21 29.99 73.03 39.04L361 215z" fill="currentColor" transform="translate(-192 -256)"></path></g></g></svg>',r.setAttribute("aria-label","Python Script Run Button"),r.addEventListener("click",(async t=>{r.blur(),await e.handleEvent(t)})),r})(e,t),o=document.createElement("div");return o.addEventListener("keydown",(e=>{e.stopPropagation()})),r.append(n,o),r},y=(e,t)=>{const r=document.createElement("div");r.className=`${t}-editor-box`;const n=h(e,t),o=(e=>{const t=document.createElement("div");return t.className=`${e}-editor-output`,t.id=`${u(e)}-output`,t})(t);return r.append(n,o),[r,o,n.querySelector("button")]},b=async(e,s,a)=>{const[{basicSetup:i,EditorView:c},{Compartment:d},{python:f},{indentUnit:g},{keymap:h},{defaultKeymap:b,indentWithTab:w}]=await Promise.all([t.core,t.state,t.python,t.language,t.view,t.commands]);let E=e.hasAttribute("setup");const k=e.hasAttribute("config"),$=e.getAttribute("service-worker"),A=`${a}-${e.getAttribute("env")||u(s)}`;if($&&(new r("data:application/javascript,postMessage(0)",{type:"dummy",serviceWorker:$}).onmessage=({target:e})=>e.terminate()),k&&p.has(A))throw new SyntaxError(p.get(A)?`duplicated config for env: ${A}`:`unable to add a config to the env: ${A}`);p.set(A,k);let x=e.textContent;const{src:S}=e;if(S)try{x=v(S,await fetch(S).then((e=>e.ok&&e.text())))}catch(e){return void l(e)}const L={handleEvent:m,serviceWorker:$,interpreter:a,env:A,config:k&&e.getAttribute("config"),get pySrc(){return E?x:B.state.doc.toString()},get outDiv(){return E?null:j}};let C;n(e,{target:{get:()=>C},handleEvent:{get:()=>L.handleEvent,set:e=>{L.handleEvent=e===m?m:async t=>{const{currentTarget:r}=t;n(t,{code:{value:L.pySrc}}),!1!==await e(t)&&await m.call(L,{currentTarget:r})}}},code:{get:()=>L.pySrc,set:e=>{E||B.update([B.state.update({changes:{from:0,to:B.state.doc.length,insert:e}})])}},process:{value(e,t=!1){if(t)return N();const r=E,n=x;E=!0,x=e;const o=()=>{E=r,x=n};return L.handleEvent({currentTarget:null}).then(o,o)}}});const T=()=>{const t=new Event(`${s}-editor`,{bubbles:!0});e.dispatchEvent(t)};if(E)return await L.handleEvent({currentTarget:null}),void T();const M=e.getAttribute("target");if(M){if(C=document.getElementById(M)||document.querySelector(M),!C)throw new Error(`Unknown target ${M}`)}else C=document.createElement(`${s}-editor`),C.style.display="block",e.after(C);C.id||(C.id=u(s)),C.hasAttribute("exec-id")||C.setAttribute("exec-id",0),C.hasAttribute("root")||C.setAttribute("root",C.id);const[R,j,U]=y(L,s);R.dataset.env=e.hasAttribute("env")?A:a;const P=R.querySelector(`.${s}-editor-input > div`).attachShadow({mode:"open"});P.innerHTML="<style> :host { all: initial; }</style>",C.appendChild(R);const W=o(e.textContent).trim(),H=/^([ \t]+)/m.test(W)?RegExp.$1:" ",N=()=>U.click(),B=new c({extensions:[g.of(H),(new d).of(f()),h.of([...b,{key:"Ctrl-Enter",run:N,preventDefault:!0},{key:"Cmd-Enter",run:N,preventDefault:!0},{key:"Shift-Enter",run:N,preventDefault:!0},w]),i],foldGutter:!0,gutters:["CodeMirror-linenumbers","CodeMirror-foldgutter"],parent:P,doc:W});B.focus(),T()};let w=0,E=Promise.resolve();const k=()=>{w=0,$()},$=()=>{if(!w){w=setTimeout(k,250);for(const[t,r]of e){const e=`script[type="${t}-editor"]`;for(const n of document.querySelectorAll(e))n.type+="-active",E=E.then((()=>b(n,t,r)))}return E}};new MutationObserver($).observe(document,{childList:!0,subtree:!0});var A=$();export{A as default};
|
2
|
-
//# sourceMappingURL=py-editor-DnliBZkx.js.map
|
@@ -1 +0,0 @@
|
|
1
|
-
{"version":3,"file":"py-editor-DnliBZkx.js","sources":["../src/plugins/py-editor.js"],"sourcesContent":["// PyScript py-editor plugin\nimport { Hook, XWorker, dedent, defineProperties } from \"polyscript/exports\";\nimport { TYPES, offline_interpreter, relative_url, stdlib } from \"../core.js\";\nimport { notify } from \"./error.js\";\nimport codemirror from \"./codemirror.js\";\n\nconst RUN_BUTTON = `<svg style=\"height:20px;width:20px;vertical-align:-.125em;transform-origin:center;overflow:visible;color:green\" viewBox=\"0 0 384 512\" aria-hidden=\"true\" role=\"img\" xmlns=\"http://www.w3.org/2000/svg\"><g transform=\"translate(192 256)\" transform-origin=\"96 0\"><g transform=\"translate(0,0) scale(1,1)\"><path d=\"M361 215C375.3 223.8 384 239.3 384 256C384 272.7 375.3 288.2 361 296.1L73.03 472.1C58.21 482 39.66 482.4 24.52 473.9C9.377 465.4 0 449.4 0 432V80C0 62.64 9.377 46.63 24.52 38.13C39.66 29.64 58.21 29.99 73.03 39.04L361 215z\" fill=\"currentColor\" transform=\"translate(-192 -256)\"></path></g></g></svg>`;\n\nlet id = 0;\nconst getID = (type) => `${type}-editor-${id++}`;\n\nconst envs = new Map();\nconst configs = new Map();\n\nconst hooks = {\n worker: {\n codeBeforeRun: () => stdlib,\n // works on both Pyodide and MicroPython\n onReady: ({ runAsync, io }, { sync }) => {\n io.stdout = io.buffered(sync.write);\n io.stderr = io.buffered(sync.writeErr);\n sync.revoke();\n sync.runAsync = runAsync;\n },\n },\n};\n\nconst validate = (config, result) => {\n if (typeof result === \"boolean\") throw `Invalid source: ${config}`;\n return result;\n};\n\nasync function execute({ currentTarget }) {\n const { env, pySrc, outDiv } = this;\n const hasRunButton = !!currentTarget;\n\n if (hasRunButton) {\n currentTarget.disabled = true;\n outDiv.innerHTML = \"\";\n }\n\n if (!envs.has(env)) {\n const srcLink = URL.createObjectURL(new Blob([\"\"]));\n const details = {\n type: this.interpreter,\n serviceWorker: this.serviceWorker,\n };\n const { config } = this;\n if (config) {\n // verify that config can be parsed and used\n try {\n details.configURL = relative_url(config);\n if (config.endsWith(\".toml\")) {\n const [{ parse }, toml] = await Promise.all([\n import(\n /* webpackIgnore: true */ \"../3rd-party/toml.js\"\n ),\n fetch(config).then((r) => r.ok && r.text()),\n ]);\n details.config = parse(validate(config, toml));\n } else if (config.endsWith(\".json\")) {\n const json = await fetch(config).then(\n (r) => r.ok && r.json(),\n );\n details.config = validate(config, json);\n } else {\n details.configURL = relative_url(\"./config.txt\");\n details.config = JSON.parse(config);\n }\n details.version = offline_interpreter(details.config);\n } catch (error) {\n notify(error);\n return;\n }\n } else {\n details.config = {};\n }\n\n const xworker = XWorker.call(new Hook(null, hooks), srcLink, details);\n\n // expose xworker like in terminal or other workers to allow\n // creation and destruction of editors on the fly\n if (hasRunButton) {\n for (const type of TYPES.keys()) {\n const editor = currentTarget.closest(`.${type}-editor-box`);\n const script = editor?.parentNode?.previousElementSibling;\n if (script) {\n defineProperties(script, { xworker: { value: xworker } });\n break;\n }\n }\n }\n\n const { sync } = xworker;\n const { promise, resolve } = Promise.withResolvers();\n envs.set(env, promise);\n sync.revoke = () => {\n URL.revokeObjectURL(srcLink);\n resolve(xworker);\n };\n }\n\n // wait for the env then set the target div\n // before executing the current code\n return envs.get(env).then((xworker) => {\n xworker.onerror = ({ error }) => {\n if (hasRunButton) {\n outDiv.insertAdjacentHTML(\n \"beforeend\",\n `<span style='color:red'>${\n error.message || error\n }</span>\\n`,\n );\n }\n console.error(error);\n };\n\n const enable = () => {\n if (hasRunButton) currentTarget.disabled = false;\n };\n const { sync } = xworker;\n sync.write = (str) => {\n if (hasRunButton) outDiv.innerText += `${str}\\n`;\n else console.log(str);\n };\n sync.writeErr = (str) => {\n if (hasRunButton) {\n outDiv.insertAdjacentHTML(\n \"beforeend\",\n `<span style='color:red'>${str}</span>\\n`,\n );\n } else {\n notify(str);\n console.error(str);\n }\n };\n sync.runAsync(pySrc).then(enable, enable);\n });\n}\n\nconst makeRunButton = (handler, type) => {\n const runButton = document.createElement(\"button\");\n runButton.className = `absolute ${type}-editor-run-button`;\n runButton.innerHTML = RUN_BUTTON;\n runButton.setAttribute(\"aria-label\", \"Python Script Run Button\");\n runButton.addEventListener(\"click\", async (event) => {\n runButton.blur();\n await handler.handleEvent(event);\n });\n return runButton;\n};\n\nconst makeEditorDiv = (handler, type) => {\n const editorDiv = document.createElement(\"div\");\n editorDiv.className = `${type}-editor-input`;\n editorDiv.setAttribute(\"aria-label\", \"Python Script Area\");\n\n const runButton = makeRunButton(handler, type);\n const editorShadowContainer = document.createElement(\"div\");\n\n // avoid outer elements intercepting key events (reveal as example)\n editorShadowContainer.addEventListener(\"keydown\", (event) => {\n event.stopPropagation();\n });\n\n editorDiv.append(runButton, editorShadowContainer);\n\n return editorDiv;\n};\n\nconst makeOutDiv = (type) => {\n const outDiv = document.createElement(\"div\");\n outDiv.className = `${type}-editor-output`;\n outDiv.id = `${getID(type)}-output`;\n return outDiv;\n};\n\nconst makeBoxDiv = (handler, type) => {\n const boxDiv = document.createElement(\"div\");\n boxDiv.className = `${type}-editor-box`;\n\n const editorDiv = makeEditorDiv(handler, type);\n const outDiv = makeOutDiv(type);\n boxDiv.append(editorDiv, outDiv);\n\n return [boxDiv, outDiv, editorDiv.querySelector(\"button\")];\n};\n\nconst init = async (script, type, interpreter) => {\n const [\n { basicSetup, EditorView },\n { Compartment },\n { python },\n { indentUnit },\n { keymap },\n { defaultKeymap, indentWithTab },\n ] = await Promise.all([\n codemirror.core,\n codemirror.state,\n codemirror.python,\n codemirror.language,\n codemirror.view,\n codemirror.commands,\n ]);\n\n let isSetup = script.hasAttribute(\"setup\");\n const hasConfig = script.hasAttribute(\"config\");\n const serviceWorker = script.getAttribute(\"service-worker\");\n const env = `${interpreter}-${script.getAttribute(\"env\") || getID(type)}`;\n\n // helps preventing too lazy ServiceWorker initialization on button run\n if (serviceWorker) {\n new XWorker(\"data:application/javascript,postMessage(0)\", {\n type: \"dummy\",\n serviceWorker,\n }).onmessage = ({ target }) => target.terminate();\n }\n\n if (hasConfig && configs.has(env)) {\n throw new SyntaxError(\n configs.get(env)\n ? `duplicated config for env: ${env}`\n : `unable to add a config to the env: ${env}`,\n );\n }\n\n configs.set(env, hasConfig);\n\n let source = script.textContent;\n\n // verify the src points to a valid file that can be parsed\n const { src } = script;\n if (src) {\n try {\n source = validate(\n src,\n await fetch(src).then((b) => b.ok && b.text()),\n );\n } catch (error) {\n notify(error);\n return;\n }\n }\n\n const context = {\n // allow the listener to be overridden at distance\n handleEvent: execute,\n serviceWorker,\n interpreter,\n env,\n config: hasConfig && script.getAttribute(\"config\"),\n get pySrc() {\n return isSetup ? source : editor.state.doc.toString();\n },\n get outDiv() {\n return isSetup ? null : outDiv;\n },\n };\n\n let target;\n defineProperties(script, {\n target: { get: () => target },\n handleEvent: {\n get: () => context.handleEvent,\n set: (callback) => {\n // do not bother with logic if it was set back as its original handler\n if (callback === execute) context.handleEvent = execute;\n // in every other case be sure that if the listener override returned\n // `false` nothing happens, otherwise keep doing what it always did\n else {\n context.handleEvent = async (event) => {\n // trap the currentTarget ASAP (if any)\n // otherwise it gets lost asynchronously\n const { currentTarget } = event;\n // augment a code snapshot before invoking the override\n defineProperties(event, {\n code: { value: context.pySrc },\n });\n // avoid executing the default handler if the override returned `false`\n if ((await callback(event)) !== false)\n await execute.call(context, { currentTarget });\n };\n }\n },\n },\n code: {\n get: () => context.pySrc,\n set: (insert) => {\n if (isSetup) return;\n editor.update([\n editor.state.update({\n changes: {\n from: 0,\n to: editor.state.doc.length,\n insert,\n },\n }),\n ]);\n },\n },\n process: {\n /**\n * Simulate a setup node overriding the source to evaluate.\n * @param {string} code the Python code to evaluate.\n * @param {boolean} asRunButtonAction invoke the `Run` button handler.\n * @returns {Promise<...>} fulfill once code has been evaluated.\n */\n value(code, asRunButtonAction = false) {\n if (asRunButtonAction) return listener();\n const wasSetup = isSetup;\n const wasSource = source;\n isSetup = true;\n source = code;\n const restore = () => {\n isSetup = wasSetup;\n source = wasSource;\n };\n return context\n .handleEvent({ currentTarget: null })\n .then(restore, restore);\n },\n },\n });\n\n const notifyEditor = () => {\n const event = new Event(`${type}-editor`, { bubbles: true });\n script.dispatchEvent(event);\n };\n\n if (isSetup) {\n await context.handleEvent({ currentTarget: null });\n notifyEditor();\n return;\n }\n\n const selector = script.getAttribute(\"target\");\n\n if (selector) {\n target =\n document.getElementById(selector) ||\n document.querySelector(selector);\n if (!target) throw new Error(`Unknown target ${selector}`);\n } else {\n target = document.createElement(`${type}-editor`);\n target.style.display = \"block\";\n script.after(target);\n }\n\n if (!target.id) target.id = getID(type);\n if (!target.hasAttribute(\"exec-id\")) target.setAttribute(\"exec-id\", 0);\n if (!target.hasAttribute(\"root\")) target.setAttribute(\"root\", target.id);\n\n // @see https://github.com/JeffersGlass/mkdocs-pyscript/blob/main/mkdocs_pyscript/js/makeblocks.js\n const [boxDiv, outDiv, runButton] = makeBoxDiv(context, type);\n boxDiv.dataset.env = script.hasAttribute(\"env\") ? env : interpreter;\n\n const inputChild = boxDiv.querySelector(`.${type}-editor-input > div`);\n const parent = inputChild.attachShadow({ mode: \"open\" });\n // avoid inheriting styles from the outer component\n parent.innerHTML = `<style> :host { all: initial; }</style>`;\n\n target.appendChild(boxDiv);\n\n const doc = dedent(script.textContent).trim();\n\n // preserve user indentation, if any\n const indentation = /^([ \\t]+)/m.test(doc) ? RegExp.$1 : \" \";\n\n const listener = () => runButton.click();\n const editor = new EditorView({\n extensions: [\n indentUnit.of(indentation),\n new Compartment().of(python()),\n keymap.of([\n ...defaultKeymap,\n { key: \"Ctrl-Enter\", run: listener, preventDefault: true },\n { key: \"Cmd-Enter\", run: listener, preventDefault: true },\n { key: \"Shift-Enter\", run: listener, preventDefault: true },\n // @see https://codemirror.net/examples/tab/\n indentWithTab,\n ]),\n basicSetup,\n ],\n foldGutter: true,\n gutters: [\"CodeMirror-linenumbers\", \"CodeMirror-foldgutter\"],\n parent,\n doc,\n });\n\n editor.focus();\n notifyEditor();\n};\n\n// avoid too greedy MutationObserver operations at distance\nlet timeout = 0;\n\n// avoid delayed initialization\nlet queue = Promise.resolve();\n\n// reset interval value then check for new scripts\nconst resetTimeout = () => {\n timeout = 0;\n pyEditor();\n};\n\n// triggered both ASAP on the living DOM and via MutationObserver later\nconst pyEditor = () => {\n if (timeout) return;\n timeout = setTimeout(resetTimeout, 250);\n for (const [type, interpreter] of TYPES) {\n const selector = `script[type=\"${type}-editor\"]`;\n for (const script of document.querySelectorAll(selector)) {\n // avoid any further bootstrap by changing the type as active\n script.type += \"-active\";\n // don't await in here or multiple calls might happen\n // while the first script is being initialized\n queue = queue.then(() => init(script, type, interpreter));\n }\n }\n return queue;\n};\n\nnew MutationObserver(pyEditor).observe(document, {\n childList: true,\n subtree: true,\n});\n\n// try to check the current document ASAP\nexport default pyEditor();\n"],"names":["id","getID","type","envs","Map","configs","hooks","worker","codeBeforeRun","stdlib","onReady","runAsync","io","sync","stdout","buffered","write","stderr","writeErr","revoke","validate","config","result","async","execute","currentTarget","env","pySrc","outDiv","this","hasRunButton","disabled","innerHTML","has","srcLink","URL","createObjectURL","Blob","details","interpreter","serviceWorker","configURL","relative_url","endsWith","parse","toml","Promise","all","import","fetch","then","r","ok","text","json","JSON","version","offline_interpreter","error","notify","xworker","XWorker","call","Hook","TYPES","keys","editor","closest","script","parentNode","previousElementSibling","defineProperties","value","promise","resolve","withResolvers","set","revokeObjectURL","get","onerror","insertAdjacentHTML","message","console","enable","str","innerText","log","makeEditorDiv","handler","editorDiv","document","createElement","className","setAttribute","runButton","addEventListener","event","blur","handleEvent","makeRunButton","editorShadowContainer","stopPropagation","append","makeBoxDiv","boxDiv","makeOutDiv","querySelector","init","basicSetup","EditorView","Compartment","python","indentUnit","keymap","defaultKeymap","indentWithTab","codemirror","core","state","language","view","commands","isSetup","hasAttribute","hasConfig","getAttribute","onmessage","target","terminate","SyntaxError","source","textContent","src","b","context","doc","toString","callback","code","insert","update","changes","from","to","length","process","asRunButtonAction","listener","wasSetup","wasSource","restore","notifyEditor","Event","bubbles","dispatchEvent","selector","getElementById","Error","style","display","after","dataset","parent","attachShadow","mode","appendChild","dedent","trim","indentation","test","RegExp","$1","click","extensions","of","key","run","preventDefault","foldGutter","gutters","focus","timeout","queue","resetTimeout","pyEditor","setTimeout","querySelectorAll","MutationObserver","observe","childList","subtree","pyEditor$1"],"mappings":"4IAQA,IAAIA,EAAK,EACT,MAAMC,EAASC,GAAS,GAAGA,YAAeF,MAEpCG,EAAO,IAAIC,IACXC,EAAU,IAAID,IAEdE,EAAQ,CACVC,OAAQ,CACJC,cAAe,IAAMC,EAErBC,QAAS,EAAGC,WAAUC,OAAQC,WAC1BD,EAAGE,OAASF,EAAGG,SAASF,EAAKG,OAC7BJ,EAAGK,OAASL,EAAGG,SAASF,EAAKK,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