@pyscript/core 0.3.2 → 0.3.4
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.js +3 -3
- package/dist/core.js.map +1 -1
- package/dist/py-terminal-XWbSa71s.js +2 -0
- package/dist/py-terminal-XWbSa71s.js.map +1 -0
- package/dist/toml--Dzglv4T.js.map +1 -1
- package/dist/xterm-f2QfYNGL.js +2 -0
- package/dist/xterm-f2QfYNGL.js.map +1 -0
- package/dist/xterm-readline-ONk85xtH.js +2 -0
- package/dist/xterm-readline-ONk85xtH.js.map +1 -0
- package/dist/xterm.css +8 -0
- package/package.json +12 -9
- package/src/3rd-party/README.md +7 -0
- package/src/3rd-party/xterm-readline.js +8 -0
- package/src/3rd-party/xterm.css +8 -0
- package/src/3rd-party/xterm.js +8 -0
- package/src/config.js +1 -1
- package/src/plugins/py-terminal.js +30 -42
- package/src/stdlib/pyscript.js +1 -1
- package/src/stdlib/pyweb/pydom.py +24 -0
- package/types/3rd-party/toml.d.ts +12 -0
- package/types/3rd-party/xterm-readline.d.ts +138 -0
- package/types/3rd-party/xterm.d.ts +4 -0
- package/types/core.d.ts +40 -4
- package/types/fetch.d.ts +1 -0
- package/dist/py-terminal-_uJ8pDjX.js +0 -2
- package/dist/py-terminal-_uJ8pDjX.js.map +0 -1
- /package/src/{toml.js → 3rd-party/toml.js} +0 -0
package/src/config.js
CHANGED
@@ -1,47 +1,48 @@
|
|
1
1
|
// PyScript py-terminal plugin
|
2
2
|
import { TYPES, hooks } from "../core.js";
|
3
|
+
import { notify } from "./error.js";
|
3
4
|
|
4
|
-
const CDN = "https://cdn.jsdelivr.net/npm/xterm";
|
5
|
-
const XTERM = "5.3.0";
|
6
|
-
const XTERM_READLINE = "1.1.1";
|
7
5
|
const SELECTOR = [...TYPES.keys()]
|
8
6
|
.map((type) => `script[type="${type}"][terminal],${type}-script[terminal]`)
|
9
7
|
.join(",");
|
10
8
|
|
9
|
+
// show the error on main and
|
10
|
+
// stops the module from keep executing
|
11
|
+
const notifyAndThrow = (message) => {
|
12
|
+
notify(message);
|
13
|
+
throw new Error(message);
|
14
|
+
};
|
15
|
+
|
11
16
|
const pyTerminal = async () => {
|
12
17
|
const terminals = document.querySelectorAll(SELECTOR);
|
13
18
|
|
14
19
|
// no results will look further for runtime nodes
|
15
20
|
if (!terminals.length) return;
|
16
21
|
|
17
|
-
// we currently support only one terminal as in "classic"
|
18
|
-
if (terminals.length > 1)
|
19
|
-
console.warn("Unable to satisfy multiple terminals");
|
20
|
-
|
21
22
|
// if we arrived this far, let's drop the MutationObserver
|
23
|
+
// as we only support one terminal per page (right now).
|
22
24
|
mo.disconnect();
|
23
25
|
|
26
|
+
// we currently support only one terminal as in "classic"
|
27
|
+
if (terminals.length > 1) notifyAndThrow("You can use at most 1 terminal.");
|
28
|
+
|
24
29
|
const [element] = terminals;
|
25
30
|
// hopefully to be removed in the near future!
|
26
31
|
if (element.matches('script[type="mpy"],mpy-script'))
|
27
|
-
|
28
|
-
|
29
|
-
// import styles
|
30
|
-
|
31
|
-
document.
|
32
|
-
|
33
|
-
|
34
|
-
|
35
|
-
|
36
|
-
);
|
37
|
-
}
|
32
|
+
notifyAndThrow("Unsupported terminal.");
|
33
|
+
|
34
|
+
// import styles lazily
|
35
|
+
document.head.append(
|
36
|
+
Object.assign(document.createElement("link"), {
|
37
|
+
rel: "stylesheet",
|
38
|
+
href: new URL("./xterm.css", import.meta.url),
|
39
|
+
}),
|
40
|
+
);
|
38
41
|
|
39
42
|
// lazy load these only when a valid terminal is found
|
40
43
|
const [{ Terminal }, { Readline }] = await Promise.all([
|
41
|
-
import(/* webpackIgnore: true */
|
42
|
-
import(
|
43
|
-
/* webpackIgnore: true */ `${CDN}-readline@${XTERM_READLINE}/+esm`
|
44
|
-
),
|
44
|
+
import(/* webpackIgnore: true */ "../3rd-party/xterm.js"),
|
45
|
+
import(/* webpackIgnore: true */ "../3rd-party/xterm-readline.js"),
|
45
46
|
]);
|
46
47
|
|
47
48
|
const readline = new Readline();
|
@@ -80,32 +81,23 @@ const pyTerminal = async () => {
|
|
80
81
|
const workerReady = ({ interpreter }, { sync }) => {
|
81
82
|
sync.pyterminal_drop_hooks();
|
82
83
|
const decoder = new TextDecoder();
|
84
|
+
let data = "";
|
83
85
|
const generic = {
|
84
86
|
isatty: true,
|
85
87
|
write(buffer) {
|
86
|
-
|
88
|
+
data = decoder.decode(buffer);
|
89
|
+
sync.pyterminal_write(data);
|
87
90
|
return buffer.length;
|
88
91
|
},
|
89
92
|
};
|
90
93
|
interpreter.setStdout(generic);
|
91
94
|
interpreter.setStderr(generic);
|
95
|
+
interpreter.setStdin({
|
96
|
+
isatty: true,
|
97
|
+
stdin: () => sync.pyterminal_read(data),
|
98
|
+
});
|
92
99
|
};
|
93
100
|
|
94
|
-
// run in python code able to replace builtins.input
|
95
|
-
// using the xworker.sync non blocking prompt
|
96
|
-
const codeBefore = `
|
97
|
-
import builtins
|
98
|
-
from pyscript import sync as _sync
|
99
|
-
|
100
|
-
builtins.input = lambda prompt: _sync.pyterminal_read(prompt)
|
101
|
-
`;
|
102
|
-
|
103
|
-
// at the end of the code, make the terminal interactive
|
104
|
-
const codeAfter = `
|
105
|
-
import code as _code
|
106
|
-
_code.interact()
|
107
|
-
`;
|
108
|
-
|
109
101
|
// add a hook on the main thread to setup all sync helpers
|
110
102
|
// also bootstrapping the XTerm target on main
|
111
103
|
hooks.main.onWorker.add(function worker(_, xworker) {
|
@@ -120,16 +112,12 @@ const pyTerminal = async () => {
|
|
120
112
|
// allow a worker to drop main thread hooks ASAP
|
121
113
|
xworker.sync.pyterminal_drop_hooks = () => {
|
122
114
|
hooks.worker.onReady.delete(workerReady);
|
123
|
-
hooks.worker.codeBeforeRun.delete(codeBefore);
|
124
|
-
hooks.worker.codeAfterRun.delete(codeAfter);
|
125
115
|
};
|
126
116
|
});
|
127
117
|
|
128
118
|
// setup remote thread JS/Python code for whenever the
|
129
119
|
// worker is ready to become a terminal
|
130
120
|
hooks.worker.onReady.add(workerReady);
|
131
|
-
hooks.worker.codeBeforeRun.add(codeBefore);
|
132
|
-
hooks.worker.codeAfterRun.add(codeAfter);
|
133
121
|
} else {
|
134
122
|
// in the main case, just bootstrap XTerm without
|
135
123
|
// allowing any input as that's not possible / awkward
|
package/src/stdlib/pyscript.js
CHANGED
@@ -8,6 +8,6 @@ export default {
|
|
8
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 object.__setattr__(self, \"name\", name)\n object.__setattr__(self, \"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"
|
9
9
|
},
|
10
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"
|
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 @property\n def value(self):\n return self._js.value\n\n @value.setter\n def value(self, value):\n # in order to avoid confusion to the user, we don't allow setting the\n # value of elements that don't have a value attribute\n if not hasattr(self._js, \"value\"):\n raise AttributeError(\n f\"Element {self._js.tagName} has no value attribute. If you want to \"\n \"force a value attribute, set it directly using the `_js.value = <value>` \"\n \"javascript API attribute instead.\"\n )\n self._js.value = 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 value(self):\n return self._get_attribute(\"value\")\n\n @value.setter\n def value(self, value):\n self._set_attribute(\"value\", 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
12
|
}
|
13
13
|
};
|
@@ -131,6 +131,22 @@ class Element(BaseElement):
|
|
131
131
|
def id(self, value):
|
132
132
|
self._js.id = value
|
133
133
|
|
134
|
+
@property
|
135
|
+
def value(self):
|
136
|
+
return self._js.value
|
137
|
+
|
138
|
+
@value.setter
|
139
|
+
def value(self, value):
|
140
|
+
# in order to avoid confusion to the user, we don't allow setting the
|
141
|
+
# value of elements that don't have a value attribute
|
142
|
+
if not hasattr(self._js, "value"):
|
143
|
+
raise AttributeError(
|
144
|
+
f"Element {self._js.tagName} has no value attribute. If you want to "
|
145
|
+
"force a value attribute, set it directly using the `_js.value = <value>` "
|
146
|
+
"javascript API attribute instead."
|
147
|
+
)
|
148
|
+
self._js.value = value
|
149
|
+
|
134
150
|
def clone(self, new_id=None):
|
135
151
|
clone = Element(self._js.cloneNode(True))
|
136
152
|
clone.id = new_id
|
@@ -264,6 +280,14 @@ class ElementCollection:
|
|
264
280
|
def html(self, value):
|
265
281
|
self._set_attribute("html", value)
|
266
282
|
|
283
|
+
@property
|
284
|
+
def value(self):
|
285
|
+
return self._get_attribute("value")
|
286
|
+
|
287
|
+
@value.setter
|
288
|
+
def value(self, value):
|
289
|
+
self._set_attribute("value", value)
|
290
|
+
|
267
291
|
@property
|
268
292
|
def children(self):
|
269
293
|
return self._elements
|
@@ -0,0 +1,12 @@
|
|
1
|
+
/*! (c) Jak Wings - MIT */ declare class e extends SyntaxError {
|
2
|
+
constructor(r: any, { offset: t, line: e, column: n }: {
|
3
|
+
offset: any;
|
4
|
+
line: any;
|
5
|
+
column: any;
|
6
|
+
});
|
7
|
+
offset: any;
|
8
|
+
line: any;
|
9
|
+
column: any;
|
10
|
+
}
|
11
|
+
declare function n(n: any): any;
|
12
|
+
export { e as SyntaxError, n as parse };
|
@@ -0,0 +1,138 @@
|
|
1
|
+
declare var b: any;
|
2
|
+
declare var I: boolean;
|
3
|
+
declare namespace r {
|
4
|
+
export let __esModule: boolean;
|
5
|
+
export { Readline };
|
6
|
+
}
|
7
|
+
declare class Readline {
|
8
|
+
highlighter: {
|
9
|
+
highlight(t: any, e: any): any;
|
10
|
+
highlightPrompt(t: any): any;
|
11
|
+
highlightChar(t: any, e: any): boolean;
|
12
|
+
};
|
13
|
+
history: {
|
14
|
+
entries: any[];
|
15
|
+
cursor: number;
|
16
|
+
maxEntries: any;
|
17
|
+
saveToLocalStorage(): void;
|
18
|
+
restoreFromLocalStorage(): void;
|
19
|
+
append(t: any): void;
|
20
|
+
resetCursor(): void;
|
21
|
+
next(): any;
|
22
|
+
prev(): any;
|
23
|
+
};
|
24
|
+
disposables: any[];
|
25
|
+
watermark: number;
|
26
|
+
highWatermark: number;
|
27
|
+
lowWatermark: number;
|
28
|
+
highWater: boolean;
|
29
|
+
state: {
|
30
|
+
line: {
|
31
|
+
buf: string;
|
32
|
+
pos: number;
|
33
|
+
buffer(): string;
|
34
|
+
pos_buffer(): string;
|
35
|
+
length(): number;
|
36
|
+
char_length(): number;
|
37
|
+
update(t: any, e: any): void;
|
38
|
+
insert(t: any): boolean;
|
39
|
+
moveBack(t: any): boolean;
|
40
|
+
moveForward(t: any): boolean;
|
41
|
+
moveHome(): boolean;
|
42
|
+
moveEnd(): boolean;
|
43
|
+
startOfLine(): number;
|
44
|
+
endOfLine(): number;
|
45
|
+
moveLineUp(t: any): boolean;
|
46
|
+
moveLineDown(t: any): boolean;
|
47
|
+
set_pos(t: any): void;
|
48
|
+
prevPos(t: any): number;
|
49
|
+
nextPos(t: any): number;
|
50
|
+
backspace(t: any): boolean;
|
51
|
+
delete(t: any): boolean;
|
52
|
+
deleteEndOfLine(): boolean;
|
53
|
+
};
|
54
|
+
highlighting: boolean;
|
55
|
+
prompt: any;
|
56
|
+
tty: any;
|
57
|
+
highlighter: any;
|
58
|
+
history: any;
|
59
|
+
promptSize: any;
|
60
|
+
layout: p;
|
61
|
+
buffer(): string;
|
62
|
+
shouldHighlight(): boolean;
|
63
|
+
clearScreen(): void;
|
64
|
+
editInsert(t: any): void;
|
65
|
+
update(t: any): void;
|
66
|
+
editBackspace(t: any): void;
|
67
|
+
editDelete(t: any): void;
|
68
|
+
editDeleteEndOfLine(): void;
|
69
|
+
refresh(): void;
|
70
|
+
moveCursorBack(t: any): void;
|
71
|
+
moveCursorForward(t: any): void;
|
72
|
+
moveCursorUp(t: any): void;
|
73
|
+
moveCursorDown(t: any): void;
|
74
|
+
moveCursorHome(): void;
|
75
|
+
moveCursorEnd(): void;
|
76
|
+
moveCursorToEnd(): void;
|
77
|
+
previousHistory(): void;
|
78
|
+
nextHistory(): void;
|
79
|
+
moveCursor(): void;
|
80
|
+
};
|
81
|
+
checkHandler: () => boolean;
|
82
|
+
ctrlCHandler: () => void;
|
83
|
+
pauseHandler: (t: any) => void;
|
84
|
+
activate(t: any): void;
|
85
|
+
term: any;
|
86
|
+
dispose(): void;
|
87
|
+
appendHistory(t: any): void;
|
88
|
+
setHighlighter(t: any): void;
|
89
|
+
setCheckHandler(t: any): void;
|
90
|
+
setCtrlCHandler(t: any): void;
|
91
|
+
setPauseHandler(t: any): void;
|
92
|
+
writeReady(): boolean;
|
93
|
+
write(t: any): void;
|
94
|
+
print(t: any): void;
|
95
|
+
println(t: any): void;
|
96
|
+
output(): this;
|
97
|
+
tty(): {
|
98
|
+
tabWidth: any;
|
99
|
+
col: any;
|
100
|
+
row: any;
|
101
|
+
out: any;
|
102
|
+
write(t: any): any;
|
103
|
+
print(t: any): any;
|
104
|
+
println(t: any): any;
|
105
|
+
clearScreen(): void;
|
106
|
+
calculatePosition(t: any, e: any): any;
|
107
|
+
computeLayout(t: any, e: any): {
|
108
|
+
promptSize: any;
|
109
|
+
cursor: any;
|
110
|
+
end: any;
|
111
|
+
};
|
112
|
+
refreshLine(t: any, e: any, s: any, i: any, r: any): void;
|
113
|
+
clearOldRows(t: any): void;
|
114
|
+
moveCursor(t: any, e: any): void;
|
115
|
+
};
|
116
|
+
read(t: any): Promise<any>;
|
117
|
+
activeRead: {
|
118
|
+
prompt: any;
|
119
|
+
resolve: (value: any) => void;
|
120
|
+
reject: (reason?: any) => void;
|
121
|
+
};
|
122
|
+
handleKeyEvent(t: any): boolean;
|
123
|
+
readData(t: any): void;
|
124
|
+
readPaste(t: any): void;
|
125
|
+
readKey(t: any): void;
|
126
|
+
}
|
127
|
+
declare class p {
|
128
|
+
constructor(t: any);
|
129
|
+
promptSize: any;
|
130
|
+
cursor: c;
|
131
|
+
end: c;
|
132
|
+
}
|
133
|
+
declare class c {
|
134
|
+
constructor(t: any, e: any);
|
135
|
+
row: any;
|
136
|
+
col: any;
|
137
|
+
}
|
138
|
+
export { b as Readline, I as __esModule, r as default };
|
package/types/core.d.ts
CHANGED
@@ -1,6 +1,42 @@
|
|
1
1
|
import TYPES from "./types.js";
|
2
|
-
|
3
|
-
|
4
|
-
|
5
|
-
|
2
|
+
/**
|
3
|
+
* A `Worker` facade able to bootstrap on the worker thread only a PyScript module.
|
4
|
+
* @param {string} file the python file to run ina worker.
|
5
|
+
* @param {{config?: string | object, async?: boolean}} [options] optional configuration for the worker.
|
6
|
+
* @returns {Worker & {sync: ProxyHandler<object>}}
|
7
|
+
*/
|
8
|
+
declare function exportedPyWorker(file: string, options?: {
|
9
|
+
config?: string | object;
|
10
|
+
async?: boolean;
|
11
|
+
}): Worker & {
|
12
|
+
sync: ProxyHandler<object>;
|
13
|
+
};
|
14
|
+
declare const exportedHooks: {
|
15
|
+
main: {
|
16
|
+
onWorker: Set<Function>;
|
17
|
+
onReady: Set<Function>;
|
18
|
+
onBeforeRun: Set<Function>;
|
19
|
+
onBeforeRunAsync: Set<Function>;
|
20
|
+
onAfterRun: Set<Function>;
|
21
|
+
onAfterRunAsync: Set<Function>;
|
22
|
+
codeBeforeRun: Set<string>;
|
23
|
+
codeBeforeRunAsync: Set<string>;
|
24
|
+
codeAfterRun: Set<string>;
|
25
|
+
codeAfterRunAsync: Set<string>;
|
26
|
+
};
|
27
|
+
worker: {
|
28
|
+
onReady: Set<Function>;
|
29
|
+
onBeforeRun: Set<Function>;
|
30
|
+
onBeforeRunAsync: Set<Function>;
|
31
|
+
onAfterRun: Set<Function>;
|
32
|
+
onAfterRunAsync: Set<Function>;
|
33
|
+
codeBeforeRun: Set<string>;
|
34
|
+
codeBeforeRunAsync: Set<string>;
|
35
|
+
codeAfterRun: Set<string>;
|
36
|
+
codeAfterRunAsync: Set<string>;
|
37
|
+
};
|
38
|
+
};
|
39
|
+
declare const exportedConfig: {};
|
40
|
+
declare const exportedWhenDefined: (type: string) => Promise<any>;
|
41
|
+
import sync from "./sync.js";
|
6
42
|
export { TYPES, exportedPyWorker as PyWorker, exportedHooks as hooks, exportedConfig as config, exportedWhenDefined as whenDefined };
|
package/types/fetch.d.ts
CHANGED
@@ -1,2 +0,0 @@
|
|
1
|
-
import{TYPES as e,hooks as t}from"./core.js";const r="https://cdn.jsdelivr.net/npm/xterm",n="5.3.0",o=[...e.keys()].map((e=>`script[type="${e}"][terminal],${e}-script[terminal]`)).join(","),i=async()=>{const e=document.querySelectorAll(o);if(!e.length)return;e.length>1&&console.warn("Unable to satisfy multiple terminals"),s.disconnect();const[i]=e;if(i.matches('script[type="mpy"],mpy-script'))throw new Error("Unsupported terminal");document.querySelector(`link[href^="${r}"]`)||document.head.append(Object.assign(document.createElement("link"),{rel:"stylesheet",href:`${r}@${n}/css/xterm.min.css`}));const[{Terminal:d},{Readline:a}]=await Promise.all([import(`${r}@${n}/+esm`),import(`${r}-readline@1.1.1/+esm`)]),c=new a,l=e=>{let t=i;const r=i.getAttribute("target");if(r){if(t=document.getElementById(r)||document.querySelector(r),!t)throw new Error(`Unknown target ${r}`)}else t=document.createElement("py-terminal"),t.style.display="block",i.after(t);const n=new d({theme:{background:"#191A19",foreground:"#F5F2E7"},...e});n.loadAddon(c),n.open(t),n.focus()};if(i.hasAttribute("worker")){const e=({interpreter:e},{sync:t})=>{t.pyterminal_drop_hooks();const r=new TextDecoder,n={isatty:!0,write:e=>(t.pyterminal_write(r.decode(e)),e.length)};e.setStdout(n),e.setStderr(n)},r="\n import builtins\n from pyscript import sync as _sync\n\n builtins.input = lambda prompt: _sync.pyterminal_read(prompt)\n ",n="\n import code as _code\n _code.interact()\n ";t.main.onWorker.add((function o(i,s){t.main.onWorker.delete(o),l({disableStdin:!1,cursorBlink:!0,cursorStyle:"block"}),s.sync.pyterminal_read=c.read.bind(c),s.sync.pyterminal_write=c.write.bind(c),s.sync.pyterminal_drop_hooks=()=>{t.worker.onReady.delete(e),t.worker.codeBeforeRun.delete(r),t.worker.codeAfterRun.delete(n)}})),t.worker.onReady.add(e),t.worker.codeBeforeRun.add(r),t.worker.codeAfterRun.add(n)}else t.main.onReady.add((function e({io:r}){console.warn("py-terminal is read only on main thread"),t.main.onReady.delete(e),l({disableStdin:!0,cursorBlink:!1,cursorStyle:"underline"}),r.stdout=e=>{c.write(`${e}\n`)},r.stderr=e=>{c.write(`${e.message||e}\n`)}}))},s=new MutationObserver(i);s.observe(document,{childList:!0,subtree:!0});var d=i();export{d as default};
|
2
|
-
//# sourceMappingURL=py-terminal-_uJ8pDjX.js.map
|
@@ -1 +0,0 @@
|
|
1
|
-
{"version":3,"file":"py-terminal-_uJ8pDjX.js","sources":["../src/plugins/py-terminal.js"],"sourcesContent":["// PyScript py-terminal plugin\nimport { TYPES, hooks } from \"../core.js\";\n\nconst CDN = \"https://cdn.jsdelivr.net/npm/xterm\";\nconst XTERM = \"5.3.0\";\nconst XTERM_READLINE = \"1.1.1\";\nconst SELECTOR = [...TYPES.keys()]\n .map((type) => `script[type=\"${type}\"][terminal],${type}-script[terminal]`)\n .join(\",\");\n\nconst pyTerminal = async () => {\n const terminals = document.querySelectorAll(SELECTOR);\n\n // no results will look further for runtime nodes\n if (!terminals.length) return;\n\n // we currently support only one terminal as in \"classic\"\n if (terminals.length > 1)\n console.warn(\"Unable to satisfy multiple terminals\");\n\n // if we arrived this far, let's drop the MutationObserver\n mo.disconnect();\n\n const [element] = terminals;\n // hopefully to be removed in the near future!\n if (element.matches('script[type=\"mpy\"],mpy-script'))\n throw new Error(\"Unsupported terminal\");\n\n // import styles once and lazily (only on valid terminal)\n if (!document.querySelector(`link[href^=\"${CDN}\"]`)) {\n document.head.append(\n Object.assign(document.createElement(\"link\"), {\n rel: \"stylesheet\",\n href: `${CDN}@${XTERM}/css/xterm.min.css`,\n }),\n );\n }\n\n // lazy load these only when a valid terminal is found\n const [{ Terminal }, { Readline }] = await Promise.all([\n import(/* webpackIgnore: true */ `${CDN}@${XTERM}/+esm`),\n import(\n /* webpackIgnore: true */ `${CDN}-readline@${XTERM_READLINE}/+esm`\n ),\n ]);\n\n const readline = new Readline();\n\n // common main thread initialization for both worker\n // or main case, bootstrapping the terminal on its target\n const init = (options) => {\n let target = element;\n const selector = element.getAttribute(\"target\");\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(\"py-terminal\");\n target.style.display = \"block\";\n element.after(target);\n }\n const terminal = new Terminal({\n theme: {\n background: \"#191A19\",\n foreground: \"#F5F2E7\",\n },\n ...options,\n });\n terminal.loadAddon(readline);\n terminal.open(target);\n terminal.focus();\n };\n\n // branch logic for the worker\n if (element.hasAttribute(\"worker\")) {\n // when the remote thread onReady triggers:\n // setup the interpreter stdout and stderr\n const workerReady = ({ interpreter }, { sync }) => {\n sync.pyterminal_drop_hooks();\n const decoder = new TextDecoder();\n const generic = {\n isatty: true,\n write(buffer) {\n sync.pyterminal_write(decoder.decode(buffer));\n return buffer.length;\n },\n };\n interpreter.setStdout(generic);\n interpreter.setStderr(generic);\n };\n\n // run in python code able to replace builtins.input\n // using the xworker.sync non blocking prompt\n const codeBefore = `\n import builtins\n from pyscript import sync as _sync\n\n builtins.input = lambda prompt: _sync.pyterminal_read(prompt)\n `;\n\n // at the end of the code, make the terminal interactive\n const codeAfter = `\n import code as _code\n _code.interact()\n `;\n\n // add a hook on the main thread to setup all sync helpers\n // also bootstrapping the XTerm target on main\n hooks.main.onWorker.add(function worker(_, xworker) {\n hooks.main.onWorker.delete(worker);\n init({\n disableStdin: false,\n cursorBlink: true,\n cursorStyle: \"block\",\n });\n xworker.sync.pyterminal_read = readline.read.bind(readline);\n xworker.sync.pyterminal_write = readline.write.bind(readline);\n // allow a worker to drop main thread hooks ASAP\n xworker.sync.pyterminal_drop_hooks = () => {\n hooks.worker.onReady.delete(workerReady);\n hooks.worker.codeBeforeRun.delete(codeBefore);\n hooks.worker.codeAfterRun.delete(codeAfter);\n };\n });\n\n // setup remote thread JS/Python code for whenever the\n // worker is ready to become a terminal\n hooks.worker.onReady.add(workerReady);\n hooks.worker.codeBeforeRun.add(codeBefore);\n hooks.worker.codeAfterRun.add(codeAfter);\n } else {\n // in the main case, just bootstrap XTerm without\n // allowing any input as that's not possible / awkward\n hooks.main.onReady.add(function main({ io }) {\n console.warn(\"py-terminal is read only on main thread\");\n hooks.main.onReady.delete(main);\n init({\n disableStdin: true,\n cursorBlink: false,\n cursorStyle: \"underline\",\n });\n io.stdout = (value) => {\n readline.write(`${value}\\n`);\n };\n io.stderr = (error) => {\n readline.write(`${error.message || error}\\n`);\n };\n });\n }\n};\n\nconst mo = new MutationObserver(pyTerminal);\nmo.observe(document, { childList: true, subtree: true });\n\n// try to check the current document ASAP\nexport default pyTerminal();\n"],"names":["CDN","XTERM","SELECTOR","TYPES","keys","map","type","join","pyTerminal","async","terminals","document","querySelectorAll","length","console","warn","mo","disconnect","element","matches","Error","querySelector","head","append","Object","assign","createElement","rel","href","Terminal","Readline","Promise","all","import","readline","init","options","target","selector","getAttribute","getElementById","style","display","after","terminal","theme","background","foreground","loadAddon","open","focus","hasAttribute","workerReady","interpreter","sync","pyterminal_drop_hooks","decoder","TextDecoder","generic","isatty","write","buffer","pyterminal_write","decode","setStdout","setStderr","codeBefore","codeAfter","hooks","main","onWorker","add","worker","_","xworker","delete","disableStdin","cursorBlink","cursorStyle","pyterminal_read","read","bind","onReady","codeBeforeRun","codeAfterRun","io","stdout","value","stderr","error","message","MutationObserver","observe","childList","subtree","pyTerminal$1"],"mappings":"6CAGA,MAAMA,EAAM,qCACNC,EAAQ,QAERC,EAAW,IAAIC,EAAMC,QACtBC,KAAKC,GAAS,gBAAgBA,iBAAoBA,uBAClDC,KAAK,KAEJC,EAAaC,UACf,MAAMC,EAAYC,SAASC,iBAAiBV,GAG5C,IAAKQ,EAAUG,OAAQ,OAGnBH,EAAUG,OAAS,GACnBC,QAAQC,KAAK,wCAGjBC,EAAGC,aAEH,MAAOC,GAAWR,EAElB,GAAIQ,EAAQC,QAAQ,iCAChB,MAAM,IAAIC,MAAM,wBAGfT,SAASU,cAAc,eAAerB,QACvCW,SAASW,KAAKC,OACVC,OAAOC,OAAOd,SAASe,cAAc,QAAS,CAC1CC,IAAK,aACLC,KAAM,GAAG5B,KAAOC,yBAM5B,OAAO4B,SAAEA,IAAYC,SAAEA,UAAoBC,QAAQC,IAAI,CACnDC,OAAiC,GAAGjC,KAAOC,UAC3CgC,OAC8B,GAAGjC,2BAI/BkC,EAAW,IAAIJ,EAIfK,EAAQC,IACV,IAAIC,EAASnB,EACb,MAAMoB,EAAWpB,EAAQqB,aAAa,UACtC,GAAID,GAIA,GAHAD,EACI1B,SAAS6B,eAAeF,IACxB3B,SAASU,cAAciB,IACtBD,EAAQ,MAAM,IAAIjB,MAAM,kBAAkBkB,UAE/CD,EAAS1B,SAASe,cAAc,eAChCW,EAAOI,MAAMC,QAAU,QACvBxB,EAAQyB,MAAMN,GAElB,MAAMO,EAAW,IAAIf,EAAS,CAC1BgB,MAAO,CACHC,WAAY,UACZC,WAAY,cAEbX,IAEPQ,EAASI,UAAUd,GACnBU,EAASK,KAAKZ,GACdO,EAASM,OAAO,EAIpB,GAAIhC,EAAQiC,aAAa,UAAW,CAGhC,MAAMC,EAAc,EAAGC,gBAAiBC,WACpCA,EAAKC,wBACL,MAAMC,EAAU,IAAIC,YACdC,EAAU,CACZC,QAAQ,EACRC,MAAMC,IACFP,EAAKQ,iBAAiBN,EAAQO,OAAOF,IAC9BA,EAAOhD,SAGtBwC,EAAYW,UAAUN,GACtBL,EAAYY,UAAUP,EAAQ,EAK5BQ,EAAa,uKAQbC,EAAY,6EAOlBC,EAAMC,KAAKC,SAASC,KAAI,SAASC,EAAOC,EAAGC,GACvCN,EAAMC,KAAKC,SAASK,OAAOH,GAC3BrC,EAAK,CACDyC,cAAc,EACdC,aAAa,EACbC,YAAa,UAEjBJ,EAAQpB,KAAKyB,gBAAkB7C,EAAS8C,KAAKC,KAAK/C,GAClDwC,EAAQpB,KAAKQ,iBAAmB5B,EAAS0B,MAAMqB,KAAK/C,GAEpDwC,EAAQpB,KAAKC,sBAAwB,KACjCa,EAAMI,OAAOU,QAAQP,OAAOvB,GAC5BgB,EAAMI,OAAOW,cAAcR,OAAOT,GAClCE,EAAMI,OAAOY,aAAaT,OAAOR,EAAU,CAE3D,IAIQC,EAAMI,OAAOU,QAAQX,IAAInB,GACzBgB,EAAMI,OAAOW,cAAcZ,IAAIL,GAC/BE,EAAMI,OAAOY,aAAab,IAAIJ,EACtC,MAGQC,EAAMC,KAAKa,QAAQX,KAAI,SAASF,GAAKgB,GAAEA,IACnCvE,QAAQC,KAAK,2CACbqD,EAAMC,KAAKa,QAAQP,OAAON,GAC1BlC,EAAK,CACDyC,cAAc,EACdC,aAAa,EACbC,YAAa,cAEjBO,EAAGC,OAAUC,IACTrD,EAAS0B,MAAM,GAAG2B,MAAU,EAEhCF,EAAGG,OAAUC,IACTvD,EAAS0B,MAAM,GAAG6B,EAAMC,SAAWD,MAAU,CAE7D,GACK,EAGCzE,EAAK,IAAI2E,iBAAiBnF,GAChCQ,EAAG4E,QAAQjF,SAAU,CAAEkF,WAAW,EAAMC,SAAS,IAGjD,IAAAC,EAAevF"}
|
File without changes
|