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/hdrs.py ADDED
@@ -0,0 +1,80 @@
1
+ """App integration: the headers that carry the registry's assets
2
+
3
+ An app integrates answerui by passing `reg.hdrs()` and `reg.ftrs()` to `FastHTML` (or `fast_app`). The headers are the stylesheet and the behavior script. The footer is the sprite sheet for icons. The registry can change after that call, so the headers are lazy: each response renders them from the current state of the registry.
4
+
5
+ Docs: https://AnswerDotAI.github.io/answerui/hdrs.html.md"""
6
+
7
+ # AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/03_hdrs.ipynb.
8
+
9
+ # %% auto #0
10
+ __all__ = []
11
+
12
+ # %% ../nbs/03_hdrs.ipynb #cfc40afc
13
+ from fastcore.utils import *
14
+ from fasthtml.common import Style, Script, Link
15
+ from .registry import Registry
16
+ import answerui.behaviors # installs Registry.build_js
17
+ from fastlucide.icons import spritesheet
18
+ import hashlib, mimetypes
19
+ from starlette.responses import Response
20
+
21
+ # %% ../nbs/03_hdrs.ipynb #89f8f25a
22
+ def _hash(s): return hashlib.sha256(s.encode()).hexdigest()[:12]
23
+
24
+ @patch
25
+ def assets(self:Registry):
26
+ "The stylesheet and script with their content hashes, keyed by extension, built once per registry version"
27
+ if getattr(self, '_assets_version', None) != self.version:
28
+ self._assets = {ext: AttrDict(body=body, hash=_hash(body)) for ext,body in (('css', self.build_css()), ('js', self.build_js()))}
29
+ self._assets_version = self.version
30
+ return self._assets
31
+
32
+
33
+ # %% ../nbs/03_hdrs.ipynb #a8b08b14
34
+ class _Lazy:
35
+ def __init__(self, f): self.f = f
36
+ def __ft__(self): return self.f()
37
+
38
+ @patch
39
+ def hdrs(self:Registry):
40
+ "Headers for `fast_app(hdrs=...)`: the stylesheet and behavior script, rendered from this registry per response"
41
+ return _Lazy(lambda: Style(self.assets()['css'].body)), _Lazy(lambda: Script(self.assets()['js'].body))
42
+
43
+
44
+ # %% ../nbs/03_hdrs.ipynb #0a31b42e
45
+ @patch
46
+ def ftrs(self:Registry):
47
+ "Footers for `fast_app(ftrs=...)`: fastlucide's sprite sheet, with every icon that any module has imported"
48
+ return (spritesheet,)
49
+
50
+ # %% ../nbs/03_hdrs.ipynb #8c17128d
51
+ @patch
52
+ def serve(
53
+ self:Registry,
54
+ app, # The FastHTML app to mount the route on and add the headers to
55
+ path='/answerui', # URL prefix the assets are served under
56
+ ):
57
+ "Serve the stylesheet and script under content-hashed names and add the sprite sheet to `app`; returns the two headers, for an app that builds its own head"
58
+ served, mimes = {}, {'css': 'text/css', 'js': 'text/javascript'}
59
+ def local(body):
60
+ "`body` with the URL of each registered file replaced by a served copy of that file"
61
+ for name,(p,url) in self.files.items():
62
+ data = p.read_bytes()
63
+ fname = f'{hashlib.sha256(data).hexdigest()[:12]}-{name}'
64
+ served[fname] = (data, mimetypes.guess_type(name)[0])
65
+ body = body.replace(url, f'{path}/{fname}')
66
+ return body
67
+ def link(ext):
68
+ a = self.assets()[ext]
69
+ name = f'{a.hash}.{ext}'
70
+ if name not in served: served[name] = (local(a.body), mimes[ext])
71
+ return f'{path}/{name}'
72
+ @app.get(f'{path}/{{name}}')
73
+ def asset(name: str):
74
+ for ext in mimes: link(ext)
75
+ if name not in served: return Response(status_code=404)
76
+ body, mime = served[name]
77
+ return Response(body, media_type=mime, headers={'Cache-Control': 'public, max-age=31536000, immutable'})
78
+ hdrs = _Lazy(lambda: Link(rel='stylesheet', href=link('css'))), _Lazy(lambda: Script(src=link('js')))
79
+ app.hdrs, app.ftrs = [*app.hdrs, *hdrs], [*app.ftrs, *self.ftrs()]
80
+ return hdrs
answerui/layout.py ADDED
@@ -0,0 +1,113 @@
1
+ """Stack, cluster, grid, and document flow
2
+
3
+ A component owns its internal spacing. Its parent decides how it sits beside other components. Here we define four relationships between children: a vertical stack, a wrapping row, an adaptive grid, and document flow. Each is an attribute that can go on an existing element. The matching constructor adds it to a `Div`, so `Stack(...)` and `Section(..., stack=True)` use the same CSS.
4
+
5
+ Docs: https://AnswerDotAI.github.io/answerui/layout.html.md"""
6
+
7
+ # AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/07_layout.ipynb.
8
+
9
+ # %% auto #0
10
+ __all__ = ['Stack', 'Cluster', 'Grid', 'Flow']
11
+
12
+ # %% ../nbs/07_layout.ipynb #ded57221
13
+ from fasthtml.common import Div, H2, H3, P, Code, Small
14
+ from .registry import hypelt, reg
15
+ from .demo import example
16
+ import answerui.base # the reset the spacing assumes, and the tokens it reads
17
+
18
+ # %% ../nbs/07_layout.ipynb #bc0f1724
19
+ def _layout(*c, props, style='', **attrs):
20
+ style = ''.join(f'{k}: {v};' for k,v in props.items() if v is not None) + (style or '')
21
+ return Div(*c, style=style or None, **attrs)
22
+
23
+ # %% ../nbs/07_layout.ipynb #30079ba6
24
+ @hypelt(sel='[stack]', layer='layout', css=r"""
25
+ [stack] { --gap: var(--space); display: flex; flex-direction: column; gap: var(--gap); }
26
+ """)
27
+ def Stack(
28
+ *c, # Children to arrange vertically
29
+ gap=None, # CSS length or token reference; None uses --space
30
+ **attrs, # Attributes for the containing div
31
+ ):
32
+ "A vertical group with space between its children"
33
+ return _layout(*c, props={'--gap': gap}, stack=True, **attrs)
34
+
35
+ # %% ../nbs/07_layout.ipynb #5e0daa0e
36
+ @example(Stack)
37
+ def _stack_example():
38
+ return Stack(H2('Account'), P('Manage your profile and preferences.'), Small('Changes apply to this workspace.'))
39
+
40
+ # %% ../nbs/07_layout.ipynb #7851b131
41
+ @hypelt(sel='[cluster]', layer='layout', css=r"""
42
+ [cluster] { --gap: var(--space); display: flex; flex-wrap: wrap; align-items: center; gap: var(--gap); }
43
+ """)
44
+ def Cluster(
45
+ *c, # Children to arrange in a wrapping row
46
+ gap=None, # CSS length or token reference; None uses --space
47
+ **attrs, # Attributes for the containing div
48
+ ):
49
+ "A row of naturally sized children that wraps to fit"
50
+ return _layout(*c, props={'--gap': gap}, cluster=True, **attrs)
51
+
52
+ # %% ../nbs/07_layout.ipynb #21a62461
53
+ @example(Cluster)
54
+ def _cluster_example():
55
+ return Cluster(Code('FastHTML'), Code('htmx'), Code('semantic HTML'), Code('CSS'), gap='var(--space-2)')
56
+
57
+ # %% ../nbs/07_layout.ipynb #173858a6
58
+ Cluster.rule('grow', '& > [grow] { flex: 1; min-inline-size: 0; }', layer='layout', doc='A child marked `grow` takes the width the others leave, so what follows it sits at the end of the row.')
59
+
60
+
61
+ # %% ../nbs/07_layout.ipynb #f5f6e17d
62
+ @hypelt(sel='[grid]', layer='layout', css=r"""
63
+ [grid] {
64
+ --gap: var(--space); --grid-min: 16rem;
65
+ display: grid; gap: var(--gap);
66
+ grid-template-columns: repeat(auto-fit, minmax(min(100%, var(--grid-min)), 1fr));
67
+ }
68
+ [grid] > * { min-inline-size: 0; }
69
+ """)
70
+ def Grid(
71
+ *c, # Children to arrange in equal-width columns
72
+ gap=None, # CSS length or token reference; None uses --space
73
+ min_width=None, # Minimum column width; None uses 16rem, capped at the container width
74
+ **attrs, # Attributes for the containing div
75
+ ):
76
+ "Equal-width columns whose count adapts to the available width"
77
+ return _layout(*c, props={'--gap': gap, '--grid-min': min_width}, grid=True, **attrs)
78
+
79
+ # %% ../nbs/07_layout.ipynb #20674b35
80
+ @example(Grid)
81
+ def _grid_example():
82
+ return Grid(
83
+ Stack(H3('Inbox'), P('Requests waiting for a first look.'), gap='var(--space-2)'),
84
+ Stack(H3('In progress'), P('Work the team has picked up.'), gap='var(--space-2)'),
85
+ Stack(H3('Done'), P('Completed work, ready to share.'), gap='var(--space-2)'))
86
+
87
+ # %% ../nbs/07_layout.ipynb #71663ee9
88
+ Stack.rule('grow', '& > [grow] { flex: 1; }', layer='layout', doc='A child marked `grow` takes the height the others leave, so what follows it sits at the bottom of the stack.')
89
+
90
+ # %% ../nbs/07_layout.ipynb #8d30542c
91
+ reg.rule('list', ':is(ul, ol):is([stack], [cluster], [grid]) { list-style: none; padding: 0; margin: 0; }', layer='layout',
92
+ doc='A list that carries a layout is a layout, not prose: no markers, no indent.')
93
+
94
+ # %% ../nbs/07_layout.ipynb #8355d595
95
+ @hypelt(sel='[flow]', layer='layout', css=r"""
96
+ [flow] { --flow-space: 1em; }
97
+ [flow] > * + * { margin-block-start: var(--flow-space); }
98
+ [flow] > :is(h1, h2, h3, h4, h5, h6) + * { margin-block-start: calc(var(--flow-space) / 2); }
99
+ """)
100
+ def Flow(
101
+ *c, # Children in normal document flow
102
+ gap=None, # CSS length or token reference; None uses 1em with half the space after headings
103
+ **attrs, # Attributes for the containing div
104
+ ):
105
+ "Document flow with closer spacing after headings"
106
+ return _layout(*c, props={'--flow-space': gap}, flow=True, **attrs)
107
+
108
+ # %% ../nbs/07_layout.ipynb #7e917c8f
109
+ @example(Flow)
110
+ def _flow_example():
111
+ return Flow(H2('Sharing a workspace'), P('Invite your colleagues to work on the same projects.'),
112
+ P('Everyone sees the latest changes.'), H3('Permissions'),
113
+ P('Choose who can edit and who can view.'))
answerui/navigation.py ADDED
@@ -0,0 +1,113 @@
1
+ """The navbar
2
+
3
+ A navbar names the application and offers its main routes. `NavBar` combines a brand link, a `nav` of links, and actions such as search or an account menu.
4
+
5
+ Docs: https://AnswerDotAI.github.io/answerui/navigation.html.md"""
6
+
7
+ # AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/12_navigation.ipynb.
8
+
9
+ # %% auto #0
10
+ __all__ = ['NavBar']
11
+
12
+ # %% ../nbs/12_navigation.ipynb #4e943eeb
13
+ from fasthtml.common import Header, Nav, A, Div, Button, Input, Hr, unqid
14
+ from fastlucide.icons import Menu
15
+ from fastcore.utils import *
16
+ from .registry import hypelt, reg
17
+ from .layout import Cluster
18
+ from .surfaces import Avatar
19
+ from .overlays import Dropdown
20
+ from .demo import example
21
+ import answerui.base # the reset and tokens this styling is written on
22
+ import answerui.controls # the controls the example places in the bar
23
+
24
+ # %% ../nbs/12_navigation.ipynb #f51b5de9
25
+ _navbar_css = r"""
26
+ [navbar] {
27
+ display: flex; flex-wrap: wrap; align-items: center; gap: var(--space-2) var(--space);
28
+ padding: var(--space-2) var(--space);
29
+ --face: var(--n-3); background: var(--face); color: var(--n2);
30
+ border-block-end: 1px solid var(--n-1);
31
+ > a:first-child {
32
+ display: flex; align-items: center; gap: var(--space-3); flex-shrink: 0; white-space: nowrap;
33
+ font-weight: var(--weight1); font-size: var(--text1); color: inherit; text-decoration: none;
34
+ }
35
+ > [bar-content] { display: contents; }
36
+ nav { display: flex; flex-wrap: wrap; gap: var(--space-3); }
37
+ nav a { display: inline-block; padding: var(--space-3) var(--space-2); border-radius: var(--radius-1); color: inherit; text-decoration: none; }
38
+ nav a:is(:hover, :focus-visible) { background: var(--tint); }
39
+ nav a[aria-current=page] { background: var(--v-3); color: var(--v2); }
40
+ > [end] { margin-inline-start: auto; --gap: var(--space-2); }
41
+ > [burger] { display: none; padding: var(--space-3); }
42
+ }
43
+ """
44
+
45
+ @hypelt(sel='[navbar]', layer='components', css=_navbar_css)
46
+ def NavBar(
47
+ brand, # Brand content, linked to href
48
+ *c, # Navigation and other content that collapses with it
49
+ end=(), # One element or a sequence that stays visible on narrow screens
50
+ href='/', # Where the brand links
51
+ collapse=False, # Fold c behind a disclosure on a narrow bar, or when it no longer fits
52
+ **attrs, # Attributes for the header
53
+ ):
54
+ "The bar at the top of a page: brand, links, and actions"
55
+ id = unqid()
56
+ content = Div(*c, bar_content=True, id=id) if c else None
57
+ burger = Button(Menu(aria_hidden='true'), type='button', quiet=True, burger=True, aria_controls=id, aria_expanded='false', aria_label='Navigation') if collapse and c else None
58
+ return Header(A(brand, href=href), content, Cluster(*listify(end), end=True), burger,
59
+ navbar=True, anchor=True, collapse=collapse, **attrs)
60
+
61
+ NavBar.variant('align', r"""
62
+ &[align=center] { nav { margin-inline: auto; } > [end] { margin-inline-start: 0; } }
63
+ &[align=end] { nav { margin-inline-start: auto; } > [end] { margin-inline-start: 0; } }
64
+ """, layer='components', doc='Where the links sit in the space after the brand: `center`, or `end` beside the actions.')
65
+ NavBar.variant('sticky', 'position: sticky; inset-block-start: 0; z-index: 1;', layer='components', doc='Stays at the top as the page scrolls, and keeps a scrolled-to anchor from landing under it.',
66
+ on={('&', 'init'): r'''const set = () => document.documentElement.style.setProperty('--navbar-size', el.getBoundingClientRect().height + 'px');
67
+ set(); new ResizeObserver(set).observe(el)'''})
68
+ reg.rule('anchors', 'html { scroll-padding-block-start: calc(var(--navbar-size, 0px) + var(--space)); }', layer='components', doc='A scrolled-to anchor stops below the sticky navbar, with a little space.')
69
+ NavBar.variant('vivid', r"""
70
+ --face: var(--v); color: var(--n-3);
71
+ nav a[aria-current=page] { background: oklch(from var(--tint) l c h / calc(alpha * 2)); color: inherit; }
72
+ """, layer='components', doc='The brand and links on the accent.')
73
+ NavBar.variant('dark', 'color-scheme: dark;', layer='components', doc='A dark bar whatever the page scheme.')
74
+
75
+ _collapse_on = {
76
+ ('& > [burger]', 'click'): "el.setAttribute('aria-expanded', el.getAttribute('aria-expanded') !== 'true')",
77
+ ('& > [bar-content] a[href]', 'click'): "el.closest('[navbar]').querySelector(':scope > [burger]')?.setAttribute('aria-expanded', 'false')",
78
+ ('& [popover]', 'beforetoggle', True): "if (e.newState === 'open') el.closest('[navbar]').querySelector(':scope > [burger]')?.setAttribute('aria-expanded', 'false')",
79
+ (':root', 'click'): r"for (const b of document.querySelectorAll('[navbar] > [burger][aria-expanded=true]')) if (!b.closest('[navbar]').contains(e.target)) b.setAttribute('aria-expanded', 'false')",
80
+ (':root', 'keydown'): r"""
81
+ if (e.key !== 'Escape') return;
82
+ for (const b of document.querySelectorAll('[navbar] > [burger][aria-expanded=true]')) { b.setAttribute('aria-expanded', 'false'); b.focus(); }""",
83
+ ('&', 'init'): r"""
84
+ if (el._collapse) return;
85
+ const rem = parseFloat(getComputedStyle(document.documentElement).fontSize);
86
+ el._collapse = new ResizeObserver(() => {
87
+ el.removeAttribute('collapsed');
88
+ const below = parseFloat(getComputedStyle(el).getPropertyValue('--collapse-below')) * rem;
89
+ el.toggleAttribute('collapsed', el.scrollWidth > el.clientWidth || el.clientWidth < below);
90
+ });
91
+ el._collapse.observe(el);"""}
92
+
93
+ NavBar.variant('collapse', r"""
94
+ --collapse-below: 48rem; flex-wrap: nowrap;
95
+ > [bar-content] > *, > [end] { flex-shrink: 0; }
96
+ nav { flex-wrap: nowrap; }
97
+ &[collapsed] {
98
+ flex-wrap: wrap;
99
+ > [burger] { display: inline-flex; }
100
+ > [bar-content] { display: none; order: 1; flex-basis: 100%; }
101
+ &:has(> [burger][aria-expanded=true]) > [bar-content] { display: grid; gap: var(--space-2); }
102
+ nav { display: grid; margin: 0; }
103
+ }
104
+ """, on=_collapse_on, layer='components', doc='Folds the content behind a disclosure when the bar is narrower than `--collapse-below` or its content no longer fits; `collapsed` is the state its observer sets. A click outside the bar or Escape closes it.')
105
+
106
+ # %% ../nbs/12_navigation.ipynb #78679da4
107
+ def _links(): return Nav(A('Overview', href='#', aria_current='page'), A('Inventory', href='#'), A('Customers', href='#'), A('Products', href='#'))
108
+
109
+ @example(NavBar)
110
+ def _navbar_example():
111
+ return NavBar('Acme', _links(), Div(Input(type='search', placeholder='Search…', aria_label='Search'), role='search'),
112
+ end=Dropdown(Button(Avatar('Ada Lovelace', style='--avatar-size: 1.75rem'), aria_label='Account'), A('Profile', href='#'), A('Settings', href='#'), Hr(), Button('Sign out', type='button')),
113
+ collapse=True)
answerui/overlays.py ADDED
@@ -0,0 +1,243 @@
1
+ """Popovers, menus, dialogs, drawers, and tooltips
2
+
3
+ An overlay sits above the page without changing its layout. Popovers provide light dismiss; dialogs make the page behind them inert. We keep those native behaviours, add a shared floating surface, and position popovers beside the control that opened them. Menus and tooltips build on that panel.
4
+
5
+ Docs: https://AnswerDotAI.github.io/answerui/overlays.html.md"""
6
+
7
+ # AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/11_overlays.ipynb.
8
+
9
+ # %% auto #0
10
+ __all__ = ['Dialog', 'Popover', 'Dropdown', 'Tooltip']
11
+
12
+ # %% ../nbs/11_overlays.ipynb #cc79711b
13
+ from fasthtml.common import Div, Span, Button, A, P, Small, H2, Hr, FT, unqid
14
+ from .registry import reg, hypelt
15
+ from .layout import Stack, Cluster
16
+ from .demo import example
17
+ import answerui.base # the reset and tokens this styling is written on
18
+ import answerui.controls # the buttons and menu items the panels hold
19
+
20
+
21
+ # %% ../nbs/11_overlays.ipynb #1f52b05f
22
+ _fallback = "if (CSS.supports('position-area', 'center')) return;\n"
23
+ _popover_on = {
24
+ ('button[popovertarget], button[commandfor]', 'click'): _fallback + r"""
25
+ const id = el.getAttribute('popovertarget') || el.getAttribute('commandfor');
26
+ const panel = document.getElementById(id);
27
+ if (panel?.matches('[popover][anchored]')) panel._anchor = el;""",
28
+ ('&', 'beforetoggle', True): _fallback + r"""
29
+ if (e.target !== el) return;
30
+ if (e.newState === 'open') {
31
+ if (e.source) el._anchor = e.source;
32
+ el.style.visibility = 'hidden';
33
+ } else el._unwatch?.();""",
34
+ ('&', 'toggle', True): _fallback + r"""
35
+ if (e.target !== el) return;
36
+ el._unwatch?.();
37
+ if (!el.matches(':popover-open')) return;
38
+ const anchor = el._anchor;
39
+ const place = () => {
40
+ if (!anchor?.isConnected) { el.hidePopover(); return; }
41
+ const r = anchor.getBoundingClientRect(), b = (anchor.closest('[anchor]') ?? anchor).getBoundingClientRect(), gap = 4, edge = 8;
42
+ const vw = document.documentElement.getBoundingClientRect().width, vh = document.documentElement.clientHeight;
43
+ const below = vh - b.bottom - gap - edge, above = b.top - gap - edge;
44
+ const height = el.scrollHeight + el.offsetHeight - el.clientHeight;
45
+ const up = height > below && above > below;
46
+ el.style.setProperty('--_available-height', Math.max(0, up ? above : below) + 'px');
47
+ const x = getComputedStyle(anchor).direction === 'rtl' ? r.right - el.offsetWidth : r.left;
48
+ const y = up ? b.top - gap - el.offsetHeight : b.bottom + gap;
49
+ el.style.left = Math.max(edge, Math.min(x, vw - el.offsetWidth - edge)) + 'px';
50
+ el.style.top = Math.max(edge, Math.min(y, vh - el.offsetHeight - edge)) + 'px';
51
+ };
52
+ if (anchor) {
53
+ place();
54
+ const watch = new AbortController(), size = new ResizeObserver(place);
55
+ addEventListener('resize', place, {signal: watch.signal});
56
+ document.addEventListener('scroll', place, {capture: true, signal: watch.signal});
57
+ size.observe(anchor); size.observe(el);
58
+ el._unwatch = () => { watch.abort(); size.disconnect(); };
59
+ }
60
+ el.style.visibility = '';""",
61
+ ('&', 'cleanup'): _fallback + "if (e.target === el) el._unwatch?.()"}
62
+
63
+ _popover_css = r"""
64
+ [popover][anchored] {
65
+ --face: var(--n-2); background: var(--face); color: var(--n2);
66
+ border: 1px solid var(--n-1); border-radius: var(--radius); padding: var(--space); box-shadow: var(--floating);
67
+ position: fixed; inset: auto; margin: 0; max-inline-size: calc(100vw - 2 * var(--space)); overflow: auto;
68
+ position-area: block-end span-inline-end; position-try-fallbacks: flip-block, flip-inline, flip-block flip-inline; position-try-order: most-block-size;
69
+ margin-block-start: 4px; max-block-size: calc(100% - 12px);
70
+ }
71
+ [anchor] { anchor-name: --anchor; }
72
+ [anchor] [popover][anchored] { inset-block-start: anchor(--anchor bottom); }
73
+ @supports not (position-area: center) {
74
+ [popover][anchored] { margin: 0; max-block-size: var(--_available-height, calc(100dvh - 2 * var(--space))); }
75
+ }
76
+ """
77
+
78
+ @hypelt(sel='[popover][anchored]', layer='components', css=_popover_css)
79
+ def Popover(*c, popover='auto', **attrs):
80
+ "A floating panel positioned beside the button that opens it"
81
+ return Div(*c, popover=popover, anchored=True, **attrs)
82
+
83
+ Popover.rule('expanded', on={('[popover]', 'toggle', True): r"""
84
+ if (e.target !== el) return;
85
+ for (const b of document.querySelectorAll(`[popovertarget="${CSS.escape(el.id)}"]:not([popovertargetaction=hide]), [commandfor="${CSS.escape(el.id)}"]:is([command=toggle-popover], [command=show-popover])`)) b.setAttribute('aria-expanded', String(el.matches(':popover-open')));"""},
86
+ layer='components', doc='Every button that opens or toggles the panel carries `aria-expanded` while it is open.')
87
+ Popover.rule('placement', on=_popover_on, layer='components', doc='In an engine without anchor positioning: remembers the button that opened the panel, places the panel beside it within the viewport, and follows scrolling and resizing until it closes.')
88
+
89
+ # %% ../nbs/11_overlays.ipynb #a924da10
90
+ reg.rule('fade', r'''
91
+ :is(dialog, [popover][anchored]), dialog::backdrop {
92
+ opacity: 0;
93
+ transition: opacity var(--motion) var(--ease), translate var(--motion) var(--ease), display var(--motion) allow-discrete, overlay var(--motion) allow-discrete;
94
+ }
95
+ :is(dialog[open], [popover][anchored]:popover-open), dialog[open]::backdrop { opacity: 1; @starting-style { opacity: 0; } }
96
+ ''', layer='components', doc='Dialogs, their backdrops, and anchored popovers fade over `--motion`, staying in the top layer until the fade ends.')
97
+
98
+ # %% ../nbs/11_overlays.ipynb #483c7ce2
99
+ @example(Popover)
100
+ def _popover_example():
101
+ id = unqid()
102
+ return Cluster(Button('What is a workspace?', type='button', secondary=True, popovertarget=id),
103
+ Popover(P("A workspace holds a team's projects, members, and billing."), id=id, style='max-inline-size: 18rem'))
104
+
105
+ # %% ../nbs/11_overlays.ipynb #698fc804
106
+ _dropdown_disabled = {('& > [aria-disabled=true]', 'click', True): "e.preventDefault(); e.stopImmediatePropagation()"}
107
+
108
+ _dropdown_css = r"""
109
+ [popover][dropdown] { min-inline-size: min(12rem, calc(100vw - 2 * var(--space))); padding: var(--space-3); }
110
+ [popover][dropdown]:popover-open { display: grid; align-content: start; block-size: max-content; }
111
+ [dropdown] > :is(a, button) {
112
+ display: block; inline-size: 100%; text-align: start; padding: var(--space-2) var(--space-1);
113
+ font: inherit; font-weight: var(--weight); color: inherit; text-decoration: none;
114
+ background: none; border: 0; border-radius: var(--radius-1); box-shadow: none;
115
+ }
116
+ [dropdown] > :is(a, button):not(:disabled, [aria-disabled=true]):is(:hover, :focus-visible) {
117
+ background: var(--v-3); color: var(--v2);
118
+ }
119
+ [dropdown] > :is(a, button)[danger]:not(:disabled, [aria-disabled=true]) { color: var(--v); }
120
+ [dropdown] > :is(a, button):is(:disabled, [aria-disabled=true]) { color: var(--n1); cursor: default; }
121
+ [dropdown] > hr { margin-block: var(--space-3); }
122
+ [dropdown] > :not(a, button, hr) { padding-inline: var(--space-1); }
123
+ """
124
+
125
+ @hypelt(sel='[popover][dropdown]', layer='components', css=_dropdown_css)
126
+ def Dropdown(
127
+ trigger, # Label text or a configured Button
128
+ *items, # Buttons, links, Hr separators, and other content such as a heading, which aligns with the items
129
+ id=None, # Panel id; generated when omitted
130
+ **attrs, # Attributes for the panel
131
+ ):
132
+ "A button and its popover of ordinary links and actions"
133
+ id = id or unqid()
134
+ if not isinstance(trigger, FT) or trigger.tag != 'button': trigger = Button(trigger, secondary=True)
135
+ acts = [c for c in items if isinstance(c, FT) and c.tag in ('a', 'button')]
136
+ for c in acts:
137
+ if c.tag == 'button' and 'popovertarget' not in c.attrs: c(popovertarget=id, popovertargetaction='hide')
138
+ live = [c for c in acts if (c.get('href') if c.tag == 'a' else not c.get('disabled')) and c.get('aria-disabled') != 'true' and not c.get('hidden')]
139
+ if live: live[0](autofocus=True)
140
+ return trigger(type='button', popovertarget=id), Popover(*items, dropdown=True, id=id, **attrs)
141
+
142
+ Dropdown.rule('disabled', on=_dropdown_disabled, layer='components', doc='An item marked aria-disabled does nothing.')
143
+ Dropdown.rule('choose', on={('& > a[href]', 'click'): "el.closest('[popover]').hidePopover()"}, layer='components',
144
+ doc='Following a link closes the dropdown; a button closes it natively through popovertargetaction.')
145
+
146
+ # %% ../nbs/11_overlays.ipynb #516efdb7
147
+ @example(Dropdown)
148
+ def _dropdown_example():
149
+ trigger, panel = Dropdown(Button('Options', aria_label='Project actions'),
150
+ Button('Rename', type='button'), Button('Duplicate', type='button', disabled=True),
151
+ Hr(), Button('Delete', type='button', danger=True))
152
+ assert trigger.get('aria-label') == 'Project actions'
153
+ return Cluster(Dropdown('Account', P('Ada Lovelace'), Small('ada@example.com'), Hr(), A('Profile', href='#'), A('Billing', href='#'),
154
+ Hr(), Button('Sign out', type='button')), trigger, panel)
155
+
156
+ # %% ../nbs/11_overlays.ipynb #ee3e977b
157
+ reg.rule('commands', sel='button[commandfor]', on={('&', 'click'): r"""
158
+ if ('commandForElement' in el) return;
159
+ const t = document.getElementById(el.getAttribute('commandfor')), c = el.getAttribute('command');
160
+ if (!t) return;
161
+ if (!['show-modal', 'close', 'toggle-popover'].includes(c)) return;
162
+ e.preventDefault();
163
+ if (c === 'show-modal') t.showModal();
164
+ else if (c === 'close') t.close();
165
+ else { t._anchor = el; t.togglePopover(); }"""},
166
+ layer='components', doc='`command` and `commandfor` on engines without invoker commands.')
167
+
168
+ # %% ../nbs/11_overlays.ipynb #8b29bffc
169
+ Dialog = hypelt('Dialog', layer='components', doc='A modal panel over an inert page; `drawer` slides it in from an edge.', css=r"""
170
+ dialog {
171
+ --face: var(--n-2); background: var(--face); color: var(--n2);
172
+ border: 1px solid var(--n-1); border-radius: var(--radius1); padding: var(--space1); box-shadow: var(--floating);
173
+ inline-size: min(32rem, calc(100% - 2 * var(--space)));
174
+ translate: 0 var(--space-2);
175
+ }
176
+ dialog[open] { translate: none; @starting-style { translate: 0 var(--space-2); } }
177
+ dialog::backdrop { background: oklch(from var(--n2) l c h / .4); }
178
+ """)
179
+ Dialog.variant('drawer', r"""
180
+ --_slide: 100%; --drawer-size: 24rem; --face: var(--n-3); inset: 0; inset-inline-start: auto; overflow-y: auto;
181
+ block-size: 100dvh; max-block-size: none; inline-size: var(--drawer-size); max-inline-size: none; margin: 0;
182
+ border-radius: 0; border-block: 0; border-inline-end: 0; translate: var(--_slide) 0;
183
+ &:dir(rtl) { --_slide: -100%; }
184
+ &[drawer=start] { --_slide: -100%; inset-inline: 0 auto; border-inline: 0; border-inline-end: 1px solid var(--n-1); }
185
+ &[drawer=start]:dir(rtl) { --_slide: 100%; }
186
+ &[open] { translate: none; @starting-style { translate: var(--_slide) 0; } }
187
+ @media (width < 40rem) { &, &[drawer=start] { inline-size: 100%; border: 0; } }
188
+ """, layer='components', doc='Slides in from the end edge and runs the full height, `--drawer-size` wide, or the whole screen below 40rem, on the page colour, scrolling when its content is taller; `start` slides in from the other edge.')
189
+
190
+ # %% ../nbs/11_overlays.ipynb #41c6963e
191
+ Dialog.rule('fill', on={('&', ':after-swap'): "if (e.target !== el && !el.open) el.showModal()"}, layer='components',
192
+ doc='A closed dialog opens when htmx swaps content into it; a swap of the dialog itself leaves it as it is.')
193
+
194
+ # %% ../nbs/11_overlays.ipynb #8166b428
195
+ @example(Dialog)
196
+ def _dialog_example():
197
+ id, title = unqid(), unqid()
198
+ return Cluster(Button('Delete project', type='button', danger=True, command='show-modal', commandfor=id),
199
+ Dialog(Stack(H2('Delete this project?', id=title), P('Everything in it is removed. This cannot be undone.'),
200
+ Cluster(Button('Cancel', type='button', secondary=True, command='close', commandfor=id, autofocus=True),
201
+ Button('Delete', type='button', danger=True, command='close', commandfor=id), gap='var(--space-2)')),
202
+ id=id, aria_labelledby=title))
203
+
204
+ # %% ../nbs/11_overlays.ipynb #7e401e03
205
+ _tooltip_css = r"""
206
+ [tooltip] { display: inline-block; position: relative; }
207
+ [tooltip] > [role=tooltip] {
208
+ --face: var(--n2); background: var(--face); color: var(--n-3); border: 0;
209
+ padding: var(--space-3) var(--space-2); border-radius: var(--radius-1);
210
+ inline-size: max-content; max-inline-size: min(20rem, calc(100vw - 2 * var(--space))); overflow-wrap: anywhere;
211
+ font-size: var(--text-1); font-weight: var(--weight); line-height: var(--leading);
212
+ position: fixed; inset: auto; position-area: block-start; position-try-fallbacks: flip-block; margin-block-end: 4px; z-index: 1;
213
+ visibility: hidden; opacity: 0;
214
+ transition: opacity var(--motion) var(--ease) 150ms, visibility 0s linear calc(var(--motion) + 150ms);
215
+ }
216
+ [tooltip]:is(:hover, :has(:focus-visible)) > [role=tooltip] { visibility: visible; opacity: 1; transition: none; }
217
+ :root:has([tooltip]:is(:hover, :has(:focus-visible))) [tooltip]:not(:hover, :has(:focus-visible)) > [role=tooltip] { transition: none; }
218
+ @supports not (position-area: center) {
219
+ [tooltip] > [role=tooltip] { position: absolute; inset: auto auto 100% 0; }
220
+ }
221
+ """
222
+
223
+ @hypelt(sel='[tooltip]', layer='components', css=_tooltip_css)
224
+ def Tooltip(
225
+ trigger, # A control with its own accessible name
226
+ text, # Supplementary, non-interactive content
227
+ id=None, # Description id; generated when omitted
228
+ **attrs, # Attributes for the description
229
+ ):
230
+ "A control and its supplementary description, shown on hover or keyboard focus"
231
+ id = id or unqid()
232
+ describedby = ' '.join(filter(None, [trigger.get('aria-describedby'), id]))
233
+ trigger(aria_describedby=describedby, style=' '.join(filter(None, [trigger.get('style'), f'anchor-name: --{id};'])))
234
+ tip = Div(text, role='tooltip', id=id, **attrs)(style=' '.join(filter(None, [attrs.get('style'), f'position-anchor: --{id};'])))
235
+ return Span(trigger, tip, tooltip=True)
236
+
237
+
238
+ # %% ../nbs/11_overlays.ipynb #c9c2bdd5
239
+ @example(Tooltip)
240
+ def _tooltip_example():
241
+ return Cluster(Tooltip(Button('Archive', type='button', secondary=True), 'Move to the archive'),
242
+ Tooltip(Button('Share', type='button', secondary=True), 'Copy a link'),
243
+ Tooltip(Button('Delete', type='button', danger=True), 'This cannot be undone'))