quantumgui 1.0.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.
Files changed (73) hide show
  1. quantumgui/__init__.py +9 -0
  2. quantumgui/__main__.py +6 -0
  3. quantumgui/cli.py +341 -0
  4. quantumgui/core/__init__.py +39 -0
  5. quantumgui/core/animation.py +221 -0
  6. quantumgui/core/audit.py +323 -0
  7. quantumgui/core/context.py +54 -0
  8. quantumgui/core/data_source.py +426 -0
  9. quantumgui/core/draw.py +428 -0
  10. quantumgui/core/enterprise.py +402 -0
  11. quantumgui/core/enterprise_app.py +419 -0
  12. quantumgui/core/events.py +34 -0
  13. quantumgui/core/geometry.py +108 -0
  14. quantumgui/core/native_dialogs.py +276 -0
  15. quantumgui/core/pdf_report.py +390 -0
  16. quantumgui/core/rules.py +284 -0
  17. quantumgui/core/state.py +42 -0
  18. quantumgui/core/task_runner.py +181 -0
  19. quantumgui/core/widget.py +498 -0
  20. quantumgui/core/window.py +920 -0
  21. quantumgui/core/xlsx_export.py +145 -0
  22. quantumgui/py.typed +0 -0
  23. quantumgui/theme/__init__.py +32 -0
  24. quantumgui/theme/hct.py +191 -0
  25. quantumgui/theme/theme.py +93 -0
  26. quantumgui/theme/tokens.py +423 -0
  27. quantumgui/ui.py +2142 -0
  28. quantumgui/widgets/__init__.py +168 -0
  29. quantumgui/widgets/advanced.py +499 -0
  30. quantumgui/widgets/button.py +224 -0
  31. quantumgui/widgets/charts.py +625 -0
  32. quantumgui/widgets/charts_bi.py +528 -0
  33. quantumgui/widgets/charts_extra.py +430 -0
  34. quantumgui/widgets/charts_pro.py +568 -0
  35. quantumgui/widgets/checkbox.py +199 -0
  36. quantumgui/widgets/chip.py +219 -0
  37. quantumgui/widgets/containers.py +321 -0
  38. quantumgui/widgets/data_controls.py +487 -0
  39. quantumgui/widgets/data_grid.py +956 -0
  40. quantumgui/widgets/data_table.py +551 -0
  41. quantumgui/widgets/date_picker.py +407 -0
  42. quantumgui/widgets/display_media.py +372 -0
  43. quantumgui/widgets/display_pro.py +407 -0
  44. quantumgui/widgets/drawer.py +252 -0
  45. quantumgui/widgets/enterprise_controls.py +934 -0
  46. quantumgui/widgets/fab.py +261 -0
  47. quantumgui/widgets/forms_pro.py +703 -0
  48. quantumgui/widgets/forms_pro_media.py +587 -0
  49. quantumgui/widgets/inputs.py +870 -0
  50. quantumgui/widgets/layout_pro.py +162 -0
  51. quantumgui/widgets/list_view.py +307 -0
  52. quantumgui/widgets/masked_input.py +131 -0
  53. quantumgui/widgets/master_detail.py +155 -0
  54. quantumgui/widgets/navigation.py +382 -0
  55. quantumgui/widgets/overlays.py +355 -0
  56. quantumgui/widgets/productivity.py +500 -0
  57. quantumgui/widgets/productivity_boards.py +544 -0
  58. quantumgui/widgets/radio.py +209 -0
  59. quantumgui/widgets/scroll_view.py +129 -0
  60. quantumgui/widgets/select.py +373 -0
  61. quantumgui/widgets/sheets.py +249 -0
  62. quantumgui/widgets/slider.py +209 -0
  63. quantumgui/widgets/switch.py +196 -0
  64. quantumgui/widgets/tabs.py +175 -0
  65. quantumgui/widgets/text.py +101 -0
  66. quantumgui/widgets/text_field.py +490 -0
  67. quantumgui/widgets/time_picker.py +499 -0
  68. quantumgui-1.0.0.dist-info/METADATA +137 -0
  69. quantumgui-1.0.0.dist-info/RECORD +73 -0
  70. quantumgui-1.0.0.dist-info/WHEEL +5 -0
  71. quantumgui-1.0.0.dist-info/entry_points.txt +2 -0
  72. quantumgui-1.0.0.dist-info/licenses/LICENSE +32 -0
  73. quantumgui-1.0.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,407 @@
1
+ """Phase 10 Display & Feedback Controls (Part 1): Alert, Avatar, AvatarGroup, EmptyState, StatusBar."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Callable, Literal, Sequence
6
+
7
+ import skia
8
+
9
+ from ..core.draw import (
10
+ draw_icon,
11
+ draw_text_centered_y,
12
+ font_for_style,
13
+ get_font,
14
+ make_rrect,
15
+ make_rrect_spec,
16
+ measure_text,
17
+ resolve_color,
18
+ )
19
+ from ..core.events import MouseEvent
20
+ from ..core.geometry import Constraints, Rect, Size
21
+ from ..core.widget import Widget
22
+ from ..theme import Color, Theme
23
+ from .data_table import _draw_image_cover, _resolve_skia_image
24
+
25
+ AlertSeverity = Literal["info", "success", "warning", "error"]
26
+ PresenceStatus = Literal["online", "away", "busy", "offline"]
27
+
28
+
29
+ # ---------------------------------------------------------------------------
30
+ # 1. Alert / Banner
31
+ # ---------------------------------------------------------------------------
32
+
33
+
34
+ class Alert(Widget):
35
+ """Embedded Material Design 3 Alert / Banner (`info`, `success`, `warning`, `error`)."""
36
+
37
+ interactive = True
38
+ manages_own_box = True
39
+
40
+ def __init__(
41
+ self,
42
+ title: str,
43
+ *,
44
+ message: str = "",
45
+ severity: AlertSeverity = "info",
46
+ action_label: str | None = None,
47
+ on_action: Callable[[], None] | None = None,
48
+ closable: bool = False,
49
+ on_close: Callable[[], None] | None = None,
50
+ ) -> None:
51
+ super().__init__()
52
+ self.title = title
53
+ self.message = message
54
+ self.severity: AlertSeverity = severity
55
+ self.action_label = action_label
56
+ self.on_action = on_action
57
+ self.closable = closable
58
+ self.on_close = on_close
59
+ self._action_rect: Rect = Rect(0, 0, 0, 0)
60
+ self._close_rect: Rect = Rect(0, 0, 0, 0)
61
+ self._fill_width = True
62
+
63
+ def _palette(self, theme: Theme) -> tuple[Color, Color, Color, str]:
64
+ c = theme.colors
65
+ if self.severity == "error":
66
+ return (c.error_container, c.on_error_container, c.error, "close")
67
+ if self.severity == "warning":
68
+ bg = Color.from_hex("#FFF3CD") if theme.mode == "light" else Color.from_hex("#4A3800")
69
+ fg = Color.from_hex("#664D03") if theme.mode == "light" else Color.from_hex("#FFE082")
70
+ accent = Color.from_hex("#D97706")
71
+ return (bg, fg, accent, "notifications")
72
+ if self.severity == "success":
73
+ bg = Color.from_hex("#D8F5E3") if theme.mode == "light" else Color.from_hex("#0F3D22")
74
+ fg = Color.from_hex("#0F5132") if theme.mode == "light" else Color.from_hex("#A7F3C9")
75
+ accent = Color.from_hex("#16A34A")
76
+ return (bg, fg, accent, "check")
77
+ return (c.primary_container, c.on_primary_container, c.primary, "star")
78
+
79
+ def _measure_content(self, constraints: Constraints, theme: Theme) -> Size:
80
+ w = constraints.max_width if constraints.max_width != float("inf") else 460.0
81
+ h = 68.0 if self.message else 48.0
82
+ return Size(w, h)
83
+
84
+ def on_mouse_up(self, event: MouseEvent) -> None:
85
+ was_pressed = self.pressed
86
+ super().on_mouse_up(event)
87
+ if not was_pressed:
88
+ return
89
+ if self.closable and self._close_rect.contains(event.x, event.y):
90
+ self.visible(False)
91
+ if self.on_close is not None:
92
+ self.on_close()
93
+ return
94
+ if self.action_label and self._action_rect.contains(event.x, event.y):
95
+ if self.on_action is not None:
96
+ self.on_action()
97
+
98
+ def _paint_self(self, canvas: skia.Canvas, theme: Theme, now: float) -> None:
99
+ r = self.rect
100
+ bg, fg, accent, icon_name = self._palette(theme)
101
+ bg = resolve_color(self._bg_override, theme, bg) or bg
102
+ fg = resolve_color(self._fg_override, theme, fg) or fg
103
+ rad_spec = self._shape_override if self._shape_override is not None else "medium"
104
+ rrect = make_rrect_spec(r, rad_spec, theme)
105
+
106
+ canvas.drawRRect(rrect, skia.Paint(AntiAlias=True, Color=bg.to_skia()))
107
+ # Left accent bar
108
+ canvas.save()
109
+ canvas.clipRRect(rrect, doAntiAlias=True)
110
+ canvas.drawRect(skia.Rect.MakeXYWH(r.x, r.y, 4.0, r.height), skia.Paint(Color=accent.to_skia()))
111
+ canvas.restore()
112
+
113
+ bc = resolve_color(self._border_color_override, theme, accent.with_alpha(0.35)) or accent
114
+ bw = self._border_width_override if self._border_width_override is not None else 1.0
115
+ canvas.drawRRect(rrect, skia.Paint(AntiAlias=True, Color=bc.to_skia(), Style=skia.Paint.kStroke_Style, StrokeWidth=bw))
116
+
117
+ # Icon badge
118
+ canvas.drawCircle(r.x + 26.0, r.center_y, 12.0, skia.Paint(AntiAlias=True, Color=accent.to_skia()))
119
+ draw_icon(canvas, icon_name, r.x + 26.0, r.center_y, 13.0, Color(255, 255, 255))
120
+
121
+ tfont = font_for_style(theme.font_family, theme.typography.title_small)
122
+ mfont = font_for_style(theme.font_family, theme.typography.body_small)
123
+ tx = r.x + 48.0
124
+ if self.message:
125
+ draw_text_centered_y(canvas, self.title, tx, r.center_y - 10.0, tfont, fg)
126
+ draw_text_centered_y(canvas, self.message, tx, r.center_y + 11.0, mfont, fg.with_alpha(0.85))
127
+ else:
128
+ draw_text_centered_y(canvas, self.title, tx, r.center_y, tfont, fg)
129
+
130
+ right_x = r.right - 12.0
131
+ if self.closable:
132
+ self._close_rect = Rect(right_x - 24.0, r.center_y - 12.0, 24.0, 24.0)
133
+ draw_icon(canvas, "close", self._close_rect.center_x, self._close_rect.center_y, 14.0, fg)
134
+ right_x -= 32.0
135
+ if self.action_label:
136
+ afont = font_for_style(theme.font_family, theme.typography.label_large)
137
+ aw = measure_text(afont, self.action_label) + 20.0
138
+ self._action_rect = Rect(right_x - aw, r.center_y - 15.0, aw, 30.0)
139
+ canvas.drawRRect(make_rrect(self._action_rect, 15.0), skia.Paint(AntiAlias=True, Color=accent.with_alpha(0.16).to_skia()))
140
+ draw_text_centered_y(canvas, self.action_label, self._action_rect.x + 10.0, self._action_rect.center_y, afont, fg)
141
+
142
+
143
+ # ---------------------------------------------------------------------------
144
+ # 2. Avatar & AvatarGroup
145
+ # ---------------------------------------------------------------------------
146
+
147
+
148
+ def _initials(name: str) -> str:
149
+ parts = [p for p in name.strip().split() if p]
150
+ if not parts:
151
+ return "?"
152
+ if len(parts) == 1:
153
+ return parts[0][:2].upper()
154
+ return (parts[0][0] + parts[-1][0]).upper()
155
+
156
+
157
+ def _status_color(status: PresenceStatus) -> Color:
158
+ if status == "online":
159
+ return Color.from_hex("#22C55E")
160
+ if status == "away":
161
+ return Color.from_hex("#F59E0B")
162
+ if status == "busy":
163
+ return Color.from_hex("#EF4444")
164
+ return Color.from_hex("#9CA3AF")
165
+
166
+
167
+ class Avatar(Widget):
168
+ """Circular Material Design 3 Avatar (initials or image) with optional presence status dot."""
169
+
170
+ manages_own_box = True
171
+
172
+ def __init__(
173
+ self,
174
+ name: str = "",
175
+ *,
176
+ image: Any = None,
177
+ diameter: float = 42.0,
178
+ status: PresenceStatus | None = None,
179
+ ) -> None:
180
+ super().__init__()
181
+ self.name = name
182
+ self.image = image
183
+ self.diameter = float(diameter)
184
+ self.status: PresenceStatus | None = status
185
+
186
+ def _measure_content(self, constraints: Constraints, theme: Theme) -> Size:
187
+ return Size(self.diameter, self.diameter)
188
+
189
+ def _paint_self(self, canvas: skia.Canvas, theme: Theme, now: float) -> None:
190
+ c = theme.colors
191
+ r = self.rect
192
+ rad = min(r.width, r.height) * 0.5
193
+ rrect = make_rrect(r, rad)
194
+ img = _resolve_skia_image(self.image) if self.image is not None else None
195
+
196
+ if img is not None:
197
+ canvas.save()
198
+ canvas.clipRRect(rrect, doAntiAlias=True)
199
+ _draw_image_cover(canvas, img, r)
200
+ canvas.restore()
201
+ else:
202
+ bg = resolve_color(self._bg_override, theme, c.primary_container) or c.primary_container
203
+ fg = resolve_color(self._fg_override, theme, c.on_primary_container) or c.on_primary_container
204
+ canvas.drawCircle(r.center_x, r.center_y, rad, skia.Paint(AntiAlias=True, Color=bg.to_skia()))
205
+ txt = _initials(self.name)
206
+ font = get_font(theme.font_family, max(11.0, rad * 0.72), 600)
207
+ tw = measure_text(font, txt)
208
+ draw_text_centered_y(canvas, txt, r.center_x - tw * 0.5, r.center_y, font, fg)
209
+
210
+ if self._border_color_override is not None:
211
+ bc = resolve_color(self._border_color_override, theme)
212
+ if bc is not None:
213
+ bw = self._border_width_override if self._border_width_override is not None else 2.0
214
+ canvas.drawCircle(r.center_x, r.center_y, rad - bw * 0.5, skia.Paint(AntiAlias=True, Color=bc.to_skia(), Style=skia.Paint.kStroke_Style, StrokeWidth=bw))
215
+
216
+ if self.status is not None:
217
+ dot_r = max(4.5, rad * 0.28)
218
+ dx = r.right - dot_r * 0.85
219
+ dy = r.bottom - dot_r * 0.85
220
+ canvas.drawCircle(dx, dy, dot_r + 1.8, skia.Paint(AntiAlias=True, Color=c.surface.to_skia()))
221
+ canvas.drawCircle(dx, dy, dot_r, skia.Paint(AntiAlias=True, Color=_status_color(self.status).to_skia()))
222
+
223
+
224
+ class AvatarGroup(Widget):
225
+ """Overlapping stack of circular Avatars with automatic `+N` overflow badge."""
226
+
227
+ manages_own_box = False
228
+
229
+ def __init__(
230
+ self,
231
+ names: Sequence[str],
232
+ *,
233
+ max_visible: int = 4,
234
+ diameter: float = 38.0,
235
+ ) -> None:
236
+ super().__init__()
237
+ self.names: list[str] = list(names)
238
+ self.max_visible = max(1, int(max_visible))
239
+ self.diameter = float(diameter)
240
+
241
+ def _measure_content(self, constraints: Constraints, theme: Theme) -> Size:
242
+ shown = min(len(self.names), self.max_visible)
243
+ extra = 1 if len(self.names) > self.max_visible else 0
244
+ count = max(1, shown + extra)
245
+ step = self.diameter * 0.70
246
+ w = self.diameter + (count - 1) * step
247
+ return Size(w, self.diameter)
248
+
249
+ def _paint_self(self, canvas: skia.Canvas, theme: Theme, now: float) -> None:
250
+ c = theme.colors
251
+ rad = self.diameter * 0.5
252
+ step = self.diameter * 0.70
253
+ palettes = [
254
+ (c.primary_container, c.on_primary_container),
255
+ (c.secondary_container, c.on_secondary_container),
256
+ (c.tertiary_container, c.on_tertiary_container),
257
+ ]
258
+ font = get_font(theme.font_family, max(10.5, rad * 0.68), 600)
259
+ visible = self.names[: self.max_visible]
260
+ overflow = max(0, len(self.names) - self.max_visible)
261
+
262
+ for i, name in enumerate(visible):
263
+ cx = self.rect.x + rad + i * step
264
+ cy = self.rect.center_y
265
+ bg, fg = palettes[i % len(palettes)]
266
+ canvas.drawCircle(cx, cy, rad + 2.0, skia.Paint(AntiAlias=True, Color=c.surface.to_skia()))
267
+ canvas.drawCircle(cx, cy, rad, skia.Paint(AntiAlias=True, Color=bg.to_skia()))
268
+ txt = _initials(name)
269
+ draw_text_centered_y(canvas, txt, cx - measure_text(font, txt) * 0.5, cy, font, fg)
270
+
271
+ if overflow > 0:
272
+ cx = self.rect.x + rad + len(visible) * step
273
+ cy = self.rect.center_y
274
+ canvas.drawCircle(cx, cy, rad + 2.0, skia.Paint(AntiAlias=True, Color=c.surface.to_skia()))
275
+ canvas.drawCircle(cx, cy, rad, skia.Paint(AntiAlias=True, Color=c.surface_container_highest.to_skia()))
276
+ txt = f"+{overflow}"
277
+ draw_text_centered_y(canvas, txt, cx - measure_text(font, txt) * 0.5, cy, font, c.on_surface_variant)
278
+
279
+
280
+ # ---------------------------------------------------------------------------
281
+ # 3. EmptyState
282
+ # ---------------------------------------------------------------------------
283
+
284
+
285
+ class EmptyState(Widget):
286
+ """Material Design 3 EmptyState placeholder with icon, title, subtitle, and optional CTA."""
287
+
288
+ interactive = True
289
+ manages_own_box = True
290
+
291
+ def __init__(
292
+ self,
293
+ title: str,
294
+ *,
295
+ description: str = "",
296
+ icon: str = "search",
297
+ action_label: str | None = None,
298
+ on_action: Callable[[], None] | None = None,
299
+ ) -> None:
300
+ super().__init__()
301
+ self.title = title
302
+ self.description = description
303
+ self.icon = icon
304
+ self.action_label = action_label
305
+ self.on_action = on_action
306
+ self._btn_rect: Rect = Rect(0, 0, 0, 0)
307
+ self._fill_width = True
308
+
309
+ def _measure_content(self, constraints: Constraints, theme: Theme) -> Size:
310
+ w = constraints.max_width if constraints.max_width != float("inf") else 420.0
311
+ h = 200.0 if self.action_label else 156.0
312
+ return Size(w, h)
313
+
314
+ def on_mouse_up(self, event: MouseEvent) -> None:
315
+ was_pressed = self.pressed
316
+ super().on_mouse_up(event)
317
+ if was_pressed and self.action_label and self._btn_rect.contains(event.x, event.y):
318
+ if self.on_action is not None:
319
+ self.on_action()
320
+
321
+ def _paint_self(self, canvas: skia.Canvas, theme: Theme, now: float) -> None:
322
+ c = theme.colors
323
+ r = self.rect
324
+ rad_spec = self._shape_override if self._shape_override is not None else "large"
325
+ rrect = make_rrect_spec(r, rad_spec, theme)
326
+ bg = resolve_color(self._bg_override, theme, c.surface_container_low) or c.surface_container_low
327
+ canvas.drawRRect(rrect, skia.Paint(AntiAlias=True, Color=bg.to_skia()))
328
+
329
+ cx = r.center_x
330
+ canvas.drawCircle(cx, r.y + 46.0, 26.0, skia.Paint(AntiAlias=True, Color=c.primary_container.to_skia()))
331
+ draw_icon(canvas, self.icon, cx, r.y + 46.0, 24.0, c.on_primary_container)
332
+
333
+ tfont = font_for_style(theme.font_family, theme.typography.title_medium)
334
+ dfont = font_for_style(theme.font_family, theme.typography.body_medium)
335
+ draw_text_centered_y(canvas, self.title, cx - measure_text(tfont, self.title) * 0.5, r.y + 92.0, tfont, c.on_surface)
336
+ if self.description:
337
+ draw_text_centered_y(canvas, self.description, cx - measure_text(dfont, self.description) * 0.5, r.y + 116.0, dfont, c.on_surface_variant)
338
+
339
+ if self.action_label:
340
+ bfont = font_for_style(theme.font_family, theme.typography.label_large)
341
+ bw = measure_text(bfont, self.action_label) + 32.0
342
+ self._btn_rect = Rect(cx - bw * 0.5, r.y + 140.0, bw, 38.0)
343
+ canvas.drawRRect(make_rrect(self._btn_rect, 19.0), skia.Paint(AntiAlias=True, Color=c.primary.to_skia()))
344
+ draw_text_centered_y(canvas, self.action_label, self._btn_rect.x + 16.0, self._btn_rect.center_y, bfont, c.on_primary)
345
+
346
+ bc = resolve_color(self._border_color_override, theme, c.outline_variant) or c.outline_variant
347
+ bw_s = self._border_width_override if self._border_width_override is not None else 1.0
348
+ canvas.drawRRect(rrect, skia.Paint(AntiAlias=True, Color=bc.to_skia(), Style=skia.Paint.kStroke_Style, StrokeWidth=bw_s))
349
+
350
+
351
+ # ---------------------------------------------------------------------------
352
+ # 4. StatusBar (Desktop Bottom Status Bar)
353
+ # ---------------------------------------------------------------------------
354
+
355
+
356
+ class StatusBar(Widget):
357
+ """Compact desktop StatusBar (28dp) with left and right status indicators."""
358
+
359
+ manages_own_box = True
360
+
361
+ def __init__(
362
+ self,
363
+ left: Sequence[str] = (),
364
+ *,
365
+ right: Sequence[str] = (),
366
+ status_dot: PresenceStatus | None = "online",
367
+ ) -> None:
368
+ super().__init__()
369
+ self.left: list[str] = list(left)
370
+ self.right: list[str] = list(right)
371
+ self.status_dot = status_dot
372
+ self._fill_width = True
373
+
374
+ def _measure_content(self, constraints: Constraints, theme: Theme) -> Size:
375
+ w = constraints.max_width if constraints.max_width != float("inf") else 640.0
376
+ return Size(w, 28.0)
377
+
378
+ def _paint_self(self, canvas: skia.Canvas, theme: Theme, now: float) -> None:
379
+ c = theme.colors
380
+ r = self.rect
381
+ bg = resolve_color(self._bg_override, theme, c.surface_container) or c.surface_container
382
+ canvas.drawRect(skia.Rect.MakeXYWH(r.x, r.y, r.width, r.height), skia.Paint(Color=bg.to_skia()))
383
+ canvas.drawLine(r.x, r.y, r.right, r.y, skia.Paint(Color=c.outline_variant.to_skia(), StrokeWidth=1.0))
384
+
385
+ font = font_for_style(theme.font_family, theme.typography.label_small)
386
+ lx = r.x + 12.0
387
+ if self.status_dot is not None:
388
+ canvas.drawCircle(lx + 4.0, r.center_y, 4.0, skia.Paint(AntiAlias=True, Color=_status_color(self.status_dot).to_skia()))
389
+ lx += 14.0
390
+
391
+ for i, item in enumerate(self.left):
392
+ if i > 0:
393
+ draw_text_centered_y(canvas, "·", lx, r.center_y, font, c.outline)
394
+ lx += 12.0
395
+ draw_text_centered_y(canvas, item, lx, r.center_y, font, c.on_surface_variant)
396
+ lx += measure_text(font, item) + 10.0
397
+
398
+ rx = r.right - 12.0
399
+ for i, item in enumerate(reversed(self.right)):
400
+ tw = measure_text(font, item)
401
+ rx -= tw
402
+ draw_text_centered_y(canvas, item, rx, r.center_y, font, c.on_surface_variant)
403
+ rx -= 12.0
404
+ if i < len(self.right) - 1:
405
+ draw_text_centered_y(canvas, "·", rx, r.center_y, font, c.outline)
406
+ rx -= 10.0
407
+ self._paint_custom_border(canvas, theme, 0.0)
@@ -0,0 +1,252 @@
1
+ """Material Design 3 NavigationDrawer (Standard inline or Modal with scrim)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from typing import TYPE_CHECKING, Callable, Sequence
7
+
8
+ import skia
9
+
10
+ from ..core.context import context
11
+ from ..core.draw import (
12
+ draw_elevation_shadow,
13
+ draw_icon,
14
+ draw_text_centered_y,
15
+ font_for_style,
16
+ make_rrect,
17
+ measure_text,
18
+ resolve_color,
19
+ )
20
+ from ..core.events import MouseEvent
21
+ from ..core.geometry import Constraints, Rect, Size
22
+ from ..core.state import State
23
+ from ..core.widget import Widget
24
+ from ..theme import Theme
25
+
26
+ if TYPE_CHECKING:
27
+ from ..core.window import Window
28
+
29
+
30
+ @dataclass
31
+ class DrawerItem:
32
+ """Navigable destination inside a Material Design 3 `NavigationDrawer`."""
33
+
34
+ icon: str
35
+ label: str
36
+ badge: str | int | None = None
37
+
38
+
39
+ class NavigationDrawer(Widget):
40
+ """Official Material Design 3 NavigationDrawer (Standard inline or Modal overlay).
41
+
42
+ `items` may contain `DrawerItem(icon, label, badge)`, `(icon, label)` tuples,
43
+ `"---"` for a divider, or plain strings for section headers.
44
+ """
45
+
46
+ interactive = True
47
+ cursor = "pointer"
48
+
49
+ ITEM_H = 52.0
50
+ HEADER_H = 36.0
51
+ DIVIDER_H = 16.0
52
+
53
+ def __init__(
54
+ self,
55
+ items: Sequence[DrawerItem | tuple[str, str] | tuple[str, str, str | int] | str],
56
+ *,
57
+ title: str | None = None,
58
+ selected: int = 0,
59
+ modal: bool = True,
60
+ width: float = 300.0,
61
+ bind: State[int] | None = None,
62
+ on_change: Callable[[int], None] | None = None,
63
+ window: Window | None = None,
64
+ ) -> None:
65
+ self.modal = modal
66
+ if modal:
67
+ self.auto_attach = False
68
+ super().__init__()
69
+ self._owner_window: Window | None = window or context.current_window or context.last_window
70
+ self.title = title
71
+ self.drawer_width = float(width)
72
+ self._bind = bind
73
+ self._selected = int(bind.value) if bind is not None else int(selected)
74
+ self.on_change = on_change
75
+ self._hover_idx: int = -1
76
+ self._panel_rect = Rect(0.0, 0.0, 0.0, 0.0)
77
+
78
+ # Normalize entries: ("item", dest_index, DrawerItem) | ("section", str) | ("divider", None)
79
+ self._entries: list[tuple[str, int, DrawerItem | str | None]] = []
80
+ dest_idx = 0
81
+ for it in items:
82
+ if isinstance(it, DrawerItem):
83
+ self._entries.append(("item", dest_idx, it))
84
+ dest_idx += 1
85
+ elif isinstance(it, tuple):
86
+ di = DrawerItem(it[0], it[1], it[2] if len(it) > 2 else None)
87
+ self._entries.append(("item", dest_idx, di))
88
+ dest_idx += 1
89
+ elif it == "---":
90
+ self._entries.append(("divider", -1, None))
91
+ else:
92
+ self._entries.append(("section", -1, str(it)))
93
+ self._dest_count = dest_idx
94
+
95
+ if bind is not None:
96
+ bind.subscribe(self._on_bound_change)
97
+
98
+ def _on_bound_change(self, idx: int) -> None:
99
+ i = int(idx)
100
+ if i != self._selected:
101
+ self._selected = i
102
+ self.invalidate()
103
+
104
+ @property
105
+ def selected(self) -> int:
106
+ return self._selected
107
+
108
+ @selected.setter
109
+ def selected(self, idx: int) -> None:
110
+ i = max(0, min(self._dest_count - 1, int(idx))) if self._dest_count else 0
111
+ if i != self._selected:
112
+ self._selected = i
113
+ if self._bind is not None and self._bind.value != i:
114
+ self._bind.value = i
115
+ self.invalidate()
116
+
117
+ def open(self) -> None:
118
+ if not self.modal:
119
+ return
120
+ win = self._owner_window or context.last_window
121
+ if win is not None:
122
+ self._owner_window = win
123
+ win.open_overlay(self)
124
+
125
+ def close(self) -> None:
126
+ if not self.modal:
127
+ return
128
+ win = self._owner_window or self.window
129
+ if win is not None:
130
+ win.close_overlay(self)
131
+
132
+ def _measure_content(self, constraints: Constraints, theme: Theme) -> Size:
133
+ h = constraints.max_height if constraints.max_height != float("inf") else 480.0
134
+ return Size(self.drawer_width, h)
135
+
136
+ def layout(self, rect: Rect, theme: Theme) -> None:
137
+ self.rect = rect
138
+ if self.modal:
139
+ pw = min(self.drawer_width, rect.width - 48.0)
140
+ self._panel_rect = Rect(rect.x, rect.y, pw, rect.height)
141
+ else:
142
+ self._panel_rect = rect
143
+
144
+ def _entry_rects(self) -> list[tuple[str, int, DrawerItem | str | None, Rect]]:
145
+ pr = self._panel_rect
146
+ y = pr.y + (64.0 if self.title else 16.0)
147
+ out = []
148
+ for kind, idx, payload in self._entries:
149
+ h = self.ITEM_H if kind == "item" else (self.HEADER_H if kind == "section" else self.DIVIDER_H)
150
+ out.append((kind, idx, payload, Rect(pr.x + 12.0, y, pr.width - 24.0, h)))
151
+ y += h
152
+ return out
153
+
154
+ def hit_test(self, x: float, y: float) -> Widget | None:
155
+ if not self.rect.contains(x, y):
156
+ return None
157
+ return self
158
+
159
+ def on_mouse_move(self, event: MouseEvent) -> None:
160
+ found = -1
161
+ for kind, idx, _, r in self._entry_rects():
162
+ if kind == "item" and r.contains(event.x, event.y):
163
+ found = idx
164
+ break
165
+ if found != self._hover_idx:
166
+ self._hover_idx = found
167
+ self.invalidate()
168
+
169
+ def on_mouse_leave(self) -> None:
170
+ super().on_mouse_leave()
171
+ self._hover_idx = -1
172
+
173
+ def on_mouse_up(self, event: MouseEvent) -> None:
174
+ was_pressed = self.pressed
175
+ super().on_mouse_up(event)
176
+ if not was_pressed:
177
+ return
178
+ if self.modal and not self._panel_rect.contains(event.x, event.y):
179
+ self.close()
180
+ return
181
+ for kind, idx, _, r in self._entry_rects():
182
+ if kind == "item" and r.contains(event.x, event.y):
183
+ self.selected = idx
184
+ if self.on_change is not None:
185
+ self.on_change(idx)
186
+ if self.modal:
187
+ self.close()
188
+ return
189
+
190
+ def _paint_self(self, canvas: skia.Canvas, theme: Theme, now: float) -> None:
191
+ c = theme.colors
192
+ pr = self._panel_rect
193
+
194
+ if self.modal:
195
+ canvas.drawRect(
196
+ skia.Rect.MakeXYWH(self.rect.x, self.rect.y, self.rect.width, self.rect.height),
197
+ skia.Paint(AntiAlias=True, Color=c.scrim.with_alpha(0.34).to_skia()),
198
+ )
199
+ rrect = skia.RRect()
200
+ rrect.setRectRadii(
201
+ skia.Rect.MakeXYWH(pr.x, pr.y, pr.width, pr.height),
202
+ [(0.0, 0.0), (16.0, 16.0), (16.0, 16.0), (0.0, 0.0)],
203
+ )
204
+ draw_elevation_shadow(canvas, pr, 16.0, 2, c.shadow)
205
+ bg = resolve_color(self._bg_override, theme, c.surface_container_low) or c.surface_container_low
206
+ canvas.drawRRect(rrect, skia.Paint(AntiAlias=True, Color=bg.to_skia()))
207
+ else:
208
+ bg = resolve_color(self._bg_override, theme, c.surface_container_low) or c.surface_container_low
209
+ canvas.drawRect(
210
+ skia.Rect.MakeXYWH(pr.x, pr.y, pr.width, pr.height),
211
+ skia.Paint(AntiAlias=True, Color=bg.to_skia()),
212
+ )
213
+ canvas.drawLine(
214
+ pr.right - 0.5, pr.y, pr.right - 0.5, pr.bottom,
215
+ skia.Paint(AntiAlias=True, Color=c.outline_variant.to_skia(), StrokeWidth=1.0),
216
+ )
217
+
218
+ if self.title:
219
+ tfont = font_for_style(theme.font_family, theme.typography.title_medium)
220
+ draw_text_centered_y(canvas, self.title, pr.x + 28.0, pr.y + 34.0, tfont, c.on_surface_variant)
221
+
222
+ item_font = font_for_style(theme.font_family, theme.typography.label_large)
223
+ sec_font = font_for_style(theme.font_family, theme.typography.title_small)
224
+ badge_font = font_for_style(theme.font_family, theme.typography.label_large)
225
+
226
+ for kind, idx, payload, r in self._entry_rects():
227
+ if kind == "divider":
228
+ canvas.drawLine(
229
+ r.x + 16.0, r.center_y, r.right - 16.0, r.center_y,
230
+ skia.Paint(AntiAlias=True, Color=c.outline_variant.to_skia(), StrokeWidth=1.0),
231
+ )
232
+ elif kind == "section":
233
+ draw_text_centered_y(canvas, str(payload), r.x + 16.0, r.center_y, sec_font, c.on_surface_variant)
234
+ elif kind == "item" and isinstance(payload, DrawerItem):
235
+ is_sel = idx == self._selected
236
+ pill = make_rrect(r, r.height * 0.5)
237
+ if is_sel:
238
+ canvas.drawRRect(pill, skia.Paint(AntiAlias=True, Color=c.secondary_container.to_skia()))
239
+ elif idx == self._hover_idx:
240
+ canvas.drawRRect(
241
+ pill,
242
+ skia.Paint(AntiAlias=True, Color=c.on_surface.with_alpha(theme.state_layers.hover).to_skia()),
243
+ )
244
+
245
+ fg = c.on_secondary_container if is_sel else c.on_surface_variant
246
+ draw_icon(canvas, payload.icon, r.x + 26.0, r.center_y, 20.0, fg)
247
+ draw_text_centered_y(canvas, payload.label, r.x + 52.0, r.center_y, item_font, fg)
248
+
249
+ if payload.badge is not None:
250
+ btxt = str(payload.badge)
251
+ bw = measure_text(badge_font, btxt)
252
+ draw_text_centered_y(canvas, btxt, r.right - 20.0 - bw, r.center_y, badge_font, fg)