pihanga-remote 0.1.0__tar.gz
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.
- pihanga_remote-0.1.0/PKG-INFO +50 -0
- pihanga_remote-0.1.0/README.md +26 -0
- pihanga_remote-0.1.0/pihanga_remote/__init__.py +16 -0
- pihanga_remote-0.1.0/pihanga_remote/card.py +186 -0
- pihanga_remote-0.1.0/pihanga_remote/cards/__init__.py +0 -0
- pihanga_remote-0.1.0/pihanga_remote/cards/acme.py +45 -0
- pihanga_remote-0.1.0/pihanga_remote/cards/shadcn.py +2131 -0
- pihanga_remote-0.1.0/pihanga_remote/codegen.py +292 -0
- pihanga_remote-0.1.0/pihanga_remote/options.py +130 -0
- pihanga_remote-0.1.0/pihanga_remote/server.py +184 -0
- pihanga_remote-0.1.0/pihanga_remote/session.py +300 -0
- pihanga_remote-0.1.0/pihanga_remote/static/assets/index-BdVsT3Pe.css +2 -0
- pihanga_remote-0.1.0/pihanga_remote/static/assets/index-DFqJX7SU.js +201 -0
- pihanga_remote-0.1.0/pihanga_remote/static/index.html +13 -0
- pihanga_remote-0.1.0/pihanga_remote/static_cdn/index.html +39 -0
- pihanga_remote-0.1.0/pihanga_remote/static_cdn/pkg/@pihanga2/runtime@0.1.0/chunks/client-CLBj9RPT.js +10 -0
- pihanga_remote-0.1.0/pihanga_remote/static_cdn/pkg/@pihanga2/runtime@0.1.0/chunks/jsx-runtime-B2VO6FEe.js +2 -0
- pihanga_remote-0.1.0/pihanga_remote/static_cdn/pkg/@pihanga2/runtime@0.1.0/chunks/react-dom-DAOS2QVz.js +2 -0
- pihanga_remote-0.1.0/pihanga_remote/static_cdn/pkg/@pihanga2/runtime@0.1.0/chunks/react-mgxO_Kgs.js +2 -0
- pihanga_remote-0.1.0/pihanga_remote/static_cdn/pkg/@pihanga2/runtime@0.1.0/chunks/rolldown-runtime-CbXtAM7H.js +1 -0
- pihanga_remote-0.1.0/pihanga_remote/static_cdn/pkg/@pihanga2/runtime@0.1.0/core.js +2 -0
- pihanga_remote-0.1.0/pihanga_remote/static_cdn/pkg/@pihanga2/runtime@0.1.0/react-dom-client.js +2 -0
- pihanga_remote-0.1.0/pihanga_remote/static_cdn/pkg/@pihanga2/runtime@0.1.0/react-dom.js +2 -0
- pihanga_remote-0.1.0/pihanga_remote/static_cdn/pkg/@pihanga2/runtime@0.1.0/react-jsx-runtime.js +2 -0
- pihanga_remote-0.1.0/pihanga_remote/static_cdn/pkg/@pihanga2/runtime@0.1.0/react.js +2 -0
- pihanga_remote-0.1.0/pihanga_remote/static_cdn/pkg/@pihanga2/shadcn@0.2.23/pihanga-shadcn.css +3 -0
- pihanga_remote-0.1.0/pihanga_remote/static_cdn/pkg/@pihanga2/shadcn@0.2.23/pihanga-shadcn.js +197 -0
- pihanga_remote-0.1.0/pihanga_remote/static_cdn/pkg/acme-cards@0.1.0/acme-cards.js +44 -0
- pihanga_remote-0.1.0/pihanga_remote/static_cdn/pkg/acme-cards@0.1.0/cards.schema.json +31 -0
- pihanga_remote-0.1.0/pyproject.toml +43 -0
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pihanga-remote
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Drive a Pihanga card UI (prebuilt generic bundle) from Python via JSON-Patch over WebSocket
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Keywords: pihanga,ui,fastapi,websocket,json-patch,shadcn,server-driven-ui
|
|
7
|
+
Author: Max Ott
|
|
8
|
+
Author-email: max.ott@data61.csiro.au
|
|
9
|
+
Requires-Python: >=3.10,<4.0
|
|
10
|
+
Classifier: Development Status :: 3 - Alpha
|
|
11
|
+
Classifier: Framework :: FastAPI
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Topic :: Software Development :: User Interfaces
|
|
15
|
+
Requires-Dist: fastapi (>=0.110)
|
|
16
|
+
Requires-Dist: jsonpatch (>=1.33)
|
|
17
|
+
Requires-Dist: pydantic (>=2.6)
|
|
18
|
+
Requires-Dist: uvicorn[standard] (>=0.29)
|
|
19
|
+
Project-URL: Documentation, https://github.com/ivcap-works/pihanga-remote#readme
|
|
20
|
+
Project-URL: Homepage, https://github.com/ivcap-works/pihanga-remote
|
|
21
|
+
Project-URL: Repository, https://github.com/ivcap-works/pihanga-remote
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
|
|
24
|
+
# pihanga-remote
|
|
25
|
+
|
|
26
|
+
Drive a [Pihanga](https://github.com/ivcap-works/pihanga-core) card UI from Python.
|
|
27
|
+
|
|
28
|
+
The package contains:
|
|
29
|
+
- a prebuilt browser bundle: the lean runtime plus the `@pihanga2/shadcn` cards;
|
|
30
|
+
- typed pydantic classes for every card (`pihanga_remote.cards.shadcn`);
|
|
31
|
+
- a FastAPI server that serves the bundle and keeps each browser tab in sync over a WebSocket, using JSON Patch.
|
|
32
|
+
|
|
33
|
+
You don't need any JavaScript tooling to use it.
|
|
34
|
+
|
|
35
|
+
```python
|
|
36
|
+
from pihanga_remote import create_app
|
|
37
|
+
from pihanga_remote.cards.shadcn import SdFramework, Stack, Typography, Button
|
|
38
|
+
|
|
39
|
+
def build(s): # called once per browser tab
|
|
40
|
+
count = Typography(text="0", level="h2")
|
|
41
|
+
def inc(ev):
|
|
42
|
+
count.text = str(int(count.text) + 1) # mutate the card; the browser is patched
|
|
43
|
+
s.window(SdFramework(page=Stack(direction="column",
|
|
44
|
+
content=[count, Button(label="+", on_clicked=inc)])))
|
|
45
|
+
|
|
46
|
+
app = create_app(build) # python -m uvicorn mymodule:app
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
See the project README for the protocol, the design, and how to build an app.
|
|
50
|
+
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
# pihanga-remote
|
|
2
|
+
|
|
3
|
+
Drive a [Pihanga](https://github.com/ivcap-works/pihanga-core) card UI from Python.
|
|
4
|
+
|
|
5
|
+
The package contains:
|
|
6
|
+
- a prebuilt browser bundle: the lean runtime plus the `@pihanga2/shadcn` cards;
|
|
7
|
+
- typed pydantic classes for every card (`pihanga_remote.cards.shadcn`);
|
|
8
|
+
- a FastAPI server that serves the bundle and keeps each browser tab in sync over a WebSocket, using JSON Patch.
|
|
9
|
+
|
|
10
|
+
You don't need any JavaScript tooling to use it.
|
|
11
|
+
|
|
12
|
+
```python
|
|
13
|
+
from pihanga_remote import create_app
|
|
14
|
+
from pihanga_remote.cards.shadcn import SdFramework, Stack, Typography, Button
|
|
15
|
+
|
|
16
|
+
def build(s): # called once per browser tab
|
|
17
|
+
count = Typography(text="0", level="h2")
|
|
18
|
+
def inc(ev):
|
|
19
|
+
count.text = str(int(count.text) + 1) # mutate the card; the browser is patched
|
|
20
|
+
s.window(SdFramework(page=Stack(direction="column",
|
|
21
|
+
content=[count, Button(label="+", on_clicked=inc)])))
|
|
22
|
+
|
|
23
|
+
app = create_app(build) # python -m uvicorn mymodule:app
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
See the project README for the protocol, the design, and how to build an app.
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"""pihanga-remote: drive a Pihanga card UI from Python.
|
|
2
|
+
|
|
3
|
+
The browser runs a prebuilt generic bundle (lean runtime + card library). The
|
|
4
|
+
UI is a flat map ``{cardName: declaration}`` owned by this backend; changes are
|
|
5
|
+
sent as JSON-Patch, events come back over the same WebSocket.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from .card import CardModel, CardRef, EventContext, GenericCard, PropModel
|
|
9
|
+
from .options import CDN_BUNDLE, SINGLE_BUNDLE, AppOptions
|
|
10
|
+
from .server import DEFAULT_BUNDLE, Hub, create_app, get_hub
|
|
11
|
+
from .session import Session
|
|
12
|
+
|
|
13
|
+
__all__ = [
|
|
14
|
+
"AppOptions", "CardModel", "CardRef", "EventContext", "GenericCard", "Hub", "PropModel", "Session",
|
|
15
|
+
"create_app", "get_hub", "CDN_BUNDLE", "DEFAULT_BUNDLE", "SINGLE_BUNDLE",
|
|
16
|
+
]
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
"""Card models ("proxies") and the flattening of a card tree into the wire format.
|
|
2
|
+
|
|
3
|
+
A card in Python is a pydantic model. Assigning to its fields is all an app
|
|
4
|
+
does; the session later dumps the tree, diffs it against what the browser has
|
|
5
|
+
and sends JSON-Patch ops.
|
|
6
|
+
|
|
7
|
+
Child cards can be referenced *by name* (a ``str``) or *by instance*. Instances
|
|
8
|
+
nested anywhere inside another card are given a deterministic name
|
|
9
|
+
(``parent/prop`` or ``parent/prop/<i>``, the same scheme @pihanga2/core uses
|
|
10
|
+
for inline card declarations) and sent as separate top-level entries. This is
|
|
11
|
+
how "anonymous" cards are resolved in the backend: the browser only ever sees a
|
|
12
|
+
flat ``{cardName: declaration}`` map.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import datetime as _dt
|
|
18
|
+
import enum
|
|
19
|
+
from dataclasses import dataclass, field
|
|
20
|
+
from typing import TYPE_CHECKING, Any, Callable, ClassVar, Optional, Union
|
|
21
|
+
|
|
22
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
23
|
+
|
|
24
|
+
if TYPE_CHECKING: # pragma: no cover
|
|
25
|
+
from .session import Session
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class PropModel(BaseModel):
|
|
29
|
+
"""Base for nested prop structures and event payloads generated from the
|
|
30
|
+
card library's JSON Schema. Unknown keys are kept (``extra="allow"``) so a
|
|
31
|
+
newer bundle never breaks an older backend."""
|
|
32
|
+
|
|
33
|
+
model_config = ConfigDict(
|
|
34
|
+
extra="allow",
|
|
35
|
+
populate_by_name=True,
|
|
36
|
+
validate_assignment=True,
|
|
37
|
+
arbitrary_types_allowed=True,
|
|
38
|
+
protected_namespaces=(),
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass
|
|
43
|
+
class EventContext:
|
|
44
|
+
"""Second (optional) argument passed to event handlers."""
|
|
45
|
+
|
|
46
|
+
session: "Session"
|
|
47
|
+
card: "CardModel"
|
|
48
|
+
card_name: str
|
|
49
|
+
event: str # "onClicked"
|
|
50
|
+
action_type: str # "pi/button/clicked"
|
|
51
|
+
seq: int
|
|
52
|
+
card_key: Optional[str] = None
|
|
53
|
+
raw: dict[str, Any] = field(default_factory=dict)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
Handler = Callable[..., Any]
|
|
57
|
+
"""``fn(event)`` or ``fn(event, ctx: EventContext)``; may be ``async``."""
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class CardModel(PropModel):
|
|
61
|
+
"""Base class of all card proxies.
|
|
62
|
+
|
|
63
|
+
Class-level metadata (filled in by the code generator):
|
|
64
|
+
|
|
65
|
+
* ``__card_type__`` – the card type registered in the browser bundle
|
|
66
|
+
* ``__events__`` – python handler attribute → ``onXxx`` event name
|
|
67
|
+
* ``__event_payloads__`` – ``onXxx`` → payload model class
|
|
68
|
+
* ``__default_events_policy__`` – default ``$events`` (echo/debounce hints)
|
|
69
|
+
"""
|
|
70
|
+
|
|
71
|
+
__card_type__: ClassVar[str] = ""
|
|
72
|
+
__events__: ClassVar[dict[str, str]] = {}
|
|
73
|
+
__event_payloads__: ClassVar[dict[str, type[BaseModel]]] = {}
|
|
74
|
+
__default_events_policy__: ClassVar[dict[str, dict[str, Any]]] = {}
|
|
75
|
+
|
|
76
|
+
events_policy: Optional[dict[str, dict[str, Any]]] = Field(
|
|
77
|
+
default=None,
|
|
78
|
+
alias="$events",
|
|
79
|
+
description="Per-event policy overriding the card type's default (echo, debounceMs, send).",
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
def card_type(self) -> str:
|
|
83
|
+
return self.__card_type__
|
|
84
|
+
|
|
85
|
+
def handler_for(self, event: str) -> Optional[Handler]:
|
|
86
|
+
for attr, ev in type(self).__events__.items():
|
|
87
|
+
if ev == event:
|
|
88
|
+
return getattr(self, attr, None)
|
|
89
|
+
return None
|
|
90
|
+
|
|
91
|
+
def __hash__(self) -> int: # identity semantics: cards are mutable proxies
|
|
92
|
+
return id(self)
|
|
93
|
+
|
|
94
|
+
def __eq__(self, other: object) -> bool:
|
|
95
|
+
return self is other
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class GenericCard(CardModel):
|
|
99
|
+
"""Escape hatch for card types without a generated proxy::
|
|
100
|
+
|
|
101
|
+
GenericCard(card_type_="acme/gauge", value=3, handlers={"onChanged": fn})
|
|
102
|
+
"""
|
|
103
|
+
|
|
104
|
+
card_type_: str = Field(exclude=True)
|
|
105
|
+
handlers: dict[str, Handler] = Field(default_factory=dict, exclude=True)
|
|
106
|
+
|
|
107
|
+
def card_type(self) -> str:
|
|
108
|
+
return self.card_type_
|
|
109
|
+
|
|
110
|
+
def handler_for(self, event: str) -> Optional[Handler]:
|
|
111
|
+
return self.handlers.get(event)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
CardRef = Union[str, CardModel]
|
|
115
|
+
"""A child card: its name, or the card proxy itself."""
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
# --------------------------------------------------------------------------- flattening
|
|
119
|
+
|
|
120
|
+
class Flattener:
|
|
121
|
+
"""Turns named root cards (and every card instance reachable from them)
|
|
122
|
+
into the flat ``{name: declaration}`` map sent to the browser."""
|
|
123
|
+
|
|
124
|
+
def __init__(self, roots: dict[str, CardModel]):
|
|
125
|
+
self.roots = roots
|
|
126
|
+
self.decls: dict[str, dict[str, Any]] = {}
|
|
127
|
+
self.by_name: dict[str, CardModel] = {}
|
|
128
|
+
self._names: dict[int, str] = {}
|
|
129
|
+
|
|
130
|
+
def run(self) -> tuple[dict[str, dict[str, Any]], dict[str, CardModel]]:
|
|
131
|
+
for name, card in self.roots.items(): # explicit names win over derived ones
|
|
132
|
+
self._names.setdefault(id(card), name)
|
|
133
|
+
for name, card in self.roots.items():
|
|
134
|
+
self._card(card, name)
|
|
135
|
+
return self.decls, self.by_name
|
|
136
|
+
|
|
137
|
+
def _card(self, card: CardModel, suggested: str) -> str:
|
|
138
|
+
name = self._names.setdefault(id(card), suggested)
|
|
139
|
+
if name in self.by_name:
|
|
140
|
+
if self.by_name[name] is not card:
|
|
141
|
+
raise ValueError(f"two different cards would both be named '{name}'")
|
|
142
|
+
return name # already emitted (shared or cyclic reference)
|
|
143
|
+
self.by_name[name] = card
|
|
144
|
+
self.decls[name] = {} # reserve (cycles)
|
|
145
|
+
decl: dict[str, Any] = {"cardType": card.card_type()}
|
|
146
|
+
policy = dict(type(card).__default_events_policy__)
|
|
147
|
+
policy.update(card.events_policy or {})
|
|
148
|
+
if policy:
|
|
149
|
+
decl["$events"] = policy
|
|
150
|
+
decl.update(self._fields(card, name, skip={"events_policy"}))
|
|
151
|
+
self.decls[name] = decl
|
|
152
|
+
return name
|
|
153
|
+
|
|
154
|
+
def _fields(self, m: BaseModel, path: str, skip: set[str] = frozenset()) -> dict[str, Any]:
|
|
155
|
+
out: dict[str, Any] = {}
|
|
156
|
+
for fname, finfo in type(m).model_fields.items():
|
|
157
|
+
if fname in skip or finfo.exclude:
|
|
158
|
+
continue
|
|
159
|
+
v = getattr(m, fname)
|
|
160
|
+
if v is None:
|
|
161
|
+
continue
|
|
162
|
+
key = finfo.alias or fname
|
|
163
|
+
out[key] = self._value(v, f"{path}/{key}")
|
|
164
|
+
for k, v in (m.__pydantic_extra__ or {}).items():
|
|
165
|
+
if v is not None:
|
|
166
|
+
out[k] = self._value(v, f"{path}/{k}")
|
|
167
|
+
return out
|
|
168
|
+
|
|
169
|
+
def _value(self, v: Any, path: str) -> Any:
|
|
170
|
+
if isinstance(v, CardModel):
|
|
171
|
+
return self._card(v, path)
|
|
172
|
+
if isinstance(v, BaseModel):
|
|
173
|
+
return self._fields(v, path)
|
|
174
|
+
if isinstance(v, enum.Enum):
|
|
175
|
+
return v.value
|
|
176
|
+
if isinstance(v, (list, tuple)):
|
|
177
|
+
return [self._value(x, f"{path}/{i}") for i, x in enumerate(v)]
|
|
178
|
+
if isinstance(v, dict):
|
|
179
|
+
return {str(k): self._value(x, f"{path}/{k}") for k, x in v.items()}
|
|
180
|
+
if isinstance(v, (_dt.datetime, _dt.date)):
|
|
181
|
+
return v.isoformat()
|
|
182
|
+
if v is None or isinstance(v, (str, int, float, bool)):
|
|
183
|
+
return v
|
|
184
|
+
if callable(v):
|
|
185
|
+
raise TypeError(f"'{path}': functions cannot be sent to the browser (use an on_* handler)")
|
|
186
|
+
raise TypeError(f"'{path}': value of type {type(v).__name__} is not JSON serialisable")
|
|
File without changes
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""Card proxies for acme-cards 0.1.0.
|
|
2
|
+
|
|
3
|
+
GENERATED by pihanga_remote.codegen from hand-written – do not edit.
|
|
4
|
+
"""
|
|
5
|
+
# ruff: noqa
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from typing import Any, Callable, ClassVar, Literal, Optional, Union
|
|
9
|
+
|
|
10
|
+
from pydantic import Field as _Field
|
|
11
|
+
|
|
12
|
+
from pihanga_remote.card import CardModel, CardRef, EventContext, PropModel
|
|
13
|
+
|
|
14
|
+
LIBRARY = 'acme-cards'
|
|
15
|
+
LIBRARY_VERSION = '0.1.0'
|
|
16
|
+
|
|
17
|
+
# --- models (annotations are resolved lazily by model_rebuild below)
|
|
18
|
+
|
|
19
|
+
class AcmeGaugeResetEvent(PropModel):
|
|
20
|
+
value: float
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class Gauge(CardModel):
|
|
24
|
+
"""Card `acme/gauge` (acme-cards 0.1.0, module acme-cards)."""
|
|
25
|
+
__card_type__: ClassVar[str] = 'acme/gauge'
|
|
26
|
+
__events__: ClassVar[dict[str, str]] = {'on_reset': 'onReset'}
|
|
27
|
+
__default_events_policy__: ClassVar[dict[str, dict[str, Any]]] = {}
|
|
28
|
+
on_reset: Optional[Union[Callable[[AcmeGaugeResetEvent], Any], Callable[[AcmeGaugeResetEvent, EventContext], Any]]] = _Field(default=None, exclude=True, description='Handler for onReset (acme/gauge/reset)')
|
|
29
|
+
label: Optional[str] = _Field(default=None)
|
|
30
|
+
value: Optional[float] = _Field(default=None)
|
|
31
|
+
max: Optional[float] = _Field(default=None)
|
|
32
|
+
badge_card: Optional[CardRef] = _Field(default=None, alias='badgeCard', description='Optional card (any library) shown next to the gauge.')
|
|
33
|
+
|
|
34
|
+
# --- type aliases
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
# --- card metadata
|
|
38
|
+
Gauge.__event_payloads__ = {'onReset': AcmeGaugeResetEvent}
|
|
39
|
+
|
|
40
|
+
AcmeGaugeResetEvent.model_rebuild()
|
|
41
|
+
Gauge.model_rebuild()
|
|
42
|
+
|
|
43
|
+
CARDS: dict[str, type[CardModel]] = {c.__card_type__: c for c in [Gauge]}
|
|
44
|
+
|
|
45
|
+
__all__ = ['Gauge', 'CARDS', 'LIBRARY', 'LIBRARY_VERSION']
|