weft-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.
- weft_ui/__init__.py +172 -0
- weft_ui/_block.py +412 -0
- weft_ui/_charts.py +409 -0
- weft_ui/_chat.py +316 -0
- weft_ui/_display.py +577 -0
- weft_ui/_forms.py +142 -0
- weft_ui/_icons.py +266 -0
- weft_ui/_layout.py +475 -0
- weft_ui/_marketing.py +263 -0
- weft_ui/_navigation.py +241 -0
- weft_ui/_nodes.py +2231 -0
- weft_ui/_overlays.py +329 -0
- weft_ui/_page.py +147 -0
- weft_ui/_social.json +1 -0
- weft_ui/_style.py +32 -0
- weft_ui/_table.py +148 -0
- weft_ui/_tree.py +99 -0
- weft_ui/_upload.py +160 -0
- weft_ui/_wire.py +85 -0
- weft_ui/icons/lucide.json.gz +0 -0
- weft_ui/icons/tabler.json.gz +0 -0
- weft_ui/py.typed +0 -0
- weft_ui/pyproject.toml +12 -0
- weft_ui/static/chunk--gxUMRzL.js +1 -0
- weft_ui/static/chunk-0QYwWBp9.js +5 -0
- weft_ui/static/chunk-21HbvanZ.js +1 -0
- weft_ui/static/chunk-5lpsNjwR.js +1 -0
- weft_ui/static/chunk-B08NRPrW.js +1 -0
- weft_ui/static/chunk-B1Z9pqBd.js +1 -0
- weft_ui/static/chunk-B2l0eAkF.js +1 -0
- weft_ui/static/chunk-B4ar8Mb4.js +1 -0
- weft_ui/static/chunk-B5gZQ1MQ.js +1 -0
- weft_ui/static/chunk-B6dnFzwM.js +1 -0
- weft_ui/static/chunk-BCRKdrea.js +1 -0
- weft_ui/static/chunk-BD_BLx4t.js +1 -0
- weft_ui/static/chunk-BFD0q6D6.js +1 -0
- weft_ui/static/chunk-BKcqAyUr.js +7 -0
- weft_ui/static/chunk-BN63N6mo.js +1 -0
- weft_ui/static/chunk-BNkdYcMn.js +6 -0
- weft_ui/static/chunk-BPzqjXsd.js +1 -0
- weft_ui/static/chunk-BYZs-Qnc.js +1 -0
- weft_ui/static/chunk-BjXCZ1Zm.js +1 -0
- weft_ui/static/chunk-BnbbGKVG.js +1 -0
- weft_ui/static/chunk-Brh5FDD9.js +1 -0
- weft_ui/static/chunk-BskvQx0x.js +1 -0
- weft_ui/static/chunk-BvUxY7bA.js +1 -0
- weft_ui/static/chunk-BwWKFnVP.js +2 -0
- weft_ui/static/chunk-C2mavYUa.js +1 -0
- weft_ui/static/chunk-C4qSufNa.js +1 -0
- weft_ui/static/chunk-C5BQa1wB.js +1 -0
- weft_ui/static/chunk-CE0REZ1j.js +1 -0
- weft_ui/static/chunk-CEYipSgi.js +1 -0
- weft_ui/static/chunk-CXdvmI8m.js +15 -0
- weft_ui/static/chunk-CZsdZyMT.js +1 -0
- weft_ui/static/chunk-CbDctLqM.js +1 -0
- weft_ui/static/chunk-Ce1Y4sSj.js +1 -0
- weft_ui/static/chunk-Cezp23NZ.js +1 -0
- weft_ui/static/chunk-ChZOBmOv.js +1 -0
- weft_ui/static/chunk-ChxaCvvQ.js +1 -0
- weft_ui/static/chunk-CnHyI2uu.js +1 -0
- weft_ui/static/chunk-CwSgymUc.js +1 -0
- weft_ui/static/chunk-CwTq6Dzi.js +1 -0
- weft_ui/static/chunk-Cza9cDJt.js +1 -0
- weft_ui/static/chunk-DE8VnE-o.js +1 -0
- weft_ui/static/chunk-DGU3uHKf.js +5 -0
- weft_ui/static/chunk-DIJCPYCk.js +1 -0
- weft_ui/static/chunk-DMla9Riu.js +1 -0
- weft_ui/static/chunk-DRsjBNev.js +1 -0
- weft_ui/static/chunk-DUypoC7m.js +1 -0
- weft_ui/static/chunk-DYfQ5iaD.js +1 -0
- weft_ui/static/chunk-DZRnbrfy.js +1 -0
- weft_ui/static/chunk-De7USdX7.js +1 -0
- weft_ui/static/chunk-DhtOHcji.js +1 -0
- weft_ui/static/chunk-DlY2ovAQ.js +1 -0
- weft_ui/static/chunk-DnliWZoB.js +1 -0
- weft_ui/static/chunk-Dp_mkdnI.js +10 -0
- weft_ui/static/chunk-DqX27U5H.js +1 -0
- weft_ui/static/chunk-EqfrW3Fz.js +1 -0
- weft_ui/static/chunk-RNzQGsRY.js +1 -0
- weft_ui/static/chunk-RgbrCBQ8.js +1 -0
- weft_ui/static/chunk-TMVXTkix.js +1 -0
- weft_ui/static/chunk-UFEcgRNO.js +1 -0
- weft_ui/static/chunk-k4qiW1vh.js +1 -0
- weft_ui/static/chunk-lpe48EsX.js +1 -0
- weft_ui/static/chunk-lvr72rfA.js +1 -0
- weft_ui/static/chunk-sQQGM7il.js +1 -0
- weft_ui/static/chunk-vrBhIj2-.js +1 -0
- weft_ui/static/chunk-xr5IqJE_.js +1 -0
- weft_ui/static/index-CC6C-XgA.js +11 -0
- weft_ui-0.1.0.dist-info/METADATA +284 -0
- weft_ui-0.1.0.dist-info/RECORD +94 -0
- weft_ui-0.1.0.dist-info/WHEEL +4 -0
- weft_ui-0.1.0.dist-info/licenses/LICENSE +21 -0
- weft_ui-0.1.0.dist-info/licenses/THIRD_PARTY_LICENSES +136 -0
weft_ui/__init__.py
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
"""weft-ui: animated React components for Streamlit, one mount per block.
|
|
2
|
+
|
|
3
|
+
import weft_ui as ui
|
|
4
|
+
|
|
5
|
+
with ui.render():
|
|
6
|
+
dark = ui.Switch("Dark mode")
|
|
7
|
+
if ui.Button("Save"):
|
|
8
|
+
st.toast(f"Saved, dark={dark.value}")
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from weft_ui._block import Block, Event, render
|
|
12
|
+
from weft_ui._charts import AreaChart, BarChart, DonutChart, Heatmap, LineChart, Sparkline
|
|
13
|
+
from weft_ui._chat import Chat, ChatInput, ChatMessage, Markdown, Step
|
|
14
|
+
from weft_ui._display import (
|
|
15
|
+
Alert,
|
|
16
|
+
Code,
|
|
17
|
+
EmptyState,
|
|
18
|
+
Heading,
|
|
19
|
+
Icon,
|
|
20
|
+
Image,
|
|
21
|
+
Link,
|
|
22
|
+
List,
|
|
23
|
+
NumberTicker,
|
|
24
|
+
Progress,
|
|
25
|
+
Skeleton,
|
|
26
|
+
Spinner,
|
|
27
|
+
Stat,
|
|
28
|
+
Stepper,
|
|
29
|
+
)
|
|
30
|
+
from weft_ui._forms import Form, NumberInput
|
|
31
|
+
from weft_ui._layout import Accordion, Box, Card, Grid, Stack, Text
|
|
32
|
+
from weft_ui._marketing import BrowserFrame, Marquee, Navbar, Reveal, Section
|
|
33
|
+
from weft_ui._navigation import Nav, NavGroup, NavItem, Sidebar
|
|
34
|
+
from weft_ui._nodes import (
|
|
35
|
+
Announcement,
|
|
36
|
+
Avatar,
|
|
37
|
+
AvatarGroup,
|
|
38
|
+
Badge,
|
|
39
|
+
Breadcrumb,
|
|
40
|
+
Button,
|
|
41
|
+
ButtonGroup,
|
|
42
|
+
Carousel,
|
|
43
|
+
Checkbox,
|
|
44
|
+
Chip,
|
|
45
|
+
DatePicker,
|
|
46
|
+
DateRangePicker,
|
|
47
|
+
Divider,
|
|
48
|
+
Dropdown,
|
|
49
|
+
IconButton,
|
|
50
|
+
Input,
|
|
51
|
+
Kbd,
|
|
52
|
+
LinkButton,
|
|
53
|
+
MeetingScheduler,
|
|
54
|
+
Notification,
|
|
55
|
+
OTPInput,
|
|
56
|
+
Pagination,
|
|
57
|
+
Radio,
|
|
58
|
+
RangeSlider,
|
|
59
|
+
SegmentedControl,
|
|
60
|
+
Select,
|
|
61
|
+
Slider,
|
|
62
|
+
SocialButton,
|
|
63
|
+
StatusDot,
|
|
64
|
+
Switch,
|
|
65
|
+
Table,
|
|
66
|
+
Tabs,
|
|
67
|
+
Textarea,
|
|
68
|
+
Tooltip,
|
|
69
|
+
Tree,
|
|
70
|
+
toast,
|
|
71
|
+
)
|
|
72
|
+
from weft_ui._overlays import CommandMenu, Dialog, Drawer, Popover
|
|
73
|
+
from weft_ui._page import page, theme
|
|
74
|
+
from weft_ui._table import TableAction, TableColumn
|
|
75
|
+
from weft_ui._tree import Container, WeftUIError
|
|
76
|
+
from weft_ui._upload import FileUpload, UploadedFile
|
|
77
|
+
|
|
78
|
+
__all__ = [
|
|
79
|
+
"page",
|
|
80
|
+
"theme",
|
|
81
|
+
"Link",
|
|
82
|
+
"List",
|
|
83
|
+
"BrowserFrame",
|
|
84
|
+
"Marquee",
|
|
85
|
+
"Navbar",
|
|
86
|
+
"Reveal",
|
|
87
|
+
"Section",
|
|
88
|
+
"Code",
|
|
89
|
+
"Markdown",
|
|
90
|
+
"Chat",
|
|
91
|
+
"ChatInput",
|
|
92
|
+
"ChatMessage",
|
|
93
|
+
"Step",
|
|
94
|
+
"Stat",
|
|
95
|
+
"Alert",
|
|
96
|
+
"Stepper",
|
|
97
|
+
"EmptyState",
|
|
98
|
+
"Heading",
|
|
99
|
+
"Icon",
|
|
100
|
+
"Image",
|
|
101
|
+
"Progress",
|
|
102
|
+
"NumberTicker",
|
|
103
|
+
"Skeleton",
|
|
104
|
+
"Spinner",
|
|
105
|
+
"TableAction",
|
|
106
|
+
"TableColumn",
|
|
107
|
+
"AreaChart",
|
|
108
|
+
"BarChart",
|
|
109
|
+
"DonutChart",
|
|
110
|
+
"Heatmap",
|
|
111
|
+
"LineChart",
|
|
112
|
+
"Sparkline",
|
|
113
|
+
"Form",
|
|
114
|
+
"NumberInput",
|
|
115
|
+
"CommandMenu",
|
|
116
|
+
"Dialog",
|
|
117
|
+
"Drawer",
|
|
118
|
+
"Nav",
|
|
119
|
+
"NavGroup",
|
|
120
|
+
"NavItem",
|
|
121
|
+
"Popover",
|
|
122
|
+
"Accordion",
|
|
123
|
+
"Box",
|
|
124
|
+
"Card",
|
|
125
|
+
"Grid",
|
|
126
|
+
"Announcement",
|
|
127
|
+
"Avatar",
|
|
128
|
+
"AvatarGroup",
|
|
129
|
+
"Badge",
|
|
130
|
+
"Block",
|
|
131
|
+
"Breadcrumb",
|
|
132
|
+
"Button",
|
|
133
|
+
"ButtonGroup",
|
|
134
|
+
"Carousel",
|
|
135
|
+
"Checkbox",
|
|
136
|
+
"Chip",
|
|
137
|
+
"Container",
|
|
138
|
+
"DatePicker",
|
|
139
|
+
"DateRangePicker",
|
|
140
|
+
"Divider",
|
|
141
|
+
"Dropdown",
|
|
142
|
+
"Event",
|
|
143
|
+
"FileUpload",
|
|
144
|
+
"IconButton",
|
|
145
|
+
"Input",
|
|
146
|
+
"Kbd",
|
|
147
|
+
"LinkButton",
|
|
148
|
+
"MeetingScheduler",
|
|
149
|
+
"Notification",
|
|
150
|
+
"OTPInput",
|
|
151
|
+
"Pagination",
|
|
152
|
+
"Radio",
|
|
153
|
+
"RangeSlider",
|
|
154
|
+
"SegmentedControl",
|
|
155
|
+
"Select",
|
|
156
|
+
"Sidebar",
|
|
157
|
+
"Slider",
|
|
158
|
+
"SocialButton",
|
|
159
|
+
"Stack",
|
|
160
|
+
"StatusDot",
|
|
161
|
+
"Switch",
|
|
162
|
+
"Table",
|
|
163
|
+
"Tabs",
|
|
164
|
+
"Text",
|
|
165
|
+
"Textarea",
|
|
166
|
+
"Tooltip",
|
|
167
|
+
"Tree",
|
|
168
|
+
"UploadedFile",
|
|
169
|
+
"WeftUIError",
|
|
170
|
+
"render",
|
|
171
|
+
"toast",
|
|
172
|
+
]
|
weft_ui/_block.py
ADDED
|
@@ -0,0 +1,412 @@
|
|
|
1
|
+
"""`ui.render()`: collect a node tree, then mount it as ONE Streamlit component.
|
|
2
|
+
|
|
3
|
+
How a click reaches Python:
|
|
4
|
+
|
|
5
|
+
1. The browser keeps every value locally and queues events with a rising
|
|
6
|
+
sequence number `q`. It sends `{"v": values, "e": queued_events}` as one
|
|
7
|
+
state key, `s`, so one interaction means one rerun request.
|
|
8
|
+
2. Streamlit calls `_dispatch` before the script runs. It keeps events with
|
|
9
|
+
`q` above the last one handled, then runs their `on_*` callbacks.
|
|
10
|
+
3. The block hands those events to the handles built this run (`.clicked`).
|
|
11
|
+
4. The payload sends back `a` (the last handled `q`). The browser then drops
|
|
12
|
+
those events from its queue, so a slow rerun can never lose or repeat one.
|
|
13
|
+
|
|
14
|
+
An event goes to the first render of its block after it happened. If the
|
|
15
|
+
block is hidden on that run, the event waits for the next run that shows it.
|
|
16
|
+
|
|
17
|
+
Updates during a run (a streamed answer, a redraw of the same block) can't
|
|
18
|
+
use that component again: Streamlit allows a key once per run. They go
|
|
19
|
+
through a "feed" instead: a hidden, keyless copy of the component in an
|
|
20
|
+
`st.empty()` slot. Its only job is to carry data to the block in the browser.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import sys
|
|
26
|
+
import time
|
|
27
|
+
from collections.abc import Callable, Iterable
|
|
28
|
+
from dataclasses import dataclass, field
|
|
29
|
+
from functools import cache, partial
|
|
30
|
+
from hashlib import blake2b
|
|
31
|
+
from pathlib import Path
|
|
32
|
+
from typing import Any, Literal, cast
|
|
33
|
+
|
|
34
|
+
import streamlit as st
|
|
35
|
+
from streamlit.components.v2 import component
|
|
36
|
+
|
|
37
|
+
from weft_ui import _tree
|
|
38
|
+
from weft_ui._page import theme_options
|
|
39
|
+
from weft_ui._style import CSSColor
|
|
40
|
+
from weft_ui._tree import Json, Node, WeftUIError
|
|
41
|
+
from weft_ui._wire import dumps, encode
|
|
42
|
+
|
|
43
|
+
_STATIC = Path(__file__).parent / "static"
|
|
44
|
+
_SLOT_PREFIX = "__weft_ui__:"
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@dataclass(frozen=True, slots=True)
|
|
48
|
+
class Event:
|
|
49
|
+
"""An event sent from the browser.
|
|
50
|
+
|
|
51
|
+
Args:
|
|
52
|
+
key: Stable key of the component that sent the event.
|
|
53
|
+
type: Event name sent by the browser, such as "click" or "change".
|
|
54
|
+
payload: Optional JSON value sent with the event; defaults to None.
|
|
55
|
+
"""
|
|
56
|
+
|
|
57
|
+
key: str
|
|
58
|
+
type: str
|
|
59
|
+
payload: Json = None
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@dataclass(slots=True)
|
|
63
|
+
class _BlockState:
|
|
64
|
+
"""What Python keeps per block in session state, across reruns."""
|
|
65
|
+
|
|
66
|
+
seq: int = 0
|
|
67
|
+
# How many ui.toast() calls this block has made, so each call is new to the browser.
|
|
68
|
+
toasts: int = 0
|
|
69
|
+
# How many streams this block has started. Each one gets a new token.
|
|
70
|
+
streams: int = 0
|
|
71
|
+
values: dict[str, tuple[Json, int]] = field(default_factory=dict[str, tuple[Json, int]])
|
|
72
|
+
events: list[Event] = field(default_factory=list[Event])
|
|
73
|
+
handlers: dict[tuple[str, str], Callable[[], None]] = field(
|
|
74
|
+
default_factory=dict[tuple[str, str], Callable[[], None]]
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _state(key: str) -> _BlockState:
|
|
79
|
+
slot = _SLOT_PREFIX + key
|
|
80
|
+
state = st.session_state.get(slot)
|
|
81
|
+
if not isinstance(state, _BlockState):
|
|
82
|
+
state = _BlockState()
|
|
83
|
+
st.session_state[slot] = state
|
|
84
|
+
return state
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def apply_commit(state: _BlockState, commit: object) -> list[Event]:
|
|
88
|
+
"""Merge a browser commit into `state` and return the events not seen before."""
|
|
89
|
+
if not isinstance(commit, dict):
|
|
90
|
+
return []
|
|
91
|
+
commit = cast(dict[str, Any], commit)
|
|
92
|
+
values = commit.get("v")
|
|
93
|
+
if isinstance(values, dict):
|
|
94
|
+
state.values = {}
|
|
95
|
+
for k, v in cast(dict[str, Any], values).items():
|
|
96
|
+
pair = cast(list[Any], v) if isinstance(v, list) else []
|
|
97
|
+
if len(pair) == 2 and isinstance(pair[1], int):
|
|
98
|
+
state.values[k] = (pair[0], pair[1])
|
|
99
|
+
new: list[Event] = []
|
|
100
|
+
events = commit.get("e")
|
|
101
|
+
for raw in cast(list[Any], events) if isinstance(events, list) else []:
|
|
102
|
+
if not isinstance(raw, dict):
|
|
103
|
+
continue
|
|
104
|
+
e = cast(dict[str, Any], raw)
|
|
105
|
+
q = e.get("q")
|
|
106
|
+
if isinstance(q, int) and q > state.seq:
|
|
107
|
+
state.seq = q
|
|
108
|
+
new.append(Event(str(e.get("i")), str(e.get("t")), e.get("p")))
|
|
109
|
+
return new
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _dispatch(key: str) -> None:
|
|
113
|
+
state = _state(key)
|
|
114
|
+
result: object = st.session_state.get(key) # pyright: ignore[reportUnknownMemberType]
|
|
115
|
+
commit = cast(dict[str, object], result).get("s") if isinstance(result, dict) else None
|
|
116
|
+
new = apply_commit(state, commit)
|
|
117
|
+
state.events.extend(new)
|
|
118
|
+
for event in new:
|
|
119
|
+
handler = state.handlers.get((event.key, event.type))
|
|
120
|
+
if handler is not None:
|
|
121
|
+
handler()
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
@cache
|
|
125
|
+
def _runtime() -> Callable[..., Any]:
|
|
126
|
+
if not any(_STATIC.glob("index-*.js")):
|
|
127
|
+
raise WeftUIError(
|
|
128
|
+
"The weft-ui frontend bundle is missing. Run `pnpm -C frontend build` "
|
|
129
|
+
"(or `pnpm -C frontend dev` to rebuild on save)."
|
|
130
|
+
)
|
|
131
|
+
return component("weft-ui.runtime", js="index-*.js")
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
# Chunks are grouped so the browser gets at most one update per interval.
|
|
135
|
+
_STREAM_INTERVAL = 0.04
|
|
136
|
+
# A long answer is resent whole each time, so slow down as it grows.
|
|
137
|
+
_STREAM_BYTES_PER_SECOND = 400_000
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def chunk_text(chunk: object) -> str:
|
|
141
|
+
"""The text in one stream chunk: a string, or a chunk object from an LLM SDK.
|
|
142
|
+
|
|
143
|
+
Knows OpenAI chat chunks (`choices[0].delta.content`), OpenAI response
|
|
144
|
+
events and Anthropic events (`delta` or `delta.text`), and LangChain
|
|
145
|
+
message chunks (`content`). Chunks of those shapes without text give "".
|
|
146
|
+
"""
|
|
147
|
+
if isinstance(chunk, str):
|
|
148
|
+
return chunk
|
|
149
|
+
choices = getattr(chunk, "choices", None)
|
|
150
|
+
if choices is not None:
|
|
151
|
+
delta = getattr(choices[0], "delta", None) if choices else None
|
|
152
|
+
text = getattr(delta, "content", None)
|
|
153
|
+
return text if isinstance(text, str) else ""
|
|
154
|
+
if hasattr(chunk, "delta") or hasattr(chunk, "type"):
|
|
155
|
+
delta = getattr(chunk, "delta", None)
|
|
156
|
+
kind = getattr(chunk, "type", "")
|
|
157
|
+
if isinstance(delta, str):
|
|
158
|
+
return delta if kind == "response.output_text.delta" else ""
|
|
159
|
+
text = getattr(delta, "text", None)
|
|
160
|
+
return text if isinstance(text, str) else ""
|
|
161
|
+
content = getattr(chunk, "content", None)
|
|
162
|
+
if isinstance(content, str):
|
|
163
|
+
return content
|
|
164
|
+
raise WeftUIError(
|
|
165
|
+
f"A stream gave a {type(chunk).__name__}, which has no text. "
|
|
166
|
+
"Yield strings, or pass an OpenAI, Anthropic or LangChain stream."
|
|
167
|
+
)
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
@dataclass(slots=True)
|
|
171
|
+
class _Stream:
|
|
172
|
+
"""A text stream waiting to run when its block closes."""
|
|
173
|
+
|
|
174
|
+
token: str
|
|
175
|
+
chunks: Iterable[object]
|
|
176
|
+
# Called with the full text so far, after every chunk that has text.
|
|
177
|
+
on_text: Callable[[str], None]
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def _auto_key(depth: int) -> str:
|
|
181
|
+
frame = sys._getframe(depth + 1) # pyright: ignore[reportPrivateUsage]
|
|
182
|
+
where = f"{frame.f_code.co_filename}:{frame.f_lineno}"
|
|
183
|
+
return "wui-" + blake2b(where.encode(), digest_size=6).hexdigest()
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
type Width = Literal["stretch", "content"] | int
|
|
187
|
+
type Height = Literal["content", "stretch"] | int
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
class Block:
|
|
191
|
+
"""One mounted tree. Create it with `ui.render()`, not directly.
|
|
192
|
+
|
|
193
|
+
Use the same block in a second `with` during one run to redraw it in
|
|
194
|
+
place, for example to show each step of a slow job as it finishes:
|
|
195
|
+
|
|
196
|
+
block = ui.render(key="job")
|
|
197
|
+
for step in steps:
|
|
198
|
+
with block:
|
|
199
|
+
draw(step)
|
|
200
|
+
|
|
201
|
+
A redraw gets no new events, so `.clicked` and `.changed` are False in it.
|
|
202
|
+
|
|
203
|
+
Args:
|
|
204
|
+
key: Stable name for this mounted block across reruns.
|
|
205
|
+
width: Use "stretch", "content", or a width in pixels.
|
|
206
|
+
height: Use "content", "stretch", or a height in pixels.
|
|
207
|
+
theme: "auto" follows the app theme; "light" or "dark" forces one.
|
|
208
|
+
Defaults to the mode set with `ui.theme()`, else "auto".
|
|
209
|
+
accent: Palette name or CSS color for this block; defaults to `ui.theme()`.
|
|
210
|
+
font: CSS font family for this block; defaults to `ui.theme()`.
|
|
211
|
+
"""
|
|
212
|
+
|
|
213
|
+
def __init__(
|
|
214
|
+
self,
|
|
215
|
+
key: str,
|
|
216
|
+
width: Width,
|
|
217
|
+
height: Height,
|
|
218
|
+
*,
|
|
219
|
+
theme: Literal["auto", "light", "dark"] | None = None,
|
|
220
|
+
accent: CSSColor | None = None,
|
|
221
|
+
font: str | None = None,
|
|
222
|
+
) -> None:
|
|
223
|
+
if "__" in key:
|
|
224
|
+
raise WeftUIError(f"render(key={key!r}): keys can't contain '__' (Streamlit uses it).")
|
|
225
|
+
# ui.theme() sets the app's look; this block's own options win.
|
|
226
|
+
self.appearance: dict[str, Json] = theme_options()
|
|
227
|
+
if theme == "auto":
|
|
228
|
+
self.appearance.pop("theme", None)
|
|
229
|
+
elif theme is not None:
|
|
230
|
+
self.appearance["theme"] = theme
|
|
231
|
+
if accent is not None:
|
|
232
|
+
self.appearance["accent"] = accent
|
|
233
|
+
if font is not None:
|
|
234
|
+
self.appearance["font"] = font
|
|
235
|
+
self.key = key
|
|
236
|
+
self._width = width
|
|
237
|
+
self._height = height
|
|
238
|
+
self.roots: list[Node] = []
|
|
239
|
+
self.stack: list[list[Node]] = [self.roots]
|
|
240
|
+
self._keys: dict[str, str] = {}
|
|
241
|
+
self._values: dict[str, tuple[Json, int]] = {}
|
|
242
|
+
self.events: list[Event] = []
|
|
243
|
+
self.form_open = False
|
|
244
|
+
self._streams: list[_Stream] = []
|
|
245
|
+
# Set once the block is on the page this run; later renders use the feed.
|
|
246
|
+
self._sent = False
|
|
247
|
+
self._feed_box: Any = None
|
|
248
|
+
self._slots: dict[str, Any] = {}
|
|
249
|
+
self._feeds = 0
|
|
250
|
+
|
|
251
|
+
def claim_key(self, key: str, type: str) -> None:
|
|
252
|
+
other = self._keys.get(key)
|
|
253
|
+
if other is not None:
|
|
254
|
+
raise WeftUIError(
|
|
255
|
+
f"Two nodes in render(key={self.key!r}) share the key {key!r} "
|
|
256
|
+
f"({other} and {type}). Pass key= to tell them apart."
|
|
257
|
+
)
|
|
258
|
+
self._keys[key] = type
|
|
259
|
+
|
|
260
|
+
def value(self, key: str, default: Json) -> Json:
|
|
261
|
+
"""The value the browser has for `key`, or `default` if it has none yet."""
|
|
262
|
+
current = self._state.values.get(key)
|
|
263
|
+
self._values[key] = current if current is not None else (default, 0)
|
|
264
|
+
return self._values[key][0]
|
|
265
|
+
|
|
266
|
+
def next_toast(self) -> int:
|
|
267
|
+
"""A number no earlier toast in this block used."""
|
|
268
|
+
self._state.toasts += 1
|
|
269
|
+
return self._state.toasts
|
|
270
|
+
|
|
271
|
+
def stream(self, chunks: Iterable[object], on_text: Callable[[str], None]) -> str:
|
|
272
|
+
"""Queue a text stream to run when the block closes. Returns its token."""
|
|
273
|
+
self._state.streams += 1
|
|
274
|
+
token = f"{self.key}:{self._state.streams}"
|
|
275
|
+
self._streams.append(_Stream(token, chunks, on_text))
|
|
276
|
+
return token
|
|
277
|
+
|
|
278
|
+
def _feed(self, slot: str, body: str) -> None:
|
|
279
|
+
"""Send `body` (JSON) to this block in the browser, outside a rerun.
|
|
280
|
+
|
|
281
|
+
Each stream, and the redraw, has its own slot. The browser shows only
|
|
282
|
+
the newest feed of a slot, which is all it needs: the newest text of
|
|
283
|
+
each stream and the newest tree.
|
|
284
|
+
"""
|
|
285
|
+
if self._feed_box is None:
|
|
286
|
+
# The frontend hides containers with this key prefix (styles.ts),
|
|
287
|
+
# so a feed never takes space, not even for one frame.
|
|
288
|
+
self._feed_box = st.container(key=f"weft-ui-feed-{self.key}")
|
|
289
|
+
place = self._slots.get(slot)
|
|
290
|
+
if place is None:
|
|
291
|
+
place = self._slots[slot] = self._feed_box.empty()
|
|
292
|
+
# The counter makes each payload new, or Streamlit rejects a repeat.
|
|
293
|
+
self._feeds += 1
|
|
294
|
+
with place:
|
|
295
|
+
_runtime()(data=f'{{"v":1,"f":{self._feeds},"b":{dumps(self.key)},{body}}}'.encode())
|
|
296
|
+
|
|
297
|
+
def _run_streams(self) -> None:
|
|
298
|
+
"""Read each queued stream to its end, sending the text as it grows.
|
|
299
|
+
|
|
300
|
+
Every feed carries the whole text so far, because the browser may
|
|
301
|
+
skip a feed when a newer one for the same slot is already there.
|
|
302
|
+
"""
|
|
303
|
+
streams, self._streams = self._streams, []
|
|
304
|
+
for stream in streams:
|
|
305
|
+
token = dumps(stream.token)
|
|
306
|
+
text = ""
|
|
307
|
+
last = 0.0
|
|
308
|
+
try:
|
|
309
|
+
for chunk in stream.chunks:
|
|
310
|
+
piece = chunk_text(chunk)
|
|
311
|
+
if not piece:
|
|
312
|
+
continue
|
|
313
|
+
text += piece
|
|
314
|
+
stream.on_text(text)
|
|
315
|
+
now = time.monotonic()
|
|
316
|
+
if now - last >= max(_STREAM_INTERVAL, len(text) / _STREAM_BYTES_PER_SECOND):
|
|
317
|
+
last = now
|
|
318
|
+
self._feed(stream.token, f'"x":{token},"s":{dumps(text)}')
|
|
319
|
+
except Exception:
|
|
320
|
+
# Show what arrived and stop the cursor before the error shows.
|
|
321
|
+
self._feed(stream.token, f'"x":{token},"s":{dumps(text)},"d":1')
|
|
322
|
+
raise
|
|
323
|
+
self._feed(stream.token, f'"x":{token},"s":{dumps(text)},"d":1')
|
|
324
|
+
|
|
325
|
+
def fired(self, key: str, type: str) -> Event | None:
|
|
326
|
+
return next((e for e in self.events if e.key == key and e.type == type), None)
|
|
327
|
+
|
|
328
|
+
def bind(
|
|
329
|
+
self, key: str, default: Json, on_change: Callable[[], None] | None
|
|
330
|
+
) -> tuple[Json, bool]:
|
|
331
|
+
"""The browser's value for a node and whether it changed this run."""
|
|
332
|
+
self.on(key, "change", on_change)
|
|
333
|
+
return self.value(key, default), self.fired(key, "change") is not None
|
|
334
|
+
|
|
335
|
+
def on(self, key: str, type: str, handler: Callable[[], None] | None) -> None:
|
|
336
|
+
if handler is not None:
|
|
337
|
+
self._state.handlers[(key, type)] = handler
|
|
338
|
+
|
|
339
|
+
def __enter__(self) -> Block:
|
|
340
|
+
self._state = _state(self.key)
|
|
341
|
+
# Take this run's events, and drop handlers from the last run: the
|
|
342
|
+
# nodes built below register the ones that still exist.
|
|
343
|
+
self.events, self._state.events = self._state.events, []
|
|
344
|
+
self._state.handlers = {}
|
|
345
|
+
# A redraw starts from an empty tree.
|
|
346
|
+
self.roots = []
|
|
347
|
+
self.stack = [self.roots]
|
|
348
|
+
self._keys = {}
|
|
349
|
+
self._values = {}
|
|
350
|
+
self._streams = []
|
|
351
|
+
self.form_open = False
|
|
352
|
+
self._first_stream = self._state.streams
|
|
353
|
+
self._token = _tree._block.set(self) # pyright: ignore[reportPrivateUsage]
|
|
354
|
+
return self
|
|
355
|
+
|
|
356
|
+
def __exit__(self, exc_type: object, *_: object) -> None:
|
|
357
|
+
_tree._block.reset(self._token) # pyright: ignore[reportPrivateUsage]
|
|
358
|
+
if exc_type is not None:
|
|
359
|
+
return
|
|
360
|
+
data = encode(
|
|
361
|
+
self.roots,
|
|
362
|
+
self._values,
|
|
363
|
+
self._state.seq,
|
|
364
|
+
self.appearance,
|
|
365
|
+
key=self.key,
|
|
366
|
+
streams=self._first_stream,
|
|
367
|
+
)
|
|
368
|
+
if self._sent:
|
|
369
|
+
self._feed("", '"p":' + data.decode())
|
|
370
|
+
else:
|
|
371
|
+
self._sent = True
|
|
372
|
+
_runtime()(
|
|
373
|
+
key=self.key,
|
|
374
|
+
data=data,
|
|
375
|
+
width=self._width,
|
|
376
|
+
height=self._height,
|
|
377
|
+
on_s_change=partial(_dispatch, self.key),
|
|
378
|
+
)
|
|
379
|
+
self._run_streams()
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
def render(
|
|
383
|
+
key: str | None = None,
|
|
384
|
+
*,
|
|
385
|
+
width: Width = "stretch",
|
|
386
|
+
height: Height = "content",
|
|
387
|
+
theme: Literal["auto", "light", "dark"] | None = None,
|
|
388
|
+
accent: CSSColor | None = None,
|
|
389
|
+
font: str | None = None,
|
|
390
|
+
) -> Block:
|
|
391
|
+
"""Open a block. Every ui.* call inside it renders in one Streamlit component.
|
|
392
|
+
|
|
393
|
+
`key` defaults to one made from the calling line, so it stays the same
|
|
394
|
+
across reruns. Pass a key when you call render() in a loop.
|
|
395
|
+
|
|
396
|
+
Args:
|
|
397
|
+
key: Stable block name; defaults to the calling line. Set it when rendering in loops.
|
|
398
|
+
width: Use "stretch", "content", or a width in pixels.
|
|
399
|
+
height: Use "content", "stretch", or a height in pixels.
|
|
400
|
+
theme: "auto" follows the app theme; "light" or "dark" forces one.
|
|
401
|
+
Defaults to the mode set with `ui.theme()`, else "auto".
|
|
402
|
+
accent: Palette name or CSS color for this block; defaults to `ui.theme()`.
|
|
403
|
+
font: CSS font family for this block; defaults to `ui.theme()`.
|
|
404
|
+
"""
|
|
405
|
+
return Block(
|
|
406
|
+
key if key is not None else _auto_key(1),
|
|
407
|
+
width,
|
|
408
|
+
height,
|
|
409
|
+
theme=theme,
|
|
410
|
+
accent=accent,
|
|
411
|
+
font=font,
|
|
412
|
+
)
|