astralprims 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,115 @@
1
+ """Astral Primitives — composable, serializable UI primitives for Python.
2
+
3
+ >>> from astralprims import Button
4
+ >>> Button(label="Click me", action="open",
5
+ ... css={"background-color": "white", "color": "#000000"}).to_dict()
6
+ {'type': 'button', 'css': {'background-color': 'white', 'color': '#000000'}, 'label': 'Click me', 'action': 'open', 'payload': {}, 'variant': 'primary'}
7
+ """
8
+
9
+ from .base import CSS, Primitive
10
+ from .primitives import (
11
+ Alert,
12
+ Audio,
13
+ BarChart,
14
+ Button,
15
+ Card,
16
+ ChartDataset,
17
+ CodeBlock,
18
+ Collapsible,
19
+ ColorPicker,
20
+ Container,
21
+ Divider,
22
+ FileDownload,
23
+ FileUpload,
24
+ Grid,
25
+ Grids,
26
+ Image,
27
+ Input,
28
+ LineChart,
29
+ List_,
30
+ MetricCard,
31
+ ParamPicker,
32
+ PieChart,
33
+ PlotlyChart,
34
+ ProgressBar,
35
+ Table,
36
+ Tabs,
37
+ TabItem,
38
+ Text,
39
+ ThemeApply,
40
+ )
41
+ from .response import create_ui_response
42
+
43
+ from typing import Annotated, Union
44
+
45
+ from pydantic import Field as _Field, TypeAdapter
46
+
47
+ from .base import _REGISTRY
48
+
49
+ __version__ = "0.1.0"
50
+
51
+
52
+ def _build_union():
53
+ """Build a discriminated union + TypeAdapter over all registered primitives.
54
+
55
+ Used for validating/parsing arbitrary primitive payloads and for generating
56
+ a combined JSON Schema (e.g. for FastAPI request bodies / OpenAPI docs).
57
+ """
58
+ members = tuple(_REGISTRY.values())
59
+ union = Annotated[Union[members], _Field(discriminator="type")]
60
+ return union, TypeAdapter(union)
61
+
62
+
63
+ AnyPrimitive, primitive_adapter = _build_union()
64
+
65
+
66
+ def rebuild_primitive_union():
67
+ """Rebuild :data:`AnyPrimitive`/:data:`primitive_adapter` after registering
68
+ custom primitives. Returns the refreshed adapter."""
69
+ global AnyPrimitive, primitive_adapter
70
+ AnyPrimitive, primitive_adapter = _build_union()
71
+ return primitive_adapter
72
+
73
+
74
+ __all__ = [
75
+ "CSS",
76
+ "Primitive",
77
+ "AnyPrimitive",
78
+ "primitive_adapter",
79
+ "rebuild_primitive_union",
80
+ "create_ui_response",
81
+ # Layout
82
+ "Container",
83
+ "Card",
84
+ "Grid",
85
+ "Grids",
86
+ "Tabs",
87
+ "TabItem",
88
+ "Collapsible",
89
+ "Divider",
90
+ # Content & controls
91
+ "Text",
92
+ "Button",
93
+ "Input",
94
+ "ParamPicker",
95
+ "Image",
96
+ "CodeBlock",
97
+ "Alert",
98
+ "ProgressBar",
99
+ "MetricCard",
100
+ "List_",
101
+ "Table",
102
+ # Charts
103
+ "BarChart",
104
+ "LineChart",
105
+ "PieChart",
106
+ "PlotlyChart",
107
+ "ChartDataset",
108
+ # Media & I/O
109
+ "Audio",
110
+ "FileUpload",
111
+ "FileDownload",
112
+ # Theming
113
+ "ColorPicker",
114
+ "ThemeApply",
115
+ ]
astralprims/base.py ADDED
@@ -0,0 +1,157 @@
1
+ """Base machinery shared by every UI primitive.
2
+
3
+ A primitive is a Pydantic model describing a piece of UI. It validates on
4
+ construction, serializes to a plain ``dict``/JSON (``to_dict``/``to_json``), and
5
+ can be reconstructed from a ``dict`` (``from_dict``) — so primitives can be
6
+ stored, transported, validated on inbound FastAPI requests, and rendered by a
7
+ server-driven UI. JSON stays the wire format; Pydantic is the authoring layer.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ from typing import Any, ClassVar, Dict, List, Optional
14
+
15
+ from pydantic import BaseModel, ConfigDict, Field, field_validator, model_serializer
16
+
17
+ # A CSS block is just a mapping of (kebab-case) property -> value.
18
+ CSS = Dict[str, str]
19
+
20
+ # Registry of ``type`` string -> Primitive subclass, populated as subclasses are
21
+ # defined. Used by :func:`Primitive.from_dict` to round-trip dicts back into
22
+ # objects and by ``__init__`` to build the discriminated union.
23
+ _REGISTRY: Dict[str, type["Primitive"]] = {}
24
+
25
+
26
+ def _dump(value: Any) -> Any:
27
+ """Recursively serialize a value, dispatching nested models to their own
28
+ serializer (so each model controls its own output shape)."""
29
+ if isinstance(value, BaseModel):
30
+ return value.model_dump()
31
+ if isinstance(value, list):
32
+ return [_dump(v) for v in value]
33
+ if isinstance(value, dict):
34
+ return {k: _dump(v) for k, v in value.items()}
35
+ return value
36
+
37
+
38
+ def _coerce_children(value: Any) -> Any:
39
+ """Turn a list of child dicts (each carrying a ``type``) into primitives."""
40
+ if isinstance(value, list):
41
+ return [
42
+ Primitive.from_dict(v) if isinstance(v, dict) and "type" in v else v
43
+ for v in value
44
+ ]
45
+ return value
46
+
47
+
48
+ class SerModel(BaseModel):
49
+ """A model that serializes by dropping ``None`` fields and honoring aliases.
50
+
51
+ Used for nested non-primitive helpers (``TabItem``, ``ChartDataset``).
52
+ """
53
+
54
+ @model_serializer(mode="plain")
55
+ def _serialize(self) -> Dict[str, Any]:
56
+ out: Dict[str, Any] = {}
57
+ for name, field in type(self).model_fields.items():
58
+ value = getattr(self, name)
59
+ if value is None:
60
+ continue
61
+ out[field.alias or name] = _dump(value)
62
+ return out
63
+
64
+
65
+ class Primitive(BaseModel):
66
+ """Base class for all UI primitives.
67
+
68
+ Subclasses set ``type`` to a ``Literal[...]`` and declare their own fields.
69
+ Serialization emits ``"type"`` first, drops ``None``, omits an empty ``css``
70
+ block, renames ``class_name`` to ``"class"``, and merges ``attributes`` at
71
+ the top level.
72
+ """
73
+
74
+ model_config = ConfigDict(populate_by_name=True, extra="ignore")
75
+
76
+ type: str = "primitive"
77
+ css: Optional[CSS] = None
78
+ id: Optional[str] = None
79
+ class_name: Optional[str] = Field(default=None, alias="class")
80
+ tooltip: Optional[str] = None
81
+ # Free-form extra attributes merged into the output (escape hatch).
82
+ attributes: Dict[str, Any] = Field(default_factory=dict)
83
+
84
+ @classmethod
85
+ def __pydantic_init_subclass__(cls, **kwargs: Any) -> None:
86
+ super().__pydantic_init_subclass__(**kwargs)
87
+ type_field = cls.model_fields.get("type")
88
+ if type_field is not None and isinstance(type_field.default, str):
89
+ _REGISTRY[type_field.default] = cls
90
+
91
+ # Reconstruct nested ``children``/``content`` dicts into primitives. Declared
92
+ # here with check_fields=False so it applies to whichever subclasses have
93
+ # those fields (Container, Card, Grids, Collapsible, ...).
94
+ @field_validator("children", "content", mode="before", check_fields=False)
95
+ @classmethod
96
+ def _coerce_primitive_children(cls, v: Any) -> Any:
97
+ return _coerce_children(v)
98
+
99
+ # -- serialization ----------------------------------------------------
100
+
101
+ @model_serializer(mode="plain")
102
+ def _serialize(self) -> Dict[str, Any]:
103
+ out: Dict[str, Any] = {"type": self.type}
104
+ for name, field in type(self).model_fields.items():
105
+ if name in ("type", "attributes"):
106
+ continue
107
+ value = getattr(self, name)
108
+ if value is None:
109
+ continue
110
+ if name == "css" and not value:
111
+ continue # omit empty style blocks
112
+ out[field.alias or name] = _dump(value)
113
+ # Extra attributes are merged last so callers can override or extend.
114
+ out.update(self.attributes or {})
115
+ return out
116
+
117
+ def to_dict(self) -> Dict[str, Any]:
118
+ """Serialize to a plain ``dict`` with ``"type"`` first."""
119
+ return self.model_dump()
120
+
121
+ def to_json(self, **kwargs: Any) -> str:
122
+ """Serialize to a JSON string. Extra kwargs go to :func:`json.dumps`."""
123
+ return json.dumps(self.model_dump(), **kwargs)
124
+
125
+ # -- deserialization --------------------------------------------------
126
+
127
+ @classmethod
128
+ def from_dict(cls, data: Dict[str, Any]) -> "Primitive":
129
+ """Reconstruct a primitive (and any children) from a ``dict``.
130
+
131
+ Dispatches on the ``"type"`` key to the matching registered subclass.
132
+ Unknown keys are funneled into ``attributes``.
133
+ """
134
+ if "type" not in data:
135
+ raise ValueError("primitive dict is missing required 'type' key")
136
+
137
+ type_name = data["type"]
138
+ target = cls if cls is not Primitive else _REGISTRY.get(type_name)
139
+ if target is None:
140
+ raise ValueError(f"unknown primitive type: {type_name!r}")
141
+
142
+ known = set()
143
+ for name, field in target.model_fields.items():
144
+ known.add(name)
145
+ if field.alias:
146
+ known.add(field.alias)
147
+
148
+ kwargs: Dict[str, Any] = {}
149
+ extra: Dict[str, Any] = {}
150
+ for key, value in data.items():
151
+ if key == "type":
152
+ continue
153
+ (kwargs if key in known else extra)[key] = value
154
+
155
+ if extra:
156
+ kwargs["attributes"] = {**kwargs.get("attributes", {}), **extra}
157
+ return target.model_validate(kwargs)
@@ -0,0 +1,367 @@
1
+ """Concrete UI primitives.
2
+
3
+ Each primitive is a Pydantic model that inherits ``css``, ``id``, ``class_name``,
4
+ ``tooltip`` and ``attributes`` from :class:`Primitive` and adds its own fields.
5
+ Nesting (children / content / tabs) is reconstructed and serialized by the base
6
+ class. Import the ones you need::
7
+
8
+ from astralprims import Button, Container, Card
9
+
10
+ Container().add(
11
+ Card(title="Welcome", content=[Button(label="Get started", action="go")])
12
+ )
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from typing import Any, Dict, List, Literal, Optional, Union
18
+
19
+ from pydantic import Field, field_validator
20
+
21
+ from .base import SerModel, _coerce_children
22
+ from .base import Primitive
23
+
24
+ # ---------------------------------------------------------------------------
25
+ # Layout
26
+ # ---------------------------------------------------------------------------
27
+
28
+
29
+ class Container(Primitive):
30
+ """A layout container holding child primitives."""
31
+
32
+ type: Literal["container"] = "container"
33
+ children: List[Primitive] = Field(default_factory=list)
34
+ direction: Optional[str] = None # e.g. "row" | "column"
35
+
36
+ def add(self, *children: Primitive) -> "Container":
37
+ """Append one or more children and return self (chainable)."""
38
+ self.children.extend(children)
39
+ return self
40
+
41
+
42
+ class Card(Primitive):
43
+ """A titled card wrapping child primitives."""
44
+
45
+ type: Literal["card"] = "card"
46
+ title: str = ""
47
+ content: List[Primitive] = Field(default_factory=list)
48
+ variant: str = "default"
49
+
50
+ def add(self, *content: Primitive) -> "Card":
51
+ self.content.extend(content)
52
+ return self
53
+
54
+
55
+ class Grids(Primitive):
56
+ """A grid layout with a fixed column count."""
57
+
58
+ type: Literal["grid"] = "grid"
59
+ columns: int = 2
60
+ children: List[Primitive] = Field(default_factory=list)
61
+ gap: int = 20
62
+
63
+ def add(self, *children: Primitive) -> "Grids":
64
+ self.children.extend(children)
65
+ return self
66
+
67
+
68
+ # Backwards-compatible alias.
69
+ Grid = Grids
70
+
71
+
72
+ class TabItem(SerModel):
73
+ """A single tab. Not a primitive itself (no ``type``); nested in ``Tabs``."""
74
+
75
+ label: str = ""
76
+ content: List[Primitive] = Field(default_factory=list)
77
+ value: Optional[str] = None
78
+
79
+ @field_validator("content", mode="before")
80
+ @classmethod
81
+ def _coerce_content(cls, v: Any) -> Any:
82
+ return _coerce_children(v)
83
+
84
+
85
+ class Tabs(Primitive):
86
+ """A tabbed container."""
87
+
88
+ type: Literal["tabs"] = "tabs"
89
+ tabs: List[TabItem] = Field(default_factory=list)
90
+ variant: str = "default"
91
+
92
+ @field_validator("tabs", mode="before")
93
+ @classmethod
94
+ def _coerce_tabs(cls, v: Any) -> Any:
95
+ if isinstance(v, list):
96
+ return [TabItem.model_validate(t) if isinstance(t, dict) else t for t in v]
97
+ return v
98
+
99
+
100
+ class Collapsible(Primitive):
101
+ """A collapsible / accordion section."""
102
+
103
+ type: Literal["collapsible"] = "collapsible"
104
+ title: str = ""
105
+ content: List[Primitive] = Field(default_factory=list)
106
+ default_open: bool = False
107
+
108
+
109
+ class Divider(Primitive):
110
+ """A horizontal rule / visual separator."""
111
+
112
+ type: Literal["divider"] = "divider"
113
+ variant: str = "solid"
114
+
115
+
116
+ # ---------------------------------------------------------------------------
117
+ # Content & controls
118
+ # ---------------------------------------------------------------------------
119
+
120
+
121
+ class Text(Primitive):
122
+ """A run of text. ``variant`` is one of h1, h2, h3, body, caption."""
123
+
124
+ type: Literal["text"] = "text"
125
+ content: str = ""
126
+ variant: str = "body"
127
+
128
+
129
+ class Button(Primitive):
130
+ """A clickable button that dispatches an action with an optional payload."""
131
+
132
+ type: Literal["button"] = "button"
133
+ label: str = ""
134
+ action: str = ""
135
+ payload: Dict[str, Any] = Field(default_factory=dict)
136
+ variant: str = "primary"
137
+
138
+
139
+ class Input(Primitive):
140
+ """A single-line form input."""
141
+
142
+ type: Literal["input"] = "input"
143
+ placeholder: str = ""
144
+ name: str = ""
145
+ value: str = ""
146
+
147
+
148
+ class ParamPicker(Primitive):
149
+ """Interactive parameter form rendered as a card with form fields.
150
+
151
+ Each entry in ``fields`` is a dict of the shape::
152
+
153
+ {"name": "models_to_train",
154
+ "label": "Models to train",
155
+ "kind": "boolean"|"number"|"text"|"checklist"|"select",
156
+ "default": <starting value>,
157
+ "options": [...] # for checklist/select
158
+ "help": "...",
159
+ "step": 1 # optional, for number kind
160
+ }
161
+
162
+ On submit the renderer interpolates ``submit_message_template`` with the
163
+ user's field values. Two placeholder forms are supported:
164
+
165
+ * ``{field_name}`` — replaced with that field's value (JSON-encoded for
166
+ lists/dicts/bools).
167
+ * ``{__values_json__}`` — replaced with the JSON of the entire form state.
168
+ """
169
+
170
+ type: Literal["param_picker"] = "param_picker"
171
+ title: str = ""
172
+ description: str = ""
173
+ fields: List[Dict[str, Any]] = Field(default_factory=list)
174
+ submit_label: str = "Submit"
175
+ submit_message_template: str = ""
176
+
177
+
178
+ class Image(Primitive):
179
+ """An image."""
180
+
181
+ type: Literal["image"] = "image"
182
+ url: str = ""
183
+ alt: Optional[str] = None
184
+ width: Optional[str] = None
185
+ height: Optional[str] = None
186
+
187
+
188
+ class CodeBlock(Primitive):
189
+ """A syntax-highlighted code block."""
190
+
191
+ type: Literal["code"] = "code"
192
+ code: str = ""
193
+ language: str = "text"
194
+ show_line_numbers: bool = False
195
+
196
+
197
+ class Alert(Primitive):
198
+ """A callout / banner. ``variant`` is info, success, warning, or error."""
199
+
200
+ type: Literal["alert"] = "alert"
201
+ message: str = ""
202
+ variant: str = "info"
203
+ title: Optional[str] = None
204
+
205
+
206
+ class ProgressBar(Primitive):
207
+ """A progress bar."""
208
+
209
+ type: Literal["progress"] = "progress"
210
+ value: float = 0.0
211
+ label: Optional[str] = None
212
+ variant: str = "default"
213
+ show_percentage: bool = True
214
+
215
+
216
+ class MetricCard(Primitive):
217
+ """A single KPI / metric tile."""
218
+
219
+ type: Literal["metric"] = "metric"
220
+ title: str = ""
221
+ value: str = ""
222
+ subtitle: Optional[str] = None
223
+ icon: Optional[str] = None
224
+ variant: str = "default"
225
+ progress: Optional[float] = None
226
+
227
+
228
+ class List_(Primitive):
229
+ """An ordered or unordered list of strings or dict items."""
230
+
231
+ type: Literal["list"] = "list"
232
+ items: List[Union[str, Dict[str, Any]]] = Field(default_factory=list)
233
+ ordered: bool = False
234
+ variant: str = "default"
235
+
236
+
237
+ class Table(Primitive):
238
+ """A data table with optional pagination and re-invocation context."""
239
+
240
+ type: Literal["table"] = "table"
241
+ headers: List[str] = Field(default_factory=list)
242
+ rows: List[List[Any]] = Field(default_factory=list)
243
+ variant: str = "default"
244
+ # Pagination (optional — when present, the renderer shows controls).
245
+ total_rows: Optional[int] = None
246
+ page_size: Optional[int] = None
247
+ page_offset: Optional[int] = None
248
+ page_sizes: List[int] = Field(default_factory=list)
249
+ # Tool re-invocation context (lets the renderer request different pages).
250
+ source_tool: Optional[str] = None
251
+ source_agent: Optional[str] = None
252
+ source_params: Dict[str, Any] = Field(default_factory=dict)
253
+
254
+
255
+ # ---------------------------------------------------------------------------
256
+ # Charts
257
+ # ---------------------------------------------------------------------------
258
+
259
+
260
+ class ChartDataset(SerModel):
261
+ """A named series of values. Not a primitive itself."""
262
+
263
+ label: str = ""
264
+ data: List[float] = Field(default_factory=list)
265
+ color: Optional[str] = None
266
+
267
+
268
+ class BarChart(Primitive):
269
+ """A bar chart."""
270
+
271
+ type: Literal["bar_chart"] = "bar_chart"
272
+ title: str = ""
273
+ labels: List[str] = Field(default_factory=list)
274
+ datasets: List[Dict[str, Any]] = Field(default_factory=list)
275
+
276
+
277
+ class LineChart(Primitive):
278
+ """A line chart."""
279
+
280
+ type: Literal["line_chart"] = "line_chart"
281
+ title: str = ""
282
+ labels: List[str] = Field(default_factory=list)
283
+ datasets: List[Dict[str, Any]] = Field(default_factory=list)
284
+
285
+
286
+ class PieChart(Primitive):
287
+ """A pie chart."""
288
+
289
+ type: Literal["pie_chart"] = "pie_chart"
290
+ title: str = ""
291
+ labels: List[str] = Field(default_factory=list)
292
+ data: List[float] = Field(default_factory=list)
293
+ colors: List[str] = Field(default_factory=list)
294
+
295
+
296
+ class PlotlyChart(Primitive):
297
+ """An arbitrary Plotly figure (data + layout + config)."""
298
+
299
+ type: Literal["plotly_chart"] = "plotly_chart"
300
+ title: str = ""
301
+ data: List[Dict[str, Any]] = Field(default_factory=list)
302
+ layout: Dict[str, Any] = Field(default_factory=dict)
303
+ config: Dict[str, Any] = Field(default_factory=dict)
304
+
305
+
306
+ # ---------------------------------------------------------------------------
307
+ # Media & I/O
308
+ # ---------------------------------------------------------------------------
309
+
310
+
311
+ class Audio(Primitive):
312
+ """Audio player primitive.
313
+
314
+ Supports inline base64 data, URLs, generated speech, and MIDI.
315
+ """
316
+
317
+ type: Literal["audio"] = "audio"
318
+ src: str = ""
319
+ contentType: Optional[str] = None # audio/mpeg, audio/wav, audio/midi, ...
320
+ autoplay: bool = False
321
+ loop: bool = False
322
+ label: Optional[str] = None # optional title above the player
323
+ showControls: bool = True
324
+ description: Optional[str] = None # optional caption/description
325
+
326
+
327
+ class FileUpload(Primitive):
328
+ """A file upload control."""
329
+
330
+ type: Literal["file_upload"] = "file_upload"
331
+ label: str = "Upload File"
332
+ accept: str = "*/*"
333
+ action: str = ""
334
+
335
+
336
+ class FileDownload(Primitive):
337
+ """A file download link/button."""
338
+
339
+ type: Literal["file_download"] = "file_download"
340
+ label: str = "Download File"
341
+ url: str = ""
342
+ filename: Optional[str] = None
343
+
344
+
345
+ # ---------------------------------------------------------------------------
346
+ # Theming
347
+ # ---------------------------------------------------------------------------
348
+
349
+
350
+ class ColorPicker(Primitive):
351
+ """A color picker bound to a theme color key."""
352
+
353
+ type: Literal["color_picker"] = "color_picker"
354
+ label: str = ""
355
+ color_key: str = ""
356
+ value: str = "#000000"
357
+
358
+
359
+ class ThemeApply(Primitive):
360
+ """Applies a theme preset or individual color change."""
361
+
362
+ type: Literal["theme_apply"] = "theme_apply"
363
+ preset: Optional[str] = None
364
+ colors: Optional[Dict[str, str]] = None
365
+ color_key: Optional[str] = None
366
+ color_value: Optional[str] = None
367
+ message: str = ""
astralprims/py.typed ADDED
File without changes
@@ -0,0 +1,15 @@
1
+ """Helpers for shipping primitives over the wire."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Dict, List
6
+
7
+ from .base import Primitive
8
+
9
+
10
+ def create_ui_response(components: List[Primitive]) -> Dict[str, Any]:
11
+ """Wrap a list of primitives in the standard UI response envelope."""
12
+ return {
13
+ "_ui_components": [c.to_dict() for c in components],
14
+ "_data": None,
15
+ }
@@ -0,0 +1,135 @@
1
+ Metadata-Version: 2.4
2
+ Name: astralprims
3
+ Version: 0.1.0
4
+ Summary: Composable, serializable UI primitives for Python
5
+ Project-URL: Homepage, https://github.com/AstralDeep/Astral-Primitives
6
+ Project-URL: Issues, https://github.com/AstralDeep/Astral-Primitives/issues
7
+ Author-email: Sam Armstrong <admin@example.com>
8
+ License-Expression: Apache-2.0
9
+ License-File: LICENSE
10
+ Keywords: components,json,primitives,serialization,ui
11
+ Classifier: License :: OSI Approved :: Apache Software License
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Typing :: Typed
15
+ Requires-Python: >=3.9
16
+ Requires-Dist: pydantic>=2
17
+ Provides-Extra: dev
18
+ Requires-Dist: pytest>=7.0; extra == 'dev'
19
+ Description-Content-Type: text/markdown
20
+
21
+ # Astral Primitives
22
+
23
+ Composable, serializable UI primitives for Python. Describe UI as plain Python
24
+ objects, then serialize them to a `dict`/JSON for storage or for a server-driven
25
+ UI to render.
26
+
27
+ ## Install
28
+
29
+ ```bash
30
+ pip install -e ".[dev]" # editable install with test deps
31
+ ```
32
+
33
+ ## Quick start
34
+
35
+ ```python
36
+ from astralprims import Button
37
+
38
+ button = Button(
39
+ label="the button text",
40
+ action="open",
41
+ css={"background-color": "white", "color": "#000000"},
42
+ )
43
+
44
+ button.to_dict()
45
+ # {
46
+ # "type": "button",
47
+ # "css": {"background-color": "white", "color": "#000000"},
48
+ # "label": "the button text",
49
+ # "action": "open",
50
+ # "payload": {},
51
+ # "variant": "primary",
52
+ # }
53
+
54
+ button.to_json() # -> JSON string
55
+ ```
56
+
57
+ `None` and empty `css` are dropped from the output, so payloads stay clean.
58
+
59
+ ### Composing layouts
60
+
61
+ ```python
62
+ from astralprims import Card, Container, Text, Button
63
+
64
+ page = Container(css={"display": "flex"}, direction="column").add(
65
+ Text(content="Welcome", variant="h1"),
66
+ Card(title="Sign up").add(
67
+ Text(content="Enter your details below."),
68
+ Button(label="Get started", action="signup"),
69
+ ),
70
+ )
71
+ page.to_dict() # children/content serialize recursively
72
+ ```
73
+
74
+ ### Round-tripping from data
75
+
76
+ Already have a primitive as a `dict` (from storage or an API)? Rebuild it —
77
+ including the full nested tree:
78
+
79
+ ```python
80
+ from astralprims import Primitive
81
+
82
+ spec = {"type": "button", "label": "Buy", "action": "checkout"}
83
+ button = Primitive.from_dict(spec) # -> Button(...)
84
+ ```
85
+
86
+ ### Shipping a response
87
+
88
+ ```python
89
+ from astralprims import create_ui_response, Text, Button
90
+
91
+ create_ui_response([Text(content="hi"), Button(label="ok", action="go")])
92
+ # {"_ui_components": [{...}, {...}], "_data": None}
93
+ ```
94
+
95
+ A FastAPI endpoint can return `primitive.to_dict()` or `create_ui_response(...)`
96
+ directly.
97
+
98
+ ## Built-in primitives
99
+
100
+ | Group | Primitives |
101
+ |-----------|----------------------------------------------------------------------------|
102
+ | Layout | `Container`, `Card`, `Grid`/`Grids`, `Tabs` (+ `TabItem`), `Collapsible`, `Divider` |
103
+ | Content | `Text`, `Button`, `Input`, `ParamPicker`, `Image`, `CodeBlock`, `Alert`, `ProgressBar`, `MetricCard`, `List_`, `Table` |
104
+ | Charts | `BarChart`, `LineChart`, `PieChart`, `PlotlyChart` (+ `ChartDataset`) |
105
+ | Media/IO | `Audio`, `FileUpload`, `FileDownload` |
106
+ | Theming | `ColorPicker`, `ThemeApply` |
107
+
108
+ Every primitive also accepts `css`, `id`, `class_name` (serialized as `class`),
109
+ `tooltip`, and an `attributes` dict for arbitrary extra keys.
110
+
111
+ ## Defining your own primitive
112
+
113
+ Subclassing auto-registers the new `type` for `from_dict` — no manual map:
114
+
115
+ ```python
116
+ from dataclasses import dataclass
117
+ from typing import ClassVar, Optional
118
+ from astralprims import Primitive
119
+
120
+ @dataclass
121
+ class Badge(Primitive):
122
+ type: ClassVar[str] = "badge" # registered automatically
123
+ label: str = ""
124
+ count: Optional[int] = None
125
+ ```
126
+
127
+ ## Tests
128
+
129
+ ```bash
130
+ pytest
131
+ ```
132
+
133
+ ## License
134
+
135
+ Apache-2.0
@@ -0,0 +1,9 @@
1
+ astralprims/__init__.py,sha256=p7uq3IbSOmperEQNd0QoBzA9xYE2pHeyop4VJKVwmr4,2489
2
+ astralprims/base.py,sha256=swlwdXGwvsnXjE31M4urz9D9rWG8frxkCA2cDfCLGHc,5982
3
+ astralprims/primitives.py,sha256=UtEJojo2c7fq5JFXqZifvYEqNpmhQj1i9HsJ3O0Kzm4,10299
4
+ astralprims/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ astralprims/response.py,sha256=KshWYR-FpgUx4ftie-jkxk9JrUTkDVXJWSdgd1zVw74,404
6
+ astralprims-0.1.0.dist-info/METADATA,sha256=EuSXHq9ZmFvZ9gWGRcJ3tVxhcELen1v4V7pDGR4JDEE,3871
7
+ astralprims-0.1.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
8
+ astralprims-0.1.0.dist-info/licenses/LICENSE,sha256=d0VzGR8il10kGRtEpIGtqFW9xxj6e90y-cPkIluMfOM,11344
9
+ astralprims-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.29.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 Sam Armstrong
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.