pyweft 0.2.0__py3-none-any.whl
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.
- pyweft/__init__.py +60 -0
- pyweft/__main__.py +4 -0
- pyweft/background.py +203 -0
- pyweft/binding.py +118 -0
- pyweft/cli.py +1006 -0
- pyweft/component.py +487 -0
- pyweft/desktop.py +606 -0
- pyweft/dialogs.py +123 -0
- pyweft/differ.py +195 -0
- pyweft/dommodel.py +63 -0
- pyweft/effects.py +191 -0
- pyweft/events.py +102 -0
- pyweft/expressions.py +184 -0
- pyweft/hotreload.py +122 -0
- pyweft/packaging.py +186 -0
- pyweft/parser.py +426 -0
- pyweft/prerender.py +121 -0
- pyweft/renderer.py +802 -0
- pyweft/routing.py +364 -0
- pyweft/static/loading.html +102 -0
- pyweft/static/runtime.js +341 -0
- pyweft/static/shell.html +693 -0
- pyweft/static/worker.js +89 -0
- pyweft/store.py +118 -0
- pyweft/styles.py +171 -0
- pyweft/vdom.py +57 -0
- pyweft-0.2.0.dist-info/METADATA +324 -0
- pyweft-0.2.0.dist-info/RECORD +31 -0
- pyweft-0.2.0.dist-info/WHEEL +4 -0
- pyweft-0.2.0.dist-info/entry_points.txt +2 -0
- pyweft-0.2.0.dist-info/licenses/LICENSE +21 -0
pyweft/dialogs.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
"""Opening and saving files, and asking the user, the same way everywhere.
|
|
2
|
+
|
|
3
|
+
In a handler (they're ``async``, so the handler is too)::
|
|
4
|
+
|
|
5
|
+
from pyweft import dialogs
|
|
6
|
+
|
|
7
|
+
async def load(self):
|
|
8
|
+
file = await dialogs.open_file(types=["csv"])
|
|
9
|
+
if file: # None when the user cancelled
|
|
10
|
+
self.rows = parse(file.text)
|
|
11
|
+
|
|
12
|
+
async def export(self):
|
|
13
|
+
await dialogs.save_file(self.as_csv(), name="orders.csv")
|
|
14
|
+
|
|
15
|
+
async def clear(self):
|
|
16
|
+
if await dialogs.confirm("Delete all orders?"):
|
|
17
|
+
self.orders = []
|
|
18
|
+
|
|
19
|
+
In a desktop app these are the system's own dialogs; in the browser, the
|
|
20
|
+
browser's file picker, a download, and its confirm box. Files come back as
|
|
21
|
+
their contents, not paths, because a browser never shows a page the user's
|
|
22
|
+
file system; on the desktop the path is there too.
|
|
23
|
+
|
|
24
|
+
The core only defines the calls. Each host supplies them with
|
|
25
|
+
:func:`set_host`, as background.py does for run_in_background: desktop.py
|
|
26
|
+
for the window, shell.html for the browser.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
from __future__ import annotations
|
|
30
|
+
|
|
31
|
+
import mimetypes
|
|
32
|
+
from dataclasses import dataclass
|
|
33
|
+
from typing import Any, Sequence
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass(frozen=True)
|
|
37
|
+
class PickedFile:
|
|
38
|
+
"""A file the user chose: its name, its contents, and on the desktop
|
|
39
|
+
where it is."""
|
|
40
|
+
|
|
41
|
+
name: str
|
|
42
|
+
data: bytes
|
|
43
|
+
path: str | None = None # desktop only: a browser never says
|
|
44
|
+
|
|
45
|
+
@property
|
|
46
|
+
def text(self) -> str:
|
|
47
|
+
"""The contents as text (UTF-8)."""
|
|
48
|
+
return self.data.decode("utf-8")
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class _NoHost:
|
|
52
|
+
async def _missing(self, *args: Any) -> Any:
|
|
53
|
+
raise RuntimeError(
|
|
54
|
+
"dialogs need a page to show them on: they work in the browser and "
|
|
55
|
+
"in a desktop window. In tests, install a stand-in with "
|
|
56
|
+
"pyweft.dialogs.set_host()"
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
open = save = confirm = _missing
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
_host: Any = _NoHost()
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def set_host(host: Any) -> None:
|
|
66
|
+
"""For hosts: an object with ``async open(types, multiple)`` returning
|
|
67
|
+
``[(name, data, path), ...]`` (empty when cancelled), ``async save(name,
|
|
68
|
+
data, types)`` returning whether it was saved, and ``async
|
|
69
|
+
confirm(message, title)`` returning a bool."""
|
|
70
|
+
global _host
|
|
71
|
+
_host = host
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _extensions(types: Sequence[str]) -> list[str]:
|
|
75
|
+
# "csv", ".csv" and "*.csv" all mean the same.
|
|
76
|
+
out = []
|
|
77
|
+
for kind in types:
|
|
78
|
+
ext = kind.strip().lstrip("*").lstrip(".").lower()
|
|
79
|
+
if not ext or not ext.replace("-", "").replace("_", "").isalnum():
|
|
80
|
+
raise ValueError(f"file types are extensions like 'csv', got {kind!r}")
|
|
81
|
+
out.append(ext)
|
|
82
|
+
return out
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
async def _open(types: Sequence[str], multiple: bool) -> list[PickedFile]:
|
|
86
|
+
chosen = await _host.open(_extensions(types), multiple)
|
|
87
|
+
return [PickedFile(name, bytes(data), path) for name, data, path in chosen]
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
async def open_file(*, types: Sequence[str] = ()) -> PickedFile | None:
|
|
91
|
+
"""Let the user choose a file, and return it, or ``None`` if they
|
|
92
|
+
cancelled. ``types=["csv", "txt"]`` limits what can be chosen."""
|
|
93
|
+
files = await _open(types, multiple=False)
|
|
94
|
+
return files[0] if files else None
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
async def open_files(*, types: Sequence[str] = ()) -> list[PickedFile]:
|
|
98
|
+
"""Let the user choose any number of files; an empty list if they
|
|
99
|
+
cancelled."""
|
|
100
|
+
return await _open(types, multiple=True)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
async def save_file(
|
|
104
|
+
data: bytes | str, *, name: str = "download", types: Sequence[str] = ()
|
|
105
|
+
) -> bool:
|
|
106
|
+
"""Save ``data`` (text is saved as UTF-8) as a file the user chooses,
|
|
107
|
+
suggesting ``name``. In a desktop app that's a Save As dialog, and the
|
|
108
|
+
result is False if they cancelled; in the browser it's a download, which
|
|
109
|
+
the browser saves where it saves downloads."""
|
|
110
|
+
if isinstance(data, str):
|
|
111
|
+
data = data.encode("utf-8")
|
|
112
|
+
exts = _extensions(types) or _extensions([name.rpartition(".")[2]] if "." in name else [])
|
|
113
|
+
return bool(await _host.save(name, bytes(data), exts))
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
async def confirm(message: str, *, title: str = "") -> bool:
|
|
117
|
+
"""Ask a yes-or-no question; True for OK."""
|
|
118
|
+
return bool(await _host.confirm(message, title))
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def mime_type(name: str) -> str:
|
|
122
|
+
"""For hosts: the type a saved file is given."""
|
|
123
|
+
return mimetypes.guess_type(name)[0] or "application/octet-stream"
|
pyweft/differ.py
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
"""Diff two vdom trees into a flat, ordered list of patch ops.
|
|
2
|
+
|
|
3
|
+
Ops are plain JSON-serialisable dicts, which is the whole point: the same list
|
|
4
|
+
can cross a webview bridge, a websocket, or nothing at all under Pyodide.
|
|
5
|
+
|
|
6
|
+
Addressing convention, applied consistently:
|
|
7
|
+
|
|
8
|
+
* structural ops (insert / remove / move / replace) carry the **parent** path
|
|
9
|
+
plus an index, because that is what a DOM parent needs to act
|
|
10
|
+
* in-place ops (set_text / set_attrs / set_events / set_key) carry the
|
|
11
|
+
**node's own** path
|
|
12
|
+
|
|
13
|
+
Ordering rule: at every level, all structural ops for a parent are emitted
|
|
14
|
+
before any op that descends into that parent's children. Indices in descendant
|
|
15
|
+
ops therefore refer to positions *after* this level has been reconciled, so a
|
|
16
|
+
consumer can apply the list front to back with no bookkeeping.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
from typing import Any
|
|
22
|
+
|
|
23
|
+
from .vdom import Element, Node, Text
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class DiffError(RuntimeError):
|
|
27
|
+
pass
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def diff(old_roots: list[Node], new_roots: list[Node]) -> list[dict]:
|
|
31
|
+
"""Diff two root lists, treating them as children of a virtual root."""
|
|
32
|
+
return _diff_children(old_roots, new_roots, [])
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _key_of(node: Node, index: int) -> tuple[str, Any]:
|
|
36
|
+
key = getattr(node, "key", None)
|
|
37
|
+
return ("k", key) if key is not None else ("i", index)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _check_duplicates(keys: list[tuple[str, Any]]) -> None:
|
|
41
|
+
seen = set()
|
|
42
|
+
for kind, value in keys:
|
|
43
|
+
if kind != "k":
|
|
44
|
+
continue
|
|
45
|
+
if value in seen:
|
|
46
|
+
raise DiffError(
|
|
47
|
+
f"duplicate key {value!r} among siblings; keys must be unique"
|
|
48
|
+
)
|
|
49
|
+
seen.add(value)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _diff_map(old: dict, new: dict) -> dict:
|
|
53
|
+
changed = {k: v for k, v in new.items() if old.get(k) != v}
|
|
54
|
+
removed = [k for k in old if k not in new]
|
|
55
|
+
result: dict[str, Any] = {}
|
|
56
|
+
if changed:
|
|
57
|
+
result["set"] = changed
|
|
58
|
+
if removed:
|
|
59
|
+
result["remove"] = removed
|
|
60
|
+
return result
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _diff_node(
|
|
64
|
+
old: Node, new: Node, parent_path: list[int], index: int
|
|
65
|
+
) -> list[dict]:
|
|
66
|
+
node_path = parent_path + [index]
|
|
67
|
+
|
|
68
|
+
if type(old) is not type(new):
|
|
69
|
+
return [
|
|
70
|
+
{
|
|
71
|
+
"op": "replace",
|
|
72
|
+
"path": parent_path,
|
|
73
|
+
"index": index,
|
|
74
|
+
"node": new.to_dict(),
|
|
75
|
+
}
|
|
76
|
+
]
|
|
77
|
+
|
|
78
|
+
if isinstance(old, Text):
|
|
79
|
+
if old.text != new.text:
|
|
80
|
+
return [{"op": "set_text", "path": node_path, "text": new.text}]
|
|
81
|
+
return []
|
|
82
|
+
|
|
83
|
+
assert isinstance(old, Element) and isinstance(new, Element)
|
|
84
|
+
|
|
85
|
+
if old.tag != new.tag:
|
|
86
|
+
return [
|
|
87
|
+
{
|
|
88
|
+
"op": "replace",
|
|
89
|
+
"path": parent_path,
|
|
90
|
+
"index": index,
|
|
91
|
+
"node": new.to_dict(),
|
|
92
|
+
}
|
|
93
|
+
]
|
|
94
|
+
|
|
95
|
+
ops: list[dict] = []
|
|
96
|
+
|
|
97
|
+
attrs = _diff_map(old.attrs, new.attrs)
|
|
98
|
+
if attrs:
|
|
99
|
+
ops.append({"op": "set_attrs", "path": node_path, **attrs})
|
|
100
|
+
|
|
101
|
+
events = _diff_map(old.events, new.events)
|
|
102
|
+
if events:
|
|
103
|
+
ops.append({"op": "set_events", "path": node_path, **events})
|
|
104
|
+
|
|
105
|
+
if old.key != new.key:
|
|
106
|
+
ops.append({"op": "set_key", "path": node_path, "key": new.key})
|
|
107
|
+
|
|
108
|
+
ops += _diff_children(old.children, new.children, node_path)
|
|
109
|
+
return ops
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _diff_children(
|
|
113
|
+
old: list[Node], new: list[Node], path: list[int]
|
|
114
|
+
) -> list[dict]:
|
|
115
|
+
keyed = any(getattr(n, "key", None) is not None for n in old) or any(
|
|
116
|
+
getattr(n, "key", None) is not None for n in new
|
|
117
|
+
)
|
|
118
|
+
if not keyed:
|
|
119
|
+
return _diff_positional(old, new, path)
|
|
120
|
+
return _diff_keyed(old, new, path)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _diff_positional(
|
|
124
|
+
old: list[Node], new: list[Node], path: list[int]
|
|
125
|
+
) -> list[dict]:
|
|
126
|
+
common = min(len(old), len(new))
|
|
127
|
+
struct: list[dict] = []
|
|
128
|
+
for i in range(len(old) - 1, common - 1, -1):
|
|
129
|
+
struct.append({"op": "remove", "path": path, "index": i})
|
|
130
|
+
for i in range(common, len(new)):
|
|
131
|
+
struct.append(
|
|
132
|
+
{"op": "insert", "path": path, "index": i, "node": new[i].to_dict()}
|
|
133
|
+
)
|
|
134
|
+
descend: list[dict] = []
|
|
135
|
+
for i in range(common):
|
|
136
|
+
descend += _diff_node(old[i], new[i], path, i)
|
|
137
|
+
return struct + descend
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _diff_keyed(old: list[Node], new: list[Node], path: list[int]) -> list[dict]:
|
|
141
|
+
current = [_key_of(n, i) for i, n in enumerate(old)]
|
|
142
|
+
target = [_key_of(n, i) for i, n in enumerate(new)]
|
|
143
|
+
_check_duplicates(target)
|
|
144
|
+
|
|
145
|
+
old_by_key: dict[tuple[str, Any], Node] = {}
|
|
146
|
+
for i, key in enumerate(current):
|
|
147
|
+
old_by_key.setdefault(key, old[i])
|
|
148
|
+
|
|
149
|
+
struct: list[dict] = []
|
|
150
|
+
descend: list[dict] = []
|
|
151
|
+
|
|
152
|
+
# Evict keys that are gone before reconciling the survivors. Without this
|
|
153
|
+
# pass, deleting one row from the middle of a list makes every row below it
|
|
154
|
+
# look "out of place" and the main loop shuffles them up one by one --
|
|
155
|
+
# correct, but O(n) moves for what should be a single removal.
|
|
156
|
+
surviving = set(target)
|
|
157
|
+
for j in range(len(current) - 1, -1, -1):
|
|
158
|
+
if current[j] not in surviving:
|
|
159
|
+
struct.append({"op": "remove", "path": path, "index": j})
|
|
160
|
+
current.pop(j)
|
|
161
|
+
|
|
162
|
+
for position, key in enumerate(target):
|
|
163
|
+
if position < len(current) and current[position] == key:
|
|
164
|
+
descend += _diff_node(old_by_key[key], new[position], path, position)
|
|
165
|
+
continue
|
|
166
|
+
|
|
167
|
+
found = None
|
|
168
|
+
for j in range(position, len(current)):
|
|
169
|
+
if current[j] == key:
|
|
170
|
+
found = j
|
|
171
|
+
break
|
|
172
|
+
|
|
173
|
+
if found is not None:
|
|
174
|
+
struct.append(
|
|
175
|
+
{"op": "move", "path": path, "from": found, "to": position}
|
|
176
|
+
)
|
|
177
|
+
current.insert(position, current.pop(found))
|
|
178
|
+
descend += _diff_node(old_by_key[key], new[position], path, position)
|
|
179
|
+
else:
|
|
180
|
+
struct.append(
|
|
181
|
+
{
|
|
182
|
+
"op": "insert",
|
|
183
|
+
"path": path,
|
|
184
|
+
"index": position,
|
|
185
|
+
"node": new[position].to_dict(),
|
|
186
|
+
}
|
|
187
|
+
)
|
|
188
|
+
current.insert(position, key)
|
|
189
|
+
|
|
190
|
+
# Anything left past the end of the new list is stale. Remove back to
|
|
191
|
+
# front so earlier indices stay valid as we go.
|
|
192
|
+
for j in range(len(current) - 1, len(target) - 1, -1):
|
|
193
|
+
struct.append({"op": "remove", "path": path, "index": j})
|
|
194
|
+
|
|
195
|
+
return struct + descend
|
pyweft/dommodel.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""A plain-Python model of the DOM that applies patch ops.
|
|
2
|
+
|
|
3
|
+
This is the executable spec for the JavaScript runtime that will live in the
|
|
4
|
+
webview: whatever this file does, ``runtime.js`` must do to real DOM nodes. It
|
|
5
|
+
also lets the differ be tested properly -- apply the patches to the old tree
|
|
6
|
+
and assert the result equals the new tree, which catches ordering and indexing
|
|
7
|
+
bugs that op-by-op assertions happily miss.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import copy
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _node_at(roots: list[dict], path: list[int]) -> dict:
|
|
17
|
+
node = roots[path[0]]
|
|
18
|
+
for index in path[1:]:
|
|
19
|
+
node = node["children"][index]
|
|
20
|
+
return node
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _children_at(roots: list[dict], path: list[int]) -> list[dict]:
|
|
24
|
+
if not path:
|
|
25
|
+
return roots
|
|
26
|
+
return _node_at(roots, path)["children"]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def apply_patches(roots: list[dict], ops: list[dict]) -> list[dict]:
|
|
30
|
+
"""Apply ops to a deep copy of ``roots`` and return the result."""
|
|
31
|
+
roots = copy.deepcopy(roots)
|
|
32
|
+
|
|
33
|
+
for op in ops:
|
|
34
|
+
kind = op["op"]
|
|
35
|
+
|
|
36
|
+
if kind in ("insert", "remove", "move", "replace"):
|
|
37
|
+
children = _children_at(roots, op["path"])
|
|
38
|
+
if kind == "insert":
|
|
39
|
+
children.insert(op["index"], copy.deepcopy(op["node"]))
|
|
40
|
+
elif kind == "remove":
|
|
41
|
+
children.pop(op["index"])
|
|
42
|
+
elif kind == "replace":
|
|
43
|
+
children[op["index"]] = copy.deepcopy(op["node"])
|
|
44
|
+
else:
|
|
45
|
+
children.insert(op["to"], children.pop(op["from"]))
|
|
46
|
+
continue
|
|
47
|
+
|
|
48
|
+
node = _node_at(roots, op["path"])
|
|
49
|
+
if kind == "set_text":
|
|
50
|
+
node["text"] = op["text"]
|
|
51
|
+
elif kind == "set_key":
|
|
52
|
+
node["key"] = op["key"]
|
|
53
|
+
elif kind in ("set_attrs", "set_events"):
|
|
54
|
+
target: dict[str, Any] = node[
|
|
55
|
+
"attrs" if kind == "set_attrs" else "events"
|
|
56
|
+
]
|
|
57
|
+
for name in op.get("remove", []):
|
|
58
|
+
target.pop(name, None)
|
|
59
|
+
target.update(op.get("set", {}))
|
|
60
|
+
else: # pragma: no cover - defensive
|
|
61
|
+
raise ValueError(f"unknown op {kind!r}")
|
|
62
|
+
|
|
63
|
+
return roots
|
pyweft/effects.py
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
"""``@effect``: methods that re-run after a render when the state they read
|
|
2
|
+
changes.
|
|
3
|
+
|
|
4
|
+
There is no reactive state to subscribe to, so dependencies are discovered by
|
|
5
|
+
running the effect against a stand-in for ``self`` that records every state
|
|
6
|
+
attribute read through it -- including reads inside computed properties and
|
|
7
|
+
helper methods, which are re-bound to the stand-in. Only effects pay for this;
|
|
8
|
+
ordinary attribute access on components stays a plain attribute access.
|
|
9
|
+
|
|
10
|
+
After each render has been applied, the host calls ``Renderer.after_render()``,
|
|
11
|
+
which compares each effect's recorded values with the current ones and re-runs
|
|
12
|
+
only the effects whose inputs changed. Values are snapshotted with a deep copy,
|
|
13
|
+
so ``self.items.append(x)`` counts as a change, not just reassignment.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import copy
|
|
19
|
+
import inspect
|
|
20
|
+
import types
|
|
21
|
+
from typing import Any, Callable
|
|
22
|
+
|
|
23
|
+
_MARK = "__pyweft_effect__"
|
|
24
|
+
_MISSING = object()
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def effect(fn: Callable) -> Callable:
|
|
28
|
+
"""Mark a component method as an effect.
|
|
29
|
+
|
|
30
|
+
The method runs after the component's first render, then again after any
|
|
31
|
+
later render in which a state value it read has changed. If it returns a
|
|
32
|
+
callable, that callable is the cleanup: it runs before the next run and
|
|
33
|
+
when the component is disposed.
|
|
34
|
+
"""
|
|
35
|
+
if inspect.iscoroutinefunction(fn):
|
|
36
|
+
raise TypeError(_ASYNC_EFFECT.format(name=fn.__name__))
|
|
37
|
+
setattr(fn, _MARK, True)
|
|
38
|
+
return fn
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
# Only reads before the first await could be tracked, and a write after it
|
|
42
|
+
# would land after the render it belongs to. A task started from the effect
|
|
43
|
+
# makes that split explicit, and returning task.cancel makes "latest wins".
|
|
44
|
+
_ASYNC_EFFECT = (
|
|
45
|
+
"@effect {name} cannot be async. Start the async work from a plain "
|
|
46
|
+
"effect and return its cancel as the cleanup: "
|
|
47
|
+
"task = self.start_task(self.load(...)); return task.cancel"
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def effect_names(cls: type) -> list[str]:
|
|
52
|
+
"""Names of ``@effect`` methods on ``cls`` and its bases, base-first."""
|
|
53
|
+
names: list[str] = []
|
|
54
|
+
for klass in reversed(cls.__mro__):
|
|
55
|
+
for name, value in vars(klass).items():
|
|
56
|
+
if getattr(value, _MARK, False) and name not in names:
|
|
57
|
+
names.append(name)
|
|
58
|
+
return names
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class EffectState:
|
|
62
|
+
"""Per-instance bookkeeping for one effect."""
|
|
63
|
+
|
|
64
|
+
__slots__ = ("deps", "cleanup")
|
|
65
|
+
|
|
66
|
+
def __init__(self) -> None:
|
|
67
|
+
self.deps: dict[str, Any] | None = None # None: never run
|
|
68
|
+
self.cleanup: Callable[[], Any] | None = None
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _snapshot(value: Any) -> Any:
|
|
72
|
+
try:
|
|
73
|
+
return copy.deepcopy(value)
|
|
74
|
+
except Exception:
|
|
75
|
+
return value # uncopyable: fall back to comparing the object itself
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _same(old: Any, new: Any) -> bool:
|
|
79
|
+
try:
|
|
80
|
+
return bool(old == new)
|
|
81
|
+
except Exception: # e.g. an array whose == has no single truth value
|
|
82
|
+
return old is new
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _class_attr(cls: type, name: str) -> Any:
|
|
86
|
+
for klass in cls.__mro__:
|
|
87
|
+
if name in vars(klass):
|
|
88
|
+
return vars(klass)[name]
|
|
89
|
+
return _MISSING
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
class _Tracker:
|
|
93
|
+
"""Stands in for ``self`` while an effect runs.
|
|
94
|
+
|
|
95
|
+
Reads of state are recorded, writes go through to the real component and
|
|
96
|
+
are remembered so the host knows to re-render. Methods defined by the
|
|
97
|
+
framework base class are bound to the real component: they touch private
|
|
98
|
+
bookkeeping, not user state, and must not count as dependencies.
|
|
99
|
+
"""
|
|
100
|
+
|
|
101
|
+
__slots__ = ("_pw_target", "_pw_reads", "_pw_wrote")
|
|
102
|
+
|
|
103
|
+
def __init__(self, target: Any):
|
|
104
|
+
object.__setattr__(self, "_pw_target", target)
|
|
105
|
+
object.__setattr__(self, "_pw_reads", set())
|
|
106
|
+
object.__setattr__(self, "_pw_wrote", False)
|
|
107
|
+
|
|
108
|
+
def __getattribute__(self, name: str) -> Any:
|
|
109
|
+
target = object.__getattribute__(self, "_pw_target")
|
|
110
|
+
cls = type(target)
|
|
111
|
+
attr = _class_attr(cls, name)
|
|
112
|
+
|
|
113
|
+
if name not in vars(target):
|
|
114
|
+
if isinstance(attr, property):
|
|
115
|
+
return attr.fget(self) if attr.fget else getattr(target, name)
|
|
116
|
+
if isinstance(attr, types.FunctionType):
|
|
117
|
+
from .component import Component
|
|
118
|
+
|
|
119
|
+
if _class_attr(Component, name) is attr:
|
|
120
|
+
return getattr(target, name)
|
|
121
|
+
return types.MethodType(attr, self)
|
|
122
|
+
if isinstance(attr, (staticmethod, classmethod)):
|
|
123
|
+
return getattr(target, name)
|
|
124
|
+
|
|
125
|
+
value = getattr(target, name)
|
|
126
|
+
if not name.startswith("_") and not callable(value):
|
|
127
|
+
object.__getattribute__(self, "_pw_reads").add(name)
|
|
128
|
+
return value
|
|
129
|
+
|
|
130
|
+
def __setattr__(self, name: str, value: Any) -> None:
|
|
131
|
+
target = object.__getattribute__(self, "_pw_target")
|
|
132
|
+
setattr(target, name, value)
|
|
133
|
+
if not name.startswith("_"):
|
|
134
|
+
object.__setattr__(self, "_pw_wrote", True)
|
|
135
|
+
|
|
136
|
+
def __delattr__(self, name: str) -> None:
|
|
137
|
+
delattr(object.__getattribute__(self, "_pw_target"), name)
|
|
138
|
+
object.__setattr__(self, "_pw_wrote", True)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _states(component: Any) -> dict[str, EffectState]:
|
|
142
|
+
states = component.__dict__.get("_pw_effects")
|
|
143
|
+
if states is None:
|
|
144
|
+
states = {name: EffectState() for name in effect_names(type(component))}
|
|
145
|
+
component.__dict__["_pw_effects"] = states
|
|
146
|
+
return states
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _changed(component: Any, deps: dict[str, Any]) -> bool:
|
|
150
|
+
for name, old in deps.items():
|
|
151
|
+
if not _same(old, getattr(component, name, _MISSING)):
|
|
152
|
+
return True
|
|
153
|
+
return False
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def run_effects(component: Any) -> bool:
|
|
157
|
+
"""Run the component's due effects. Returns True if any of them wrote
|
|
158
|
+
state, meaning the host should render again."""
|
|
159
|
+
wrote = False
|
|
160
|
+
for name, state in _states(component).items():
|
|
161
|
+
if state.deps is not None and not _changed(component, state.deps):
|
|
162
|
+
continue
|
|
163
|
+
if state.cleanup is not None:
|
|
164
|
+
cleanup, state.cleanup = state.cleanup, None
|
|
165
|
+
cleanup()
|
|
166
|
+
tracker = _Tracker(component)
|
|
167
|
+
fn = _class_attr(type(component), name)
|
|
168
|
+
result = fn(tracker)
|
|
169
|
+
if inspect.isawaitable(result):
|
|
170
|
+
if inspect.iscoroutine(result):
|
|
171
|
+
result.close()
|
|
172
|
+
raise TypeError(_ASYNC_EFFECT.format(name=name))
|
|
173
|
+
# Snapshot after the run, so an effect that writes one of its own
|
|
174
|
+
# inputs settles instead of re-triggering itself on the next pass.
|
|
175
|
+
state.deps = {
|
|
176
|
+
dep: _snapshot(getattr(component, dep, _MISSING))
|
|
177
|
+
for dep in object.__getattribute__(tracker, "_pw_reads")
|
|
178
|
+
}
|
|
179
|
+
state.cleanup = result if callable(result) else None
|
|
180
|
+
wrote = wrote or object.__getattribute__(tracker, "_pw_wrote")
|
|
181
|
+
return wrote
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def dispose_effects(component: Any) -> None:
|
|
185
|
+
states = component.__dict__.get("_pw_effects")
|
|
186
|
+
if not states:
|
|
187
|
+
return
|
|
188
|
+
for state in states.values():
|
|
189
|
+
if state.cleanup is not None:
|
|
190
|
+
cleanup, state.cleanup = state.cleanup, None
|
|
191
|
+
cleanup()
|
pyweft/events.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"""Event specs (``@keydown.enter.ctrl``) and the event object handlers get.
|
|
2
|
+
|
|
3
|
+
A template's event attribute is kept whole as the event *spec*:
|
|
4
|
+
``keydown.enter`` travels unchanged through the vdom and the patch ops as an
|
|
5
|
+
``events`` key, so two handlers for one DOM event (``@keydown.enter`` and
|
|
6
|
+
``@keydown.esc``) are simply two keys. The host's runtime splits the spec and
|
|
7
|
+
applies the modifiers inside its listener, because ``preventDefault()`` and
|
|
8
|
+
``stopPropagation()`` cannot wait for a round trip to Python. This module only
|
|
9
|
+
validates specs, so a typo is a template error instead of a handler that
|
|
10
|
+
silently never fires.
|
|
11
|
+
|
|
12
|
+
The payload a host sends with an event is a plain dict; see ``Event`` for the
|
|
13
|
+
keys the browser host fills in.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import re
|
|
19
|
+
from typing import Any
|
|
20
|
+
|
|
21
|
+
# Change how the event is delivered; valid on any event.
|
|
22
|
+
EVENT_OPTIONS = frozenset({"prevent", "stop", "self", "once", "capture", "passive"})
|
|
23
|
+
# The handler runs only if these keys are held; ``exact``: and no others.
|
|
24
|
+
SYSTEM_KEYS = frozenset({"ctrl", "alt", "shift", "meta", "exact"})
|
|
25
|
+
# On mouse events, which button; on key events left/right are arrow keys.
|
|
26
|
+
MOUSE_BUTTONS = frozenset({"left", "middle", "right"})
|
|
27
|
+
KEY_EVENTS = frozenset({"keydown", "keyup", "keypress"})
|
|
28
|
+
# Any key, by its KeyboardEvent.key value in kebab-case: enter, a, page-down.
|
|
29
|
+
_KEY_NAME = re.compile(r"^[a-z0-9]+(-[a-z0-9]+)*$")
|
|
30
|
+
|
|
31
|
+
BIND_MODIFIERS = frozenset({"lazy", "trim", "number"})
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def parse_event_spec(spec: str) -> str:
|
|
35
|
+
"""Validate ``click.prevent`` / ``keydown.enter.ctrl`` and return it
|
|
36
|
+
normalised (modifiers lower-cased). Raises ValueError with a readable
|
|
37
|
+
message for an unknown modifier."""
|
|
38
|
+
name, *mods = spec.split(".")
|
|
39
|
+
if not name:
|
|
40
|
+
raise ValueError(f"@{spec}: missing event name")
|
|
41
|
+
mods = [m.lower() for m in mods]
|
|
42
|
+
for mod in mods:
|
|
43
|
+
if mod in EVENT_OPTIONS or mod in SYSTEM_KEYS:
|
|
44
|
+
continue
|
|
45
|
+
if name in KEY_EVENTS:
|
|
46
|
+
if _KEY_NAME.match(mod):
|
|
47
|
+
continue # a key name: enter, esc, a, f1, page-down ...
|
|
48
|
+
elif mod in MOUSE_BUTTONS:
|
|
49
|
+
continue
|
|
50
|
+
hint = (
|
|
51
|
+
"key modifiers such as .enter only work on keydown/keyup"
|
|
52
|
+
if name not in KEY_EVENTS and _KEY_NAME.match(mod)
|
|
53
|
+
else "modifiers are " + ", ".join(sorted(EVENT_OPTIONS | SYSTEM_KEYS))
|
|
54
|
+
)
|
|
55
|
+
raise ValueError(f"@{spec}: unknown modifier .{mod} ({hint})")
|
|
56
|
+
if "passive" in mods and "prevent" in mods:
|
|
57
|
+
raise ValueError(
|
|
58
|
+
f"@{spec}: .passive and .prevent contradict each other (a passive "
|
|
59
|
+
"listener cannot prevent the default action)"
|
|
60
|
+
)
|
|
61
|
+
return ".".join([name, *mods])
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def parse_bind_modifiers(directive: str) -> tuple[str, ...]:
|
|
65
|
+
"""``bind.lazy.trim`` -> ``("lazy", "trim")``."""
|
|
66
|
+
_, *mods = directive.split(".")
|
|
67
|
+
mods = [m.lower() for m in mods]
|
|
68
|
+
unknown = [m for m in mods if m not in BIND_MODIFIERS]
|
|
69
|
+
if unknown:
|
|
70
|
+
raise ValueError(
|
|
71
|
+
f"@{directive}: unknown modifier .{unknown[0]} (@bind takes "
|
|
72
|
+
+ ", ".join(f".{m}" for m in sorted(BIND_MODIFIERS))
|
|
73
|
+
+ ")"
|
|
74
|
+
)
|
|
75
|
+
return tuple(mods)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class Event(dict):
|
|
79
|
+
"""The event a handler receives: a dict, with attribute access too, so
|
|
80
|
+
``event["key"]`` and ``event.key`` both work.
|
|
81
|
+
|
|
82
|
+
Keys the browser host provides, where they apply:
|
|
83
|
+
|
|
84
|
+
- ``type``: the DOM event name (``"click"``, ``"keydown"``)
|
|
85
|
+
- ``value``: the target's value (inputs, selects, textareas)
|
|
86
|
+
- ``checked``: checkboxes and radio buttons
|
|
87
|
+
- ``key``, ``code``, ``repeat``: keyboard events
|
|
88
|
+
- ``ctrlKey``, ``shiftKey``, ``altKey``, ``metaKey``: keyboard and mouse
|
|
89
|
+
- ``clientX``, ``clientY``, ``offsetX``, ``offsetY``, ``button``,
|
|
90
|
+
``buttons``: mouse and pointer events (``deltaX``/``deltaY`` on wheel)
|
|
91
|
+
- ``form``: on ``submit``, the form's fields as ``{name: value}`` (a list
|
|
92
|
+
when several fields share a name)
|
|
93
|
+
"""
|
|
94
|
+
|
|
95
|
+
def __getattr__(self, name: str) -> Any:
|
|
96
|
+
try:
|
|
97
|
+
return self[name]
|
|
98
|
+
except KeyError:
|
|
99
|
+
raise AttributeError(
|
|
100
|
+
f"this {self.get('type', 'event')} event has no {name!r}; "
|
|
101
|
+
f"it has {', '.join(sorted(self)) or 'nothing'}"
|
|
102
|
+
) from None
|