@pyscript/core 0.1.19 → 0.1.20

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.
Files changed (41) hide show
  1. package/README.md +19 -2
  2. package/dist/core.js +3 -3
  3. package/dist/core.js.map +1 -1
  4. package/docs/README.md +3 -12
  5. package/package.json +3 -3
  6. package/src/config.js +32 -24
  7. package/src/core.js +1 -1
  8. package/src/stdlib/pyscript/__init__.py +34 -0
  9. package/src/stdlib/pyscript/display.py +154 -0
  10. package/src/stdlib/pyscript/event_handling.py +45 -0
  11. package/src/stdlib/pyscript/magic_js.py +32 -0
  12. package/src/stdlib/pyscript/util.py +22 -0
  13. package/src/stdlib/pyscript.js +9 -5
  14. package/src/stdlib/pyweb/pydom.py +314 -0
  15. package/tests/integration/__init__.py +0 -0
  16. package/tests/integration/conftest.py +184 -0
  17. package/tests/integration/support.py +1038 -0
  18. package/tests/integration/test_00_support.py +495 -0
  19. package/tests/integration/test_01_basic.py +353 -0
  20. package/tests/integration/test_02_display.py +452 -0
  21. package/tests/integration/test_03_element.py +303 -0
  22. package/tests/integration/test_assets/line_plot.png +0 -0
  23. package/tests/integration/test_assets/tripcolor.png +0 -0
  24. package/tests/integration/test_async.py +197 -0
  25. package/tests/integration/test_event_handling.py +193 -0
  26. package/tests/integration/test_importmap.py +66 -0
  27. package/tests/integration/test_interpreter.py +98 -0
  28. package/tests/integration/test_plugins.py +419 -0
  29. package/tests/integration/test_py_config.py +294 -0
  30. package/tests/integration/test_py_repl.py +663 -0
  31. package/tests/integration/test_py_terminal.py +270 -0
  32. package/tests/integration/test_runtime_attributes.py +64 -0
  33. package/tests/integration/test_script_type.py +121 -0
  34. package/tests/integration/test_shadow_root.py +33 -0
  35. package/tests/integration/test_splashscreen.py +124 -0
  36. package/tests/integration/test_stdio_handling.py +370 -0
  37. package/tests/integration/test_style.py +47 -0
  38. package/tests/integration/test_warnings_and_banners.py +32 -0
  39. package/tests/integration/test_zz_examples.py +419 -0
  40. package/tests/integration/test_zzz_docs_snippets.py +305 -0
  41. package/types/stdlib/pyscript.d.ts +8 -4
package/docs/README.md CHANGED
@@ -111,7 +111,7 @@ import { hooks } from "https://cdn.jsdelivr.net/npm/@pyscript/core";
111
111
 
112
112
  // example
113
113
  hooks.onInterpreterReady.add((utils, element) => {
114
- console.lot(element, 'found', 'pyscript is ready');
114
+ console.log(element, 'found', 'pyscript is ready');
115
115
  });
116
116
 
117
117
  // the hooks namespace
@@ -148,9 +148,9 @@ Please note that a *worker* is a completely different environment and it's not p
148
148
 
149
149
  However, each worker string can use `from pyscript import x, y, z` as that will be available out of the box.
150
150
 
151
- ## PyScript Module API
151
+ ## PyScript Python API
152
152
 
153
- The python module offers various utilities in either the main thread or the worker.
153
+ The `pyscript` python package offers various utilities in either the main thread or the worker.
154
154
 
155
155
  The commonly shared utilities are:
156
156
 
@@ -257,15 +257,6 @@ We might decide to allow TOML too in the future, but the direct config as attrib
257
257
  </div>
258
258
  </details>
259
259
 
260
- <details>
261
- <summary><strong>why worker attribute needs an external file?</strong></summary>
262
- <div markdown=1>
263
-
264
- It would create confusion to have worker code embedded directly in the page and let *PyScript* forward the content to be executed as worker, but the separation of concerns felt more aligned with the meaning of bootstrapping a worker: it inevitably happens elsewhere and with little caveats or features here and there, so it's OK for now to keep that separation explicit.
265
-
266
- </div>
267
- </details>
268
-
269
260
  <details>
270
261
  <summary><strong>what are the worker's caveats?</strong></summary>
271
262
  <div markdown=1>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pyscript/core",
3
- "version": "0.1.19",
3
+ "version": "0.1.20",
4
4
  "type": "module",
5
5
  "description": "PyScript",
6
6
  "module": "./index.js",
@@ -33,12 +33,12 @@
33
33
  "dependencies": {
34
34
  "@ungap/with-resolvers": "^0.1.0",
35
35
  "basic-devtools": "^0.1.6",
36
- "polyscript": "^0.3.6"
36
+ "polyscript": "^0.3.7"
37
37
  },
38
38
  "devDependencies": {
39
39
  "@rollup/plugin-node-resolve": "^15.2.1",
40
40
  "@rollup/plugin-terser": "^0.4.3",
41
- "rollup": "^3.29.1",
41
+ "rollup": "^3.29.2",
42
42
  "rollup-plugin-postcss": "^4.0.2",
43
43
  "rollup-plugin-string": "^3.0.0",
44
44
  "static-handler": "^0.4.2",
package/src/config.js CHANGED
@@ -48,36 +48,44 @@ const syntaxError = (type, url, { message }) => {
48
48
  // find the shared config for all py-script elements
49
49
  let config, plugins, parsed, error, type;
50
50
  let pyConfig = $("py-config");
51
- if (pyConfig) config = pyConfig.getAttribute("src") || pyConfig.textContent;
52
- else {
53
- pyConfig = $('script[type="py"][config]');
51
+ if (pyConfig) {
52
+ config = pyConfig.getAttribute("src") || pyConfig.textContent;
53
+ type = pyConfig.getAttribute("type");
54
+ } else {
55
+ pyConfig = $(
56
+ [
57
+ 'script[type="py"][config]:not([worker])',
58
+ "py-script[config]:not([worker])",
59
+ ].join(","),
60
+ );
54
61
  if (pyConfig) config = pyConfig.getAttribute("config");
55
62
  }
56
- if (pyConfig) type = pyConfig.getAttribute("type");
57
63
 
58
64
  // catch possible fetch errors
59
- try {
60
- const { json, toml, text, url } = await configDetails(config);
61
- config = text;
62
- if (json || type === "json") {
63
- try {
64
- parsed = JSON.parse(text);
65
- } catch (e) {
66
- error = syntaxError("JSON", url, e);
67
- }
68
- } else if (toml || type === "toml") {
69
- try {
70
- const { parse } = await import(
71
- /* webpackIgnore: true */
72
- "https://cdn.jsdelivr.net/npm/@webreflection/toml-j0.4/toml.js"
73
- );
74
- parsed = parse(text);
75
- } catch (e) {
76
- error = syntaxError("TOML", url, e);
65
+ if (config) {
66
+ try {
67
+ const { json, toml, text, url } = await configDetails(config);
68
+ config = text;
69
+ if (json || type === "json") {
70
+ try {
71
+ parsed = JSON.parse(text);
72
+ } catch (e) {
73
+ error = syntaxError("JSON", url, e);
74
+ }
75
+ } else if (toml || type === "toml") {
76
+ try {
77
+ const { parse } = await import(
78
+ /* webpackIgnore: true */
79
+ "https://cdn.jsdelivr.net/npm/@webreflection/toml-j0.4/toml.js"
80
+ );
81
+ parsed = parse(text);
82
+ } catch (e) {
83
+ error = syntaxError("TOML", url, e);
84
+ }
77
85
  }
86
+ } catch (e) {
87
+ error = e;
78
88
  }
79
- } catch (e) {
80
- error = e;
81
89
  }
82
90
 
83
91
  // parse all plugins and optionally ignore only
package/src/core.js CHANGED
@@ -82,7 +82,7 @@ const registerModule = ({ XWorker: $XWorker, interpreter, io }) => {
82
82
  }
83
83
 
84
84
  // enrich the Python env with some JS utility for main
85
- interpreter.registerJsModule("_pyscript_js", {
85
+ interpreter.registerJsModule("_pyscript", {
86
86
  PyWorker,
87
87
  get target() {
88
88
  return isScript(currentElement)
@@ -0,0 +1,34 @@
1
+ # Some notes about the naming conventions and the relationship between various
2
+ # similar-but-different names.
3
+ #
4
+ # import pyscript
5
+ # this package contains the main user-facing API offered by pyscript. All
6
+ # the names which are supposed be used by end users should be made
7
+ # available in pyscript/__init__.py (i.e., this file)
8
+ #
9
+ # import _pyscript
10
+ # this is an internal module implemented in JS. It is used internally by
11
+ # the pyscript package, end users should not use it directly. For its
12
+ # implementation, grep for `interpreter.registerJsModule("_pyscript",
13
+ # ...)` in core.js
14
+ #
15
+ # import js
16
+ # this is the JS globalThis, as exported by pyodide and/or micropython's
17
+ # FFIs. As such, it contains different things in the main thread or in a
18
+ # worker.
19
+ #
20
+ # import pyscript.magic_js
21
+ # this submodule abstracts away some of the differences between the main
22
+ # thread and the worker. In particular, it defines `window` and `document`
23
+ # in such a way that these names work in both cases: in the main thread,
24
+ # they are the "real" objects, in the worker they are proxies which work
25
+ # thanks to coincident.
26
+ #
27
+ # from pyscript import window, document
28
+ # these are just the window and document objects as defined by
29
+ # pyscript.magic_js. This is the blessed way to access them from pyscript,
30
+ # as it works transparently in both the main thread and worker cases.
31
+
32
+ from pyscript.magic_js import RUNNING_IN_WORKER, window, document, sync
33
+ from pyscript.display import HTML, display
34
+ from pyscript.event_handling import when
@@ -0,0 +1,154 @@
1
+ import base64
2
+ import html
3
+ import io
4
+ import re
5
+
6
+ from pyscript.magic_js import document, window, current_target
7
+
8
+ _MIME_METHODS = {
9
+ "__repr__": "text/plain",
10
+ "_repr_html_": "text/html",
11
+ "_repr_markdown_": "text/markdown",
12
+ "_repr_svg_": "image/svg+xml",
13
+ "_repr_png_": "image/png",
14
+ "_repr_pdf_": "application/pdf",
15
+ "_repr_jpeg_": "image/jpeg",
16
+ "_repr_latex": "text/latex",
17
+ "_repr_json_": "application/json",
18
+ "_repr_javascript_": "application/javascript",
19
+ "savefig": "image/png",
20
+ }
21
+
22
+
23
+ def _render_image(mime, value, meta):
24
+ # If the image value is using bytes we should convert it to base64
25
+ # otherwise it will return raw bytes and the browser will not be able to
26
+ # render it.
27
+ if isinstance(value, bytes):
28
+ value = base64.b64encode(value).decode("utf-8")
29
+
30
+ # This is the pattern of base64 strings
31
+ base64_pattern = re.compile(
32
+ r"^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$"
33
+ )
34
+ # If value doesn't match the base64 pattern we should encode it to base64
35
+ if len(value) > 0 and not base64_pattern.match(value):
36
+ value = base64.b64encode(value.encode("utf-8")).decode("utf-8")
37
+
38
+ data = f"data:{mime};charset=utf-8;base64,{value}"
39
+ attrs = " ".join(['{k}="{v}"' for k, v in meta.items()])
40
+ return f'<img src="{data}" {attrs}></img>'
41
+
42
+
43
+ def _identity(value, meta):
44
+ return value
45
+
46
+
47
+ _MIME_RENDERERS = {
48
+ "text/plain": html.escape,
49
+ "text/html": _identity,
50
+ "image/png": lambda value, meta: _render_image("image/png", value, meta),
51
+ "image/jpeg": lambda value, meta: _render_image("image/jpeg", value, meta),
52
+ "image/svg+xml": _identity,
53
+ "application/json": _identity,
54
+ "application/javascript": lambda value, meta: f"<script>{value}<\\/script>",
55
+ }
56
+
57
+
58
+ class HTML:
59
+ """
60
+ Wrap a string so that display() can render it as plain HTML
61
+ """
62
+
63
+ def __init__(self, html):
64
+ self._html = html
65
+
66
+ def _repr_html_(self):
67
+ return self._html
68
+
69
+
70
+ def _eval_formatter(obj, print_method):
71
+ """
72
+ Evaluates a formatter method.
73
+ """
74
+ if print_method == "__repr__":
75
+ return repr(obj)
76
+ elif hasattr(obj, print_method):
77
+ if print_method == "savefig":
78
+ buf = io.BytesIO()
79
+ obj.savefig(buf, format="png")
80
+ buf.seek(0)
81
+ return base64.b64encode(buf.read()).decode("utf-8")
82
+ return getattr(obj, print_method)()
83
+ elif print_method == "_repr_mimebundle_":
84
+ return {}, {}
85
+ return None
86
+
87
+
88
+ def _format_mime(obj):
89
+ """
90
+ Formats object using _repr_x_ methods.
91
+ """
92
+ if isinstance(obj, str):
93
+ return html.escape(obj), "text/plain"
94
+
95
+ mimebundle = _eval_formatter(obj, "_repr_mimebundle_")
96
+ if isinstance(mimebundle, tuple):
97
+ format_dict, _ = mimebundle
98
+ else:
99
+ format_dict = mimebundle
100
+
101
+ output, not_available = None, []
102
+ for method, mime_type in reversed(_MIME_METHODS.items()):
103
+ if mime_type in format_dict:
104
+ output = format_dict[mime_type]
105
+ else:
106
+ output = _eval_formatter(obj, method)
107
+
108
+ if output is None:
109
+ continue
110
+ elif mime_type not in _MIME_RENDERERS:
111
+ not_available.append(mime_type)
112
+ continue
113
+ break
114
+ if output is None:
115
+ if not_available:
116
+ window.console.warn(
117
+ f"Rendered object requested unavailable MIME renderers: {not_available}"
118
+ )
119
+ output = repr(output)
120
+ mime_type = "text/plain"
121
+ elif isinstance(output, tuple):
122
+ output, meta = output
123
+ else:
124
+ meta = {}
125
+ return _MIME_RENDERERS[mime_type](output, meta), mime_type
126
+
127
+
128
+ def _write(element, value, append=False):
129
+ html, mime_type = _format_mime(value)
130
+ if html == "\\n":
131
+ return
132
+
133
+ if append:
134
+ out_element = document.createElement("div")
135
+ element.append(out_element)
136
+ else:
137
+ out_element = element.lastElementChild
138
+ if out_element is None:
139
+ out_element = element
140
+
141
+ if mime_type in ("application/javascript", "text/html"):
142
+ script_element = document.createRange().createContextualFragment(html)
143
+ out_element.append(script_element)
144
+ else:
145
+ out_element.innerHTML = html
146
+
147
+
148
+ def display(*values, target=None, append=True):
149
+ if target is None:
150
+ target = current_target()
151
+
152
+ element = document.getElementById(target)
153
+ for v in values:
154
+ _write(element, v, append=append)
@@ -0,0 +1,45 @@
1
+ import inspect
2
+
3
+ from pyodide.ffi.wrappers import add_event_listener
4
+ from pyscript.magic_js import document
5
+
6
+
7
+ def when(event_type=None, selector=None):
8
+ """
9
+ Decorates a function and passes py-* events to the decorated function
10
+ The events might or not be an argument of the decorated function
11
+ """
12
+
13
+ def decorator(func):
14
+ if isinstance(selector, str):
15
+ elements = document.querySelectorAll(selector)
16
+ else:
17
+ # TODO: This is a hack that will be removed when pyscript becomes a package
18
+ # and we can better manage the imports without circular dependencies
19
+ from pyweb import pydom
20
+
21
+ if isinstance(selector, pydom.Element):
22
+ elements = [selector._js]
23
+ elif isinstance(selector, pydom.ElementCollection):
24
+ elements = [el._js for el in selector]
25
+ else:
26
+ raise ValueError(
27
+ f"Invalid selector: {selector}. Selector must"
28
+ " be a string, a pydom.Element or a pydom.ElementCollection."
29
+ )
30
+
31
+ sig = inspect.signature(func)
32
+ # Function doesn't receive events
33
+ if not sig.parameters:
34
+
35
+ def wrapper(*args, **kwargs):
36
+ func()
37
+
38
+ for el in elements:
39
+ add_event_listener(el, event_type, wrapper)
40
+ else:
41
+ for el in elements:
42
+ add_event_listener(el, event_type, func)
43
+ return func
44
+
45
+ return decorator
@@ -0,0 +1,32 @@
1
+ from pyscript.util import NotSupported
2
+ import js as globalThis
3
+
4
+ RUNNING_IN_WORKER = not hasattr(globalThis, "document")
5
+
6
+ if RUNNING_IN_WORKER:
7
+ import polyscript
8
+
9
+ PyWorker = NotSupported(
10
+ 'pyscript.PyWorker',
11
+ 'pyscript.PyWorker works only when running in the main thread')
12
+ window = polyscript.xworker.window
13
+ document = window.document
14
+ sync = polyscript.xworker.sync
15
+
16
+ # in workers the display does not have a default ID
17
+ # but there is a sync utility from xworker
18
+ def current_target():
19
+ return polyscript.target
20
+
21
+ else:
22
+ import _pyscript
23
+ from _pyscript import PyWorker
24
+ window = globalThis
25
+ document = globalThis.document
26
+ sync = NotSupported(
27
+ 'pyscript.sync',
28
+ 'pyscript.sync works only when running in a worker')
29
+
30
+ # in MAIN the current element target exist, just use it
31
+ def current_target():
32
+ return _pyscript.target
@@ -0,0 +1,22 @@
1
+ class NotSupported:
2
+ """
3
+ Small helper that raises exceptions if you try to get/set any attribute on
4
+ it.
5
+ """
6
+
7
+ def __init__(self, name, error):
8
+ # we set attributes using self.__dict__ to bypass the __setattr__
9
+ self.__dict__['name'] = name
10
+ self.__dict__['error'] = error
11
+
12
+ def __repr__(self):
13
+ return f'<NotSupported {self.name} [{self.error}]>'
14
+
15
+ def __getattr__(self, attr):
16
+ raise AttributeError(self.error)
17
+
18
+ def __setattr__(self, attr, value):
19
+ raise AttributeError(self.error)
20
+
21
+ def __call__(self, *args):
22
+ raise TypeError(self.error)
@@ -1,9 +1,13 @@
1
1
  // ⚠️ This file is an artifact: DO NOT MODIFY
2
2
  export default {
3
- "_pyscript": {
4
- "__init__.py": "import js as window\n\nIS_WORKER = not hasattr(window, \"document\")\n\nif IS_WORKER:\n from polyscript import xworker as _xworker\n\n window = _xworker.window\n document = window.document\n sync = _xworker.sync\nelse:\n document = window.document\n",
5
- "display.py": "import base64\nimport html\nimport io\nimport re\n\nfrom . import document, window\n\n_MIME_METHODS = {\n \"__repr__\": \"text/plain\",\n \"_repr_html_\": \"text/html\",\n \"_repr_markdown_\": \"text/markdown\",\n \"_repr_svg_\": \"image/svg+xml\",\n \"_repr_png_\": \"image/png\",\n \"_repr_pdf_\": \"application/pdf\",\n \"_repr_jpeg_\": \"image/jpeg\",\n \"_repr_latex\": \"text/latex\",\n \"_repr_json_\": \"application/json\",\n \"_repr_javascript_\": \"application/javascript\",\n \"savefig\": \"image/png\",\n}\n\n\ndef _render_image(mime, value, meta):\n # If the image value is using bytes we should convert it to base64\n # otherwise it will return raw bytes and the browser will not be able to\n # render it.\n if isinstance(value, bytes):\n value = base64.b64encode(value).decode(\"utf-8\")\n\n # This is the pattern of base64 strings\n base64_pattern = re.compile(\n r\"^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$\"\n )\n # If value doesn't match the base64 pattern we should encode it to base64\n if len(value) > 0 and not base64_pattern.match(value):\n value = base64.b64encode(value.encode(\"utf-8\")).decode(\"utf-8\")\n\n data = f\"data:{mime};charset=utf-8;base64,{value}\"\n attrs = \" \".join(['{k}=\"{v}\"' for k, v in meta.items()])\n return f'<img src=\"{data}\" {attrs}></img>'\n\n\ndef _identity(value, meta):\n return value\n\n\n_MIME_RENDERERS = {\n \"text/plain\": html.escape,\n \"text/html\": _identity,\n \"image/png\": lambda value, meta: _render_image(\"image/png\", value, meta),\n \"image/jpeg\": lambda value, meta: _render_image(\"image/jpeg\", value, meta),\n \"image/svg+xml\": _identity,\n \"application/json\": _identity,\n \"application/javascript\": lambda value, meta: f\"<script>{value}<\\\\/script>\",\n}\n\n\nclass HTML:\n \"\"\"\n Wrap a string so that display() can render it as plain HTML\n \"\"\"\n\n def __init__(self, html):\n self._html = html\n\n def _repr_html_(self):\n return self._html\n\n\ndef _eval_formatter(obj, print_method):\n \"\"\"\n Evaluates a formatter method.\n \"\"\"\n if print_method == \"__repr__\":\n return repr(obj)\n elif hasattr(obj, print_method):\n if print_method == \"savefig\":\n buf = io.BytesIO()\n obj.savefig(buf, format=\"png\")\n buf.seek(0)\n return base64.b64encode(buf.read()).decode(\"utf-8\")\n return getattr(obj, print_method)()\n elif print_method == \"_repr_mimebundle_\":\n return {}, {}\n return None\n\n\ndef _format_mime(obj):\n \"\"\"\n Formats object using _repr_x_ methods.\n \"\"\"\n if isinstance(obj, str):\n return html.escape(obj), \"text/plain\"\n\n mimebundle = _eval_formatter(obj, \"_repr_mimebundle_\")\n if isinstance(mimebundle, tuple):\n format_dict, _ = mimebundle\n else:\n format_dict = mimebundle\n\n output, not_available = None, []\n for method, mime_type in reversed(_MIME_METHODS.items()):\n if mime_type in format_dict:\n output = format_dict[mime_type]\n else:\n output = _eval_formatter(obj, method)\n\n if output is None:\n continue\n elif mime_type not in _MIME_RENDERERS:\n not_available.append(mime_type)\n continue\n break\n if output is None:\n if not_available:\n window.console.warn(\n f\"Rendered object requested unavailable MIME renderers: {not_available}\"\n )\n output = repr(output)\n mime_type = \"text/plain\"\n elif isinstance(output, tuple):\n output, meta = output\n else:\n meta = {}\n return _MIME_RENDERERS[mime_type](output, meta), mime_type\n\n\ndef _write(element, value, append=False):\n html, mime_type = _format_mime(value)\n if html == \"\\\\n\":\n return\n\n if append:\n out_element = document.createElement(\"div\")\n element.append(out_element)\n else:\n out_element = element.lastElementChild\n if out_element is None:\n out_element = element\n\n if mime_type in (\"application/javascript\", \"text/html\"):\n script_element = document.createRange().createContextualFragment(html)\n out_element.append(script_element)\n else:\n out_element.innerHTML = html\n\n\ndef display(*values, target=None, append=True):\n element = document.getElementById(target)\n for v in values:\n _write(element, v, append=append)\n",
6
- "event_handling.py": "import inspect\n\nfrom pyodide.ffi.wrappers import add_event_listener\nfrom pyscript import document\n\n\ndef when(event_type=None, selector=None):\n \"\"\"\n Decorates a function and passes py-* events to the decorated function\n The events might or not be an argument of the decorated function\n \"\"\"\n\n def decorator(func):\n elements = document.querySelectorAll(selector)\n sig = inspect.signature(func)\n # Function doesn't receive events\n if not sig.parameters:\n\n def wrapper(*args, **kwargs):\n func()\n\n for el in elements:\n add_event_listener(el, event_type, wrapper)\n else:\n for el in elements:\n add_event_listener(el, event_type, func)\n return func\n\n return decorator\n"
3
+ "pyscript": {
4
+ "__init__.py": "# Some notes about the naming conventions and the relationship between various\n# similar-but-different names.\n#\n# import pyscript\n# this package contains the main user-facing API offered by pyscript. All\n# the names which are supposed be used by end users should be made\n# available in pyscript/__init__.py (i.e., this file)\n#\n# import _pyscript\n# this is an internal module implemented in JS. It is used internally by\n# the pyscript package, end users should not use it directly. For its\n# implementation, grep for `interpreter.registerJsModule(\"_pyscript\",\n# ...)` in core.js\n#\n# import js\n# this is the JS globalThis, as exported by pyodide and/or micropython's\n# FFIs. As such, it contains different things in the main thread or in a\n# worker.\n#\n# import pyscript.magic_js\n# this submodule abstracts away some of the differences between the main\n# thread and the worker. In particular, it defines `window` and `document`\n# in such a way that these names work in both cases: in the main thread,\n# they are the \"real\" objects, in the worker they are proxies which work\n# thanks to coincident.\n#\n# from pyscript import window, document\n# these are just the window and document objects as defined by\n# pyscript.magic_js. This is the blessed way to access them from pyscript,\n# as it works transparently in both the main thread and worker cases.\n\nfrom pyscript.magic_js import RUNNING_IN_WORKER, window, document, sync\nfrom pyscript.display import HTML, display\nfrom pyscript.event_handling import when\n",
5
+ "display.py": "import base64\nimport html\nimport io\nimport re\n\nfrom pyscript.magic_js import document, window, current_target\n\n_MIME_METHODS = {\n \"__repr__\": \"text/plain\",\n \"_repr_html_\": \"text/html\",\n \"_repr_markdown_\": \"text/markdown\",\n \"_repr_svg_\": \"image/svg+xml\",\n \"_repr_png_\": \"image/png\",\n \"_repr_pdf_\": \"application/pdf\",\n \"_repr_jpeg_\": \"image/jpeg\",\n \"_repr_latex\": \"text/latex\",\n \"_repr_json_\": \"application/json\",\n \"_repr_javascript_\": \"application/javascript\",\n \"savefig\": \"image/png\",\n}\n\n\ndef _render_image(mime, value, meta):\n # If the image value is using bytes we should convert it to base64\n # otherwise it will return raw bytes and the browser will not be able to\n # render it.\n if isinstance(value, bytes):\n value = base64.b64encode(value).decode(\"utf-8\")\n\n # This is the pattern of base64 strings\n base64_pattern = re.compile(\n r\"^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$\"\n )\n # If value doesn't match the base64 pattern we should encode it to base64\n if len(value) > 0 and not base64_pattern.match(value):\n value = base64.b64encode(value.encode(\"utf-8\")).decode(\"utf-8\")\n\n data = f\"data:{mime};charset=utf-8;base64,{value}\"\n attrs = \" \".join(['{k}=\"{v}\"' for k, v in meta.items()])\n return f'<img src=\"{data}\" {attrs}></img>'\n\n\ndef _identity(value, meta):\n return value\n\n\n_MIME_RENDERERS = {\n \"text/plain\": html.escape,\n \"text/html\": _identity,\n \"image/png\": lambda value, meta: _render_image(\"image/png\", value, meta),\n \"image/jpeg\": lambda value, meta: _render_image(\"image/jpeg\", value, meta),\n \"image/svg+xml\": _identity,\n \"application/json\": _identity,\n \"application/javascript\": lambda value, meta: f\"<script>{value}<\\\\/script>\",\n}\n\n\nclass HTML:\n \"\"\"\n Wrap a string so that display() can render it as plain HTML\n \"\"\"\n\n def __init__(self, html):\n self._html = html\n\n def _repr_html_(self):\n return self._html\n\n\ndef _eval_formatter(obj, print_method):\n \"\"\"\n Evaluates a formatter method.\n \"\"\"\n if print_method == \"__repr__\":\n return repr(obj)\n elif hasattr(obj, print_method):\n if print_method == \"savefig\":\n buf = io.BytesIO()\n obj.savefig(buf, format=\"png\")\n buf.seek(0)\n return base64.b64encode(buf.read()).decode(\"utf-8\")\n return getattr(obj, print_method)()\n elif print_method == \"_repr_mimebundle_\":\n return {}, {}\n return None\n\n\ndef _format_mime(obj):\n \"\"\"\n Formats object using _repr_x_ methods.\n \"\"\"\n if isinstance(obj, str):\n return html.escape(obj), \"text/plain\"\n\n mimebundle = _eval_formatter(obj, \"_repr_mimebundle_\")\n if isinstance(mimebundle, tuple):\n format_dict, _ = mimebundle\n else:\n format_dict = mimebundle\n\n output, not_available = None, []\n for method, mime_type in reversed(_MIME_METHODS.items()):\n if mime_type in format_dict:\n output = format_dict[mime_type]\n else:\n output = _eval_formatter(obj, method)\n\n if output is None:\n continue\n elif mime_type not in _MIME_RENDERERS:\n not_available.append(mime_type)\n continue\n break\n if output is None:\n if not_available:\n window.console.warn(\n f\"Rendered object requested unavailable MIME renderers: {not_available}\"\n )\n output = repr(output)\n mime_type = \"text/plain\"\n elif isinstance(output, tuple):\n output, meta = output\n else:\n meta = {}\n return _MIME_RENDERERS[mime_type](output, meta), mime_type\n\n\ndef _write(element, value, append=False):\n html, mime_type = _format_mime(value)\n if html == \"\\\\n\":\n return\n\n if append:\n out_element = document.createElement(\"div\")\n element.append(out_element)\n else:\n out_element = element.lastElementChild\n if out_element is None:\n out_element = element\n\n if mime_type in (\"application/javascript\", \"text/html\"):\n script_element = document.createRange().createContextualFragment(html)\n out_element.append(script_element)\n else:\n out_element.innerHTML = html\n\n\ndef display(*values, target=None, append=True):\n if target is None:\n target = current_target()\n\n element = document.getElementById(target)\n for v in values:\n _write(element, v, append=append)\n",
6
+ "event_handling.py": "import inspect\n\nfrom pyodide.ffi.wrappers import add_event_listener\nfrom pyscript.magic_js import document\n\n\ndef when(event_type=None, selector=None):\n \"\"\"\n Decorates a function and passes py-* events to the decorated function\n The events might or not be an argument of the decorated function\n \"\"\"\n\n def decorator(func):\n if isinstance(selector, str):\n elements = document.querySelectorAll(selector)\n else:\n # TODO: This is a hack that will be removed when pyscript becomes a package\n # and we can better manage the imports without circular dependencies\n from pyweb import pydom\n\n if isinstance(selector, pydom.Element):\n elements = [selector._js]\n elif isinstance(selector, pydom.ElementCollection):\n elements = [el._js for el in selector]\n else:\n raise ValueError(\n f\"Invalid selector: {selector}. Selector must\"\n \" be a string, a pydom.Element or a pydom.ElementCollection.\"\n )\n\n sig = inspect.signature(func)\n # Function doesn't receive events\n if not sig.parameters:\n\n def wrapper(*args, **kwargs):\n func()\n\n for el in elements:\n add_event_listener(el, event_type, wrapper)\n else:\n for el in elements:\n add_event_listener(el, event_type, func)\n return func\n\n return decorator\n",
7
+ "magic_js.py": "from pyscript.util import NotSupported\nimport js as globalThis\n\nRUNNING_IN_WORKER = not hasattr(globalThis, \"document\")\n\nif RUNNING_IN_WORKER:\n import polyscript\n\n PyWorker = NotSupported(\n 'pyscript.PyWorker',\n 'pyscript.PyWorker works only when running in the main thread')\n window = polyscript.xworker.window\n document = window.document\n sync = polyscript.xworker.sync\n\n # in workers the display does not have a default ID\n # but there is a sync utility from xworker\n def current_target():\n return polyscript.target\n\nelse:\n import _pyscript\n from _pyscript import PyWorker\n window = globalThis\n document = globalThis.document\n sync = NotSupported(\n 'pyscript.sync',\n 'pyscript.sync works only when running in a worker')\n\n # in MAIN the current element target exist, just use it\n def current_target():\n return _pyscript.target\n",
8
+ "util.py": "class NotSupported:\n \"\"\"\n Small helper that raises exceptions if you try to get/set any attribute on\n it.\n \"\"\"\n\n def __init__(self, name, error):\n # we set attributes using self.__dict__ to bypass the __setattr__\n self.__dict__['name'] = name\n self.__dict__['error'] = error\n\n def __repr__(self):\n return f'<NotSupported {self.name} [{self.error}]>'\n\n def __getattr__(self, attr):\n raise AttributeError(self.error)\n\n def __setattr__(self, attr, value):\n raise AttributeError(self.error)\n\n def __call__(self, *args):\n raise TypeError(self.error)\n"
7
9
  },
8
- "pyscript.py": "# export only what we want to expose as `pyscript` module\n# but not what is WORKER/MAIN dependent\nfrom _pyscript import window, document, IS_WORKER\nfrom _pyscript.display import HTML, display as _display\nfrom _pyscript.event_handling import when\n\n# this part is needed to disambiguate between MAIN and WORKER\nif IS_WORKER:\n # in workers the display does not have a default ID\n # but there is a sync utility from xworker\n import polyscript as _polyscript\n from _pyscript import sync\n\n def current_target():\n return _polyscript.target\n\nelse:\n # in MAIN both PyWorker and current element target exist\n # so these are both exposed and the display will use,\n # if not specified otherwise, such current element target\n import _pyscript_js\n\n PyWorker = _pyscript_js.PyWorker\n\n def current_target():\n return _pyscript_js.target\n\n\n# the display provides a handy default target either in MAIN or WORKER\ndef display(*values, target=None, append=True):\n if target is None:\n target = current_target()\n\n return _display(*values, target=target, append=append)\n"
10
+ "pyweb": {
11
+ "pydom.py": "import sys\nimport warnings\nfrom functools import cached_property\nfrom typing import Any\n\nfrom pyodide.ffi import JsProxy\nfrom pyscript import display, document, window\n\n# from pyscript import when as _when\n\nalert = window.alert\n\n\nclass BaseElement:\n def __init__(self, js_element):\n self._js = js_element\n self._parent = None\n self.style = StyleProxy(self)\n\n def __eq__(self, obj):\n \"\"\"Check if the element is the same as the other element by comparing\n the underlying JS element\"\"\"\n return isinstance(obj, BaseElement) and obj._js == self._js\n\n @property\n def parent(self):\n if self._parent:\n return self._parent\n\n if self._js.parentElement:\n self._parent = self.__class__(self._js.parentElement)\n\n return self._parent\n\n @property\n def __class(self):\n return self.__class__ if self.__class__ != PyDom else Element\n\n def create(self, type_, is_child=True, classes=None, html=None, label=None):\n js_el = document.createElement(type_)\n element = self.__class(js_el)\n\n if classes:\n for class_ in classes:\n element.add_class(class_)\n\n if html is not None:\n element.html = html\n\n if label is not None:\n element.label = label\n\n if is_child:\n self.append(element)\n\n return element\n\n def find(self, selector):\n \"\"\"Return an ElementCollection representing all the child elements that\n match the specified selector.\n\n Args:\n selector (str): A string containing a selector expression\n\n Returns:\n ElementCollection: A collection of elements matching the selector\n \"\"\"\n elements = self._js.querySelectorAll(selector)\n if not elements:\n return None\n return ElementCollection([Element(el) for el in elements])\n\n\nclass Element(BaseElement):\n @property\n def children(self):\n return [self.__class__(el) for el in self._js.children]\n\n def append(self, child):\n # TODO: this is Pyodide specific for now!!!!!!\n # if we get passed a JSProxy Element directly we just map it to the\n # higher level Python element\n if isinstance(child, JsProxy):\n return self.append(Element(child))\n\n elif isinstance(child, Element):\n self._js.appendChild(child._js)\n\n return child\n\n elif isinstance(child, ElementCollection):\n for el in child:\n self.append(el)\n\n # -------- Pythonic Interface to Element -------- #\n @property\n def html(self):\n return self._js.innerHTML\n\n @html.setter\n def html(self, value):\n self._js.innerHTML = value\n\n @property\n def content(self):\n # TODO: This breaks with with standard template elements. Define how to best\n # handle this specifica use case. Just not support for now?\n if self._js.tagName == \"TEMPLATE\":\n warnings.warn(\n \"Content attribute not supported for template elements.\", stacklevel=2\n )\n return None\n return self._js.innerHTML\n\n @content.setter\n def content(self, value):\n # TODO: (same comment as above)\n if self._js.tagName == \"TEMPLATE\":\n warnings.warn(\n \"Content attribute not supported for template elements.\", stacklevel=2\n )\n return\n\n display(value, target=self.id)\n\n @property\n def id(self):\n return self._js.id\n\n @id.setter\n def id(self, value):\n self._js.id = value\n\n def clone(self, new_id=None):\n clone = Element(self._js.cloneNode(True))\n clone.id = new_id\n\n return clone\n\n def remove_class(self, classname):\n classList = self._js.classList\n if isinstance(classname, list):\n classList.remove(*classname)\n else:\n classList.remove(classname)\n return self\n\n def add_class(self, classname):\n classList = self._js.classList\n if isinstance(classname, list):\n classList.add(*classname)\n else:\n self._js.classList.add(classname)\n return self\n\n @property\n def classes(self):\n classes = self._js.classList.values()\n return [x for x in classes]\n\n def show_me(self):\n self._js.scrollIntoView()\n\n def when(self, event, handler):\n document.when(event, selector=self)(handler)\n\n\nclass StyleProxy(dict):\n def __init__(self, element: Element) -> None:\n self._element = element\n\n @cached_property\n def _style(self):\n return self._element._js.style\n\n def __getitem__(self, key):\n return self._style.getPropertyValue(key)\n\n def __setitem__(self, key, value):\n self._style.setProperty(key, value)\n\n def remove(self, key):\n self._style.removeProperty(key)\n\n def set(self, **kws):\n for k, v in kws.items():\n self._element._js.style.setProperty(k, v)\n\n # CSS Properties\n # Reference: https://github.com/microsoft/TypeScript/blob/main/src/lib/dom.generated.d.ts#L3799C1-L5005C2\n # Following prperties automatically generated from the above reference using\n # tools/codegen_css_proxy.py\n @property\n def visible(self):\n return self._element._js.style.visibility\n\n @visible.setter\n def visible(self, value):\n self._element._js.style.visibility = value\n\n\nclass StyleCollection:\n def __init__(self, collection: \"ElementCollection\") -> None:\n self._collection = collection\n\n def __get__(self, obj, objtype=None):\n return obj._get_attribute(\"style\")\n\n def __getitem__(self, key):\n return self._collection._get_attribute(\"style\")[key]\n\n def __setitem__(self, key, value):\n for element in self._collection._elements:\n element.style[key] = value\n\n def remove(self, key):\n for element in self._collection._elements:\n element.style.remove(key)\n\n\nclass ElementCollection:\n def __init__(self, elements: [Element]) -> None:\n self._elements = elements\n self.style = StyleCollection(self)\n\n def __getitem__(self, key):\n # If it's an integer we use it to access the elements in the collection\n if isinstance(key, int):\n return self._elements[key]\n # If it's a slice we use it to support slice operations over the elements\n # in the collection\n elif isinstance(key, slice):\n return ElementCollection(self._elements[key])\n\n # If it's anything else (basically a string) we use it as a selector\n # TODO: Write tests!\n elements = self._element.querySelectorAll(key)\n return ElementCollection([Element(el) for el in elements])\n\n def __len__(self):\n return len(self._elements)\n\n def __eq__(self, obj):\n \"\"\"Check if the element is the same as the other element by comparing\n the underlying JS element\"\"\"\n return isinstance(obj, ElementCollection) and obj._elements == self._elements\n\n def _get_attribute(self, attr, index=None):\n if index is None:\n return [getattr(el, attr) for el in self._elements]\n\n # As JQuery, when getting an attr, only return it for the first element\n return getattr(self._elements[index], attr)\n\n def _set_attribute(self, attr, value):\n for el in self._elements:\n setattr(el, attr, value)\n\n @property\n def html(self):\n return self._get_attribute(\"html\")\n\n @html.setter\n def html(self, value):\n self._set_attribute(\"html\", value)\n\n @property\n def children(self):\n return self._elements\n\n def __iter__(self):\n yield from self._elements\n\n def __repr__(self):\n return f\"{self.__class__.__name__} (length: {len(self._elements)}) {self._elements}\"\n\n\nclass DomScope:\n def __getattr__(self, __name: str) -> Any:\n element = document[f\"#{__name}\"]\n if element:\n return element[0]\n\n\nclass PyDom(BaseElement):\n # Add objects we want to expose to the DOM namespace since this class instance is being\n # remapped as \"the module\" itself\n BaseElement = BaseElement\n Element = Element\n ElementCollection = ElementCollection\n\n def __init__(self):\n super().__init__(document)\n self.ids = DomScope()\n self.body = Element(document.body)\n self.head = Element(document.head)\n\n def create(self, type_, parent=None, classes=None, html=None):\n return super().create(type_, is_child=False)\n\n def __getitem__(self, key):\n if isinstance(key, int):\n indices = range(*key.indices(len(self.list)))\n return [self.list[i] for i in indices]\n\n elements = self._js.querySelectorAll(key)\n if not elements:\n return None\n return ElementCollection([Element(el) for el in elements])\n\n\ndom = PyDom()\n\nsys.modules[__name__] = dom\n"
12
+ }
9
13
  };