hstream-webawesome 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.
@@ -0,0 +1,171 @@
1
+ """Every Web Awesome component for HStream, as ``wa.*``.
2
+
3
+ ::
4
+
5
+ from hstream import hs, wa
6
+
7
+ name = wa.input("Name", placeholder="Ada")
8
+ if wa.switch("Shout"):
9
+ name = name.upper()
10
+ with wa.card():
11
+ wa.callout(f"Hello {name}", variant="brand")
12
+
13
+ Installing the package is enough: ``from hstream import wa`` (or ``hs.wa``)
14
+ finds it through the ``hstream.components`` entry point. Import it (``import hstream_webawesome``)
15
+ only where entry points don't exist (the ``hstream build`` browser bundle).
16
+
17
+ Most of this package is generated from Web Awesome's ``custom-elements.json``
18
+ (``_generated.py``, by ``scripts/generate.py``). This module adds the parts
19
+ that need a person's judgement.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ from typing import Any, Iterable, Optional, Tuple
25
+
26
+ from hstream import component_wrapper, register_namespace
27
+ from hstream.context import current_session
28
+ from hstream.context import current_tree as _tree
29
+ from hstream_webawesome._base import (
30
+ CDN,
31
+ Content,
32
+ _options,
33
+ _wa_tag,
34
+ assets,
35
+ post_url,
36
+ to_number,
37
+ )
38
+ from hstream_webawesome._generated import (
39
+ COMPONENTS,
40
+ GeneratedRaw,
41
+ GeneratedWebAwesome,
42
+ )
43
+ from hstream_webawesome._wa_version import WA_VERSION
44
+
45
+ __all__ = ["wa", "WebAwesome", "COMPONENTS", "WA_VERSION", "CDN", "assets"]
46
+
47
+
48
+ class WebAwesome(GeneratedWebAwesome):
49
+ __doc__ = GeneratedWebAwesome.__doc__
50
+
51
+ #: Every component as a plain element without session state.
52
+ raw = GeneratedRaw()
53
+
54
+ # -- hand-tuned controls ----------------------------------------------
55
+
56
+ @component_wrapper(tag="wa-slider")
57
+ def slider(
58
+ self,
59
+ label: Content = None,
60
+ default_value: Any = None,
61
+ *,
62
+ key: Optional[str] = None,
63
+ min: Optional[float] = None,
64
+ max: Optional[float] = None,
65
+ step: Optional[float] = None,
66
+ range: Optional[bool] = None,
67
+ hint: Optional[str] = None,
68
+ **attrs: Any,
69
+ ) -> Any:
70
+ """A slider; ``range=True`` gives two thumbs and returns ``(low, high)``.
71
+
72
+ ``<wa-slider>``: https://webawesome.com/docs/components/slider
73
+
74
+ Other keyword arguments (``with_markers=True``, ``with_tooltip=True``,
75
+ ``orientation="vertical"``, ...) become attributes.
76
+
77
+ Returns: the number, or a ``(low, high)`` tuple when ``range=True``.
78
+ Before the user moves it: ``default_value``, else ``min`` (or 0); for a
79
+ range, ``default_value`` or ``(min, max)``.
80
+ """
81
+ low_bound = 0 if min is None else min
82
+ high_bound = 100 if max is None else max
83
+ common = {"min": min, "max": max, "step": step, "hint": hint}
84
+ if not range:
85
+ fallback = low_bound if default_value is None else default_value
86
+ return self._control(
87
+ "number", common, attrs, key=key, label=label, default_value=fallback
88
+ )
89
+
90
+ self._ensure_assets()
91
+ stored = attrs.pop("value", None)
92
+ fallback = tuple(default_value) if default_value else (low_bound, high_bound)
93
+
94
+ def parse(value) -> Tuple[Any, Any]:
95
+ if isinstance(value, str) and "," in value:
96
+ low, high = value.split(",", 1)
97
+ return (to_number(low, fallback[0]), to_number(high, fallback[1]))
98
+ if isinstance(value, (list, tuple)) and len(value) == 2:
99
+ return (
100
+ to_number(value[0], fallback[0]),
101
+ to_number(value[1], fallback[1]),
102
+ )
103
+ return fallback
104
+
105
+ low, high = parse(stored)
106
+ # A range slider's form value is two entries; post them as one
107
+ # "low,high" string (an HTTP client can send that directly).
108
+ _tree().attr(
109
+ ("hx-post", post_url(key)),
110
+ ("hx-trigger", "change"),
111
+ ("hx-vals", 'js:{new_value: this.minValue + "," + this.maxValue}'),
112
+ *self._attrs(
113
+ {
114
+ **common,
115
+ "range": True,
116
+ "min-value": low,
117
+ "max-value": high,
118
+ "label": None if label is None else str(label),
119
+ },
120
+ attrs,
121
+ ),
122
+ )
123
+ return parse
124
+
125
+ @component_wrapper(tag="wa-dropdown")
126
+ def menu(
127
+ self,
128
+ label: Content,
129
+ items: Iterable[Any],
130
+ *,
131
+ key: Optional[str] = None,
132
+ variant: Optional[str] = None,
133
+ appearance: Optional[str] = None,
134
+ placement: Optional[str] = None,
135
+ **attrs: Any,
136
+ ) -> Any:
137
+ """A button that opens a menu; returns the item picked, once.
138
+
139
+ ``<wa-dropdown>``: https://webawesome.com/docs/components/dropdown
140
+
141
+ ``items`` is a list of values, ``(value, label)`` pairs or a
142
+ ``{value: label}`` dict. Like ``hs.button``, the result is the picked
143
+ item on the run the pick triggers and ``None`` on every other run::
144
+
145
+ action = wa.menu("Actions", ["Copy", "Delete"])
146
+ if action == "Delete":
147
+ ...
148
+ """
149
+ self._ensure_assets()
150
+ stored = attrs.pop("value", None)
151
+ pairs = _options(items)
152
+ by_text = {str(v): v for v, _ in pairs}
153
+ session = current_session()
154
+ if stored not in (None, ""):
155
+ session[key] = None # one-shot: reset for the next run
156
+ _tree().attr(
157
+ ("hx-post", post_url(key)),
158
+ ("hx-trigger", "wa-select"),
159
+ ("hx-vals", "js:{new_value: ctx.sourceEvent.detail.item.value}"),
160
+ *self._attrs({"placement": placement}, attrs),
161
+ )
162
+ button = {"variant": variant, "appearance": appearance, "with-caret": True}
163
+ with _wa_tag("wa-button", ("slot", "trigger"), *self._attrs(button, {})):
164
+ self._content(label)
165
+ for value, text in pairs:
166
+ with _wa_tag("wa-dropdown-item", ("value", str(value))):
167
+ _tree().text(str(text))
168
+ return lambda v: None if v in (None, "") else by_text.get(str(v), v)
169
+
170
+
171
+ wa = register_namespace("wa", WebAwesome())
@@ -0,0 +1,292 @@
1
+ """Hand-written runtime the generated components call into (``wa.*``).
2
+
3
+ ``_generated.py`` (made by ``scripts/generate.py`` from Web Awesome's
4
+ ``custom-elements.json``) holds one thin method per component: its signature,
5
+ docstring and which of the helpers below renders it. Everything that decides
6
+ *how* a component behaves in HStream lives here:
7
+
8
+ * :meth:`WebAwesomeBase._element` renders a plain element (cards, badges,
9
+ icons, layout): a ``TagContext`` you can use with ``with``.
10
+ * :meth:`WebAwesomeBase._control` renders a form control bound to the session
11
+ (inside ``@component_wrapper(tag=...)``, so the control *is* the component
12
+ container, with no extra ``<div>``). ``kind`` picks how its value is sent
13
+ and parsed: ``text``, ``number``, ``bool``, ``choice``, ``list``,
14
+ ``action``.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from typing import Any, Callable, Dict, Iterable, Optional, Union
20
+ from urllib.parse import quote
21
+
22
+ from hstream import ComponentNamespace
23
+ from hstream.context import current_session, current_tree
24
+ from hstream.context import current_tree as _tree # builder calls (see below)
25
+ from hstream_webawesome._wa_version import WA_VERSION
26
+
27
+ CDN = f"https://ka-f.webawesome.com/webawesome@{WA_VERSION}"
28
+
29
+ Content = Union[str, int, float, Callable[[], Any], None]
30
+
31
+ # Pico spaces native form fields; give Web Awesome's the same rhythm.
32
+ _SPACING_CSS = (
33
+ "<style>#hs-content :is(wa-input, wa-textarea, wa-select, wa-slider,"
34
+ " wa-radio-group, wa-checkbox-group, wa-checkbox, wa-switch, wa-rating,"
35
+ " wa-tag-input, wa-color-picker, wa-number-input, wa-time-input,"
36
+ " wa-otp-input, wa-known-date, wa-callout, wa-card, wa-details,"
37
+ " wa-tab-group, wa-progress-bar):not(:last-child)"
38
+ " { display: block; margin-block-end: var(--pico-spacing, 1rem); }"
39
+ " #hs-content :is(wa-checkbox, wa-switch, wa-rating) { width: fit-content; }"
40
+ " #hs-content > :is(wa-button, wa-dropdown, wa-button-group)"
41
+ " { margin-block-end: var(--pico-spacing, 1rem); }"
42
+ "</style>"
43
+ )
44
+
45
+
46
+ def assets(theme: str = "default") -> list:
47
+ """The ``<link>``/``<script>``/``<style>`` tags Web Awesome needs on a page."""
48
+ return [
49
+ f'<link rel="stylesheet" href="{CDN}/styles/themes/{theme}.css" />',
50
+ f'<script type="module" src="{CDN}/webawesome.loader.js"></script>',
51
+ _SPACING_CSS,
52
+ ]
53
+
54
+
55
+ def _wa_tag(tag: str, *attrs):
56
+ """``tree.tag`` that gives the element a stable id from its tree path.
57
+
58
+ Some components give themselves an id when they have none (``wa-tab-1``).
59
+ htmx's morph only pairs an element that has an id with a new one of the
60
+ same id, so those elements would be replaced on every interaction, losing
61
+ their state (which tab is active). A server-side id, the same on every
62
+ run, keeps them paired, and the component keeps the id it was given.
63
+ """
64
+ context = _tree().tag(tag, *attrs)
65
+ node = context.node
66
+ if "id" not in node.attrs:
67
+ node.attrs["id"] = f"wa_{node.path}"
68
+ return context
69
+
70
+
71
+ def attr_name(python_name: str) -> str:
72
+ """``with_clear`` -> ``with-clear``; ``klass``/``class_`` -> ``class``."""
73
+ if python_name in ("klass", "class_", "_class"):
74
+ return "class"
75
+ return python_name.rstrip("_").replace("_", "-")
76
+
77
+
78
+ def attr_value(value: Any) -> Optional[str]:
79
+ """HTML attribute text: ``True`` -> present, ``False``/``None`` -> absent."""
80
+ if value is None or value is False:
81
+ return None
82
+ if value is True:
83
+ return ""
84
+ if isinstance(value, (list, tuple)):
85
+ return " ".join(str(v) for v in value)
86
+ return str(value)
87
+
88
+
89
+ def to_number(value: Any, default: Any) -> Any:
90
+ if value is None or value == "":
91
+ return default
92
+ if isinstance(value, (int, float)) and not isinstance(value, bool):
93
+ return value
94
+ for cast in (int, float):
95
+ try:
96
+ return cast(value)
97
+ except (TypeError, ValueError):
98
+ pass
99
+ return default
100
+
101
+
102
+ def to_list(value: Any) -> list:
103
+ if isinstance(value, (list, tuple)):
104
+ return list(value)
105
+ return [] if value in (None, "") else [value]
106
+
107
+
108
+ def post_url(key: str, new_value: Any = None) -> str:
109
+ url = f"/set_component_value?component_id={quote(str(key))}"
110
+ if new_value is not None:
111
+ url += f"&new_value={quote(str(new_value))}"
112
+ return url
113
+
114
+
115
+ def _options(options: Union[Iterable, Dict, None]) -> list:
116
+ """``[(value, label), ...]`` from a list of values or a ``{value: label}``."""
117
+ if options is None:
118
+ return []
119
+ if isinstance(options, dict):
120
+ return list(options.items())
121
+ pairs = []
122
+ for option in options:
123
+ if isinstance(option, tuple) and len(option) == 2:
124
+ pairs.append(option)
125
+ else:
126
+ pairs.append((option, option))
127
+ return pairs
128
+
129
+
130
+ class WebAwesomeBase(ComponentNamespace):
131
+ """Shared helpers for ``hs.wa``. Generated methods call these.
132
+
133
+ Helpers render through the tree (``_tree().tag``) instead of the inherited
134
+ ``self.tag``/``self.text``: Web Awesome has components with those names
135
+ (``<wa-tag>``), and the generated ``hs.wa.tag(...)`` replaces them.
136
+ """
137
+
138
+ # -- page setup ------------------------------------------------------
139
+
140
+ def _ensure_assets(self) -> None:
141
+ theme = getattr(current_tree(), "hs_wa_theme", "default")
142
+ for html in assets(theme):
143
+ _tree().add_asset(html)
144
+
145
+ def theme(self, name: str = "default") -> None:
146
+ """Use another free Web Awesome theme (``default``, ``awesome`` or
147
+ ``shoelace``). Call it at the top of the script, before any
148
+ ``hs.wa`` component: it applies to the run it is called in."""
149
+ current_tree().hs_wa_theme = name
150
+
151
+ # -- plain elements --------------------------------------------------
152
+
153
+ def _attrs(self, attrs: Dict[str, Any], extra: Dict[str, Any]) -> list:
154
+ """Attribute tuples from generated (HTML-named) and user (Python-named)
155
+ keyword arguments, dropping unset ones."""
156
+ pairs = [(name, attr_value(v)) for name, v in attrs.items()]
157
+ pairs += [(attr_name(name), attr_value(v)) for name, v in extra.items()]
158
+ return [(name, v) for name, v in pairs if v is not None]
159
+
160
+ def _content(self, content: Content) -> None:
161
+ if content is None:
162
+ return
163
+ if callable(content):
164
+ content()
165
+ else:
166
+ _tree().text(str(content))
167
+
168
+ def _element(
169
+ self,
170
+ tag: str,
171
+ content: Content,
172
+ attrs: Dict[str, Any],
173
+ extra: Dict[str, Any],
174
+ ):
175
+ """A plain Web Awesome element; use the result with ``with``."""
176
+ self._ensure_assets()
177
+ context = _wa_tag(tag, *self._attrs(attrs, extra))
178
+ if content is not None:
179
+ with context:
180
+ self._content(content)
181
+ return context
182
+
183
+ def element(self, tag: str, content: Content = None, **attrs):
184
+ """Any element, with Python-named attributes (``with_clear=True``).
185
+
186
+ For tags this package doesn't know yet (newer Web Awesome versions,
187
+ Pro components): ``with wa.element("wa-data-grid", rows=10): ...``.
188
+ """
189
+ return self._element(tag, content, {}, attrs)
190
+
191
+ # -- stateful controls -----------------------------------------------
192
+
193
+ def _control(
194
+ self,
195
+ kind: str,
196
+ attrs: Dict[str, Any],
197
+ extra: Dict[str, Any],
198
+ *,
199
+ key: str,
200
+ label: Content = None,
201
+ label_attr: bool = True,
202
+ default_value: Any = None,
203
+ options: Any = None,
204
+ option_tag: str = "wa-option",
205
+ ) -> Callable[[Any], Any]:
206
+ """Render a form control into the open component container.
207
+
208
+ Runs inside ``@component_wrapper(tag=...)``: the container *is* the
209
+ control, so this only sets attributes and children. Returns the
210
+ function that turns the stored session value into the Python value.
211
+ """
212
+ self._ensure_assets()
213
+ value = extra.pop("value", None)
214
+ attrs = dict(attrs)
215
+ hx = [("hx-post", post_url(key))]
216
+ children: Callable[[], None] = lambda: None # noqa: E731
217
+
218
+ if label is not None and label_attr:
219
+ attrs["label"] = str(label)
220
+
221
+ if kind == "action":
222
+ # One-shot, like hs.button: True on the run its click triggers.
223
+ hx = [("hx-post", post_url(key, "true"))]
224
+ session = current_session()
225
+ if session.get(key) in (True, "true", "True"):
226
+ session[key] = False
227
+ parse = lambda v: v in (True, "true", "True") # noqa: E731
228
+
229
+ elif kind == "bool":
230
+ # A checked control sends its value ("true"); an unchecked one
231
+ # sends nothing, so the URL's new_value=false is used instead.
232
+ hx = [("hx-post", post_url(key, "false")), ("hx-trigger", "change")]
233
+ parse = lambda v: str(v).lower() == "true" # noqa: E731
234
+ attrs["value"] = "true"
235
+ attrs["checked"] = parse(value)
236
+
237
+ elif kind == "number":
238
+ hx.append(("hx-trigger", "change"))
239
+ parse = lambda v: to_number(v, default_value) # noqa: E731
240
+ current = parse(value)
241
+ attrs["value"] = current
242
+
243
+ elif kind == "choice":
244
+ hx.append(("hx-trigger", "change"))
245
+ pairs = _options(options)
246
+ multiple = bool(attrs.get("multiple"))
247
+ by_text = {str(v): v for v, _ in pairs}
248
+ if multiple:
249
+ hx.append(("hx-vals", '{"hs_multiple": "1"}'))
250
+ chosen = {str(v) for v in to_list(value)}
251
+
252
+ def parse(v):
253
+ return [by_text.get(str(x), x) for x in to_list(v)]
254
+
255
+ else:
256
+ chosen = {str(value)} if value not in (None, "") else set()
257
+ attrs["value"] = None if not chosen else str(value)
258
+
259
+ def parse(v):
260
+ return None if v in (None, "") else by_text.get(str(v), v)
261
+
262
+ def children():
263
+ # A single choice is the group's value= attribute; a multiple
264
+ # select marks each chosen option instead.
265
+ for v, text in pairs:
266
+ selected = multiple and str(v) in chosen
267
+ flags = [("selected", "")] if selected else []
268
+ with _wa_tag(option_tag, ("value", str(v)), *flags):
269
+ _tree().text(str(text))
270
+
271
+ elif kind == "list":
272
+ hx += [("hx-trigger", "change"), ("hx-vals", '{"hs_multiple": "1"}')]
273
+ parse = to_list
274
+ delimiter = attrs.get("delimiter") or ","
275
+ attrs["value"] = (delimiter[0] + " ").join(
276
+ str(v) for v in parse(value)
277
+ ) or None
278
+
279
+ else: # "text"
280
+ hx.append(("hx-trigger", "change"))
281
+ parse = lambda v: "" if v is None else str(v) # noqa: E731
282
+ attrs["value"] = parse(value)
283
+
284
+ if kind != "action":
285
+ # (An action's value is in its URL; a name would also post the
286
+ # button's empty value=, which the server reads first.)
287
+ attrs.setdefault("name", "new_value")
288
+ _tree().attr(*hx, *self._attrs(attrs, extra))
289
+ if label is not None and not label_attr:
290
+ self._content(label)
291
+ children()
292
+ return parse