plexi-sdk 0.4.0__tar.gz → 0.5.1__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.
Files changed (48) hide show
  1. {plexi_sdk-0.4.0 → plexi_sdk-0.5.1}/.gitignore +23 -1
  2. plexi_sdk-0.5.1/PKG-INFO +87 -0
  3. plexi_sdk-0.5.1/README.md +67 -0
  4. plexi_sdk-0.5.1/plexi_sdk/__init__.py +43 -0
  5. plexi_sdk-0.5.1/plexi_sdk/_adapter.py +390 -0
  6. plexi_sdk-0.5.1/plexi_sdk/_keys.py +87 -0
  7. {plexi_sdk-0.4.0 → plexi_sdk-0.5.1}/plexi_sdk/_protocol.py +2 -2
  8. plexi_sdk-0.5.1/plexi_sdk/_theme.py +138 -0
  9. {plexi_sdk-0.4.0 → plexi_sdk-0.5.1}/plexi_sdk/_types.py +15 -28
  10. plexi_sdk-0.5.1/plexi_sdk/_v3_delta.py +184 -0
  11. plexi_sdk-0.5.1/plexi_sdk/_v3_errors.py +158 -0
  12. plexi_sdk-0.5.1/plexi_sdk/_v3_process.py +15 -0
  13. plexi_sdk-0.5.1/plexi_sdk/_v3_runtime.py +1090 -0
  14. plexi_sdk-0.5.1/plexi_sdk/_v3_state.py +210 -0
  15. plexi_sdk-0.5.1/plexi_sdk/_version.py +94 -0
  16. plexi_sdk-0.5.1/plexi_sdk/effects.py +371 -0
  17. plexi_sdk-0.5.1/plexi_sdk/events.py +351 -0
  18. plexi_sdk-0.5.1/plexi_sdk/state_format.py +57 -0
  19. plexi_sdk-0.5.1/plexi_sdk/templates/gitignore +28 -0
  20. plexi_sdk-0.5.1/plexi_sdk/templates/manifest.toml +20 -0
  21. plexi_sdk-0.5.1/plexi_sdk/templates/plugin-contract.md +51 -0
  22. plexi_sdk-0.5.1/plexi_sdk/templates/plugin_init.py +62 -0
  23. plexi_sdk-0.5.1/plexi_sdk/templates/test_plugin_init.py +61 -0
  24. {plexi_sdk-0.4.0 → plexi_sdk-0.5.1}/plexi_sdk/testing.py +221 -18
  25. plexi_sdk-0.5.1/plexi_sdk/tools.py +198 -0
  26. plexi_sdk-0.5.1/plexi_sdk/ui.py +1852 -0
  27. {plexi_sdk-0.4.0 → plexi_sdk-0.5.1}/pyproject.toml +8 -7
  28. plexi_sdk-0.4.0/PKG-INFO +0 -127
  29. plexi_sdk-0.4.0/README.md +0 -105
  30. plexi_sdk-0.4.0/plexi_sdk/__init__.py +0 -477
  31. plexi_sdk-0.4.0/plexi_sdk/_app.py +0 -1077
  32. plexi_sdk-0.4.0/plexi_sdk/_constants.py +0 -52
  33. plexi_sdk-0.4.0/plexi_sdk/_emitter.py +0 -1466
  34. plexi_sdk-0.4.0/plexi_sdk/_pipe.py +0 -92
  35. plexi_sdk-0.4.0/plexi_sdk/_render_context.py +0 -976
  36. plexi_sdk-0.4.0/plexi_sdk/midi.py +0 -222
  37. plexi_sdk-0.4.0/plexi_sdk/templates/app_init.py +0 -72
  38. plexi_sdk-0.4.0/plexi_sdk/ui.py +0 -1535
  39. plexi_sdk-0.4.0/plexi_sdk/widgets/__init__.py +0 -27
  40. plexi_sdk-0.4.0/plexi_sdk/widgets/button.py +0 -60
  41. plexi_sdk-0.4.0/plexi_sdk/widgets/keymap.py +0 -51
  42. plexi_sdk-0.4.0/plexi_sdk/widgets/list_view.py +0 -159
  43. plexi_sdk-0.4.0/plexi_sdk/widgets/scroll.py +0 -100
  44. plexi_sdk-0.4.0/plexi_sdk/widgets/text_area.py +0 -218
  45. plexi_sdk-0.4.0/plexi_sdk/widgets/text_buffer.py +0 -337
  46. plexi_sdk-0.4.0/plexi_sdk/widgets/text_input.py +0 -70
  47. {plexi_sdk-0.4.0 → plexi_sdk-0.5.1}/plexi_sdk/py.typed +0 -0
  48. {plexi_sdk-0.4.0 → plexi_sdk-0.5.1}/plexi_sdk/templates/__init__.py +0 -0
@@ -5,12 +5,14 @@ deps/egui_term/target/
5
5
  # Scratch docs
6
6
  docs/scratch/
7
7
 
8
+ # Videos
9
+ VIDEOS/
10
+
8
11
  # IDE
9
12
  .idea/
10
13
  .vscode/
11
14
 
12
15
  # AI tool configs (local only)
13
- .agents/
14
16
  .claude/settings.local.json
15
17
  .claude/*.lock
16
18
  .kiro/
@@ -49,6 +51,9 @@ __pycache__/
49
51
  *.pyo
50
52
  sdk/python/**/__pycache__/
51
53
  sdk/python/*.egg-info/
54
+ .venv/
55
+ .pytest_cache/
56
+ tools/e2e_authoring/*.egg-info/
52
57
 
53
58
  # Local config
54
59
  .plexi/
@@ -56,6 +61,23 @@ sdk/python/*.egg-info/
56
61
  .plexi-beta/
57
62
  .plexi-pr-*/
58
63
  .superpowers/
64
+ .pi/
59
65
 
60
66
  # Claude agent memory (local, not shared)
61
67
  .claude/agent-memory/
68
+
69
+ # MemPalace (local semantic memory index)
70
+ .mempalace/
71
+
72
+ # MemPalace per-project files (issue #185)
73
+ mempalace.yaml
74
+ entities.json
75
+
76
+ # Stint task graph (local only)
77
+ .stint/*
78
+
79
+
80
+ # Agent skill logs (runtime artifacts)
81
+ .agents/**/LOG.md
82
+ .agents/**/RUN_STATE.md
83
+ .agents/**/HUMAN_CHECKS.md
@@ -0,0 +1,87 @@
1
+ Metadata-Version: 2.5
2
+ Name: plexi-sdk
3
+ Version: 0.5.1
4
+ Summary: Python SDK v3 for Plexi apps running through the CPython-in-WASM runtime
5
+ Project-URL: Homepage, https://github.com/ianjamesburke/PLEXI
6
+ Project-URL: Repository, https://github.com/ianjamesburke/PLEXI
7
+ Project-URL: Documentation, https://github.com/ianjamesburke/PLEXI/tree/main/sdk/python
8
+ Author-email: Ian Burke <ianjamesburke@gmail.com>
9
+ License: MIT
10
+ Keywords: apps,pgap,plexi,sdk,tiling,window-manager
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Topic :: Software Development :: Libraries
18
+ Requires-Python: >=3.12
19
+ Description-Content-Type: text/markdown
20
+
21
+ # plexi-sdk
22
+
23
+ Python SDK v3 for building Plexi apps running inside the CPython-in-WASM runtime.
24
+
25
+ Full design spec: [`SDK_V3.md`](SDK_V3.md)
26
+
27
+ ## Install For SDK Development
28
+
29
+ ```sh
30
+ uv pip install -e ./sdk/python
31
+ ```
32
+
33
+ Changes to `sdk/python/plexi_sdk/` take effect immediately.
34
+
35
+ ## App Pattern
36
+
37
+ An app is three module-level functions:
38
+
39
+ ```python
40
+ from plexi_sdk import state
41
+ from plexi_sdk.effects import SetTitle, SetState
42
+ from plexi_sdk.events import KeyEvent
43
+ from plexi_sdk.ui import Column, AppBar, Text, FooterKeys
44
+
45
+
46
+ def init(size, args):
47
+ return [SetTitle("Counter"), SetState({"count": 0})]
48
+
49
+
50
+ def update(event):
51
+ if isinstance(event, KeyEvent) and event.key == "+" and event.pressed:
52
+ return [SetState({"count": state.get("count", 0) + 1})]
53
+ return []
54
+
55
+
56
+ def view():
57
+ return Column([
58
+ AppBar("Counter"),
59
+ Text(str(state.get("count", 0)), bold=True, align="center"),
60
+ FooterKeys([("+", "increment")]),
61
+ ], grow=True)
62
+ ```
63
+
64
+ `SetState` is process-local runtime state. Use `PersistState` when a key must survive app restart.
65
+
66
+ Games and animations should return `SetSchedulerMode("continuous", fps=60)` from `init()` and update runtime state from `RenderFrame` events. Do not build animation loops with timers.
67
+
68
+ ## Keyboard Conventions
69
+
70
+ Keys arrive in `update(event)` as `KeyEvent`. Key strings are lowercase canonical.
71
+
72
+ | Physical key | `event.key` |
73
+ |---|---|
74
+ | Enter / Return | `"enter"` |
75
+ | Escape | `"escape"` |
76
+ | Backspace | `"backspace"` |
77
+ | Space | `"space"` |
78
+ | Arrow keys | `"up"` / `"down"` / `"left"` / `"right"` |
79
+ | Operators / Punctuation | `"+"` / `"-"` / `"*"` / `"/"` / `"="` |
80
+
81
+ ## New App
82
+
83
+ ```sh
84
+ plexi app init myapp
85
+ ```
86
+
87
+ Generates `myapp/main.py` + `myapp/manifest.toml` with `python_compat = true`.
@@ -0,0 +1,67 @@
1
+ # plexi-sdk
2
+
3
+ Python SDK v3 for building Plexi apps running inside the CPython-in-WASM runtime.
4
+
5
+ Full design spec: [`SDK_V3.md`](SDK_V3.md)
6
+
7
+ ## Install For SDK Development
8
+
9
+ ```sh
10
+ uv pip install -e ./sdk/python
11
+ ```
12
+
13
+ Changes to `sdk/python/plexi_sdk/` take effect immediately.
14
+
15
+ ## App Pattern
16
+
17
+ An app is three module-level functions:
18
+
19
+ ```python
20
+ from plexi_sdk import state
21
+ from plexi_sdk.effects import SetTitle, SetState
22
+ from plexi_sdk.events import KeyEvent
23
+ from plexi_sdk.ui import Column, AppBar, Text, FooterKeys
24
+
25
+
26
+ def init(size, args):
27
+ return [SetTitle("Counter"), SetState({"count": 0})]
28
+
29
+
30
+ def update(event):
31
+ if isinstance(event, KeyEvent) and event.key == "+" and event.pressed:
32
+ return [SetState({"count": state.get("count", 0) + 1})]
33
+ return []
34
+
35
+
36
+ def view():
37
+ return Column([
38
+ AppBar("Counter"),
39
+ Text(str(state.get("count", 0)), bold=True, align="center"),
40
+ FooterKeys([("+", "increment")]),
41
+ ], grow=True)
42
+ ```
43
+
44
+ `SetState` is process-local runtime state. Use `PersistState` when a key must survive app restart.
45
+
46
+ Games and animations should return `SetSchedulerMode("continuous", fps=60)` from `init()` and update runtime state from `RenderFrame` events. Do not build animation loops with timers.
47
+
48
+ ## Keyboard Conventions
49
+
50
+ Keys arrive in `update(event)` as `KeyEvent`. Key strings are lowercase canonical.
51
+
52
+ | Physical key | `event.key` |
53
+ |---|---|
54
+ | Enter / Return | `"enter"` |
55
+ | Escape | `"escape"` |
56
+ | Backspace | `"backspace"` |
57
+ | Space | `"space"` |
58
+ | Arrow keys | `"up"` / `"down"` / `"left"` / `"right"` |
59
+ | Operators / Punctuation | `"+"` / `"-"` / `"*"` / `"/"` / `"="` |
60
+
61
+ ## New App
62
+
63
+ ```sh
64
+ plexi app init myapp
65
+ ```
66
+
67
+ Generates `myapp/main.py` + `myapp/manifest.toml` with `python_compat = true`.
@@ -0,0 +1,43 @@
1
+ """Plexi Python SDK.
2
+
3
+ Apps expose module-level ``init(size, args)``, ``update(event)``, and ``view()``
4
+ functions. The PluginRuntime drives the event loop: host sends JSON events on
5
+ stdin, app responds with effects and component trees on stdout.
6
+
7
+ Python apps are sandboxed. They run through the CPython-in-WASM adapter
8
+ (`src/host/wasm_python.rs`) inside their own `wasmtime::Store` with isolated
9
+ linear memory — the same component boundary a Rust WASM app gets, not a native
10
+ subprocess. An app reaches only the host interfaces Plexi links for its world,
11
+ and protected effects (file, network, AI, clipboard, pane, audio, GPU) each
12
+ require an explicit capability grant the user approves on first request. There
13
+ is no ambient process access to escape to. See `docs/wasm-runtime.md`
14
+ § Security Model for the full boundary.
15
+ """
16
+
17
+ from ._version import __version__
18
+
19
+ SDK_ID = f"plexi-sdk-py/{__version__}"
20
+
21
+ from ._v3_state import ComponentState, StateSnapshot, component, log, state, use_state
22
+ from . import effects as effects
23
+ from . import events as events
24
+ from . import tools as tools
25
+
26
+ from ._types import (
27
+ CapabilityDeniedError, VideoHandle,
28
+ RectCommand, TextCommand, BadgeCommand, ShortcutPair, NotifyOption,
29
+ )
30
+ from ._protocol import AiResponse, MidiPortInfo, MidiDeviceList, AudioDeviceInfo, AudioDeviceList, PROTOCOL_VERSION
31
+ from .ui import (
32
+ Tabs as Tabs,
33
+ Grid as Grid,
34
+ Toggle as Toggle,
35
+ ProgressBar as ProgressBar,
36
+ TextEdit as TextEdit,
37
+ )
38
+ from ._theme import theme, Theme, PluginPalette, rgba, dim
39
+ from .state_format import (
40
+ ChecklistItem as ChecklistItem,
41
+ parse_checklist as parse_checklist,
42
+ render_checklist as render_checklist,
43
+ )
@@ -0,0 +1,390 @@
1
+ from __future__ import annotations
2
+
3
+ import base64
4
+ import importlib
5
+ import json
6
+ from dataclasses import asdict, fields, is_dataclass
7
+ from typing import Any, cast
8
+
9
+ import plexi_sdk as sdk
10
+
11
+ from ._v3_state import StateSnapshot
12
+ from . import _v3_state
13
+ from . import effects as effect_types
14
+ from . import events as event_types
15
+
16
+ _module = None
17
+
18
+
19
+ def load_plugin(module_name: str) -> None:
20
+ global _module
21
+ _module = importlib.import_module(module_name)
22
+
23
+
24
+ def call_lifecycle(fn_name: str, json_arg: str) -> str:
25
+ if _module is None:
26
+ raise RuntimeError("no Plexi plugin module loaded")
27
+ fn = getattr(_module, fn_name)
28
+ arg = json.loads(json_arg) if json_arg else {}
29
+
30
+ if fn_name == "init":
31
+ _set_sdk_state(arg.get("state", {}), in_view=False)
32
+ result = fn(tuple(arg.get("size", [0.0, 0.0])), arg.get("args", []))
33
+ return json.dumps([_encode_effect(e) for e in result])
34
+ if fn_name == "update":
35
+ _set_sdk_state(arg.get("state", {}), in_view=False)
36
+ event = _decode_event(arg.get("event", {}))
37
+ result = fn(event)
38
+ return json.dumps([_encode_effect(e) for e in result])
39
+ if fn_name == "view":
40
+ _set_sdk_state(arg.get("state", {}), in_view=True)
41
+ try:
42
+ tree = fn()
43
+ return json.dumps(_encode_uitree(tree))
44
+ finally:
45
+ setattr(sdk, "_in_view", False)
46
+ _v3_state._in_view = False
47
+ raise ValueError(f"unknown lifecycle function: {fn_name}")
48
+
49
+
50
+ def _set_sdk_state(encoded: dict[str, str], in_view: bool) -> None:
51
+ snapshot = _decode_state(encoded)
52
+ setattr(sdk, "_state", snapshot)
53
+ setattr(sdk, "_in_view", in_view)
54
+ _v3_state._state = snapshot
55
+ _v3_state._in_view = in_view
56
+
57
+
58
+ def _decode_state(encoded: dict[str, str]) -> StateSnapshot:
59
+ values: dict[str, Any] = {}
60
+ raw: dict[str, bytes] = {}
61
+ for key, value in encoded.items():
62
+ if value.startswith("b64:"):
63
+ raw[key] = base64.b64decode(value[4:])
64
+ continue
65
+ payload = base64.b64decode(value)
66
+ raw[key] = payload
67
+ values[key] = json.loads(payload.decode("utf-8"))
68
+ return StateSnapshot(values, raw, {"global": values}, ("global",))
69
+
70
+
71
+ def _encode_effect(effect: Any) -> dict[str, Any]:
72
+ if not is_dataclass(effect):
73
+ raise TypeError(f"Unknown effect type: {type(effect).__name__}")
74
+ if getattr(effect_types, type(effect).__name__, None) is not type(effect):
75
+ raise TypeError(f"Unknown effect type: {type(effect).__name__}")
76
+ payload = _jsonable(asdict(cast(Any, effect)))
77
+ if isinstance(effect, effect_types.HttpFetch):
78
+ payload["url"] = effect.resolved_url()
79
+ if payload.get("params") is None:
80
+ payload.pop("params", None)
81
+ if payload.get("tag") is None:
82
+ payload.pop("tag", None)
83
+ if payload.get("request_id") is None:
84
+ payload.pop("request_id", None)
85
+ payload["type"] = type(effect).__name__
86
+ return payload
87
+
88
+
89
+ def _jsonable(value: Any) -> Any:
90
+ if isinstance(value, bytes):
91
+ return list(value)
92
+ if isinstance(value, dict):
93
+ return {key: _jsonable(item) for key, item in value.items()}
94
+ if isinstance(value, list):
95
+ return [_jsonable(item) for item in value]
96
+ if isinstance(value, tuple):
97
+ return [_jsonable(item) for item in value]
98
+ return value
99
+
100
+
101
+ def _decode_event(payload: dict[str, Any]) -> Any:
102
+ event_type = payload.get("type")
103
+ if not isinstance(event_type, str):
104
+ raise TypeError("event payload missing string 'type'")
105
+ cls = getattr(event_types, event_type, None)
106
+ if cls is None or not is_dataclass(cls):
107
+ raise TypeError(f"Unknown event type: {event_type}")
108
+ kwargs = {
109
+ f.name: payload[f.name]
110
+ for f in fields(cast(Any, cls))
111
+ if f.name in payload
112
+ }
113
+ if cls is event_types.KeyEvent and isinstance(kwargs.get("modifiers"), dict):
114
+ kwargs["modifiers"] = event_types.Modifiers(**kwargs["modifiers"])
115
+ if cls is event_types.HttpResponse:
116
+ if isinstance(kwargs.get("body"), list):
117
+ kwargs["body"] = bytes(kwargs["body"])
118
+ elif isinstance(kwargs.get("body"), str):
119
+ kwargs["body"] = kwargs["body"].encode("utf-8")
120
+ raw_headers = kwargs.get("headers")
121
+ if isinstance(raw_headers, dict):
122
+ kwargs["headers"] = [(str(k), str(v)) for k, v in raw_headers.items()]
123
+ elif isinstance(raw_headers, list):
124
+ kwargs["headers"] = [
125
+ (str(item[0]), str(item[1]))
126
+ for item in raw_headers
127
+ if isinstance(item, (list, tuple)) and len(item) == 2
128
+ ]
129
+ if cls is event_types.PipeMessage and isinstance(kwargs.get("payload"), dict):
130
+ kwargs["payload"] = event_types.PipePayload(**kwargs["payload"])
131
+ return cast(Any, cls)(**kwargs)
132
+
133
+
134
+ def _require_view_component(root: Any) -> None:
135
+ """Teachable failure when view() breaks the effect contract.
136
+
137
+ The most common generated-app mistake is `return tree, SetTimer(...)` from
138
+ view(); without this check it dies later as an opaque
139
+ "Unknown UINode type: tuple".
140
+ """
141
+ if isinstance(root, (tuple, list)):
142
+ raise TypeError(
143
+ f"view() must return a single component tree, got {type(root).__name__}. "
144
+ "Effects (SetTimer, SetState, ...) are returned from update() or init(), "
145
+ "never from view()."
146
+ )
147
+ if is_dataclass(root) and getattr(effect_types, type(root).__name__, None) is type(root):
148
+ raise TypeError(
149
+ f"view() returned the effect {type(root).__name__}. Effects are returned "
150
+ "from update() or init(); view() returns exactly one component."
151
+ )
152
+ if not (isinstance(root, dict) or hasattr(root, "to_node") or is_dataclass(root)):
153
+ raise TypeError(
154
+ f"view() returned {type(root).__name__}, which is not a component. "
155
+ "Return exactly one plexi_sdk.ui component, for example "
156
+ "Column(children=[Text(...)])."
157
+ )
158
+
159
+
160
+ def _encode_uitree(root: Any) -> dict[str, Any]:
161
+ _require_view_component(root)
162
+ arena: list[dict[str, Any]] = []
163
+
164
+ def flatten(node: Any, key: str) -> int:
165
+ node_id = len(arena)
166
+ arena.append({"id": node_id, "key": key, "data": {"type": "Pending"}})
167
+ # An explicit Keyed key is a path segment, not a replacement for the
168
+ # path accumulated above it. That makes the key unique in the tree
169
+ # and keeps every descendant on that keyed identity when siblings move.
170
+ own_key = getattr(node, "key", "") or (
171
+ node.get("_plexi_key", "") if isinstance(node, dict) else ""
172
+ )
173
+ # `flatten` receives a positional child address. Replace that final
174
+ # address segment for Keyed rather than appending to it: the keyed node
175
+ # is the direct child of its container, regardless of its list index.
176
+ key_parent = key.rsplit("/", 1)[0] if "/" in key else ""
177
+ explicit_key = f"{key_parent}/@{own_key}" if own_key else key
178
+ if isinstance(node, dict):
179
+ data = {k: v for k, v in node.items() if k != "_plexi_key"}
180
+ elif hasattr(node, "to_node"):
181
+ data = node.to_node()
182
+ elif is_dataclass(node):
183
+ data = asdict(cast(Any, node))
184
+ data["type"] = type(node).__name__
185
+ else:
186
+ raise TypeError(f"Unknown UINode type: {type(node).__name__}")
187
+ data = _normalize_node_data(data, explicit_key, flatten)
188
+ arena[node_id] = {"id": node_id, "key": explicit_key, "data": data}
189
+ return node_id
190
+
191
+ root_id = flatten(root, "0")
192
+ return {"root": root_id, "nodes": arena}
193
+
194
+
195
+ def _normalize_node_data(data: dict[str, Any], key: str, flatten) -> dict[str, Any]:
196
+ node_type = data.get("type") or data.get("kind")
197
+ if node_type == "pinned":
198
+ child = data.get("child")
199
+ if not isinstance(child, dict):
200
+ raise TypeError("pinned node requires a child object")
201
+ return {
202
+ "type": "Pinned",
203
+ "edge": data.get("edge", "bottom"),
204
+ "child": flatten(child, f"{key}/child"),
205
+ }
206
+ if node_type == "footer_keys":
207
+ return {
208
+ "type": "FooterKeys",
209
+ "entries": data.get("entries", []),
210
+ "divider": data.get("divider", True),
211
+ }
212
+ if node_type == "surface_header":
213
+ return {
214
+ "type": "SurfaceHeader",
215
+ "title": data.get("title", ""),
216
+ "subtitle": data.get("subtitle", ""),
217
+ }
218
+ if node_type == "spinner":
219
+ return {
220
+ "type": "Spinner",
221
+ "label": data.get("label", ""),
222
+ }
223
+ if node_type == "column":
224
+ children = data.get("children", [])
225
+ child_ids = [
226
+ flatten(child, f"{key}/{idx}") for idx, child in enumerate(children)
227
+ ]
228
+ out: dict[str, Any] = {
229
+ "type": "Column",
230
+ "children": child_ids,
231
+ "align": data.get("align", "start"),
232
+ "justify": data.get("justify", "start"),
233
+ "grow": data.get("grow", False),
234
+ }
235
+ # Carry gap only when the app set one: absence lets the host apply its
236
+ # default inter-child spacing, an explicit value (including 0) wins.
237
+ if data.get("gap") is not None:
238
+ out["gap"] = data["gap"]
239
+ return out
240
+ if node_type in ("card", "Card"):
241
+ if "child" in data and isinstance(data["child"], int):
242
+ child_id = data["child"]
243
+ elif "child" in data and data["child"] is not None:
244
+ child_id = flatten(data["child"], f"{key}/child")
245
+ else:
246
+ inner_col: dict[str, Any] = {
247
+ "type": "column",
248
+ "children": data.get("children", []),
249
+ }
250
+ if data.get("gap") is not None:
251
+ inner_col["gap"] = data["gap"]
252
+ child_id = flatten(inner_col, f"{key}/body")
253
+ pad = float(data.get("padding", data.get("top", 12.0)))
254
+ return {
255
+ "type": "Card",
256
+ "card": True,
257
+ "child": child_id,
258
+ "top": pad,
259
+ "right": pad,
260
+ "bottom": pad,
261
+ "left": pad,
262
+ }
263
+ if node_type in ("DataTable", "data_table", "table", "Table"):
264
+ children = data.get("children", [])
265
+ child_ids = [
266
+ flatten(child, f"{key}/{idx}") for idx, child in enumerate(children)
267
+ ]
268
+ selected = data.get("selected", data.get("selected_idx"))
269
+ if selected is not None:
270
+ selected = int(selected)
271
+ out = {
272
+ "type": "DataTable",
273
+ "columns": [str(c) for c in data.get("columns", [])],
274
+ "rows": [[str(cell) for cell in r] for r in data.get("rows", [])],
275
+ "selected": selected,
276
+ "on_select": data.get("on_select"),
277
+ "children": child_ids,
278
+ "align": data.get("align", "start"),
279
+ "grow": data.get("grow", False),
280
+ }
281
+ if data.get("gap") is not None:
282
+ out["gap"] = data["gap"]
283
+ return out
284
+ if node_type in ("row", "Row"):
285
+ children = data.get("children", [])
286
+ child_ids = [
287
+ flatten(child, f"{key}/{idx}") for idx, child in enumerate(children)
288
+ ]
289
+ out = {
290
+ "type": "Row",
291
+ "children": child_ids,
292
+ "align": data.get("align", "center"),
293
+ "justify": data.get("justify", "start"),
294
+ "grow": data.get("grow", False),
295
+ }
296
+ if data.get("gap") is not None:
297
+ out["gap"] = data["gap"]
298
+ return out
299
+ if node_type == "button":
300
+ return {
301
+ "type": "Button",
302
+ "label": data.get("label", ""),
303
+ "on_click": data.get("on_click", ""),
304
+ "style": data.get("style", "secondary"),
305
+ "disabled": data.get("disabled", False),
306
+ }
307
+ if node_type in ("TextInput", "text_input", "text-input"):
308
+ return {
309
+ "type": "TextInput",
310
+ "value": data.get("value", ""),
311
+ "placeholder": data.get("placeholder", ""),
312
+ "on_change": data.get("on_change", data.get("on-change", "")),
313
+ "on_submit": data.get("on_submit", data.get("on-submit", "")),
314
+ "password": data.get("password", False),
315
+ "autofocus": data.get("autofocus", False),
316
+ }
317
+ if node_type == "select_list":
318
+ items = data.get("items", [])
319
+ child_ids = []
320
+ for idx, item in enumerate(items):
321
+ if hasattr(item, "to_node"):
322
+ item_node: Any = item
323
+ elif isinstance(item, dict) and ("type" in item or "kind" in item):
324
+ item_node = item
325
+ else:
326
+ text = (
327
+ str(item.get("name", item.get("label", "")))
328
+ if isinstance(item, dict)
329
+ else str(item)
330
+ )
331
+ description = ""
332
+ leading = ""
333
+ trailing = ""
334
+ if isinstance(item, dict):
335
+ description = str(item.get("description", "") or "")
336
+ leading = str(item.get("leading", "") or "")
337
+ trailing = str(item.get("trailing", "") or "")
338
+ if description:
339
+ main: Any = {
340
+ "type": "column",
341
+ "children": [
342
+ {"type": "text", "text": text, "bold": True},
343
+ {
344
+ "type": "text",
345
+ "text": description,
346
+ "size": 12.0,
347
+ "color": "muted",
348
+ },
349
+ ],
350
+ "gap": 2.0,
351
+ }
352
+ else:
353
+ main = {"type": "text", "text": text}
354
+ if leading or trailing:
355
+ row_children: list[dict[str, Any]] = []
356
+ if leading:
357
+ row_children.append({"type": "text", "text": leading})
358
+ row_children.append(main)
359
+ if trailing:
360
+ row_children.append(
361
+ {
362
+ "type": "text",
363
+ "text": trailing,
364
+ "size": 12.0,
365
+ "color": "muted",
366
+ }
367
+ )
368
+ item_node = {"type": "row", "children": row_children, "gap": 8.0}
369
+ else:
370
+ item_node = main
371
+ child_ids.append(flatten(item_node, f"{key}/{idx}"))
372
+ selected = data.get("selected_idx", data.get("selected"))
373
+ if selected is not None:
374
+ selected = int(selected)
375
+ return {
376
+ "type": "ListView",
377
+ "items": child_ids,
378
+ "selected": selected,
379
+ "on_select": data.get("on_select"),
380
+ }
381
+ if node_type in ("scroll", "Scroll"):
382
+ child = data.get("child")
383
+ if child is None:
384
+ raise TypeError("scroll node requires a child")
385
+ return {
386
+ "type": "Scroll",
387
+ "child": flatten(child, f"{key}/0"),
388
+ "horizontal": data.get("horizontal", False),
389
+ }
390
+ return data