|
| 1 | +from typing import ClassVar |
| 2 | +from uuid import uuid4 |
| 3 | + |
| 4 | +from jinja2_simple_tags import StandaloneTag |
| 5 | + |
| 6 | +from reactpy.pyscript.utils import ( |
| 7 | + pyscript_component_html, |
| 8 | + pyscript_setup_html, |
| 9 | +) |
| 10 | +from reactpy.utils import asgi_component_html |
| 11 | + |
| 12 | + |
| 13 | +class Jinja(StandaloneTag): # type: ignore |
| 14 | + safe_output = True |
| 15 | + tags: ClassVar[set[str]] = {"component", "pyscript_component", "pyscript_setup"} |
| 16 | + |
| 17 | + def render(self, *args: str, **kwargs: str) -> str: |
| 18 | + if self.tag_name == "component": |
| 19 | + return component(*args, **kwargs) |
| 20 | + |
| 21 | + if self.tag_name == "pyscript_component": |
| 22 | + return pyscript_component(*args, **kwargs) |
| 23 | + |
| 24 | + if self.tag_name == "pyscript_setup": |
| 25 | + return pyscript_setup(*args, **kwargs) |
| 26 | + |
| 27 | + raise ValueError(f"Unknown tag: {self.tag_name}") |
| 28 | + |
| 29 | + |
| 30 | +def component(dotted_path: str, **kwargs: str) -> str: |
| 31 | + class_ = kwargs.pop("class", "") |
| 32 | + if kwargs: |
| 33 | + raise ValueError(f"Unexpected keyword arguments: {', '.join(kwargs)}") |
| 34 | + return asgi_component_html( |
| 35 | + element_id=uuid4().hex, class_=class_, component_path=f"{dotted_path}/" |
| 36 | + ) |
| 37 | + |
| 38 | + |
| 39 | +def pyscript_component(*file_paths: str, initial: str = "", root: str = "root") -> str: |
| 40 | + return pyscript_component_html(file_paths=file_paths, initial=initial, root=root) |
| 41 | + |
| 42 | + |
| 43 | +def pyscript_setup(*extra_py: str, extra_js: str = "", config: str = "") -> str: |
| 44 | + return pyscript_setup_html(extra_py=extra_py, extra_js=extra_js, config=config) |
0 commit comments