nativehtmlkit-ui 0.1.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.
- nativehtmlkit_ui/__init__.py +9 -0
- nativehtmlkit_ui/assets/__init__.py +1 -0
- nativehtmlkit_ui/assets/ui.css +81 -0
- nativehtmlkit_ui/engine.py +599 -0
- nativehtmlkit_ui/reactive.py +167 -0
- nativehtmlkit_ui-0.1.0.dist-info/METADATA +52 -0
- nativehtmlkit_ui-0.1.0.dist-info/RECORD +10 -0
- nativehtmlkit_ui-0.1.0.dist-info/WHEEL +5 -0
- nativehtmlkit_ui-0.1.0.dist-info/licenses/LICENSE +21 -0
- nativehtmlkit_ui-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"""NativeHTMLKit UI: small, SDK-only responsive/reactive desktop toolkit.
|
|
2
|
+
|
|
3
|
+
No Core, CLI, browser, JavaScript, or third-party runtime dependency.
|
|
4
|
+
"""
|
|
5
|
+
from .engine import UI
|
|
6
|
+
from .reactive import Computed, State, computed, state
|
|
7
|
+
|
|
8
|
+
__version__ = "0.1.0"
|
|
9
|
+
__all__ = ["UI", "State", "Computed", "state", "computed"]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Packaged CSS design tokens."""
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
/* NativeHTMLKit UI 0.1 — minimal native CSS profile; no JS, web fonts, or remote assets. */
|
|
2
|
+
body.nhk-theme-cobalt {
|
|
3
|
+
--nhk-bg:#101824; --nhk-panel:#192536; --nhk-panel-2:#1d2b3d;
|
|
4
|
+
--nhk-border:#304255; --nhk-text:#ecf3fc; --nhk-muted:#a6b9cc;
|
|
5
|
+
--nhk-accent:#69a6f3; --nhk-accent-strong:#458bdf; --nhk-accent-text:#0b233f;
|
|
6
|
+
--nhk-danger:#ed7f89; --nhk-radius:9px; --nhk-focus:#69a6f3;
|
|
7
|
+
color-scheme:dark;
|
|
8
|
+
}
|
|
9
|
+
body.nhk-theme-graphite {
|
|
10
|
+
--nhk-bg:#171d25; --nhk-panel:#222b36; --nhk-panel-2:#28333e;
|
|
11
|
+
--nhk-border:#3b4b5c; --nhk-text:#eff2f7; --nhk-muted:#b1becc;
|
|
12
|
+
--nhk-accent:#87a7ef; --nhk-accent-strong:#6b8ed6; --nhk-accent-text:#121d38;
|
|
13
|
+
--nhk-danger:#eb9696; --nhk-radius:9px; --nhk-focus:#87a7ef;
|
|
14
|
+
color-scheme:dark;
|
|
15
|
+
}
|
|
16
|
+
body.nhk-theme-daylight {
|
|
17
|
+
--nhk-bg:#f1f5fa; --nhk-panel:#ffffff; --nhk-panel-2:#f6f9fd;
|
|
18
|
+
--nhk-border:#d5deea; --nhk-text:#203047; --nhk-muted:#5a6d85;
|
|
19
|
+
--nhk-accent:#276fca; --nhk-accent-strong:#2365b8; --nhk-accent-text:#ffffff;
|
|
20
|
+
--nhk-danger:#bc424d; --nhk-radius:9px; --nhk-focus:#276fca;
|
|
21
|
+
color-scheme:light;
|
|
22
|
+
}
|
|
23
|
+
body.nhk-density-compact {
|
|
24
|
+
--nhk-control-h:30px; --nhk-font:13px; --nhk-gap:10px; --nhk-pad:20px;
|
|
25
|
+
}
|
|
26
|
+
body.nhk-density-regular {
|
|
27
|
+
--nhk-control-h:36px; --nhk-font:14px; --nhk-gap:13px; --nhk-pad:25px;
|
|
28
|
+
}
|
|
29
|
+
body.nhk-density-comfortable {
|
|
30
|
+
--nhk-control-h:42px; --nhk-font:15px; --nhk-gap:16px; --nhk-pad:30px;
|
|
31
|
+
}
|
|
32
|
+
* { box-sizing:border-box; }
|
|
33
|
+
html, body { min-height:100%; margin:0; }
|
|
34
|
+
body {
|
|
35
|
+
background:var(--nhk-bg); color:var(--nhk-text);
|
|
36
|
+
font-family:Inter,"Segoe UI Variable Text","Segoe UI","Noto Sans",Arial,sans-serif;
|
|
37
|
+
font-size:var(--nhk-font); line-height:1.45;
|
|
38
|
+
}
|
|
39
|
+
.nhk-app { padding:var(--nhk-pad); max-width:1380px; margin:0 auto; }
|
|
40
|
+
.nhk-row { display:flex; flex-direction:row; flex-wrap:wrap; align-items:center; gap:var(--nhk-gap); }
|
|
41
|
+
.nhk-col, .nhk-stack { display:flex; flex-direction:column; gap:var(--nhk-gap); min-width:0; }
|
|
42
|
+
.nhk-stack { gap:6px; }
|
|
43
|
+
.nhk-grid { display:grid; grid-template-columns:repeat(3,minmax(0,1fr)); gap:var(--nhk-gap); }
|
|
44
|
+
@media (max-width:1000px) { .nhk-grid { grid-template-columns:repeat(2,minmax(0,1fr)); } }
|
|
45
|
+
@media (max-width:620px) {
|
|
46
|
+
.nhk-grid { grid-template-columns:1fr; }
|
|
47
|
+
.nhk-app { padding:14px; }
|
|
48
|
+
}
|
|
49
|
+
.nhk-card { background:var(--nhk-panel); border:1px solid var(--nhk-border); border-radius:var(--nhk-radius); padding:16px; min-width:0; }
|
|
50
|
+
.nhk-heading { font-weight:640; letter-spacing:-0.02em; line-height:1.18; margin:0 0 4px 0; }
|
|
51
|
+
h1.nhk-heading { font-size:24px; } h2.nhk-heading { font-size:19px; }
|
|
52
|
+
h3.nhk-heading { font-size:16px; } h4.nhk-heading { font-size:14px; }
|
|
53
|
+
.nhk-text { margin:0; overflow-wrap:anywhere; }
|
|
54
|
+
.nhk-muted { color:var(--nhk-muted); }
|
|
55
|
+
.nhk-button, .nhk-input, .nhk-select {
|
|
56
|
+
min-height:var(--nhk-control-h); font:inherit; border-radius:6px;
|
|
57
|
+
border:1px solid var(--nhk-border); padding:5px 11px;
|
|
58
|
+
}
|
|
59
|
+
.nhk-button { cursor:pointer; background:var(--nhk-accent); color:var(--nhk-accent-text); font-weight:600; }
|
|
60
|
+
.nhk-button:hover { background:var(--nhk-accent-strong); }
|
|
61
|
+
.nhk-secondary { background:var(--nhk-panel-2); color:var(--nhk-text); }
|
|
62
|
+
.nhk-secondary:hover { background:var(--nhk-border); }
|
|
63
|
+
.nhk-quiet { background:transparent; color:var(--nhk-text); }
|
|
64
|
+
.nhk-quiet:hover { background:var(--nhk-panel-2); }
|
|
65
|
+
.nhk-danger { background:var(--nhk-danger); color:var(--nhk-accent-text); }
|
|
66
|
+
.nhk-button:disabled { opacity:0.45; cursor:default; }
|
|
67
|
+
.nhk-input, .nhk-select { background:var(--nhk-panel-2); color:var(--nhk-text); max-width:100%; }
|
|
68
|
+
.nhk-input { width:100%; }
|
|
69
|
+
.nhk-input:focus, .nhk-select:focus, .nhk-button:focus-visible { outline:2px solid var(--nhk-focus); outline-offset:2px; }
|
|
70
|
+
.nhk-field { display:flex; flex-direction:column; gap:4px; min-width:150px; flex:1 1 200px; }
|
|
71
|
+
.nhk-label { color:var(--nhk-muted); font-size:0.9em; font-weight:550; }
|
|
72
|
+
.nhk-checkrow { display:flex; align-items:center; gap:8px; min-height:var(--nhk-control-h); }
|
|
73
|
+
.nhk-checkbox { accent-color:var(--nhk-accent); width:16px; height:16px; }
|
|
74
|
+
.nhk-badge { display:inline-block; padding:2px 8px; border:1px solid var(--nhk-border); border-radius:99px; background:var(--nhk-panel-2); color:var(--nhk-accent); font-size:0.85em; font-weight:600; }
|
|
75
|
+
.nhk-alert { border:1px solid var(--nhk-border); background:var(--nhk-panel-2); border-left:3px solid var(--nhk-accent); padding:10px 12px; border-radius:5px; }
|
|
76
|
+
.nhk-hidden { display:none !important; }
|
|
77
|
+
.nhk-list { margin:0; padding:0 0 0 20px; }
|
|
78
|
+
.nhk-list li { padding:3px; }
|
|
79
|
+
.nhk-custom { min-width:0; }
|
|
80
|
+
.nhk-hr { border:0; border-top:1px solid var(--nhk-border); }
|
|
81
|
+
@media (prefers-reduced-motion:reduce) { * { transition:none !important; animation:none !important; } }
|
|
@@ -0,0 +1,599 @@
|
|
|
1
|
+
"""NativeHTMLKit UI document owner, DOM scheduler, and scoped components.
|
|
2
|
+
|
|
3
|
+
Uses public `Application.open_html`, `Document.on`, `Document.batch`, and
|
|
4
|
+
Document DOM methods exclusively. It never imports Core or SDK internals.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from contextlib import contextmanager
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
from html import escape
|
|
11
|
+
from importlib.resources import files
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from queue import Full, Queue, Empty
|
|
14
|
+
from threading import Event, Lock, Thread, current_thread
|
|
15
|
+
import logging
|
|
16
|
+
import re
|
|
17
|
+
import uuid
|
|
18
|
+
import weakref
|
|
19
|
+
from typing import Any, Callable, Iterable
|
|
20
|
+
|
|
21
|
+
from .reactive import Binding, State, Observable, _MISSING
|
|
22
|
+
|
|
23
|
+
LOG = logging.getLogger(__name__)
|
|
24
|
+
_ID = re.compile(r"^[A-Za-z][A-Za-z0-9_:\-.]*$")
|
|
25
|
+
_ATTR = re.compile(r"^[A-Za-z_:][A-Za-z0-9_:.-]*$")
|
|
26
|
+
_STOP = object()
|
|
27
|
+
_GONE_CODES = (-32004, -32008)
|
|
28
|
+
_UNSET = object()
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _string(value: Any) -> str:
|
|
32
|
+
return "" if value is None else str(value)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _attr(name: str, value: Any) -> str:
|
|
36
|
+
if not _ATTR.fullmatch(name) or name.lower().startswith("on"):
|
|
37
|
+
raise ValueError(f"Unsafe HTML attribute name: {name!r}")
|
|
38
|
+
if value is None or value is False:
|
|
39
|
+
return ""
|
|
40
|
+
if value is True:
|
|
41
|
+
return f" {name}"
|
|
42
|
+
return f' {name}="{escape(_string(value), quote=True)}"'
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass(eq=False)
|
|
46
|
+
class Element:
|
|
47
|
+
tag: str
|
|
48
|
+
id: str
|
|
49
|
+
attrs: dict[str, Any] = field(default_factory=dict)
|
|
50
|
+
children: list["Element | str"] = field(default_factory=list)
|
|
51
|
+
bindings: list[tuple[str, Binding, str | None]] = field(default_factory=list)
|
|
52
|
+
|
|
53
|
+
def html(self) -> str:
|
|
54
|
+
attrs = dict(self.attrs)
|
|
55
|
+
attrs["id"] = self.id
|
|
56
|
+
start = "<" + self.tag + "".join(_attr(k, v) for k, v in attrs.items()) + ">"
|
|
57
|
+
if self.tag in {"input", "img", "hr", "br"}:
|
|
58
|
+
return start # HTML void tag
|
|
59
|
+
return start + "".join(x.html() if isinstance(x, Element) else escape(x, quote=False)
|
|
60
|
+
for x in self.children) + f"</{self.tag}>"
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class UI:
|
|
64
|
+
"""UI builder; construct on the main thread, then mount into a connected SDK app.
|
|
65
|
+
|
|
66
|
+
The owner is one lightweight thread per UI window. SDK event workers only
|
|
67
|
+
enqueue events and do not block on DOM RPC. All runtime DOM writes happen
|
|
68
|
+
on the UI owner, except the initial document load during mount.
|
|
69
|
+
"""
|
|
70
|
+
def __init__(self, *, title: str = "NativeHTMLKit UI", width: int = 940,
|
|
71
|
+
height: int = 660, theme: str = "cobalt", density: str = "compact",
|
|
72
|
+
extra_css: str = ""):
|
|
73
|
+
if theme not in ("cobalt", "graphite", "daylight"):
|
|
74
|
+
raise ValueError("theme must be cobalt, graphite or daylight")
|
|
75
|
+
if density not in ("compact", "regular", "comfortable"):
|
|
76
|
+
raise ValueError("density must be compact, regular or comfortable")
|
|
77
|
+
self.title, self.width, self.height = title, width, height
|
|
78
|
+
self.theme, self.density, self.extra_css = theme, density, extra_css
|
|
79
|
+
self.prefix = "nhkui-" + uuid.uuid4().hex[:12]
|
|
80
|
+
self._index = 0
|
|
81
|
+
self.root = Element("main", self._id(), {"class": "nhk-app"})
|
|
82
|
+
self._stack = [self.root]
|
|
83
|
+
self._bindings: list[tuple[Element, str, Binding, str | None]] = []
|
|
84
|
+
self._actions: dict[str, dict[str, Callable[[dict], None]]] = {}
|
|
85
|
+
self._subscriptions: list[Callable[[], None]] = []
|
|
86
|
+
self._closed = False
|
|
87
|
+
self._lock = Lock()
|
|
88
|
+
self._dirty: set[Binding] = set()
|
|
89
|
+
self._scheduled = False
|
|
90
|
+
self._work: Queue = Queue(maxsize=4096)
|
|
91
|
+
self._thread: Thread | None = None
|
|
92
|
+
self._ready = Event()
|
|
93
|
+
self._errors: list[str] = []
|
|
94
|
+
self._dropped = 0
|
|
95
|
+
self._poisoned = False # A failed DOM transaction leaves the managed DOM uncertain.
|
|
96
|
+
self.window: Any = None
|
|
97
|
+
self.document: Any = None
|
|
98
|
+
self.app: Any = None
|
|
99
|
+
self._updates = 0
|
|
100
|
+
self._operations = 0
|
|
101
|
+
self._discarded = 0 # write batches dropped because the document was already gone
|
|
102
|
+
|
|
103
|
+
def _id(self) -> str:
|
|
104
|
+
self._index += 1
|
|
105
|
+
return f"{self.prefix}-{self._index}"
|
|
106
|
+
|
|
107
|
+
def element(self, tag: str, *, css_class: str = "", attrs: dict[str, Any] | None = None,
|
|
108
|
+
text: str | State | Callable[[], Any] | None = None) -> Element:
|
|
109
|
+
if tag not in {"div", "section", "main", "header", "footer", "article", "nav", "aside", "p",
|
|
110
|
+
"span", "h1", "h2", "h3", "h4", "small", "strong", "em", "button", "label",
|
|
111
|
+
"input", "select", "option", "textarea", "form", "ul", "li", "table", "thead",
|
|
112
|
+
"tbody", "tr", "th", "td", "dialog", "pre", "code", "hr"}:
|
|
113
|
+
raise ValueError(f"Use raw_html for unsupported tag {tag!r} (trusted content only)")
|
|
114
|
+
if self.document is not None or self._closed:
|
|
115
|
+
raise RuntimeError("Cannot add components after mount/disposal")
|
|
116
|
+
a = dict(attrs or {})
|
|
117
|
+
if "id" in a:
|
|
118
|
+
raise ValueError("Managed UI element ids are generated by the library")
|
|
119
|
+
if css_class:
|
|
120
|
+
a["class"] = (a.get("class", "") + " " + css_class).strip()
|
|
121
|
+
el = Element(tag, self._id(), a)
|
|
122
|
+
self._stack[-1].children.append(el)
|
|
123
|
+
if text is not None:
|
|
124
|
+
if isinstance(text, Observable) or callable(text):
|
|
125
|
+
bind = self._bind(el, "text", text)
|
|
126
|
+
el.children.append(_string(bind.last))
|
|
127
|
+
else:
|
|
128
|
+
el.children.append(_string(text))
|
|
129
|
+
return el
|
|
130
|
+
|
|
131
|
+
def _bind(self, el: Element, kind: str, value: State | Callable[[], Any], name: str | None = None) -> Binding:
|
|
132
|
+
expr = (lambda: value.value) if isinstance(value, Observable) else value
|
|
133
|
+
bind = Binding(expr, self._mark_dirty)
|
|
134
|
+
bind.last = bind.evaluate()
|
|
135
|
+
self._bindings.append((el, kind, bind, name))
|
|
136
|
+
el.bindings.append((kind, bind, name))
|
|
137
|
+
return bind
|
|
138
|
+
|
|
139
|
+
@contextmanager
|
|
140
|
+
def container(self, tag: str = "div", *, css_class: str = "", attrs: dict[str, Any] | None = None):
|
|
141
|
+
if self.document is not None:
|
|
142
|
+
raise RuntimeError("UI tree already mounted; use state bindings to update it")
|
|
143
|
+
node = self.element(tag, css_class=css_class, attrs=attrs)
|
|
144
|
+
self._stack.append(node)
|
|
145
|
+
try:
|
|
146
|
+
yield node
|
|
147
|
+
finally:
|
|
148
|
+
self._stack.pop()
|
|
149
|
+
|
|
150
|
+
def row(self):
|
|
151
|
+
return self.container(css_class="nhk-row")
|
|
152
|
+
|
|
153
|
+
def column(self):
|
|
154
|
+
return self.container(css_class="nhk-col")
|
|
155
|
+
|
|
156
|
+
def grid(self):
|
|
157
|
+
return self.container(css_class="nhk-grid")
|
|
158
|
+
|
|
159
|
+
def card(self):
|
|
160
|
+
return self.container(css_class="nhk-card")
|
|
161
|
+
|
|
162
|
+
def stack(self):
|
|
163
|
+
return self.container(css_class="nhk-stack")
|
|
164
|
+
|
|
165
|
+
def heading(self, value: str | State | Callable[[], Any], *, level: int = 2) -> Element:
|
|
166
|
+
if level not in (1, 2, 3, 4):
|
|
167
|
+
raise ValueError("heading level must be 1 through 4")
|
|
168
|
+
return self.element(f"h{level}", css_class="nhk-heading", text=value)
|
|
169
|
+
|
|
170
|
+
def text(self, value: str | State | Callable[[], Any], *, muted: bool = False) -> Element:
|
|
171
|
+
return self.element("p", css_class="nhk-text" + (" nhk-muted" if muted else ""), text=value)
|
|
172
|
+
|
|
173
|
+
def badge(self, value: str | State | Callable[[], Any]) -> Element:
|
|
174
|
+
return self.element("span", css_class="nhk-badge", text=value)
|
|
175
|
+
|
|
176
|
+
def alert(self, value: str | State | Callable[[], Any]) -> Element:
|
|
177
|
+
return self.element("div", css_class="nhk-alert", attrs={"role": "status"}, text=value)
|
|
178
|
+
|
|
179
|
+
def button(self, label: str | State | Callable[[], Any], *, on_click: Callable[[dict], None] | None = None,
|
|
180
|
+
variant: str = "primary", disabled: bool | State | Callable[[], bool] = False) -> Element:
|
|
181
|
+
if variant not in ("primary", "secondary", "danger", "quiet"):
|
|
182
|
+
raise ValueError("Unsupported button variant")
|
|
183
|
+
el = self.element("button", css_class=f"nhk-button nhk-{variant}",
|
|
184
|
+
attrs={"type": "button"}, text=label)
|
|
185
|
+
self._boolean_attr(el, "disabled", disabled)
|
|
186
|
+
if on_click is not None:
|
|
187
|
+
self.on(el, "click", on_click)
|
|
188
|
+
return el
|
|
189
|
+
|
|
190
|
+
def input(self, value: State[str], *, label: str = "", placeholder: str = "",
|
|
191
|
+
kind: str = "text") -> Element:
|
|
192
|
+
if kind not in ("text", "password", "search", "email", "number"):
|
|
193
|
+
raise ValueError("Unsupported input type")
|
|
194
|
+
if label:
|
|
195
|
+
# Native label is linked to a generated element id, never placeholder-only.
|
|
196
|
+
with self.container(css_class="nhk-field"):
|
|
197
|
+
return self._input_control(value, label, placeholder, kind)
|
|
198
|
+
return self._input_control(value, label, placeholder, kind)
|
|
199
|
+
|
|
200
|
+
def _input_control(self, value: State[str], label: str, placeholder: str, kind: str) -> Element:
|
|
201
|
+
el = self.element("input", css_class="nhk-input",
|
|
202
|
+
attrs={"type": kind, "placeholder": placeholder})
|
|
203
|
+
if label:
|
|
204
|
+
self._label_before(el, label)
|
|
205
|
+
self._value_binding(el, value, "value", "input")
|
|
206
|
+
return el
|
|
207
|
+
|
|
208
|
+
def _label_before(self, control: Element, text: str) -> Element:
|
|
209
|
+
"""Add a native <label for> that precedes its control in document (reading) order."""
|
|
210
|
+
label = self.element("label", css_class="nhk-label", attrs={"for": control.id}, text=text)
|
|
211
|
+
siblings = self._stack[-1].children
|
|
212
|
+
siblings.remove(label)
|
|
213
|
+
siblings.insert(siblings.index(control), label)
|
|
214
|
+
return label
|
|
215
|
+
|
|
216
|
+
def checkbox(self, value: State[bool], *, label: str) -> Element:
|
|
217
|
+
with self.container("div", css_class="nhk-checkrow"):
|
|
218
|
+
el = self.element("input", attrs={"type": "checkbox"}, css_class="nhk-checkbox")
|
|
219
|
+
self.element("label", attrs={"for": el.id}, text=label)
|
|
220
|
+
self._value_binding(el, value, "checked", "change")
|
|
221
|
+
return el
|
|
222
|
+
|
|
223
|
+
def select(self, value: State[str], choices: Iterable[tuple[str, str]], *, label: str = "") -> Element:
|
|
224
|
+
with self.container(css_class="nhk-field"):
|
|
225
|
+
el = self.element("select", css_class="nhk-select")
|
|
226
|
+
if label:
|
|
227
|
+
self._label_before(el, label)
|
|
228
|
+
for key, text in choices:
|
|
229
|
+
child = Element("option", self._id(), {"value": str(key)})
|
|
230
|
+
child.children.append(str(text))
|
|
231
|
+
el.children.append(child)
|
|
232
|
+
self._value_binding(el, value, "value", "change")
|
|
233
|
+
# A <select> has no value attribute: mark the bound option as selected instead.
|
|
234
|
+
el.attrs.pop("value", None)
|
|
235
|
+
for child in el.children:
|
|
236
|
+
if isinstance(child, Element) and child.attrs.get("value") == _string(value.value):
|
|
237
|
+
child.attrs["selected"] = True
|
|
238
|
+
return el
|
|
239
|
+
|
|
240
|
+
def _value_binding(self, el: Element, value: State, kind: str, event: str) -> None:
|
|
241
|
+
if not isinstance(value, State):
|
|
242
|
+
raise TypeError("Two-way controls require a State instance")
|
|
243
|
+
bind = self._bind(el, kind, value)
|
|
244
|
+
el.attrs[kind] = bind.last # checked False is omitted
|
|
245
|
+
|
|
246
|
+
def receive(payload: dict) -> None:
|
|
247
|
+
# Event value/checked is authoritative; native editor already committed it.
|
|
248
|
+
if kind not in payload:
|
|
249
|
+
# SDK may omit it on some event types; use explicit public getter.
|
|
250
|
+
current = (self.document.get_value(el.id) if kind == "value" else
|
|
251
|
+
self.document.get_checked(el.id))
|
|
252
|
+
else:
|
|
253
|
+
current = payload[kind]
|
|
254
|
+
if kind == "checked":
|
|
255
|
+
current = bool(current)
|
|
256
|
+
else:
|
|
257
|
+
current = _string(current)
|
|
258
|
+
bind.last = current # prevent an echo write from resetting selection/IME
|
|
259
|
+
value.set(current)
|
|
260
|
+
self.on(el, event, receive)
|
|
261
|
+
|
|
262
|
+
def _boolean_attr(self, el: Element, name: str, value: bool | State | Callable[[], bool]) -> None:
|
|
263
|
+
if isinstance(value, Observable) or callable(value):
|
|
264
|
+
bind = self._bind(el, "boolean", value, name)
|
|
265
|
+
if bind.last:
|
|
266
|
+
el.attrs[name] = True
|
|
267
|
+
elif value:
|
|
268
|
+
el.attrs[name] = True
|
|
269
|
+
|
|
270
|
+
def when(self, condition: State | Callable[[], bool]):
|
|
271
|
+
"""Show/hide a permanently mounted subtree; never rebuild active native inputs."""
|
|
272
|
+
@contextmanager
|
|
273
|
+
def region():
|
|
274
|
+
with self.container(css_class="nhk-region") as el:
|
|
275
|
+
b = self._bind(el, "visible", condition)
|
|
276
|
+
if not bool(b.last):
|
|
277
|
+
el.attrs["class"] += " nhk-hidden"
|
|
278
|
+
yield el
|
|
279
|
+
return region()
|
|
280
|
+
|
|
281
|
+
def text_list(self, values: State | Callable[[], Iterable[Any]],
|
|
282
|
+
*, formatter: Callable[[Any], str] = str) -> Element:
|
|
283
|
+
"""Bound text-only list. Replaces this region when changed (not a virtualized grid)."""
|
|
284
|
+
el = self.element("ul", css_class="nhk-list")
|
|
285
|
+
expr = lambda: tuple(formatter(item) for item in
|
|
286
|
+
(values.value if isinstance(values, Observable) else values()))
|
|
287
|
+
self._bind(el, "html", expr) # _render_el renders the escaped items of this binding
|
|
288
|
+
return el
|
|
289
|
+
|
|
290
|
+
def on(self, el: Element, kind: str, callback: Callable[[dict], None]) -> None:
|
|
291
|
+
if kind not in ("click", "input", "change", "keydown", "submit", "auxclick", "contextmenu"):
|
|
292
|
+
raise ValueError(f"Unsupported event type: {kind!r}")
|
|
293
|
+
self._actions.setdefault(kind, {})[el.id] = callback
|
|
294
|
+
|
|
295
|
+
def raw_html(self, markup: str) -> Element:
|
|
296
|
+
"""Trusted HTML only; no sanitization. Do not pass remote/user content."""
|
|
297
|
+
el = self.element("div", css_class="nhk-custom")
|
|
298
|
+
# Plain strings elsewhere are escaped; only this explicit method inserts raw markup.
|
|
299
|
+
setattr(el, "_trusted_html", markup)
|
|
300
|
+
return el
|
|
301
|
+
|
|
302
|
+
def _render_el(self, el: Element) -> str:
|
|
303
|
+
attrs = dict(el.attrs)
|
|
304
|
+
attrs["id"] = el.id
|
|
305
|
+
start = "<" + el.tag + "".join(_attr(k, v) for k, v in attrs.items()) + ">"
|
|
306
|
+
if el.tag == "input":
|
|
307
|
+
return start
|
|
308
|
+
if hasattr(el, "_trusted_html"):
|
|
309
|
+
body = getattr(el, "_trusted_html")
|
|
310
|
+
elif any(k == "html" for k, _, _ in el.bindings):
|
|
311
|
+
bind = next(b for kind, b, _ in el.bindings if kind == "html")
|
|
312
|
+
body = self._render_text_list(bind.last)
|
|
313
|
+
else:
|
|
314
|
+
body = "".join(self._render_el(x) if isinstance(x, Element) else escape(x, quote=False)
|
|
315
|
+
for x in el.children)
|
|
316
|
+
return start + body + f"</{el.tag}>"
|
|
317
|
+
|
|
318
|
+
@staticmethod
|
|
319
|
+
def _render_text_list(items: Iterable[Any]) -> str:
|
|
320
|
+
return "".join("<li>" + escape(_string(v), quote=False) + "</li>" for v in items)
|
|
321
|
+
|
|
322
|
+
@staticmethod
|
|
323
|
+
def _css() -> str:
|
|
324
|
+
return files("nativehtmlkit_ui.assets").joinpath("ui.css").read_text(encoding="utf-8")
|
|
325
|
+
|
|
326
|
+
def html(self) -> str:
|
|
327
|
+
if len(self._stack) != 1:
|
|
328
|
+
raise RuntimeError("An open container context is not closed")
|
|
329
|
+
body = self._render_el(self.root)
|
|
330
|
+
theme = escape(self.theme, quote=True)
|
|
331
|
+
density = escape(self.density, quote=True)
|
|
332
|
+
return ("<!doctype html><html lang='en'><head><meta charset='utf-8'>"
|
|
333
|
+
"<meta name='viewport' content='width=device-width, initial-scale=1'>"
|
|
334
|
+
"<title>" + escape(self.title) + "</title><style>" + self._css() + "\n" + self.extra_css +
|
|
335
|
+
"</style></head><body class='nhk-theme-" + theme + " nhk-density-" + density + "'>" +
|
|
336
|
+
body + "</body></html>")
|
|
337
|
+
|
|
338
|
+
def mount(self, app: Any) -> "UI":
|
|
339
|
+
if self.document is not None:
|
|
340
|
+
raise RuntimeError("UI already mounted")
|
|
341
|
+
if self._closed:
|
|
342
|
+
raise RuntimeError("UI already disposed")
|
|
343
|
+
markup = self.html()
|
|
344
|
+
self.app = app
|
|
345
|
+
self.window = app.open_html(markup, title=self.title, width=self.width, height=self.height)
|
|
346
|
+
try:
|
|
347
|
+
self.document = self.window.document
|
|
348
|
+
# Native control values initialize from HTML attrs; make the live control state explicit.
|
|
349
|
+
for el, kind, b, _ in self._bindings:
|
|
350
|
+
if kind == "value":
|
|
351
|
+
self.document.set_value(el.id, _string(b.last))
|
|
352
|
+
elif kind == "checked":
|
|
353
|
+
self.document.set_checked(el.id, bool(b.last))
|
|
354
|
+
for kind in self._actions:
|
|
355
|
+
# One subscription per event kind instead of one per managed component.
|
|
356
|
+
unsub = self.document.on(kind, lambda ev, k=kind: self._forward_event(k, ev))
|
|
357
|
+
self._subscriptions.append(unsub)
|
|
358
|
+
# Application.on_shutdown has no unsubscribe: hold this UI weakly so repeated
|
|
359
|
+
# mount/dispose cycles do not keep disposed UIs (and their trees) alive.
|
|
360
|
+
app.on_shutdown(_weak_call(self, "dispose"))
|
|
361
|
+
window_id = self.window.id
|
|
362
|
+
ref = weakref.ref(self)
|
|
363
|
+
|
|
364
|
+
def window_event(ev: dict) -> None:
|
|
365
|
+
ui = ref()
|
|
366
|
+
if ui is not None and ev.get("window_id") == window_id and ev.get("type") == "closed":
|
|
367
|
+
ui.dispose()
|
|
368
|
+
self._subscriptions.append(app.on_window_event(window_event))
|
|
369
|
+
self._thread = Thread(target=self._owner, name="nativehtmlkit-ui", daemon=True)
|
|
370
|
+
self._thread.start()
|
|
371
|
+
except BaseException:
|
|
372
|
+
# Do not leave a half-mounted UI behind; the caller still owns the SDK lifecycle.
|
|
373
|
+
self.dispose()
|
|
374
|
+
try:
|
|
375
|
+
self.window.request_close()
|
|
376
|
+
except Exception:
|
|
377
|
+
LOG.debug("Could not close the window of a failed mount", exc_info=True)
|
|
378
|
+
raise
|
|
379
|
+
with self._lock:
|
|
380
|
+
pending = bool(self._dirty)
|
|
381
|
+
if pending:
|
|
382
|
+
self._queue_flush()
|
|
383
|
+
return self
|
|
384
|
+
|
|
385
|
+
def _owner(self) -> None:
|
|
386
|
+
self._ready.set()
|
|
387
|
+
while True:
|
|
388
|
+
item = self._work.get()
|
|
389
|
+
if item is _STOP:
|
|
390
|
+
return
|
|
391
|
+
fn, args = item
|
|
392
|
+
if self._closed:
|
|
393
|
+
continue
|
|
394
|
+
try:
|
|
395
|
+
fn(*args)
|
|
396
|
+
except Exception as exc:
|
|
397
|
+
self._record_error(exc)
|
|
398
|
+
|
|
399
|
+
def _record_error(self, exc: Exception) -> None:
|
|
400
|
+
LOG.exception("NativeHTMLKit UI callback/update failed")
|
|
401
|
+
with self._lock:
|
|
402
|
+
self._errors.append(f"{type(exc).__name__}: {exc}")
|
|
403
|
+
self._errors[:] = self._errors[-64:]
|
|
404
|
+
|
|
405
|
+
@property
|
|
406
|
+
def diagnostics(self) -> dict[str, Any]:
|
|
407
|
+
with self._lock:
|
|
408
|
+
return {"errors": tuple(self._errors), "event_queue_dropped": self._dropped,
|
|
409
|
+
"pending_updates": len(self._dirty), "dom_uncertain": self._poisoned,
|
|
410
|
+
"updates": self._updates, "operations": self._operations,
|
|
411
|
+
"subscriptions": len(self._subscriptions), "disposed": self._closed,
|
|
412
|
+
"discarded_after_close": self._discarded}
|
|
413
|
+
|
|
414
|
+
def post(self, fn: Callable, *args: Any) -> None:
|
|
415
|
+
if self._closed:
|
|
416
|
+
return
|
|
417
|
+
# Even on the owner, queue rather than invoke immediately. This preserves
|
|
418
|
+
# batching across multiple changes in a single event callback.
|
|
419
|
+
try:
|
|
420
|
+
self._work.put_nowait((fn, args))
|
|
421
|
+
except Full:
|
|
422
|
+
with self._lock:
|
|
423
|
+
self._dropped += 1
|
|
424
|
+
raise RuntimeError("NativeHTMLKit UI queue full: event not delivered; inspect diagnostics")
|
|
425
|
+
|
|
426
|
+
def _forward_event(self, kind: str, event: dict) -> None:
|
|
427
|
+
"""Runs on the SDK event worker: only enqueue, never block or raise into the SDK."""
|
|
428
|
+
if self._closed:
|
|
429
|
+
return
|
|
430
|
+
try:
|
|
431
|
+
self._work.put_nowait((self._event, (kind, event)))
|
|
432
|
+
except Full:
|
|
433
|
+
with self._lock:
|
|
434
|
+
self._dropped += 1
|
|
435
|
+
first = self._dropped == 1
|
|
436
|
+
# Do not reconstruct the lost event; report it once per UI and count every loss.
|
|
437
|
+
(LOG.error if first else LOG.debug)(
|
|
438
|
+
"NativeHTMLKit UI event queue full: a %s event was dropped (total %d)", kind, self._dropped)
|
|
439
|
+
|
|
440
|
+
def _event(self, kind: str, event: dict) -> None:
|
|
441
|
+
actions = self._actions.get(kind, {})
|
|
442
|
+
path = [event.get("element"), *(event.get("path") or [])]
|
|
443
|
+
for id_ in path:
|
|
444
|
+
fn = actions.get(id_)
|
|
445
|
+
if fn is not None:
|
|
446
|
+
fn(event)
|
|
447
|
+
break # nearest registered ancestor, like a delegated native handler
|
|
448
|
+
|
|
449
|
+
def _mark_dirty(self, bind: Binding) -> None:
|
|
450
|
+
with self._lock:
|
|
451
|
+
if self._closed:
|
|
452
|
+
return
|
|
453
|
+
self._dirty.add(bind)
|
|
454
|
+
if self.document is not None:
|
|
455
|
+
self._queue_flush()
|
|
456
|
+
|
|
457
|
+
def _queue_flush(self) -> None:
|
|
458
|
+
with self._lock:
|
|
459
|
+
if self._closed or self._scheduled:
|
|
460
|
+
return
|
|
461
|
+
self._scheduled = True
|
|
462
|
+
try:
|
|
463
|
+
self.post(self._flush)
|
|
464
|
+
except Exception:
|
|
465
|
+
with self._lock:
|
|
466
|
+
self._scheduled = False
|
|
467
|
+
raise
|
|
468
|
+
|
|
469
|
+
def _flush(self) -> None:
|
|
470
|
+
with self._lock:
|
|
471
|
+
dirty = self._dirty
|
|
472
|
+
self._dirty = set()
|
|
473
|
+
self._scheduled = False
|
|
474
|
+
if not dirty or self._closed or self.document is None or self._poisoned:
|
|
475
|
+
return
|
|
476
|
+
if self._document_gone():
|
|
477
|
+
self.dispose()
|
|
478
|
+
return
|
|
479
|
+
operations: list[dict] = []
|
|
480
|
+
special: list[tuple[str, str, Any]] = []
|
|
481
|
+
for el, kind, bind, name in self._bindings:
|
|
482
|
+
if bind not in dirty or bind.closed:
|
|
483
|
+
continue
|
|
484
|
+
current = bind.evaluate()
|
|
485
|
+
if current is bind.last or current == bind.last:
|
|
486
|
+
continue
|
|
487
|
+
bind.last = current
|
|
488
|
+
if kind == "text":
|
|
489
|
+
operations.append({"op": "set_text", "element": el.id, "text": _string(current)})
|
|
490
|
+
elif kind == "visible":
|
|
491
|
+
operations.append({"op": "remove_class" if current else "add_class",
|
|
492
|
+
"element": el.id, "name": "nhk-hidden"})
|
|
493
|
+
elif kind == "boolean":
|
|
494
|
+
operations.append({"op": "set_attribute" if current else "remove_attribute",
|
|
495
|
+
"element": el.id, "name": name, **({"value": ""} if current else {})})
|
|
496
|
+
elif kind in ("value", "checked", "html"):
|
|
497
|
+
special.append((kind, el.id, current))
|
|
498
|
+
for kind, ident, value in special:
|
|
499
|
+
if kind == "html":
|
|
500
|
+
operations.append({"op": "replace_children_html", "element": ident,
|
|
501
|
+
"html": self._render_text_list(value)})
|
|
502
|
+
special = [entry for entry in special if entry[0] != "html"]
|
|
503
|
+
if not operations and not special:
|
|
504
|
+
return
|
|
505
|
+
# Do not silently recover a failed atomic batch or an outcome-unknown write; the DOM may be stale.
|
|
506
|
+
try:
|
|
507
|
+
for start in range(0, len(operations), 128):
|
|
508
|
+
batch = operations[start:start + 128]
|
|
509
|
+
if len(batch) == 1:
|
|
510
|
+
op = batch[0]
|
|
511
|
+
self.document.command(op["op"], **{k: v for k, v in op.items() if k != "op"})
|
|
512
|
+
else:
|
|
513
|
+
self.document.batch(batch)
|
|
514
|
+
self._operations += len(batch)
|
|
515
|
+
for kind, ident, value in special:
|
|
516
|
+
if kind == "value":
|
|
517
|
+
self.document.set_value(ident, _string(value))
|
|
518
|
+
else:
|
|
519
|
+
self.document.set_checked(ident, bool(value))
|
|
520
|
+
self._operations += 1
|
|
521
|
+
self._updates += 1
|
|
522
|
+
except Exception as exc:
|
|
523
|
+
if self._document_gone(exc):
|
|
524
|
+
# The window closed or the app shut down: nothing left to keep in sync.
|
|
525
|
+
LOG.debug("NativeHTMLKit UI document is gone (%s); disposing the UI", type(exc).__name__)
|
|
526
|
+
with self._lock:
|
|
527
|
+
self._discarded += 1
|
|
528
|
+
self.dispose()
|
|
529
|
+
return
|
|
530
|
+
with self._lock:
|
|
531
|
+
self._poisoned = True
|
|
532
|
+
raise
|
|
533
|
+
|
|
534
|
+
def _document_gone(self, exc: BaseException | None = None) -> bool:
|
|
535
|
+
"""True when the SDK retired this UI's window/document (closed, replaced, app.shutdown)."""
|
|
536
|
+
window = self.window
|
|
537
|
+
if window is None or getattr(window, "closed", False) or getattr(window, "document", None) is not self.document:
|
|
538
|
+
return True
|
|
539
|
+
if exc is None:
|
|
540
|
+
return False
|
|
541
|
+
if type(exc).__name__ in ("StaleDocumentError", "ApplicationShutdownError"):
|
|
542
|
+
return True
|
|
543
|
+
# Definite host rejections (not outcome-unknown): -32004 the window/document no longer
|
|
544
|
+
# exists, -32008 the application is shutting down (protocol v1 section 5). The write was not
|
|
545
|
+
# applied and there is no document left to keep in sync.
|
|
546
|
+
return (getattr(exc, "code", None) in _GONE_CODES and not getattr(exc, "local", False))
|
|
547
|
+
|
|
548
|
+
def sync(self, timeout: float = 10.0) -> None:
|
|
549
|
+
"""Drain work submitted before this call (for tests/explicit synchronization)."""
|
|
550
|
+
if self._closed:
|
|
551
|
+
raise RuntimeError("UI already disposed")
|
|
552
|
+
if self._thread is None:
|
|
553
|
+
raise RuntimeError("UI not mounted")
|
|
554
|
+
if current_thread() is self._thread:
|
|
555
|
+
self._flush()
|
|
556
|
+
return
|
|
557
|
+
marker = Event()
|
|
558
|
+
self.post(lambda: marker.set())
|
|
559
|
+
if not marker.wait(timeout):
|
|
560
|
+
raise TimeoutError("UI owner did not process the synchronization marker")
|
|
561
|
+
if self._poisoned:
|
|
562
|
+
raise RuntimeError("NativeHTMLKit UI DOM state is uncertain after a failed operation; inspect diagnostics")
|
|
563
|
+
|
|
564
|
+
def dispose(self) -> None:
|
|
565
|
+
with self._lock:
|
|
566
|
+
if self._closed:
|
|
567
|
+
return
|
|
568
|
+
self._closed = True
|
|
569
|
+
for unsubscribe in self._subscriptions:
|
|
570
|
+
try:
|
|
571
|
+
unsubscribe()
|
|
572
|
+
except Exception:
|
|
573
|
+
LOG.exception("Failed to unsubscribe a native event")
|
|
574
|
+
self._subscriptions.clear()
|
|
575
|
+
for _, _, bind, _ in self._bindings:
|
|
576
|
+
bind.close()
|
|
577
|
+
try:
|
|
578
|
+
self._work.put_nowait(_STOP)
|
|
579
|
+
except Full:
|
|
580
|
+
# A bounded queue can be full during shutdown; make room for the stop token.
|
|
581
|
+
try:
|
|
582
|
+
self._work.get_nowait()
|
|
583
|
+
self._work.put_nowait(_STOP)
|
|
584
|
+
except Empty:
|
|
585
|
+
pass
|
|
586
|
+
if self._thread is not None and current_thread() is not self._thread:
|
|
587
|
+
self._thread.join(timeout=2.0)
|
|
588
|
+
|
|
589
|
+
close = dispose
|
|
590
|
+
|
|
591
|
+
|
|
592
|
+
def _weak_call(obj: Any, method: str) -> Callable[[], None]:
|
|
593
|
+
ref = weakref.ref(obj)
|
|
594
|
+
|
|
595
|
+
def call() -> None:
|
|
596
|
+
target = ref()
|
|
597
|
+
if target is not None:
|
|
598
|
+
getattr(target, method)()
|
|
599
|
+
return call
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
"""Small, synchronous, dependency-tracked reactive primitives.
|
|
2
|
+
|
|
3
|
+
No SDK imports. State changes may originate on any Python thread. A subscriber
|
|
4
|
+
that touches the UI must marshal back to UI.post (Binding does this).
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from contextvars import ContextVar
|
|
9
|
+
from threading import RLock
|
|
10
|
+
from typing import Any, Callable, Generic, TypeVar
|
|
11
|
+
|
|
12
|
+
T = TypeVar("T")
|
|
13
|
+
_COLLECT: ContextVar[Callable[["Observable"], None] | None] = ContextVar("nhk_ui_collect", default=None)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class Observable:
|
|
17
|
+
def __init__(self) -> None:
|
|
18
|
+
self._listeners: set[Callable[[], None]] = set()
|
|
19
|
+
self._lock = RLock()
|
|
20
|
+
|
|
21
|
+
def _read(self) -> None:
|
|
22
|
+
collector = _COLLECT.get()
|
|
23
|
+
if collector is not None:
|
|
24
|
+
collector(self)
|
|
25
|
+
|
|
26
|
+
def subscribe(self, callback: Callable[[], None]) -> Callable[[], None]:
|
|
27
|
+
with self._lock:
|
|
28
|
+
self._listeners.add(callback)
|
|
29
|
+
|
|
30
|
+
def remove() -> None:
|
|
31
|
+
with self._lock:
|
|
32
|
+
self._listeners.discard(callback)
|
|
33
|
+
return remove
|
|
34
|
+
|
|
35
|
+
def _notify(self) -> None:
|
|
36
|
+
with self._lock:
|
|
37
|
+
listeners = tuple(self._listeners)
|
|
38
|
+
for callback in listeners:
|
|
39
|
+
callback()
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class State(Observable, Generic[T]):
|
|
43
|
+
"""Observable value; use .set(...) or assign .value; does not deeply proxy collections."""
|
|
44
|
+
def __init__(self, value: T):
|
|
45
|
+
super().__init__()
|
|
46
|
+
self._value = value
|
|
47
|
+
|
|
48
|
+
@property
|
|
49
|
+
def value(self) -> T:
|
|
50
|
+
self._read()
|
|
51
|
+
with self._lock:
|
|
52
|
+
return self._value
|
|
53
|
+
|
|
54
|
+
@value.setter
|
|
55
|
+
def value(self, value: T) -> None:
|
|
56
|
+
self.set(value)
|
|
57
|
+
|
|
58
|
+
def set(self, value: T) -> bool:
|
|
59
|
+
with self._lock:
|
|
60
|
+
if self._value is value or self._value == value:
|
|
61
|
+
return False
|
|
62
|
+
self._value = value
|
|
63
|
+
self._notify()
|
|
64
|
+
return True
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class Computed(Observable, Generic[T]):
|
|
68
|
+
"""Eager dependency-tracked computed value, with self-cycle detection."""
|
|
69
|
+
def __init__(self, fn: Callable[[], T]):
|
|
70
|
+
super().__init__()
|
|
71
|
+
self._fn = fn
|
|
72
|
+
self._unsub: dict[Observable, Callable[[], None]] = {}
|
|
73
|
+
self._calculating = False
|
|
74
|
+
self._closed = False
|
|
75
|
+
self._value: T = self._calculate(initial=True)
|
|
76
|
+
|
|
77
|
+
def _calculate(self, initial: bool = False) -> T:
|
|
78
|
+
if self._calculating:
|
|
79
|
+
raise RuntimeError("Circular computed-state dependency")
|
|
80
|
+
self._calculating = True
|
|
81
|
+
deps: set[Observable] = set()
|
|
82
|
+
token = _COLLECT.set(deps.add)
|
|
83
|
+
try:
|
|
84
|
+
value = self._fn()
|
|
85
|
+
finally:
|
|
86
|
+
_COLLECT.reset(token)
|
|
87
|
+
self._calculating = False
|
|
88
|
+
if self in deps:
|
|
89
|
+
raise RuntimeError("Computed value depends on itself")
|
|
90
|
+
for dep, remove in tuple(self._unsub.items()):
|
|
91
|
+
if dep not in deps:
|
|
92
|
+
remove()
|
|
93
|
+
del self._unsub[dep]
|
|
94
|
+
for dep in deps - self._unsub.keys():
|
|
95
|
+
self._unsub[dep] = dep.subscribe(self._changed)
|
|
96
|
+
return value
|
|
97
|
+
|
|
98
|
+
def _changed(self) -> None:
|
|
99
|
+
if self._closed:
|
|
100
|
+
return
|
|
101
|
+
new = self._calculate()
|
|
102
|
+
with self._lock:
|
|
103
|
+
if new is self._value or new == self._value:
|
|
104
|
+
return
|
|
105
|
+
self._value = new
|
|
106
|
+
self._notify()
|
|
107
|
+
|
|
108
|
+
@property
|
|
109
|
+
def value(self) -> T:
|
|
110
|
+
self._read()
|
|
111
|
+
return self._value
|
|
112
|
+
|
|
113
|
+
def close(self) -> None:
|
|
114
|
+
self._closed = True
|
|
115
|
+
for remove in self._unsub.values():
|
|
116
|
+
remove()
|
|
117
|
+
self._unsub.clear()
|
|
118
|
+
with self._lock:
|
|
119
|
+
self._listeners.clear()
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def state(value: T) -> State[T]:
|
|
123
|
+
return State(value)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def computed(fn: Callable[[], T]) -> Computed[T]:
|
|
127
|
+
return Computed(fn)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
class Binding:
|
|
131
|
+
"""Tracks observable reads in an expression and notifies a scheduler."""
|
|
132
|
+
def __init__(self, expression: Callable[[], Any], changed: Callable[["Binding"], None]):
|
|
133
|
+
self.expression = expression
|
|
134
|
+
self.changed = changed
|
|
135
|
+
self.last: Any = _MISSING
|
|
136
|
+
self.unsub: dict[Observable, Callable[[], None]] = {}
|
|
137
|
+
self.closed = False
|
|
138
|
+
|
|
139
|
+
def evaluate(self) -> Any:
|
|
140
|
+
if self.closed:
|
|
141
|
+
return self.last
|
|
142
|
+
deps: set[Observable] = set()
|
|
143
|
+
token = _COLLECT.set(deps.add)
|
|
144
|
+
try:
|
|
145
|
+
val = self.expression()
|
|
146
|
+
finally:
|
|
147
|
+
_COLLECT.reset(token)
|
|
148
|
+
for dep, remove in tuple(self.unsub.items()):
|
|
149
|
+
if dep not in deps:
|
|
150
|
+
remove()
|
|
151
|
+
del self.unsub[dep]
|
|
152
|
+
for dep in deps - self.unsub.keys():
|
|
153
|
+
self.unsub[dep] = dep.subscribe(self._change)
|
|
154
|
+
return val
|
|
155
|
+
|
|
156
|
+
def _change(self) -> None:
|
|
157
|
+
if not self.closed:
|
|
158
|
+
self.changed(self)
|
|
159
|
+
|
|
160
|
+
def close(self) -> None:
|
|
161
|
+
self.closed = True
|
|
162
|
+
for remove in self.unsub.values():
|
|
163
|
+
remove()
|
|
164
|
+
self.unsub.clear()
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
_MISSING = object()
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: nativehtmlkit_ui
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Minimal reactive UI toolkit for native HTML/CSS desktop applications
|
|
5
|
+
Author: NativeHTMLKit contributors
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/nativehtmlkit/nativehtmlkit_ui
|
|
8
|
+
Project-URL: Documentation, https://github.com/nativehtmlkit/nativehtmlkit_ui/blob/main/docs/API.md
|
|
9
|
+
Project-URL: Issues, https://github.com/nativehtmlkit/nativehtmlkit_ui/issues
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
12
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
13
|
+
Classifier: Operating System :: POSIX :: Linux
|
|
14
|
+
Classifier: Operating System :: Microsoft :: Windows
|
|
15
|
+
Classifier: Topic :: Software Development :: User Interfaces
|
|
16
|
+
Requires-Python: >=3.10
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
License-File: LICENSE
|
|
19
|
+
Requires-Dist: nativehtmlkit<0.2.0,>=0.1.0
|
|
20
|
+
Dynamic: license-file
|
|
21
|
+
|
|
22
|
+
# `nativehtmlkit_ui` — Python
|
|
23
|
+
|
|
24
|
+
Pure Python UI primitives over the public [`nativehtmlkit`](https://github.com/nativehtmlkit/nativehtmlkit-python) SDK.
|
|
25
|
+
No dependency on Rust sources, Core internals, the CLI, Qt, Chromium, JavaScript, Node or web servers.
|
|
26
|
+
|
|
27
|
+
- Python >=3.10; SDK `nativehtmlkit` `0.1.x` is required (qualified with 0.1.0; source-checked with 0.1.1).
|
|
28
|
+
- Install a qualified `nativehtmlkit` platform wheel first, then `python -m pip install --no-index --no-deps ./dist/nativehtmlkit_ui-0.1.0-py3-none-any.whl`.
|
|
29
|
+
- Host-first runner: `python -m nativehtmlkit run mymodule:main --name MyApp`; `main(app)` builds/mounts UI then returns; the SDK runner owns `app.run()`.
|
|
30
|
+
- For a script using direct `Application.start()`, keep side effects after `start()`; SDK re-executes the script in its backend process.
|
|
31
|
+
|
|
32
|
+
```python
|
|
33
|
+
from nativehtmlkit_ui import UI, state, computed
|
|
34
|
+
|
|
35
|
+
def main(app):
|
|
36
|
+
counter = state(0)
|
|
37
|
+
name = state("world")
|
|
38
|
+
greeting = computed(lambda: f"Hello, {name.value} ({counter.value})")
|
|
39
|
+
ui = UI(title="Hello", theme="cobalt", density="compact")
|
|
40
|
+
with ui.column():
|
|
41
|
+
ui.heading("Hello")
|
|
42
|
+
ui.text(greeting)
|
|
43
|
+
ui.input(name, label="Name")
|
|
44
|
+
ui.button("Add", on_click=lambda e: counter.set(counter.value + 1))
|
|
45
|
+
ui.mount(app)
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Text and attribute values are escaped. `ui.raw_html()` and `extra_css` accept **trusted** source content only. Runtime values should go through `state`/bindings, never raw markup.
|
|
49
|
+
|
|
50
|
+
One UI `UI` instance owns one SDK window/document. Create another UI instance for another window. `ui.post(callback, *args)` safely marshals work from background Python threads to the UI owner thread. `ui.sync()` is a test/explicit flush helper; `ui.dispose()` unsubscribes and stops the UI owner (it does not terminate the underlying SDK application).
|
|
51
|
+
|
|
52
|
+
See the repository root docs for SDK integration, limitations, packaging and qualification. The initial `text_list` replaces its local region; it is not a virtualized/keyed data grid. `when` toggles visibility but keeps its subtree mounted. No router, extension system, dynamic DOM reconciliation or generic persistence layer is included.
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
nativehtmlkit_ui/__init__.py,sha256=gjbzEIwzrKQ-ezb4xIbViiMT3M1IW114vvWRPlOvjdU,309
|
|
2
|
+
nativehtmlkit_ui/engine.py,sha256=zi8Aze0E22TqPqGu-S2w1vh_gE-JDjYzwiG_W7n5MVk,26736
|
|
3
|
+
nativehtmlkit_ui/reactive.py,sha256=kIDhVyHHQcscXUTmXk8KnA6GaZMAv-pbPalqHDiyUJI,4879
|
|
4
|
+
nativehtmlkit_ui/assets/__init__.py,sha256=V3Jv6NK5qrZAaiUnAruRkqIVZHKRiVgOWnEoO6jExlc,34
|
|
5
|
+
nativehtmlkit_ui/assets/ui.css,sha256=tDj9Kh6NAmSKXBBPvLdmYrvajaGAvQL3zXnXfyF6cBc,4632
|
|
6
|
+
nativehtmlkit_ui-0.1.0.dist-info/licenses/LICENSE,sha256=X28xnB-UFkL9UzHfNkLlJbXXzHhb5rIjgfRyxeLpM1g,1083
|
|
7
|
+
nativehtmlkit_ui-0.1.0.dist-info/METADATA,sha256=Js-eykv1EWqHceVgalnaM1STKcUODExu4jqL6W4M-xw,3067
|
|
8
|
+
nativehtmlkit_ui-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
9
|
+
nativehtmlkit_ui-0.1.0.dist-info/top_level.txt,sha256=d3uZwnD6RuKpmbimmmE2co4ABdEDwL9hxPTonTouSg8,17
|
|
10
|
+
nativehtmlkit_ui-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 NativeHTMLKit contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
nativehtmlkit_ui
|