answerui-py 0.0.2__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.
- answerui/__init__.py +20 -0
- answerui/_modidx.py +143 -0
- answerui/all.py +14 -0
- answerui/base.py +89 -0
- answerui/behaviors.py +83 -0
- answerui/controls.py +436 -0
- answerui/css/palette.css +12 -0
- answerui/css/typrose.LICENSE +21 -0
- answerui/css/typrose.css +358 -0
- answerui/data.py +43 -0
- answerui/demo.py +98 -0
- answerui/fonts/IBM-Plex.LICENSE +93 -0
- answerui/fonts/ibm-plex-mono-latin-400-normal.woff2 +0 -0
- answerui/fonts/ibm-plex-sans-latin-400-italic.woff2 +0 -0
- answerui/fonts/ibm-plex-sans-latin-400-normal.woff2 +0 -0
- answerui/fonts/ibm-plex-sans-latin-600-normal.woff2 +0 -0
- answerui/fonts/ibm-plex-serif-latin-600-normal.woff2 +0 -0
- answerui/hdrs.py +80 -0
- answerui/layout.py +113 -0
- answerui/navigation.py +113 -0
- answerui/overlays.py +243 -0
- answerui/registry.py +238 -0
- answerui/skill.py +92 -0
- answerui/status.py +187 -0
- answerui/surfaces.py +100 -0
- answerui/tokens.py +157 -0
- answerui_py-0.0.2.dist-info/METADATA +136 -0
- answerui_py-0.0.2.dist-info/RECORD +32 -0
- answerui_py-0.0.2.dist-info/WHEEL +5 -0
- answerui_py-0.0.2.dist-info/entry_points.txt +5 -0
- answerui_py-0.0.2.dist-info/licenses/LICENSE +201 -0
- answerui_py-0.0.2.dist-info/top_level.txt +1 -0
answerui/registry.py
ADDED
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
"""Defining hyperelements and collecting their styles and behaviors
|
|
2
|
+
|
|
3
|
+
A UI component needs HTML markup, CSS styling, and sometimes browser behavior. FastHTML already gives us the markup constructors. Here we build a registry to hold the styling and behaviors, associate them with their constructor, and collect everything a page needs into one stylesheet and one script. The same registry holds application styling that belongs to no component, such as page layout.
|
|
4
|
+
|
|
5
|
+
Docs: https://AnswerDotAI.github.io/answerui/registry.html.md"""
|
|
6
|
+
|
|
7
|
+
# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/00_registry.ipynb.
|
|
8
|
+
|
|
9
|
+
# %% auto #0
|
|
10
|
+
__all__ = ['LAYERS', 'reg', 'hypelt', 'Rule', 'RuleView', 'Registry', 'Hyperelement']
|
|
11
|
+
|
|
12
|
+
# %% ../nbs/00_registry.ipynb #3b435e1a
|
|
13
|
+
import inspect
|
|
14
|
+
from collections.abc import Mapping
|
|
15
|
+
from fastcore.utils import *
|
|
16
|
+
import fasthtml.components
|
|
17
|
+
|
|
18
|
+
# %% ../nbs/00_registry.ipynb #e481fdbf
|
|
19
|
+
LAYERS = ('reset','tokens','base','layout','components','app','utilities')
|
|
20
|
+
|
|
21
|
+
# %% ../nbs/00_registry.ipynb #da2ec151
|
|
22
|
+
def _behaviors(on, sel):
|
|
23
|
+
"Behavior records with `&` replaced by `sel`, wrapped in `:is()` so a selector list stays grouped"
|
|
24
|
+
res = []
|
|
25
|
+
for (selector, event, *capture), js in (on or {}).items():
|
|
26
|
+
if '&' in selector:
|
|
27
|
+
if sel is None: raise ValueError(f'`&` in {selector!r} needs sel')
|
|
28
|
+
selector = selector.replace('&', f':is({sel})')
|
|
29
|
+
res.append(dict(sel=selector, ev=event, js=js, cap=bool(capture and capture[0])))
|
|
30
|
+
return res
|
|
31
|
+
|
|
32
|
+
# %% ../nbs/00_registry.ipynb #dd2173a6
|
|
33
|
+
class Rule:
|
|
34
|
+
"A named CSS and behavior definition in a cascade layer"
|
|
35
|
+
def __init__(
|
|
36
|
+
self,
|
|
37
|
+
key, # Registry key: a name, or `owner.name` for a hyperelement's rule
|
|
38
|
+
css='', # Complete CSS, or a no-argument function returning it
|
|
39
|
+
*,
|
|
40
|
+
on=None, # Mapping of (selector, event[, capture]) to JavaScript handler bodies
|
|
41
|
+
sel=None, # Root selector substituted for `&` in behaviors
|
|
42
|
+
layer='app', # One of LAYERS
|
|
43
|
+
doc='', # Description of the rule
|
|
44
|
+
variant=None, # Attribute selecting a declared variant
|
|
45
|
+
):
|
|
46
|
+
if layer not in LAYERS: raise ValueError(f'Unknown layer: {layer}')
|
|
47
|
+
store_attr('key,css,sel,layer,doc,variant')
|
|
48
|
+
self.on = _behaviors(on, sel)
|
|
49
|
+
|
|
50
|
+
@property
|
|
51
|
+
def owner(self): return self.key.split('.', 1)[0] if '.' in self.key else None
|
|
52
|
+
|
|
53
|
+
@property
|
|
54
|
+
def name(self): return self.key.split('.', 1)[-1]
|
|
55
|
+
|
|
56
|
+
@property
|
|
57
|
+
def compiled_css(self):
|
|
58
|
+
"Evaluate callable CSS and return the stylesheet text"
|
|
59
|
+
return (self.css() if callable(self.css) else self.css).strip()
|
|
60
|
+
|
|
61
|
+
def __repr__(self):
|
|
62
|
+
sel = f' {self.sel}' if self.sel else ''
|
|
63
|
+
doc = f': {self.doc}' if self.doc else ''
|
|
64
|
+
return f'{self.key} [{self.layer}]{sel}{doc}'
|
|
65
|
+
|
|
66
|
+
# %% ../nbs/00_registry.ipynb #a5c98fe3
|
|
67
|
+
class RuleView(Mapping):
|
|
68
|
+
"A live, read-only view of one layer or one hyperelement's rules"
|
|
69
|
+
def __init__(self, registry, *, layer=None, owner=None): store_attr('registry,layer,owner')
|
|
70
|
+
def _matches(self, r): return (self.layer is None or r.layer==self.layer) and (self.owner is None or r.owner==self.owner)
|
|
71
|
+
def __iter__(self): return (r.name if self.owner is not None else k for k,r in self.registry.rules.items() if self._matches(r))
|
|
72
|
+
def __len__(self): return sum(1 for _ in self)
|
|
73
|
+
def __getitem__(self, name):
|
|
74
|
+
key = f'{self.owner}.{name}' if self.owner is not None else name
|
|
75
|
+
r = self.registry.rules[key]
|
|
76
|
+
if not self._matches(r): raise KeyError(name)
|
|
77
|
+
return r
|
|
78
|
+
def __repr__(self): return '\n'.join(repr(r) for r in self.values()) or '(no rules)'
|
|
79
|
+
|
|
80
|
+
class Registry:
|
|
81
|
+
"Named rules and hyperelements, shared by the asset builders"
|
|
82
|
+
def __init__(self):
|
|
83
|
+
self.rules, self.elements, self.files, self.version = {}, {}, {}, 0
|
|
84
|
+
self.layers = {name: RuleView(self, layer=name) for name in LAYERS}
|
|
85
|
+
|
|
86
|
+
def rule(
|
|
87
|
+
self,
|
|
88
|
+
key, # Registry key: a name, or `owner.name` for a hyperelement's rule
|
|
89
|
+
css='', # Complete CSS, or a no-argument function returning it
|
|
90
|
+
*,
|
|
91
|
+
on=None, # Mapping of (selector, event[, capture]) to JavaScript handler bodies
|
|
92
|
+
sel=None, # Root selector substituted for `&` in behaviors; does not scope CSS
|
|
93
|
+
layer='app', # One of LAYERS
|
|
94
|
+
doc='', # Description of the rule
|
|
95
|
+
variant=None, # Attribute selecting a declared variant
|
|
96
|
+
):
|
|
97
|
+
"Register a rule, replacing an existing definition in place"
|
|
98
|
+
r = Rule(key, css, on=on, sel=sel, layer=layer, doc=doc, variant=variant)
|
|
99
|
+
if r.key in self.rules: self.rules[r.key].__dict__.update(vars(r))
|
|
100
|
+
else: self.rules[r.key] = r
|
|
101
|
+
self.version += 1
|
|
102
|
+
return self.rules[r.key]
|
|
103
|
+
|
|
104
|
+
def remove(self, key):
|
|
105
|
+
"Remove and return the rule at its full registry key"
|
|
106
|
+
r = self.rules.pop(key)
|
|
107
|
+
self.version += 1
|
|
108
|
+
return r
|
|
109
|
+
|
|
110
|
+
def file(
|
|
111
|
+
self,
|
|
112
|
+
name, # Name the file is served under
|
|
113
|
+
path, # Where the file is on disk
|
|
114
|
+
url, # A public URL of the same file, which rules use to refer to it
|
|
115
|
+
):
|
|
116
|
+
"Register a file that rules refer to by `url`, returning `url`; `serve` serves the copy at `path` instead"
|
|
117
|
+
self.files[name] = (Path(path), url)
|
|
118
|
+
return url
|
|
119
|
+
|
|
120
|
+
def __repr__(self): return f'Registry({len(self.rules)} rules, {len(self.elements)} elements)'
|
|
121
|
+
|
|
122
|
+
def _repr_markdown_(self):
|
|
123
|
+
layers = '\n'.join(f'- `{name}`: {len(rules)} rules' for name,rules in self.layers.items())
|
|
124
|
+
elements = ', '.join(f'`{k}`' for k in self.elements) or 'none'
|
|
125
|
+
rules = '\n'.join(f'- `{k}` ({r.layer})' + (f': {r.doc}' if r.doc else '') for k,r in self.rules.items() if r.owner is None) or 'none'
|
|
126
|
+
return f'{self!r}\n\nLayers:\n{layers}\n\nElements: {elements}\n\nRules of no element:\n{rules}'
|
|
127
|
+
|
|
128
|
+
reg = Registry()
|
|
129
|
+
|
|
130
|
+
# %% ../nbs/00_registry.ipynb #8e44c63b
|
|
131
|
+
@patch
|
|
132
|
+
def build_css(self:Registry):
|
|
133
|
+
"Assemble the registry's CSS in cascade-layer order"
|
|
134
|
+
out = [f"@layer {', '.join(LAYERS)};"]
|
|
135
|
+
for layer, rules in self.layers.items():
|
|
136
|
+
parts = [f'/* {r.key} */\n{css}' for r in rules.values() if (css := r.compiled_css)]
|
|
137
|
+
if parts: out.append(f'@layer {layer} {{\n' + '\n'.join(parts) + '\n}')
|
|
138
|
+
return '\n\n'.join(out) + '\n'
|
|
139
|
+
|
|
140
|
+
# %% ../nbs/00_registry.ipynb #3fa0affe
|
|
141
|
+
def _nest(sel, css): return f'{sel} {{\n{css.strip()}\n}}' if css.strip() else ''
|
|
142
|
+
def _generic(*children, **attrs): ...
|
|
143
|
+
|
|
144
|
+
class Hyperelement:
|
|
145
|
+
"A callable constructor linked to its registered rules and behaviors"
|
|
146
|
+
def __init__(self, registry, name, fn, sel, doc='', generated=False):
|
|
147
|
+
self.registry, self.__name__, self.fn, self.sel = registry, name, fn, sel
|
|
148
|
+
self.__doc__, self.generated = doc, generated
|
|
149
|
+
self.rules = RuleView(registry, owner=name)
|
|
150
|
+
|
|
151
|
+
def __call__(self, *c, **attrs): return self.fn(*c, **attrs)
|
|
152
|
+
|
|
153
|
+
@property
|
|
154
|
+
def __signature__(self): return inspect.signature(_generic if self.generated else self.fn)
|
|
155
|
+
|
|
156
|
+
@property
|
|
157
|
+
def variants(self):
|
|
158
|
+
"Declared variant attributes and their rules"
|
|
159
|
+
return {r.variant: r for r in self.rules.values() if r.variant is not None}
|
|
160
|
+
|
|
161
|
+
@property
|
|
162
|
+
def behaviors(self):
|
|
163
|
+
"Behavior records declared by this hyperelement's rules"
|
|
164
|
+
return [b for r in self.rules.values() for b in r.on]
|
|
165
|
+
|
|
166
|
+
def __repr__(self): return f'{self.__name__} [{self.sel}]'
|
|
167
|
+
|
|
168
|
+
def _repr_markdown_(self):
|
|
169
|
+
name = self.__name__
|
|
170
|
+
sig = str(self.__signature__)
|
|
171
|
+
parts = [f'### `{name}{sig}`', self.__doc__, f'Root selector: `{self.sel}`.']
|
|
172
|
+
if self.variants:
|
|
173
|
+
variants = [f'- `{attr}`: {r.doc}' for attr,r in self.variants.items()]
|
|
174
|
+
parts.append('Declared variants:\n' + '\n'.join(variants))
|
|
175
|
+
rules = [f'- `{k}` ({r.layer})' + (f': {r.doc}' if r.doc and r.doc != self.__doc__ else '') for k,r in self.rules.items() if r.variant is None]
|
|
176
|
+
parts.append('Rules:\n' + '\n'.join(rules))
|
|
177
|
+
return '\n\n'.join(p for p in parts if p)
|
|
178
|
+
|
|
179
|
+
# %% ../nbs/00_registry.ipynb #71dedec6
|
|
180
|
+
@patch
|
|
181
|
+
def rule(
|
|
182
|
+
self:Hyperelement,
|
|
183
|
+
name, # Local rule name; registering it again replaces that rule
|
|
184
|
+
css='', # CSS declarations and nested rules, scoped to the root selector
|
|
185
|
+
*,
|
|
186
|
+
on=None, # Mapping of (selector, event[, capture]) to handler bodies; `&` is the root selector
|
|
187
|
+
layer='app', # One of LAYERS
|
|
188
|
+
doc='', # Description of the customization
|
|
189
|
+
):
|
|
190
|
+
"Register CSS and behaviors scoped to this hyperelement"
|
|
191
|
+
return self.registry.rule(f'{self.__name__}.{name}', _nest(self.sel, css), on=on, sel=self.sel, layer=layer, doc=doc)
|
|
192
|
+
|
|
193
|
+
@patch
|
|
194
|
+
def variant(
|
|
195
|
+
self:Hyperelement,
|
|
196
|
+
name, # Attribute selecting the variant; also its local rule name
|
|
197
|
+
css='', # CSS declarations and nested rules, scoped to the variant
|
|
198
|
+
*,
|
|
199
|
+
on=None, # Mapping of (selector, event[, capture]) to handler bodies; `&` is the variant selector
|
|
200
|
+
layer='app', # One of LAYERS
|
|
201
|
+
doc='', # Description shown with the variant
|
|
202
|
+
):
|
|
203
|
+
"Declare an attribute variant without changing the constructor"
|
|
204
|
+
if name=='base': raise ValueError('base is reserved for the constructor definition')
|
|
205
|
+
sel = f':is({self.sel})[{name}]'
|
|
206
|
+
return self.registry.rule(f'{self.__name__}.{name}', _nest(sel, css), on=on, sel=sel, layer=layer, doc=doc, variant=name)
|
|
207
|
+
|
|
208
|
+
# %% ../nbs/00_registry.ipynb #1fa06567
|
|
209
|
+
@patch
|
|
210
|
+
def hypelt(
|
|
211
|
+
self:Registry,
|
|
212
|
+
name=None, # FastHTML tag name or a constructor; omit to use as a decorator
|
|
213
|
+
*,
|
|
214
|
+
sel=None, # Root selector; required for a handwritten constructor
|
|
215
|
+
css='', # Complete CSS, or a no-argument function returning it; stored as the base rule
|
|
216
|
+
on=None, # Mapping of (selector, event[, capture]) to JavaScript handler bodies
|
|
217
|
+
layer='app', # One of LAYERS; built-ins use components, layout, or base
|
|
218
|
+
doc=None, # Description; defaults to a handwritten constructor's docstring
|
|
219
|
+
):
|
|
220
|
+
"Register a constructor and its base rule, returning a callable hyperelement"
|
|
221
|
+
if name is None: return partial(self.hypelt, sel=sel, css=css, on=on, layer=layer, doc=doc)
|
|
222
|
+
generated = isinstance(name, str)
|
|
223
|
+
if generated:
|
|
224
|
+
fn = getattr(fasthtml.components, name)
|
|
225
|
+
if sel is None: sel = fn().tag
|
|
226
|
+
else:
|
|
227
|
+
fn, name = name, name.__name__
|
|
228
|
+
if sel is None: raise ValueError('A handwritten constructor needs sel')
|
|
229
|
+
if doc is None: doc = fn.__doc__
|
|
230
|
+
if name in self.elements and self.elements[name].sel != sel:
|
|
231
|
+
raise ValueError(f'{name} is registered with root selector {self.elements[name].sel!r}, which its rules and variants target; register a new hyperelement for a new root')
|
|
232
|
+
self.rule(f'{name}.base', css, on=on, sel=sel, layer=layer, doc=doc or '')
|
|
233
|
+
obj = Hyperelement(self, name, fn, sel, doc or '', generated)
|
|
234
|
+
if name in self.elements: self.elements[name].__dict__.update(vars(obj))
|
|
235
|
+
else: self.elements[name] = obj
|
|
236
|
+
return self.elements[name]
|
|
237
|
+
|
|
238
|
+
hypelt = reg.hypelt
|
answerui/skill.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
# NB: this file is designed for an LLM reader, not a human. Add it to your LLM's context and ask it to explain.
|
|
2
|
+
r"""Style a FastHTML app with answerui: build pages from its components, change how they look through the registry, and check the result
|
|
3
|
+
|
|
4
|
+
notation: /why
|
|
5
|
+
|
|
6
|
+
- semantic HTML: component = native tag, or custom tag where HTML has none; variant, state: attribute; class: utilities only; `Button('Save', secondary=True)` → `<button secondary>`
|
|
7
|
+
- `reg`: registry of every rule, component, behavior; app setup:
|
|
8
|
+
|
|
9
|
+
```python
|
|
10
|
+
from fasthtml.common import *
|
|
11
|
+
from answerui.all import *
|
|
12
|
+
app = FastHTML(hdrs=reg.hdrs(), ftrs=reg.ftrs())
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
- re-importing `fasthtml.common` after answerui restores unstyled constructors
|
|
16
|
+
- headers: rebuilt each response; `reg.serve(app)`: cached, content-hashed URLs
|
|
17
|
+
|
|
18
|
+
## Building a page
|
|
19
|
+
|
|
20
|
+
- native HTML: styled with no attribute; long-form: `prose` attribute on its container
|
|
21
|
+
- layout attributes, any element: `stack` `cluster` `grid` `flow`; `Stack` `Cluster` `Grid` `Flow`: `Div` with one; component owns inner space only: parent spaces children (`gap`)
|
|
22
|
+
- `A('Sign up', href='/signup', button=True)`: link styled as button
|
|
23
|
+
- colour contexts: `[danger]` `[warning]` `[success]` `[info]` on any element, `mark`: re-point `--hue` inside: `Alert('Saved.', success=True)`, `Badge('3', danger=True)`
|
|
24
|
+
- dark island: `color-scheme: dark; background: var(--n-3); color: var(--n2)`; ladders re-derive inside
|
|
25
|
+
- icons: fastlucide, imported at module level, join `reg.ftrs()` sprite sheet: `from fastlucide.icons import Trash_2`; `Button(Trash_2(), aria_label='Remove')`; icon, or `svg` marked `icon`: takes text's colour and size; pass no size; icon-only button: needs `aria-label`
|
|
26
|
+
- `Tooltip(control, text)`: inline wrapper
|
|
27
|
+
- toasts: `add_toast(sess, 'Saved.', success=True)` → next page's `Toasts(*pop_toasts(sess))`; `setup_toasts(app)`: fragment responses deliver them too
|
|
28
|
+
|
|
29
|
+
## Reading what is registered
|
|
30
|
+
|
|
31
|
+
- `reg.elements`: every component; `doc(Button)`, `doc(reg)`; members: `doc(Hyperelement)`, `doc(Registry)`; also `Button.rules[key].css`, `Button.example()` (composable markup), `reg.layers[name]`, `reg.rules[key]`
|
|
32
|
+
|
|
33
|
+
## How the stylesheet is organised
|
|
34
|
+
|
|
35
|
+
- layers `reset, tokens, base, layout, components, app, utilities`: later wins for normal declarations, whatever specificity; registered rules default to `app` (beat framework); `hidden`: utility (beats component display)
|
|
36
|
+
- colour: `--hue`; neutral ladder `--n-3` (page) to `--n2` (body text); vivid `--v-3` (wash) to `--v2`; rungs `light-dark()`: `color-scheme` picks mode
|
|
37
|
+
- scales, one base each: `--space` `--radius` `--text`; recomputed per element: base set on a region rescales it
|
|
38
|
+
- depth: `--face`, `--relief` (`0`: flat); `--ring`: focus ring; `--tint`: faceless control's hover
|
|
39
|
+
- fonts: IBM Plex; `--font`, `--font-mono`; `--font-heading` on a scope: its headings, e.g. `reg.rule('reading', 'article { --font-heading: var(--font-serif); }')`; own font: `@font-face` + `reg.file(name, path, url)`
|
|
40
|
+
- popover: CSS-anchored below opener, flips at viewport edge; inside `anchor` element (e.g. navbar): hangs from its bottom
|
|
41
|
+
- behavior: delegated handler keyed `(selector, event[, capture])`, installed once per document, covers htmx swaps; `&`: root selector; `init`: on arrival; `cleanup`: before htmx removal (htmx 2, 4); leading `:` = `htmx:`, any spelling
|
|
42
|
+
|
|
43
|
+
## Changing the look
|
|
44
|
+
|
|
45
|
+
- smallest scope covering the change; register at import time in app module /every response carries it
|
|
46
|
+
- page: tokens on root: `reg.rule('theme', ':root { --hue: 150; --radius: 0; }')`
|
|
47
|
+
- one component, everywhere: `Button.rule('corners', 'border-radius: 0;')`: nests under root selector, states via `&`
|
|
48
|
+
- new treatment: `Button.variant('cta', '--pad-block: var(--space); --pad-inline: var(--space2); font-size: var(--text1);', doc='The landing page call to action.')` → `Button('Start free', cta=True)`, listed in `doc(Button)`; restate each state it changes /base rule's state selectors still apply
|
|
49
|
+
- region: `reg.rule('sidebar', '[sidebar] { --space: .75rem; }')`, or colour context `reg.context('[project]', 300)`
|
|
50
|
+
- key registered again: behavior key: later in registry order wins, e.g. dismissed alert hidden, not removed: `Alert.rule('hide', on={('& > button[dismiss]', 'click'): "el.closest('[alert]').hidden = true"})`; rule key: replaced in place, position kept /re-run library code never outranks app override
|
|
51
|
+
- `reg.remove(key)`; root selector: fixed at first registration
|
|
52
|
+
|
|
53
|
+
## Checking the result
|
|
54
|
+
|
|
55
|
+
- notebook: `Button.demo()`, `demo(markup)`: current CSS, JS, isolated iframe; `width=` is the viewport: `'24rem'` previews a phone (navbar collapses, popovers flip); stored as HTML frame + Markdown markup: models reading dialog see markup
|
|
56
|
+
- registry knows registrations only; which rules reach an element, how a state renders: same document in headless Chrome:
|
|
57
|
+
|
|
58
|
+
```python
|
|
59
|
+
from fastcdp import CDP
|
|
60
|
+
cdp = await CDP.launch(headless=True)
|
|
61
|
+
page = await cdp.new_page()
|
|
62
|
+
await page.set_content(demo_html(Button('Save')))
|
|
63
|
+
await page.wait_for_selector('button')
|
|
64
|
+
await page.eval("getComputedStyle(document.querySelector('button')).borderRadius")
|
|
65
|
+
await page.matched_styles('button') # every matching rule, cascade order
|
|
66
|
+
await cdp.quit()
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
- states: force first, e.g. set `aria-pressed`
|
|
70
|
+
- behaviors: fresh preview or page /second script copy stacks listeners
|
|
71
|
+
|
|
72
|
+
## Adding a component
|
|
73
|
+
|
|
74
|
+
- constructor + base rule; tag name: FastHTML's constructor, tag = root selector:
|
|
75
|
+
|
|
76
|
+
```python
|
|
77
|
+
Notice = hypelt('NoticeBox', css='notice-box { display: block; padding: var(--space); }',
|
|
78
|
+
on={('& [dismiss]', 'click'): "el.closest('notice-box').remove()"})
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
- handwritten: decorator, `sel=`, docstring = description:
|
|
82
|
+
|
|
83
|
+
```python
|
|
84
|
+
@hypelt(sel='aside[banner]')
|
|
85
|
+
def Banner(title, *c, **attrs):
|
|
86
|
+
"A notice across the top of a page"
|
|
87
|
+
...
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
- `@example(Notice)`: markup `Notice.demo()` renders
|
|
91
|
+
"""
|
|
92
|
+
from .all import *
|
answerui/status.py
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
"""Feedback, loading, and empty states
|
|
2
|
+
|
|
3
|
+
An interface needs to explain what happened, what is still happening, and why there may be nothing to show. These components provide that feedback without taking over the operation itself. The application owns the state; the markup describes it.
|
|
4
|
+
|
|
5
|
+
Docs: https://AnswerDotAI.github.io/answerui/status.html.md"""
|
|
6
|
+
|
|
7
|
+
# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/10_status.ipynb.
|
|
8
|
+
|
|
9
|
+
# %% auto #0
|
|
10
|
+
__all__ = ['toasts_key', 'Progress', 'Alert', 'Toasts', 'Toast', 'add_toast', 'pop_toasts', 'toasts_oob', 'toast_after',
|
|
11
|
+
'setup_toasts', 'Spinner', 'Skeleton']
|
|
12
|
+
|
|
13
|
+
# %% ../nbs/10_status.ipynb #1094213c
|
|
14
|
+
from fasthtml.common import Div, Span, H3, P, Label, Template, unqid
|
|
15
|
+
from fastcore.xml import FT
|
|
16
|
+
from fasthtml.core import FtResponse
|
|
17
|
+
from .registry import reg, hypelt
|
|
18
|
+
from .controls import Button
|
|
19
|
+
from .surfaces import Card
|
|
20
|
+
from .layout import Stack
|
|
21
|
+
from .demo import example
|
|
22
|
+
import answerui.base # the reset and tokens this styling is written on
|
|
23
|
+
|
|
24
|
+
# %% ../nbs/10_status.ipynb #6043392a
|
|
25
|
+
reg.rule('notice', r"""
|
|
26
|
+
:is([alert], [toast]) { display: flex; align-items: flex-start; gap: var(--space); }
|
|
27
|
+
:is([alert], [toast]) > [stack] { flex: 1; min-inline-size: 0; }
|
|
28
|
+
:is([alert], [toast]) > button[dismiss] { flex-shrink: 0; --pad-block: var(--space-3); --pad-inline: var(--space-2); }
|
|
29
|
+
""", layer='components', doc='The row shared by alerts and toasts: the message beside its dismiss button.')
|
|
30
|
+
|
|
31
|
+
def _notice(c, dismissible, **attrs):
|
|
32
|
+
"A stack of content beside an optional dismiss button"
|
|
33
|
+
close = Button('Dismiss', type='button', secondary=True, dismiss=True) if dismissible else None
|
|
34
|
+
return Div(Stack(*c, gap='var(--space-2)'), close, **attrs)
|
|
35
|
+
|
|
36
|
+
# %% ../nbs/10_status.ipynb #9a13ebff
|
|
37
|
+
_alert_css = r"""
|
|
38
|
+
[alert] { background: var(--v-3); color: var(--v2); border-color: var(--v-2); }
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
@hypelt(sel='[alert]', layer='components', css=_alert_css)
|
|
42
|
+
def Alert(
|
|
43
|
+
*c, # The message and any supporting content
|
|
44
|
+
dismissible=False, # Include a button that removes this alert
|
|
45
|
+
**attrs, # Attributes for the containing div, including severity and role
|
|
46
|
+
):
|
|
47
|
+
"An in-page message with optional dismissal"
|
|
48
|
+
return _notice(c, dismissible, card=True, alert=True, **attrs)
|
|
49
|
+
|
|
50
|
+
Alert.rule('dismiss', on={('& > button[dismiss]', 'click'): "el.closest('[alert]').remove()"}, layer='components', doc='The dismiss button removes the alert.')
|
|
51
|
+
|
|
52
|
+
# %% ../nbs/10_status.ipynb #5752e576
|
|
53
|
+
@example(Alert)
|
|
54
|
+
def _alert_example():
|
|
55
|
+
return Stack(
|
|
56
|
+
Alert('Your changes have been saved.', success=True, dismissible=True),
|
|
57
|
+
Alert(H3('Storage is nearly full'), P('Remove unused files or choose a larger plan.'), warning=True),
|
|
58
|
+
Alert('The upload failed. Your original file has not changed.', danger=True, dismissible=True))
|
|
59
|
+
|
|
60
|
+
# %% ../nbs/10_status.ipynb #afc1d55a
|
|
61
|
+
_toasts_on = {('&', 'init'): "if (!el.matches(':popover-open')) el.showPopover()"}
|
|
62
|
+
_toasts_css = r"""
|
|
63
|
+
[toasts][popover] {
|
|
64
|
+
position: fixed; inset: auto; inset-block-start: var(--space); inset-inline-end: var(--space); margin: 0;
|
|
65
|
+
padding: var(--space-3); border: 0; background: none; box-shadow: none; overflow: visible; color: inherit; pointer-events: none;
|
|
66
|
+
inline-size: min(22rem, calc(100vw - 2 * var(--space)));
|
|
67
|
+
}
|
|
68
|
+
[toasts][popover]:popover-open { display: grid; gap: var(--space-2); }
|
|
69
|
+
[toasts] > [toast] { pointer-events: auto; }
|
|
70
|
+
"""
|
|
71
|
+
|
|
72
|
+
@hypelt(sel='[toasts]', layer='components', on=_toasts_on, css=_toasts_css)
|
|
73
|
+
def Toasts(*c, **attrs):
|
|
74
|
+
"The page's polite live region for toast deliveries"
|
|
75
|
+
return Div(*c, popover='manual', role='status', aria_live='polite', aria_atomic='false',
|
|
76
|
+
aria_relevant='additions text', toasts=True, **attrs)
|
|
77
|
+
|
|
78
|
+
# %% ../nbs/10_status.ipynb #4b3c797b
|
|
79
|
+
_toast_css = r"""
|
|
80
|
+
[toast] {
|
|
81
|
+
--face: var(--n-2); background: var(--face); color: var(--n2); border: 1px solid var(--n-1);
|
|
82
|
+
border-radius: var(--radius); padding: var(--space-2) var(--space); box-shadow: var(--floating);
|
|
83
|
+
transition: opacity var(--motion) var(--ease), translate var(--motion) var(--ease);
|
|
84
|
+
@starting-style { opacity: 0; translate: 0 calc(-1 * var(--space-2)); }
|
|
85
|
+
animation: aui-toast-life var(--life) linear forwards; }
|
|
86
|
+
[toast]:is(:hover, :focus-within) { animation-play-state: paused; }
|
|
87
|
+
/* The lifetime is a timer that ends by hiding the toast. Without --life the shorthand is invalid, and the toast has no animation. */
|
|
88
|
+
@keyframes aui-toast-life { to { display: none; } }
|
|
89
|
+
[toast]:is([success], [warning], [danger], [info]) { --face: var(--v-3); color: var(--v2); border-color: var(--v-2); }
|
|
90
|
+
"""
|
|
91
|
+
|
|
92
|
+
@hypelt(sel='[toast]', layer='components', css=_toast_css)
|
|
93
|
+
def Toast(
|
|
94
|
+
*c, # The message
|
|
95
|
+
life=5000, # Unattended milliseconds before it hides; None to stay until dismissed
|
|
96
|
+
dismissible=True, # Include a dismiss button
|
|
97
|
+
oob=False, # Wrap for out-of-band delivery into the page's region, beside a fragment
|
|
98
|
+
**attrs, # Attributes for the message, including severity
|
|
99
|
+
):
|
|
100
|
+
"A brief message for the toast region"
|
|
101
|
+
if life: attrs['style'] = f'--life: {life}ms; ' + attrs.get('style', '')
|
|
102
|
+
toast = _notice(c, dismissible, toast=True, **attrs)
|
|
103
|
+
return Div(toast, hx_swap_oob='beforeend:[toasts]') if oob else toast
|
|
104
|
+
|
|
105
|
+
Toast.rule('dismiss', on={('& > button[dismiss]', 'click'): "el.closest('[toast]').remove()"}, layer='components', doc='The dismiss button removes the toast at once.')
|
|
106
|
+
|
|
107
|
+
# %% ../nbs/10_status.ipynb #09576dea
|
|
108
|
+
@example(Toast)
|
|
109
|
+
def _toast_example():
|
|
110
|
+
id = unqid()
|
|
111
|
+
response = Div(Toast('Your changes have been saved.', success=True),
|
|
112
|
+
Toast('The upload failed. Your original file has not changed.', life=None, danger=True),
|
|
113
|
+
hx_swap_oob='beforeend:[toasts]')
|
|
114
|
+
return Div(Button('Deliver notifications', type='button', secondary=True,
|
|
115
|
+
hx_on_click=f"htmx.swap(this, document.getElementById('{id}').innerHTML, {{swapStyle: 'none'}})"),
|
|
116
|
+
Template(response, id=id), Toasts())
|
|
117
|
+
|
|
118
|
+
# %% ../nbs/10_status.ipynb #fd43c227
|
|
119
|
+
toasts_key = 'aui_toasts'
|
|
120
|
+
|
|
121
|
+
def add_toast(sess, msg, life=5000, **attrs):
|
|
122
|
+
"Queue `msg` in `sess` for the next page or fragment, with its severity in `attrs`"
|
|
123
|
+
sess.setdefault(toasts_key, []).append((msg, life, attrs))
|
|
124
|
+
|
|
125
|
+
def pop_toasts(sess):
|
|
126
|
+
"The queued toasts as `Toast`s, clearing the queue"
|
|
127
|
+
return [Toast(m, life=l, **a) for m,l,a in sess.pop(toasts_key, [])]
|
|
128
|
+
|
|
129
|
+
def toasts_oob(sess):
|
|
130
|
+
"The queued toasts in an out-of-band wrapper, for delivery beside a fragment; None when nothing is queued"
|
|
131
|
+
toasts = pop_toasts(sess)
|
|
132
|
+
return Div(*toasts, hx_swap_oob='beforeend:[toasts]') if toasts else None
|
|
133
|
+
|
|
134
|
+
# %% ../nbs/10_status.ipynb #a20020e5
|
|
135
|
+
def toast_after(resp, req, sess):
|
|
136
|
+
"FastHTML `after` hook: a markup response, or none, carries the queued toasts out of band"
|
|
137
|
+
if sess.get(toasts_key) and (not resp or isinstance(resp, (tuple, FT, FtResponse))): req.injects.append(toasts_oob(sess))
|
|
138
|
+
|
|
139
|
+
def setup_toasts(app):
|
|
140
|
+
"Deliver queued toasts beside every markup response of `app`"
|
|
141
|
+
app.after.append(toast_after)
|
|
142
|
+
|
|
143
|
+
# %% ../nbs/10_status.ipynb #1061215e
|
|
144
|
+
Progress = hypelt('Progress', layer='components', doc='Native progress; omit value when the amount completed is unknown.', css=r"""
|
|
145
|
+
progress { inline-size: 100%; block-size: .75rem; vertical-align: middle; accent-color: var(--v); }
|
|
146
|
+
""")
|
|
147
|
+
|
|
148
|
+
# %% ../nbs/10_status.ipynb #28967652
|
|
149
|
+
@example(Progress)
|
|
150
|
+
def _progress_example():
|
|
151
|
+
return Stack(Label('Importing files', Progress(value=40, max=100), stack=True, style='--gap: var(--space-3)'),
|
|
152
|
+
Label('Waiting for the server', Progress(), stack=True, style='--gap: var(--space-3)'))
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
# %% ../nbs/10_status.ipynb #b1b3bb6e
|
|
156
|
+
@hypelt(sel='[spinner]', layer='components', css=r"""
|
|
157
|
+
[spinner] { display: inline-flex; align-items: center; gap: var(--space-2); }
|
|
158
|
+
[spinner]::before {
|
|
159
|
+
content: ''; flex-shrink: 0; inline-size: 1em; block-size: 1em;
|
|
160
|
+
border: 2px solid currentColor; border-inline-end-color: transparent; border-radius: var(--radius-full);
|
|
161
|
+
animation: aui-spin calc(var(--motion) * 5) linear infinite;
|
|
162
|
+
}
|
|
163
|
+
""")
|
|
164
|
+
def Spinner(label='Loading…', **attrs):
|
|
165
|
+
"A small spinning ring with visible text explaining the wait"
|
|
166
|
+
return Span(label, spinner=True, **attrs)
|
|
167
|
+
|
|
168
|
+
# %% ../nbs/10_status.ipynb #d43f350d
|
|
169
|
+
@example(Spinner)
|
|
170
|
+
def _spinner_example():
|
|
171
|
+
return Spinner('Checking the connection…')
|
|
172
|
+
|
|
173
|
+
# %% ../nbs/10_status.ipynb #064bdcf6
|
|
174
|
+
@hypelt(sel='[skeleton]', layer='components', css=r"""
|
|
175
|
+
[skeleton] { display: block; inline-size: 100%; block-size: 1em;
|
|
176
|
+
background: var(--n-1); border-radius: var(--radius-1); }
|
|
177
|
+
""")
|
|
178
|
+
def Skeleton(**attrs):
|
|
179
|
+
"A decorative placeholder for content that has not loaded"
|
|
180
|
+
return Span(skeleton=True, aria_hidden='true', **attrs)
|
|
181
|
+
|
|
182
|
+
# %% ../nbs/10_status.ipynb #744ad1f6
|
|
183
|
+
@example(Skeleton)
|
|
184
|
+
def _skeleton_example():
|
|
185
|
+
return Stack(P('Loading the project summary…'),
|
|
186
|
+
Card(Skeleton(style='inline-size: 40%; block-size: 1.5em'), Skeleton(), Skeleton(style='inline-size: 75%'),
|
|
187
|
+
aria_busy='true'))
|
answerui/surfaces.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
"""Containers and small pieces of visual information
|
|
2
|
+
|
|
3
|
+
Surfaces group content without prescribing what it contains. A card is a visible boundary around a group of children, using the colour, spacing, and radius tokens already in place. A badge is a short label: a category, a count, or a status. An avatar identifies a person or team, by image or by initials.
|
|
4
|
+
|
|
5
|
+
Docs: https://AnswerDotAI.github.io/answerui/surfaces.html.md"""
|
|
6
|
+
|
|
7
|
+
# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/09_surfaces.ipynb.
|
|
8
|
+
|
|
9
|
+
# %% auto #0
|
|
10
|
+
__all__ = ['Card', 'Badge', 'Avatar']
|
|
11
|
+
|
|
12
|
+
# %% ../nbs/09_surfaces.ipynb #42450679
|
|
13
|
+
from .registry import reg, hypelt
|
|
14
|
+
from .layout import Stack, Cluster
|
|
15
|
+
from .demo import example
|
|
16
|
+
from fasthtml.common import H3, P, Span, Img
|
|
17
|
+
import answerui.base # the reset and tokens this styling is written on
|
|
18
|
+
import answerui.controls # the button rules the avatar button overrides
|
|
19
|
+
|
|
20
|
+
# %% ../nbs/09_surfaces.ipynb #f7a346f2
|
|
21
|
+
_card_css = r"""
|
|
22
|
+
[card] {
|
|
23
|
+
--face: var(--n-2); background: var(--face); border: 1px solid var(--n-1); box-shadow: var(--raised);
|
|
24
|
+
border-radius: var(--radius); padding: var(--space);
|
|
25
|
+
}
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
@hypelt(sel='[card]', layer='components', css=_card_css)
|
|
29
|
+
def Card(
|
|
30
|
+
*c, # Content of the card
|
|
31
|
+
gap=None, # Space between children; None uses --space
|
|
32
|
+
**attrs, # Attributes for the containing div
|
|
33
|
+
):
|
|
34
|
+
"A bordered surface with vertically arranged content"
|
|
35
|
+
return Stack(*c, gap=gap, card=True, **attrs)
|
|
36
|
+
|
|
37
|
+
# %% ../nbs/09_surfaces.ipynb #f04c3357
|
|
38
|
+
@example(Card)
|
|
39
|
+
def _card_example():
|
|
40
|
+
return Card(H3('Shared workspace'), P('Keep your projects and notes together in one place.'))
|
|
41
|
+
|
|
42
|
+
# %% ../nbs/09_surfaces.ipynb #6e562a01
|
|
43
|
+
_badge_css = r"""
|
|
44
|
+
[badge] {
|
|
45
|
+
display: inline-block; padding: .125em .5em;
|
|
46
|
+
font-size: var(--text-1); font-weight: var(--weight1); line-height: var(--leading-1);
|
|
47
|
+
border-radius: var(--radius-1); background: var(--v-3); color: var(--v2);
|
|
48
|
+
}
|
|
49
|
+
"""
|
|
50
|
+
|
|
51
|
+
@hypelt(sel='[badge]', layer='components', css=_badge_css)
|
|
52
|
+
def Badge(*c, **attrs):
|
|
53
|
+
"A small text label, optionally coloured by a severity attribute"
|
|
54
|
+
return Span(*c, badge=True, **attrs)
|
|
55
|
+
|
|
56
|
+
Badge.variant('secondary', 'background: var(--n-1); color: var(--n2);', layer='components', doc='A neutral label.')
|
|
57
|
+
|
|
58
|
+
# %% ../nbs/09_surfaces.ipynb #912f503f
|
|
59
|
+
@example(Badge)
|
|
60
|
+
def _badge_example():
|
|
61
|
+
return Cluster(Badge('New'), Badge('Draft', secondary=True), Badge('Active', success=True),
|
|
62
|
+
Badge('Pending', warning=True), Badge('Failed', danger=True), Badge('Preview', info=True),
|
|
63
|
+
gap='var(--space-2)')
|
|
64
|
+
|
|
65
|
+
# %% ../nbs/09_surfaces.ipynb #5250078c
|
|
66
|
+
_avatar_css = r"""
|
|
67
|
+
[avatar] {
|
|
68
|
+
--avatar-size: 2.5rem;
|
|
69
|
+
display: inline-grid; place-items: center; vertical-align: middle; flex-shrink: 0;
|
|
70
|
+
inline-size: var(--avatar-size); block-size: var(--avatar-size); border-radius: var(--radius-full);
|
|
71
|
+
object-fit: cover; background: var(--v-3); color: var(--v2);
|
|
72
|
+
font-size: calc(var(--avatar-size) * .4); font-weight: var(--weight1); line-height: 1;
|
|
73
|
+
}
|
|
74
|
+
"""
|
|
75
|
+
|
|
76
|
+
@hypelt(sel='[avatar]', layer='components', css=_avatar_css)
|
|
77
|
+
def Avatar(
|
|
78
|
+
name, # Full name, used as the accessible label and to derive initials
|
|
79
|
+
src=None, # Image URL; omit to show initials
|
|
80
|
+
**attrs, # Attributes for the image or span
|
|
81
|
+
):
|
|
82
|
+
"A circular image or initials identifying a person or team"
|
|
83
|
+
if src: return Img(src=src, alt=name, avatar=True, **attrs)
|
|
84
|
+
parts = name.split()
|
|
85
|
+
initials = parts[0][0] if parts else '?'
|
|
86
|
+
if len(parts) > 1: initials += parts[-1][0]
|
|
87
|
+
return Span(initials.upper(), role='img', aria_label=name or 'Unknown', avatar=True, **attrs)
|
|
88
|
+
|
|
89
|
+
reg.rule('avatar-button', r"""
|
|
90
|
+
button:has(> [avatar]:only-child) {
|
|
91
|
+
--pad-block: 1px; --pad-inline: 1px; border-radius: var(--radius-full); --face: var(--n-2); border-color: var(--n-1);
|
|
92
|
+
}
|
|
93
|
+
button:disabled > [avatar]:only-child { opacity: .5; }
|
|
94
|
+
""", layer='components', doc='A button whose only content is an avatar is round on the neutral surface, and fades its avatar when disabled.')
|
|
95
|
+
|
|
96
|
+
# %% ../nbs/09_surfaces.ipynb #58f4956e
|
|
97
|
+
@example(Avatar)
|
|
98
|
+
def _avatar_example():
|
|
99
|
+
return Cluster(Avatar('Ada Lovelace'), Avatar('Grace Hopper'), Avatar('Prince'),
|
|
100
|
+
Avatar('Alan Turing', style='--avatar-size: 3.5rem'))
|