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/renderer.py ADDED
@@ -0,0 +1,802 @@
1
+ """Walk a parsed template and produce a vdom tree.
2
+
3
+ Handler ids are path strings built from *keys where available*, falling back to
4
+ sibling index. That matters: if an id were purely positional, every handler in
5
+ a list would change identity whenever the list reordered, and the diff would
6
+ churn event bindings on every move. With keyed segments, a row keeps its
7
+ handler id wherever it lands.
8
+
9
+ The handler table is rebuilt from scratch on every render, so ids belonging to
10
+ nodes that no longer exist simply vanish and a late event against a stale id is
11
+ a no-op rather than a crash.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import asyncio
17
+ import dataclasses
18
+ import functools
19
+ import inspect
20
+ import sys
21
+ from functools import partial
22
+ from typing import Any, Awaitable, Callable
23
+
24
+ from .binding import KEEP, bind_kind, convert, declared_type, prop_value
25
+ from .component import Component, component_named, declared_props, is_component_tag
26
+ from .effects import dispose_effects, run_effects
27
+ from .events import Event
28
+ from .expressions import ExpressionError, Scope, eval_expr, render_parts, run_handler
29
+ from .parser import TElement, TemplateError, TFill, TFor, TIf, TSlot, TStatic
30
+ from .store import _renderers as _live_renderers
31
+ from .styles import marker
32
+ from .vdom import Element, Node, Text
33
+
34
+ # Consecutive after-render passes in which effects changed state. Past this,
35
+ # effects are feeding each other forever and it is a bug in the app.
36
+ _MAX_EFFECT_PASSES = 100
37
+
38
+
39
+ class EffectLoopError(RuntimeError):
40
+ pass
41
+
42
+
43
+ # Eager tasks (3.12+) run up to their first real suspension inside the call
44
+ # that started them, so `self.loading = True` before the first await lands in
45
+ # the render that follows the click instead of one loop pass later.
46
+ _EAGER = sys.version_info >= (3, 12)
47
+
48
+
49
+ def _running_loop() -> asyncio.AbstractEventLoop:
50
+ try:
51
+ return asyncio.get_running_loop()
52
+ except RuntimeError:
53
+ raise RuntimeError(
54
+ "async handlers and start_task() need a running asyncio event loop. "
55
+ "The browser always has one; headless, drive the renderer from "
56
+ "inside asyncio.run(...) and await renderer.idle() for the tasks"
57
+ ) from None
58
+
59
+
60
+ async def _await(awaitable: Awaitable) -> Any:
61
+ return await awaitable
62
+
63
+
64
+ def _dispose(component: Any) -> None:
65
+ for task in component.__dict__.pop("_pw_tasks", ()):
66
+ task.cancel()
67
+ component.__dict__.pop("_pw_start", None)
68
+ component.__dict__.pop("_pw_command", None)
69
+ # Effect cleanups first: on_dispose is user code that may not call super().
70
+ dispose_effects(component)
71
+ component.on_dispose()
72
+ # A timer the component forgot to cancel must not keep requesting renders.
73
+ component.__dict__.pop("_pw_invalidate", None)
74
+
75
+
76
+ @functools.lru_cache(maxsize=1024)
77
+ def slot_names(cls: type) -> frozenset[str]:
78
+ """The slots a component's template renders, anywhere in it."""
79
+ found: set[str] = set()
80
+
81
+ def walk(nodes: list[Any]) -> None:
82
+ for node in nodes:
83
+ if isinstance(node, TSlot):
84
+ found.add(node.name)
85
+ if isinstance(node, TIf):
86
+ for _, children in node.branches:
87
+ walk(children)
88
+ elif isinstance(node, (TElement, TFor, TSlot, TFill)):
89
+ walk(node.children)
90
+
91
+ walk(cls.__template__)
92
+ return frozenset(found)
93
+
94
+
95
+ def _is_blank(tnode: Any) -> bool:
96
+ """Whitespace between <Fill>s on one line is not default-slot content."""
97
+ return isinstance(tnode, TStatic) and all(
98
+ kind == "static" and not text.strip() for kind, text in tnode.parts
99
+ )
100
+
101
+
102
+ def _merge_attrs(attrs: dict[str, str], extra: dict[str, str]) -> None:
103
+ """Attributes passed to a component, onto its root element: ``class``
104
+ and ``style`` add to the element's own, anything else replaces it."""
105
+ for name, value in extra.items():
106
+ own = attrs.get(name)
107
+ if name == "class" and own:
108
+ attrs[name] = f"{own} {value}"
109
+ elif name == "style" and own:
110
+ attrs[name] = f"{own.rstrip().rstrip(';')}; {value}"
111
+ else:
112
+ attrs[name] = value
113
+
114
+
115
+ def set_title(text: str) -> None:
116
+ """Set the title of the browser tab, or of the window in a desktop app:
117
+ ``set_title(f"Order #{self.id} - Acme")`` in a page's ``on_init``. It
118
+ applies once the render in progress is on the page, and stays until the
119
+ next call, so each page that wants its own title sets it."""
120
+ for renderer in list(_live_renderers):
121
+ renderer.set_title(str(text))
122
+ if not renderer.rendering:
123
+ # Outside a handler nothing else would render and settle, which
124
+ # is when hosts carry requests out.
125
+ renderer.component.state_has_changed()
126
+
127
+
128
+ def _takes_arg(fn: Callable) -> bool:
129
+ """Does this callable want the event object passed in?"""
130
+ try:
131
+ sig = inspect.signature(fn)
132
+ except (TypeError, ValueError):
133
+ return False
134
+ for param in sig.parameters.values():
135
+ if param.kind is param.VAR_POSITIONAL:
136
+ return True
137
+ if (
138
+ param.kind in (param.POSITIONAL_ONLY, param.POSITIONAL_OR_KEYWORD)
139
+ and param.default is param.empty
140
+ ):
141
+ return True
142
+ return False
143
+
144
+
145
+ class Renderer:
146
+ def __init__(self, component: Any):
147
+ self.component = component
148
+ self.handlers: dict[str, Callable[[dict | None], Any]] = {}
149
+ # Child component instances, keyed by template path so they keep their
150
+ # state across parent re-renders. Rebuilding this every render would
151
+ # reset every child -- the whole point of the cache is that it isn't.
152
+ self.instances: dict[str, Any] = {}
153
+ self._seen: set[str] = set()
154
+ self._effect_passes = 0
155
+ # Set by the host: called when a component's state changed outside
156
+ # dispatch/render/after_render, meaning nobody is about to render. The
157
+ # host should schedule a render (and coalesce repeated calls); see
158
+ # needs_render(). Without it, such changes wait for the next event.
159
+ self.on_invalidate: Callable[[], Any] | None = None
160
+ # Set by the host: called with the exception when a task (an async
161
+ # handler, async on_init, start_task) fails, since no caller is left
162
+ # to raise it to. Unset, it goes to the event loop's exception handler.
163
+ self.on_error: Callable[[BaseException], Any] | None = None
164
+ self._busy = 0
165
+ self.rendering = False # inside render(): a Store change needs no new render
166
+ # ref="..." elements of the latest render, by (owning component, name),
167
+ # and the focus/scroll requests waiting for take_commands().
168
+ self._refs: dict[tuple[int, str], Element] = {}
169
+ self._tree: list[Node] = []
170
+ self._commands: list[tuple[Any, str, str | None]] = []
171
+ self._watch(component)
172
+ _live_renderers.add(self) # a Store's changes and set_title() reach this host
173
+
174
+ def _watch(self, component: Any) -> None:
175
+ component.__dict__["_pw_invalidate"] = self._invalidated
176
+ component.__dict__["_pw_start"] = partial(self._start, component)
177
+ component.__dict__["_pw_command"] = partial(self._command, component)
178
+
179
+ # -------------------------------------------------------------- commands
180
+
181
+ def _command(self, component: Any, op: str, ref: str | None) -> None:
182
+ self._commands.append((component, op, ref))
183
+
184
+ def set_title(self, text: str) -> None:
185
+ """See the module-level set_title()."""
186
+ self._commands.append((None, "set_title", text))
187
+
188
+ def take_commands(self) -> list[dict[str, Any]]:
189
+ """Requests such as ``focus("email")`` made since the last call, as
190
+ JSON-ready dicts against the latest render: ``{"op": "focus",
191
+ "path": [0, 2]}`` (paths as in patch ops), or ``{"op":
192
+ "restore_focus"}`` for ones without an element.
193
+
194
+ Hosts call this once the render's patches are applied and
195
+ ``after_render`` has settled, and carry them out in order: the
196
+ element a request names may only exist after that render. A
197
+ request whose ``ref`` isn't on the page is dropped, like an event
198
+ for a vanished handler."""
199
+ out: list[dict[str, Any]] = []
200
+ for component, op, ref in self._commands:
201
+ if op == "set_title":
202
+ out.append({"op": op, "text": ref})
203
+ continue
204
+ if ref is None:
205
+ out.append({"op": op})
206
+ continue
207
+ element = self._refs.get((id(component), ref))
208
+ path = self._path_to(element) if element is not None else None
209
+ if path is not None:
210
+ out.append({"op": op, "path": path})
211
+ self._commands = []
212
+ return out
213
+
214
+ def _path_to(self, target: Element) -> list[int] | None:
215
+ stack: list[tuple[list[Node], list[int]]] = [(self._tree, [])]
216
+ while stack:
217
+ nodes, prefix = stack.pop()
218
+ for index, node in enumerate(nodes):
219
+ if node is target:
220
+ return prefix + [index]
221
+ if isinstance(node, Element) and node.children:
222
+ stack.append((node.children, prefix + [index]))
223
+ return None
224
+
225
+ def init_root(self) -> None:
226
+ """Run the root component's ``on_init`` (as a task if it is async).
227
+ Hosts call this once, before the first render; child components get
228
+ theirs from the renderer when they first appear."""
229
+ self._hook(self.component, self.component.on_init())
230
+
231
+ # ----------------------------------------------------------------- tasks
232
+
233
+ def _hook(self, component: Any, result: Any) -> None:
234
+ if inspect.isawaitable(result):
235
+ self._start(component, result)
236
+
237
+ def _start(self, component: Any, awaitable: Awaitable) -> asyncio.Task:
238
+ """Run ``awaitable`` as a task owned by ``component``: cancelled when
239
+ the component is disposed, and re-rendering it when it finishes."""
240
+ try:
241
+ loop = _running_loop()
242
+ except RuntimeError:
243
+ if inspect.iscoroutine(awaitable):
244
+ awaitable.close() # no "never awaited" warning on top
245
+ raise
246
+ coro = awaitable if inspect.iscoroutine(awaitable) else _await(awaitable)
247
+ if _EAGER and loop.is_running():
248
+ task = asyncio.Task(coro, loop=loop, eager_start=True)
249
+ else:
250
+ task = loop.create_task(coro)
251
+ # The first step runs on the loop's next pass; render after it.
252
+ loop.call_soon(component.state_has_changed)
253
+ if task.done():
254
+ # Finished without suspending, inside the call that started it, so
255
+ # the render the host does after that call already shows it.
256
+ self._finished(component, task, render=False)
257
+ else:
258
+ component.__dict__.setdefault("_pw_tasks", set()).add(task)
259
+ task.add_done_callback(partial(self._finished, component))
260
+ return task
261
+
262
+ def _finished(self, component: Any, task: asyncio.Task, render: bool = True) -> None:
263
+ component.__dict__.get("_pw_tasks", set()).discard(task)
264
+ if task.cancelled():
265
+ return
266
+ exc = task.exception()
267
+ if exc is not None:
268
+ if self.on_error is not None:
269
+ self.on_error(exc)
270
+ else:
271
+ task.get_loop().call_exception_handler(
272
+ {"message": "exception in a PyWeft task", "exception": exc, "task": task}
273
+ )
274
+ if render:
275
+ # Whatever the task changed, even if it then failed.
276
+ component.state_has_changed()
277
+
278
+ def pending_tasks(self) -> list[asyncio.Task]:
279
+ """Unfinished tasks of every live component."""
280
+ return [
281
+ task
282
+ for c in (self.component, *self.instances.values())
283
+ for task in c.__dict__.get("_pw_tasks", ())
284
+ ]
285
+
286
+ async def idle(self) -> None:
287
+ """Wait until every live component's tasks have finished, including
288
+ tasks started by those tasks. For headless tests: dispatch, await
289
+ this, then render to see the finished state."""
290
+ while pending := self.pending_tasks():
291
+ await asyncio.wait(pending)
292
+ await asyncio.sleep(0) # let the done callbacks run
293
+
294
+ def _invalidated(self) -> None:
295
+ # Inside a host-driven cycle the host renders afterwards anyway.
296
+ if self._busy == 0 and self.on_invalidate is not None:
297
+ self.on_invalidate()
298
+
299
+ def needs_render(self) -> bool:
300
+ """True if any live component changed state since the last render."""
301
+ return any(
302
+ getattr(c, "_dirty", False)
303
+ for c in (self.component, *self.instances.values())
304
+ )
305
+
306
+ # ---------------------------------------------------------------- render
307
+
308
+ def render(self) -> list[Node]:
309
+ self._busy += 1
310
+ self.rendering = True
311
+ previous_handlers, previous_refs = self.handlers, self._refs
312
+ try:
313
+ self.handlers = {}
314
+ self._refs = {}
315
+ self._seen = set()
316
+ out: list[Node] = []
317
+ try:
318
+ self._emit(self.component.__template__, Scope(self.component), [], out)
319
+ except BaseException:
320
+ # The page still shows the last good render; keep its handlers
321
+ # working (matters most when a hot reload's render fails).
322
+ self.handlers, self._refs = previous_handlers, previous_refs
323
+ raise
324
+ self._tree = out
325
+ for inst_id in [i for i in self.instances if i not in self._seen]:
326
+ _dispose(self.instances.pop(inst_id))
327
+ self.component._dirty = False
328
+ for instance in self.instances.values():
329
+ instance._dirty = False
330
+ return out
331
+ finally:
332
+ self._busy -= 1
333
+ self.rendering = False
334
+
335
+ def after_render(self) -> bool:
336
+ """Call once the latest render's patches have been applied.
337
+
338
+ Runs due ``@effect`` methods and ``on_after_render`` on every live
339
+ component, children before the root. Returns True when that changed
340
+ state, meaning the host should render, diff and apply again (then call
341
+ this again).
342
+ """
343
+ rerender = False
344
+ self._busy += 1
345
+ try:
346
+ for component in [*self.instances.values(), self.component]:
347
+ first = not getattr(component, "_rendered_once", False)
348
+ component._rendered_once = True
349
+ wrote = run_effects(component)
350
+ self._hook(component, component.on_after_render(first))
351
+ if wrote or getattr(component, "_dirty", False):
352
+ rerender = True
353
+ finally:
354
+ self._busy -= 1
355
+
356
+ if not rerender:
357
+ self._effect_passes = 0
358
+ return False
359
+ self._effect_passes += 1
360
+ if self._effect_passes > _MAX_EFFECT_PASSES:
361
+ self._effect_passes = 0
362
+ raise EffectLoopError(
363
+ f"effects changed state on {_MAX_EFFECT_PASSES} renders in a row; "
364
+ "an effect is probably writing state that another effect reads"
365
+ )
366
+ return True
367
+
368
+ def _emit(
369
+ self,
370
+ tnodes: list[Any],
371
+ scope: Scope,
372
+ path: list[str],
373
+ out: list[Node],
374
+ key: Any = None,
375
+ ) -> None:
376
+ for tnode in tnodes:
377
+ if isinstance(tnode, TStatic):
378
+ out.append(Text(render_parts(tnode.parts, scope)))
379
+
380
+ elif isinstance(tnode, TElement):
381
+ node_key = key
382
+ if node_key is None and tnode.key_expr:
383
+ node_key = eval_expr(tnode.key_expr, scope)
384
+ segment = (
385
+ f"k:{node_key}" if node_key is not None else f"i:{len(out)}"
386
+ )
387
+ comp_cls = self._resolve_component(scope, tnode.tag)
388
+ if tnode.tag == "Dynamic":
389
+ self._dynamic(tnode, scope, path + [segment], out, node_key)
390
+ elif comp_cls is not None:
391
+ self._component(
392
+ comp_cls, tnode, scope, path + [segment], out, node_key
393
+ )
394
+ else:
395
+ out.append(
396
+ self._element(tnode, scope, path + [segment], node_key)
397
+ )
398
+
399
+ elif isinstance(tnode, TIf):
400
+ for cond, children in tnode.branches:
401
+ if cond is None or eval_expr(cond, scope):
402
+ self._emit(children, scope, path, out, key)
403
+ break
404
+
405
+ elif isinstance(tnode, TFor):
406
+ self._loop(tnode, scope, path, out)
407
+
408
+ elif isinstance(tnode, TSlot):
409
+ self._slot(tnode, scope, path, out, key)
410
+
411
+ elif isinstance(tnode, TFill):
412
+ raise TemplateError(
413
+ f'<Fill name="{tnode.name}"> must be directly inside a component tag'
414
+ )
415
+
416
+ else: # pragma: no cover - defensive
417
+ raise TemplateError(f"unknown template node {tnode!r}")
418
+
419
+ def _loop(
420
+ self, tnode: TFor, scope: Scope, path: list[str], out: list[Node]
421
+ ) -> None:
422
+ items = eval_expr(tnode.iter_src, scope)
423
+ if items is None:
424
+ return
425
+ for index, item in enumerate(items):
426
+ child_scope = scope.child(**{tnode.var: item})
427
+ if tnode.index_var:
428
+ child_scope = child_scope.child(**{tnode.index_var: index})
429
+ item_key = (
430
+ eval_expr(tnode.key_expr, child_scope) if tnode.key_expr else None
431
+ )
432
+ before = len(out)
433
+ self._emit(tnode.children, child_scope, path, out, item_key)
434
+ if item_key is not None:
435
+ elements = [n for n in out[before:] if isinstance(n, Element)]
436
+ if len(elements) != 1:
437
+ raise TemplateError(
438
+ "a keyed <For> body must produce exactly one element "
439
+ f"per item, got {len(elements)}"
440
+ )
441
+
442
+ # ------------------------------------------------------------ components
443
+
444
+ @staticmethod
445
+ def _resolve_component(scope: Scope, tag: str) -> type | None:
446
+ """A capitalised tag (or dotted tag ending in one, ``widgets.Row``)
447
+ naming an entry in the owner's registry is a child component; anything
448
+ else is a plain element."""
449
+ if not is_component_tag(tag):
450
+ return None
451
+ owner = type(scope.component)
452
+ registry = getattr(owner, "components", None)
453
+ found = registry.get(tag) if registry else None
454
+ # Classes built with component_from_source (no loader) still find
455
+ # components they imported.
456
+ return found if found is not None else component_named(owner, tag)
457
+
458
+ def _dynamic(
459
+ self, tnode: TElement, scope: Scope, path: list[str], out: list[Node], key: Any
460
+ ) -> None:
461
+ """``<Dynamic :is="cls" :props="mapping" />``: the component comes from
462
+ an expression, so what renders here can change between renders. A
463
+ different class disposes the old instance and creates a new one, as
464
+ for any child; ``None`` renders nothing. ``:props`` passes props by
465
+ name, for when which ones apply depends on the class."""
466
+ expr_attrs = dict(tnode.expr_attrs)
467
+ cls = eval_expr(expr_attrs.pop("is"), scope)
468
+ extra = eval_expr(expr_attrs.pop("props"), scope) if "props" in expr_attrs else None
469
+ if cls is None:
470
+ return
471
+ if not (isinstance(cls, type) and issubclass(cls, Component)):
472
+ raise TemplateError(
473
+ f'<Dynamic :is="{tnode.expr_attrs["is"]}">: expected a component '
474
+ f"class, got {cls!r}"
475
+ )
476
+ named = dataclasses.replace(tnode, tag=cls.__name__, expr_attrs=expr_attrs)
477
+ self._component(cls, named, scope, path, out, key, dict(extra or {}))
478
+
479
+ def _component(
480
+ self,
481
+ cls: type,
482
+ tnode: TElement,
483
+ scope: Scope,
484
+ path: list[str],
485
+ out: list[Node],
486
+ key: Any,
487
+ extra: dict[str, Any] | None = None,
488
+ ) -> None:
489
+ if tnode.bind_mods:
490
+ raise TemplateError(
491
+ f"<{tnode.tag}>: @bind on a component takes no modifiers"
492
+ )
493
+
494
+ # Props flow down on every render: interpolated attrs as strings,
495
+ # :attrs as evaluated Python values, @events as on_<event> callbacks
496
+ # bound to the *parent's* scope (that is what emit() calls). An
497
+ # attribute the child does not declare is not a prop: it passes
498
+ # through to the child's root element (class, style, id, aria-*).
499
+ declared = declared_props(cls)
500
+ props: dict[str, Any] = {}
501
+ passthrough: dict[str, str] = {}
502
+ # A <Dynamic :props> mapping first, so attributes written out win.
503
+ for name, value in (extra or {}).items():
504
+ if name in declared:
505
+ props[name] = value
506
+ elif value is not None and value is not False:
507
+ passthrough[name] = "" if value is True else str(value)
508
+ for name, parts in tnode.attrs.items():
509
+ value = render_parts(parts, scope)
510
+ if name in declared:
511
+ try:
512
+ props[name] = prop_value(cls, name, value)
513
+ except ValueError as exc:
514
+ raise TemplateError(
515
+ f'<{tnode.tag} {name}="{value}">: {cls.__name__}.{name} {exc}'
516
+ ) from None
517
+ else:
518
+ passthrough[name] = value
519
+ for name, expr in tnode.expr_attrs.items():
520
+ value = eval_expr(expr, scope)
521
+ if name in declared:
522
+ props[name] = value
523
+ elif value is not None and value is not False:
524
+ passthrough[name] = "" if value is True else str(value)
525
+ for event, expr in tnode.events.items():
526
+ if "." in event:
527
+ raise TemplateError(
528
+ f"<{tnode.tag} @{event}>: modifiers apply to page events, "
529
+ "not to a component's own events"
530
+ )
531
+ props[f"on_{event}"] = self._make_handler(expr, scope)
532
+ if tnode.bind:
533
+ self._bind_component(tnode.bind, scope, props)
534
+ slots = self._collect_slots(cls, tnode, scope)
535
+
536
+ inst_id = "/".join(path)
537
+ instance = self.instances.get(inst_id)
538
+ if type(instance) is not cls:
539
+ if instance is not None:
540
+ _dispose(instance)
541
+ instance = cls(**props)
542
+ self._watch(instance)
543
+ self._hook(instance, instance.on_init())
544
+ self.instances[inst_id] = instance
545
+ else:
546
+ for name, value in props.items():
547
+ setattr(instance, name, value)
548
+ self._seen.add(inst_id)
549
+ # Replaced every render: what the parent passes this time is what the
550
+ # child's <Slot>s show (and what has_slot() reports).
551
+ instance.__dict__["_pw_slots"] = slots
552
+
553
+ # ref="..." on a component tag names the component's root element in
554
+ # the *parent's* refs; focus() on it then moves into the component.
555
+ ref = passthrough.pop("ref", None)
556
+
557
+ before = len(out)
558
+ self._emit(cls.__template__, Scope(instance), path, out, key)
559
+ roots = [node for node in out[before:] if isinstance(node, Element)]
560
+ if ref and roots:
561
+ self._refs[(id(scope.component), ref)] = roots[0]
562
+ # The parent's scoped styles may target the child's root element(s),
563
+ # so those carry the parent's marker as well as the child's own.
564
+ parent_scope = getattr(type(scope.component), "__scope__", None)
565
+ if parent_scope:
566
+ for node in roots:
567
+ node.attrs.setdefault(marker(parent_scope), "")
568
+ if passthrough:
569
+ if len(roots) != 1:
570
+ raise TemplateError(
571
+ f"<{tnode.tag}> renders {len(roots)} root elements, so "
572
+ f"{', '.join(sorted(passthrough))} has nowhere to go; give "
573
+ f"{cls.__name__} a single root element or declare "
574
+ "the attribute as a field"
575
+ )
576
+ _merge_attrs(roots[0].attrs, passthrough)
577
+
578
+ def _bind_component(self, field: str, scope: Scope, props: dict[str, Any]) -> None:
579
+ """``<TextField @bind="email" />``: the child gets the field as its
580
+ ``value`` prop and reports changes with ``emit("update", new)``. A
581
+ parent's own ``@update`` handler runs after the field is set."""
582
+ parent = scope.component
583
+ own = props.get("on_update")
584
+ props["value"] = getattr(parent, field, None)
585
+
586
+ def update(new: Any = None) -> Any:
587
+ setattr(parent, field, new)
588
+ if own is not None:
589
+ return own(new)
590
+ parent.state_has_changed()
591
+ return None
592
+
593
+ props["on_update"] = update
594
+
595
+ @staticmethod
596
+ def _collect_slots(
597
+ cls: type, tnode: TElement, scope: Scope
598
+ ) -> dict[str, tuple[list[Any], Scope]]:
599
+ """Content between a component's tags, by slot name. It is rendered
600
+ later, inside the child, but in *this* scope: the parent's state,
601
+ handlers and loop variables."""
602
+ fills: dict[str, list[Any]] = {}
603
+ loose: list[Any] = []
604
+ for child in tnode.children:
605
+ if isinstance(child, TFill):
606
+ if child.name in fills:
607
+ raise TemplateError(
608
+ f'<{tnode.tag}> has two <Fill name="{child.name}">'
609
+ )
610
+ fills[child.name] = child.children
611
+ elif not _is_blank(child):
612
+ loose.append(child)
613
+ if loose:
614
+ if "default" in fills:
615
+ raise TemplateError(
616
+ f'<{tnode.tag}> has both content outside <Fill> and a <Fill '
617
+ 'name="default">; use one or the other'
618
+ )
619
+ fills["default"] = loose
620
+ accepted = slot_names(cls)
621
+ for name in fills:
622
+ if name not in accepted:
623
+ where = (
624
+ f"it has {', '.join(sorted(accepted))}" if accepted else "it has no <Slot>"
625
+ )
626
+ what = "content between its tags" if name == "default" else f'<Fill name="{name}">'
627
+ raise TemplateError(
628
+ f"<{tnode.tag}> was given {what}, but {cls.__name__} would "
629
+ f"never show it: {where}"
630
+ )
631
+ return {name: (nodes, scope) for name, nodes in fills.items()}
632
+
633
+ def _slot(
634
+ self, tnode: TSlot, scope: Scope, path: list[str], out: list[Node], key: Any
635
+ ) -> None:
636
+ provided = scope.component.__dict__.get("_pw_slots", {}).get(tnode.name)
637
+ if provided is None:
638
+ # Nothing passed: the slot's own children are the fallback.
639
+ self._emit(tnode.children, scope, path, out, key)
640
+ return
641
+ nodes, fill_scope = provided
642
+ slot_props = {
643
+ name: render_parts(parts, scope) for name, parts in tnode.attrs.items()
644
+ }
645
+ for name, expr in tnode.expr_attrs.items():
646
+ slot_props[name] = eval_expr(expr, scope)
647
+ if slot_props:
648
+ fill_scope = fill_scope.child(**slot_props)
649
+ self._emit(nodes, fill_scope, path, out, key)
650
+
651
+ # -------------------------------------------------------------- elements
652
+
653
+ def _element(
654
+ self, tnode: TElement, scope: Scope, path: list[str], key: Any
655
+ ) -> Element:
656
+ attrs = {
657
+ name: render_parts(parts, scope) for name, parts in tnode.attrs.items()
658
+ }
659
+ # :attr="expr" on a plain element: None/False drops the attribute and
660
+ # True keeps it valueless, so :disabled="busy" works like Vue's.
661
+ for name, expr in tnode.expr_attrs.items():
662
+ value = eval_expr(expr, scope)
663
+ if value is None or value is False:
664
+ continue
665
+ attrs[name] = "" if value is True else str(value)
666
+ # Scoped <style> support: mark the element as belonging to its
667
+ # component so the rewritten selectors can find it.
668
+ scope_id = getattr(type(scope.component), "__scope__", None)
669
+ if scope_id:
670
+ attrs[marker(scope_id)] = ""
671
+ events: dict[str, str] = {}
672
+ prefix = "/".join(path)
673
+
674
+ for spec, expr in tnode.events.items():
675
+ if not expr.strip():
676
+ # @submit.prevent="": modifiers only. The host applies them;
677
+ # an empty id means there is nothing to call.
678
+ events[spec] = ""
679
+ continue
680
+ handler_id = f"{prefix}#{spec}"
681
+ self.handlers[handler_id] = self._make_handler(expr, scope)
682
+ events[spec] = handler_id
683
+
684
+ if tnode.bind:
685
+ self._bind(tnode, scope, attrs, events, prefix)
686
+
687
+ ref = attrs.pop("ref", None)
688
+
689
+ children: list[Node] = []
690
+ self._emit(tnode.children, scope, path, children)
691
+
692
+ element = Element(
693
+ tag=tnode.tag, attrs=attrs, events=events, children=children, key=key
694
+ )
695
+ if ref:
696
+ # The component that wrote the template owns the name, so a ref
697
+ # in slot content belongs to the parent that passed it.
698
+ self._refs[(id(scope.component), ref)] = element
699
+ return element
700
+
701
+ # -------------------------------------------------------------- handlers
702
+
703
+ def _make_handler(self, expr: str, scope: Scope) -> Callable:
704
+ # The owning component, not the root: a bare name in a child template
705
+ # must resolve to the child's method, and its state_has_changed must
706
+ # mark the child dirty.
707
+ component = scope.component
708
+ is_name = expr.isidentifier()
709
+
710
+ def handler(event: Any = None) -> Any:
711
+ # "no event" defaults to {}, but a falsy payload (0, "", False)
712
+ # from an emit must pass through untouched.
713
+ payload = {} if event is None else event
714
+ if is_name:
715
+ fn = getattr(component, expr, None)
716
+ if not callable(fn):
717
+ raise ExpressionError(f"no handler named {expr!r}")
718
+ result = fn(payload) if _takes_arg(fn) else fn()
719
+ else:
720
+ # Not a bare name: an expression such as @click="remove(item)",
721
+ # or inline statements such as @click="count += 1".
722
+ result = run_handler(expr, scope.child(event=payload))
723
+ if inspect.isawaitable(result):
724
+ # An async handler: runs on as a task, which renders again
725
+ # when it finishes.
726
+ result = self._start(component, result)
727
+ component.state_has_changed()
728
+ return result
729
+
730
+ return handler
731
+
732
+ def _bind(
733
+ self,
734
+ tnode: TElement,
735
+ scope: Scope,
736
+ attrs: dict[str, str],
737
+ events: dict[str, str],
738
+ prefix: str,
739
+ ) -> None:
740
+ field, mods = tnode.bind, tnode.bind_mods
741
+ kind = bind_kind(tnode.tag, attrs)
742
+ current = getattr(scope.component, field, None)
743
+ if kind == "checkbox":
744
+ if current:
745
+ attrs["checked"] = ""
746
+ elif kind == "radio":
747
+ if current is not None and str(current) == attrs.get("value"):
748
+ attrs["checked"] = ""
749
+ else:
750
+ attrs.setdefault("value", "" if current is None else str(current))
751
+
752
+ # Checkboxes and radios report a choice on change; .lazy waits for
753
+ # change (focus leaving the box) instead of every keystroke.
754
+ spec = "change" if kind != "value" or "lazy" in mods else "input"
755
+ bind_handler = self._make_bind_handler(field, scope, kind, mods)
756
+ handler_id = events.get(spec)
757
+ own = self.handlers.get(handler_id) if handler_id else None
758
+ if own is None:
759
+ handler_id = f"{prefix}#bind"
760
+ self.handlers[handler_id] = bind_handler
761
+ else:
762
+ # @bind and the element's own @input: update the field first, so
763
+ # the handler already sees the new value.
764
+ def both(event: Any = None) -> Any:
765
+ bind_handler(event)
766
+ return own(event)
767
+
768
+ self.handlers[handler_id] = both
769
+ events[spec] = handler_id
770
+
771
+ def _make_bind_handler(
772
+ self, field: str, scope: Scope, kind: str, mods: tuple[str, ...]
773
+ ) -> Callable:
774
+ component = scope.component
775
+ target, allows_none = declared_type(type(component), field)
776
+
777
+ def handler(event: dict | None = None) -> None:
778
+ event = event or {}
779
+ if kind == "checkbox":
780
+ value: Any = bool(event.get("checked"))
781
+ else:
782
+ text = str(event.get("value", ""))
783
+ if "trim" in mods:
784
+ text = text.strip()
785
+ value = convert(text, target, allows_none, "number" in mods)
786
+ if value is not KEEP:
787
+ setattr(component, field, value)
788
+ component.state_has_changed()
789
+
790
+ return handler
791
+
792
+ def dispatch(self, handler_id: str, event: dict | None = None) -> Any:
793
+ handler = self.handlers.get(handler_id)
794
+ if handler is None:
795
+ return None # stale id from a since-replaced render
796
+ if type(event) is dict:
797
+ event = Event(event) # event.key as well as event["key"]
798
+ self._busy += 1
799
+ try:
800
+ return handler(event)
801
+ finally:
802
+ self._busy -= 1