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,934 @@
1
+ """Enterprise M3 Visual Controls: CurrencyInput, FilterBar, Wizard, DetailDrawer, NotificationCenter."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from datetime import datetime, timezone
7
+ from typing import Any, Callable, Literal, Sequence
8
+
9
+ import glfw
10
+ import skia
11
+
12
+ from ..core.context import context
13
+ from ..core.draw import (
14
+ draw_elevation_shadow,
15
+ draw_icon,
16
+ draw_text_centered_y,
17
+ font_for_style,
18
+ make_rrect,
19
+ make_rrect_spec,
20
+ measure_text,
21
+ resolve_color,
22
+ )
23
+ from ..core.enterprise_app import I18n
24
+ from ..core.events import CharEvent, KeyEvent, MouseEvent
25
+ from ..core.geometry import Constraints, Rect, Size
26
+ from ..core.state import State
27
+ from ..core.widget import Widget
28
+ from ..theme import Color, Theme
29
+ from .text_field import TextField, TextFieldVariant
30
+
31
+
32
+ # ---------------------------------------------------------------------------
33
+ # 1. CurrencyInput (`ui.currency_input`)
34
+ # ---------------------------------------------------------------------------
35
+
36
+
37
+ def _format_currency_amount(
38
+ amount: float,
39
+ currency: str,
40
+ decimals: int,
41
+ thousands_sep: str,
42
+ decimal_sep: str,
43
+ ) -> str:
44
+ sign = "-" if amount < 0 else ""
45
+ abs_val = abs(amount)
46
+ raw = f"{abs_val:,.{decimals}f}"
47
+ # raw uses "," for thousands and "." for decimal
48
+ formatted = raw.replace(",", "\x00").replace(".", decimal_sep).replace("\x00", thousands_sep)
49
+ pref = f"{currency} " if currency else ""
50
+ return f"{sign}{pref}{formatted}"
51
+
52
+
53
+ def _parse_currency_text(raw: str, decimal_sep: str, thousands_sep: str) -> float | None:
54
+ s = raw.strip()
55
+ if not s:
56
+ return 0.0
57
+ neg = "-" in s
58
+ # Keep only digits and separators
59
+ cleaned = "".join(ch for ch in s if ch.isdigit() or ch in (".", ","))
60
+ if not cleaned:
61
+ return None
62
+ if decimal_sep == "," and "," in cleaned:
63
+ cleaned = cleaned.replace(".", "").replace(",", ".")
64
+ elif decimal_sep == "." and "." in cleaned:
65
+ cleaned = cleaned.replace(",", "")
66
+ else:
67
+ # Only one separator or none: treat thousands_sep as grouping if repeated or followed by 3 digits
68
+ if thousands_sep in cleaned and decimal_sep not in cleaned:
69
+ parts = cleaned.split(thousands_sep)
70
+ if len(parts) > 1 and all(len(p) == 3 for p in parts[1:]):
71
+ cleaned = "".join(parts)
72
+ else:
73
+ cleaned = cleaned.replace(thousands_sep, ".")
74
+ cleaned = cleaned.replace(",", ".")
75
+ try:
76
+ val = float(cleaned)
77
+ return -val if neg else val
78
+ except ValueError:
79
+ return None
80
+
81
+
82
+ class CurrencyInput(TextField):
83
+ """Material Design 3 regional CurrencyInput with live numeric parsing and `.amount` binding."""
84
+
85
+ def __init__(
86
+ self,
87
+ label: str = "Importe",
88
+ *,
89
+ amount: float = 0.0,
90
+ currency: str = "$",
91
+ decimals: int = 2,
92
+ thousands_sep: str = ".",
93
+ decimal_sep: str = ",",
94
+ i18n: I18n | None = None,
95
+ allow_negative: bool = True,
96
+ min_amount: float | None = None,
97
+ max_amount: float | None = None,
98
+ variant: TextFieldVariant = "outlined",
99
+ supporting_text: str | None = None,
100
+ error_text: str | None = None,
101
+ disabled: bool = False,
102
+ bind: State[float] | None = None,
103
+ on_change: Callable[[float], None] | None = None,
104
+ ) -> None:
105
+ if i18n is not None:
106
+ is_en = i18n.locale.lower().startswith("en")
107
+ thousands_sep = "," if is_en else "."
108
+ decimal_sep = "." if is_en else ","
109
+ self.currency = currency
110
+ self.decimals = max(0, int(decimals))
111
+ self.thousands_sep = thousands_sep
112
+ self.decimal_sep = decimal_sep
113
+ self.allow_negative = allow_negative
114
+ self.min_amount = min_amount
115
+ self.max_amount = max_amount
116
+ self._amount_bind = bind
117
+ self._on_amount_change = on_change
118
+
119
+ init_amt = float(bind.value) if bind is not None else float(amount)
120
+ self._amount: float = self._clamp_amount(init_amt)
121
+
122
+ formatted = _format_currency_amount(
123
+ self._amount, self.currency, self.decimals, self.thousands_sep, self.decimal_sep
124
+ )
125
+ super().__init__(
126
+ label,
127
+ value=formatted,
128
+ variant=variant,
129
+ supporting_text=supporting_text,
130
+ error_text=error_text,
131
+ disabled=disabled,
132
+ )
133
+
134
+ if bind is not None:
135
+ bind.subscribe(self._on_bound_amount)
136
+
137
+ def _clamp_amount(self, val: float) -> float:
138
+ if not self.allow_negative and val < 0.0:
139
+ val = 0.0
140
+ if self.min_amount is not None:
141
+ val = max(self.min_amount, val)
142
+ if self.max_amount is not None:
143
+ val = min(self.max_amount, val)
144
+ return round(float(val), self.decimals)
145
+
146
+ def _on_bound_amount(self, v: float) -> None:
147
+ clamped = self._clamp_amount(float(v))
148
+ if abs(clamped - self._amount) > 1e-9:
149
+ self._amount = clamped
150
+ self._sync_display()
151
+
152
+ def _sync_display(self) -> None:
153
+ txt = _format_currency_amount(
154
+ self._amount, self.currency, self.decimals, self.thousands_sep, self.decimal_sep
155
+ )
156
+ self._value = txt
157
+ self._cursor = len(txt)
158
+ self._sel_anchor = None
159
+ self.invalidate()
160
+
161
+ @property
162
+ def amount(self) -> float:
163
+ return self._amount
164
+
165
+ @amount.setter
166
+ def amount(self, val: float) -> None:
167
+ clamped = self._clamp_amount(float(val))
168
+ changed = abs(clamped - self._amount) > 1e-9
169
+ self._amount = clamped
170
+ self._sync_display()
171
+ if self._amount_bind is not None and abs(float(self._amount_bind.value) - clamped) > 1e-9:
172
+ self._amount_bind.value = clamped
173
+ if changed and self._on_amount_change is not None:
174
+ self._on_amount_change(clamped)
175
+
176
+ def _commit_amount(self) -> None:
177
+ parsed = _parse_currency_text(self._value, self.decimal_sep, self.thousands_sep)
178
+ if parsed is not None:
179
+ self.amount = parsed
180
+ else:
181
+ self._sync_display()
182
+
183
+ def on_focus(self) -> None:
184
+ super().on_focus()
185
+ # Show clean unformatted editable number while focused
186
+ raw = f"{self._amount:.{self.decimals}f}".replace(".", self.decimal_sep)
187
+ self._value = raw
188
+ self._cursor = len(raw)
189
+ self._sel_anchor = 0
190
+ self.invalidate()
191
+
192
+ def on_blur(self) -> None:
193
+ self._commit_amount()
194
+ super().on_blur()
195
+
196
+ def on_char(self, event: CharEvent) -> None:
197
+ if self.disabled:
198
+ return
199
+ ch = event.char
200
+ if ch.isdigit() or ch in (".", ",") or (ch == "-" and self.allow_negative):
201
+ super().on_char(event)
202
+ parsed = _parse_currency_text(self._value, self.decimal_sep, self.thousands_sep)
203
+ if parsed is not None:
204
+ clamped = self._clamp_amount(parsed)
205
+ if abs(clamped - self._amount) > 1e-9:
206
+ self._amount = clamped
207
+ if self._amount_bind is not None:
208
+ self._amount_bind.value = clamped
209
+ if self._on_amount_change is not None:
210
+ self._on_amount_change(clamped)
211
+
212
+ def on_key(self, event: KeyEvent) -> None:
213
+ if event.action in (glfw.PRESS, glfw.REPEAT) and event.key == glfw.KEY_ENTER:
214
+ self._commit_amount()
215
+ super().on_key(event)
216
+
217
+
218
+ # ---------------------------------------------------------------------------
219
+ # 2. FilterBar (`ui.filter_bar`)
220
+ # ---------------------------------------------------------------------------
221
+
222
+
223
+ class FilterBar(Widget):
224
+ """Enterprise combined FilterBar with search input, facet selectors, active chips & Clear All."""
225
+
226
+ interactive = True
227
+ focusable = True
228
+ manages_own_box = True
229
+ cursor = "pointer"
230
+
231
+ def __init__(
232
+ self,
233
+ facets: dict[str, Sequence[str]] | None = None,
234
+ *,
235
+ placeholder: str = "Buscar...",
236
+ on_filter: Callable[[dict[str, Any]], None] | None = None,
237
+ ) -> None:
238
+ super().__init__()
239
+ self.facets: dict[str, list[str]] = {
240
+ str(k): [str(v) for v in vals] for k, vals in (facets or {}).items()
241
+ }
242
+ self.placeholder = placeholder
243
+ self.on_filter = on_filter
244
+ self._search: str = ""
245
+ self._selected: dict[str, str] = {}
246
+ self._search_focused: bool = False
247
+ self._fill_width = True
248
+
249
+ self._search_rect = Rect(0.0, 0.0, 0.0, 0.0)
250
+ self._facet_rects: list[tuple[str, Rect]] = []
251
+ self._chip_remove_rects: list[tuple[str, Rect]] = []
252
+ self._clear_rect = Rect(0.0, 0.0, 0.0, 0.0)
253
+
254
+ @property
255
+ def search_text(self) -> str:
256
+ return self._search
257
+
258
+ @property
259
+ def active_filters(self) -> dict[str, Any]:
260
+ out: dict[str, Any] = {}
261
+ if self._search.strip():
262
+ out["search"] = self._search.strip()
263
+ for k, v in self._selected.items():
264
+ if v:
265
+ out[k] = v
266
+ return out
267
+
268
+ def _emit(self) -> None:
269
+ self.invalidate()
270
+ if self.on_filter is not None:
271
+ self.on_filter(self.active_filters)
272
+
273
+ def set_search(self, text: str) -> None:
274
+ s = str(text)
275
+ if s != self._search:
276
+ self._search = s
277
+ self._emit()
278
+
279
+ def set_facet(self, name: str, value: str | None) -> None:
280
+ if not value:
281
+ self._selected.pop(name, None)
282
+ else:
283
+ self._selected[name] = str(value)
284
+ self._emit()
285
+
286
+ def clear_facet(self, name: str) -> None:
287
+ if name == "search":
288
+ self._search = ""
289
+ else:
290
+ self._selected.pop(name, None)
291
+ self._emit()
292
+
293
+ def clear_all(self) -> None:
294
+ if self._search or self._selected:
295
+ self._search = ""
296
+ self._selected.clear()
297
+ self._emit()
298
+
299
+ def apply_to_rows(self, records: Sequence[dict[str, Any]]) -> list[dict[str, Any]]:
300
+ """Filter a `list[dict]` according to active search text and facet selections."""
301
+ q = self._search.strip().lower()
302
+ out: list[dict[str, Any]] = []
303
+ for rec in records:
304
+ ok = True
305
+ for fk, fv in self._selected.items():
306
+ if str(rec.get(fk, "")) != fv:
307
+ ok = False
308
+ break
309
+ if ok and q:
310
+ if not any(q in str(v).lower() for v in rec.values()):
311
+ ok = False
312
+ if ok:
313
+ out.append(rec)
314
+ return out
315
+
316
+ def _measure_content(self, constraints: Constraints, theme: Theme) -> Size:
317
+ w = constraints.max_width if constraints.max_width != float("inf") else 640.0
318
+ has_chips = bool(self.active_filters)
319
+ return Size(w, 86.0 if has_chips else 52.0)
320
+
321
+ def on_mouse_down(self, event: MouseEvent) -> None:
322
+ super().on_mouse_down(event)
323
+ if self._clear_rect.width > 0 and self._clear_rect.contains(event.x, event.y):
324
+ self.clear_all()
325
+ return
326
+ for fk, rr in self._chip_remove_rects:
327
+ if rr.contains(event.x, event.y):
328
+ self.clear_facet(fk)
329
+ return
330
+ for fk, rr in self._facet_rects:
331
+ if rr.contains(event.x, event.y):
332
+ # Cycle through facet options (None -> opt0 -> opt1 -> ... -> None)
333
+ opts = self.facets.get(fk, [])
334
+ if not opts:
335
+ return
336
+ cur = self._selected.get(fk)
337
+ if cur is None:
338
+ self.set_facet(fk, opts[0])
339
+ else:
340
+ idx = opts.index(cur) if cur in opts else -1
341
+ nxt = opts[idx + 1] if 0 <= idx + 1 < len(opts) else None
342
+ self.set_facet(fk, nxt)
343
+ return
344
+ self._search_focused = self._search_rect.contains(event.x, event.y)
345
+ self.invalidate()
346
+
347
+ def on_char(self, event: CharEvent) -> None:
348
+ if self._search_focused and event.char and event.char.isprintable():
349
+ self.set_search(self._search + event.char)
350
+
351
+ def on_key(self, event: KeyEvent) -> None:
352
+ if self._search_focused and event.action in (glfw.PRESS, glfw.REPEAT):
353
+ if event.key == glfw.KEY_BACKSPACE and self._search:
354
+ self.set_search(self._search[:-1])
355
+ elif event.key == glfw.KEY_ESCAPE:
356
+ self._search_focused = False
357
+ self.invalidate()
358
+
359
+ def _paint_self(self, canvas: skia.Canvas, theme: Theme, now: float) -> None:
360
+ c = theme.colors
361
+ r = self.rect
362
+ rad_spec = self._shape_override if self._shape_override is not None else "medium"
363
+ rrect = make_rrect_spec(r, rad_spec, theme)
364
+ bg = resolve_color(self._bg_override, theme, c.surface_container_low) or c.surface_container_low
365
+ canvas.drawRRect(rrect, skia.Paint(AntiAlias=True, Color=bg.to_skia()))
366
+
367
+ bfont = font_for_style(theme.font_family, theme.typography.body_medium)
368
+ lfont = font_for_style(theme.font_family, theme.typography.label_medium)
369
+ sfont = font_for_style(theme.font_family, theme.typography.label_small)
370
+
371
+ # Row 1: Search box + Facet pills
372
+ row1_y = r.y + 8.0
373
+ search_w = min(240.0, max(120.0, r.width * 0.36))
374
+ self._search_rect = Rect(r.x + 10.0, row1_y, search_w, 34.0)
375
+ s_rrect = make_rrect(self._search_rect, 17.0)
376
+ canvas.drawRRect(s_rrect, skia.Paint(AntiAlias=True, Color=c.surface.to_skia()))
377
+ s_bc = c.primary if self._search_focused else c.outline_variant
378
+ canvas.drawRRect(
379
+ s_rrect,
380
+ skia.Paint(AntiAlias=True, Color=s_bc.to_skia(), Style=skia.Paint.kStroke_Style, StrokeWidth=1.5 if self._search_focused else 1.0),
381
+ )
382
+ draw_icon(canvas, "search", self._search_rect.x + 16.0, self._search_rect.center_y, 15.0, c.on_surface_variant)
383
+ disp = self._search if self._search else self.placeholder
384
+ draw_text_centered_y(
385
+ canvas,
386
+ disp,
387
+ self._search_rect.x + 30.0,
388
+ self._search_rect.center_y,
389
+ bfont,
390
+ c.on_surface if self._search else c.on_surface_variant,
391
+ )
392
+
393
+ self._facet_rects = []
394
+ fx = self._search_rect.right + 10.0
395
+ for fname in self.facets:
396
+ cur = self._selected.get(fname)
397
+ label = f"{fname}: {cur}" if cur else f"{fname} ▾"
398
+ pw = measure_text(lfont, label) + 22.0
399
+ if fx + pw > r.right - 10.0:
400
+ break
401
+ fr = Rect(fx, row1_y + 1.0, pw, 32.0)
402
+ self._facet_rects.append((fname, fr))
403
+ fbg = c.secondary_container if cur else c.surface
404
+ ffg = c.on_secondary_container if cur else c.on_surface_variant
405
+ canvas.drawRRect(make_rrect(fr, 8.0), skia.Paint(AntiAlias=True, Color=fbg.to_skia()))
406
+ canvas.drawRRect(
407
+ make_rrect(fr, 8.0),
408
+ skia.Paint(AntiAlias=True, Color=c.outline_variant.to_skia(), Style=skia.Paint.kStroke_Style, StrokeWidth=1.0),
409
+ )
410
+ draw_text_centered_y(canvas, label, fr.x + 11.0, fr.center_y, lfont, ffg)
411
+ fx = fr.right + 8.0
412
+
413
+ # Row 2: Active filter chips + Clear All
414
+ self._chip_remove_rects = []
415
+ self._clear_rect = Rect(0.0, 0.0, 0.0, 0.0)
416
+ active = self.active_filters
417
+ if active:
418
+ cy = row1_y + 42.0
419
+ cx = r.x + 10.0
420
+ for k, v in active.items():
421
+ txt = f"{k}: {v} ×"
422
+ cw = measure_text(sfont, txt) + 18.0
423
+ cr = Rect(cx, cy, cw, 24.0)
424
+ self._chip_remove_rects.append((k, cr))
425
+ canvas.drawRRect(make_rrect(cr, 12.0), skia.Paint(AntiAlias=True, Color=c.primary_container.to_skia()))
426
+ draw_text_centered_y(canvas, txt, cr.x + 9.0, cr.center_y, sfont, c.on_primary_container)
427
+ cx = cr.right + 6.0
428
+
429
+ clr_txt = "Limpiar filtros"
430
+ clw = measure_text(sfont, clr_txt) + 14.0
431
+ self._clear_rect = Rect(max(cx + 4.0, r.right - clw - 10.0), cy, clw, 24.0)
432
+ draw_text_centered_y(canvas, clr_txt, self._clear_rect.x + 7.0, self._clear_rect.center_y, sfont, c.primary)
433
+
434
+ self._paint_custom_border(canvas, theme, "medium")
435
+
436
+
437
+ # ---------------------------------------------------------------------------
438
+ # 3. Wizard (`ui.wizard`)
439
+ # ---------------------------------------------------------------------------
440
+
441
+
442
+ class Wizard(Widget):
443
+ """Multi-step Enterprise Wizard composing Stepper, per-step pages, validation & navigation."""
444
+
445
+ def __init__(
446
+ self,
447
+ *,
448
+ on_finish: Callable[[], None] | None = None,
449
+ on_step_change: Callable[[int], None] | None = None,
450
+ prev_label: str = "Anterior",
451
+ next_label: str = "Siguiente",
452
+ finish_label: str = "Finalizar",
453
+ ) -> None:
454
+ super().__init__()
455
+ from .button import Button
456
+ from .containers import Column, Row
457
+ from .productivity import Stepper
458
+
459
+ self.on_finish = on_finish
460
+ self.on_step_change = on_step_change
461
+ self._prev_label = prev_label
462
+ self._next_label = next_label
463
+ self._finish_label = finish_label
464
+
465
+ self._step_titles: list[str] = []
466
+ self._step_pages: list[Column] = []
467
+ self._step_validators: list[Callable[[], bool] | None] = []
468
+ self._current: int = 0
469
+ self._fill_width = True
470
+
471
+ with context.detached():
472
+ self._root_col = Column(gap=14.0, align="stretch")
473
+ self._root_col._fill_width = True
474
+ self._stepper = Stepper([], current=0, clickable=False)
475
+ self._body_host = Column(gap=8.0, align="stretch")
476
+ self._body_host._fill_width = True
477
+ self._footer = Row(gap=10.0, justify="end", align="center")
478
+ self._footer._fill_width = True
479
+ self._btn_prev = Button(prev_label, variant="outlined", on_click=self.prev)
480
+ self._btn_next = Button(next_label, variant="filled", on_click=self.next)
481
+
482
+ self.add_child(self._root_col)
483
+ self._root_col.add_child(self._stepper)
484
+ self._root_col.add_child(self._body_host)
485
+ self._root_col.add_child(self._footer)
486
+ self._footer.add_child(self._btn_prev)
487
+ self._footer.add_child(self._btn_next)
488
+ self._sync_ui()
489
+
490
+ @property
491
+ def current_step(self) -> int:
492
+ return self._current
493
+
494
+ def step(
495
+ self,
496
+ title: str,
497
+ *,
498
+ validator: Callable[[], bool] | None = None,
499
+ ) -> Widget:
500
+ """Add a step page and return its container for use in a `with wiz.step(...):` block."""
501
+ from .containers import Column
502
+
503
+ with context.detached():
504
+ page = Column(gap=10.0, align="stretch")
505
+ page._fill_width = True
506
+ self._step_titles.append(title)
507
+ self._step_pages.append(page)
508
+ self._step_validators.append(validator)
509
+ self._body_host.add_child(page)
510
+ self._stepper.steps = list(self._step_titles)
511
+ self._sync_ui()
512
+ return page
513
+
514
+ def _sync_ui(self) -> None:
515
+ total = len(self._step_pages)
516
+ for i, page in enumerate(self._step_pages):
517
+ page.visible(i == self._current)
518
+ self._stepper.current = self._current
519
+ self._btn_prev.disabled = self._current <= 0
520
+ self._btn_next.label = self._finish_label if (total > 0 and self._current == total - 1) else self._next_label
521
+ self.invalidate()
522
+
523
+ def validate_current(self) -> bool:
524
+ if not (0 <= self._current < len(self._step_validators)):
525
+ return True
526
+ fn = self._step_validators[self._current]
527
+ if fn is None:
528
+ self._stepper.error_step = None
529
+ return True
530
+ ok = bool(fn())
531
+ self._stepper.error_step = None if ok else self._current
532
+ self.invalidate()
533
+ return ok
534
+
535
+ def next(self) -> bool:
536
+ if not self._step_pages:
537
+ return False
538
+ if not self.validate_current():
539
+ return False
540
+ if self._current < len(self._step_pages) - 1:
541
+ self._current += 1
542
+ self._sync_ui()
543
+ if self.on_step_change is not None:
544
+ self.on_step_change(self._current)
545
+ return True
546
+ if self.on_finish is not None:
547
+ self.on_finish()
548
+ return True
549
+
550
+ def prev(self) -> bool:
551
+ if self._current <= 0:
552
+ return False
553
+ self._stepper.error_step = None
554
+ self._current -= 1
555
+ self._sync_ui()
556
+ if self.on_step_change is not None:
557
+ self.on_step_change(self._current)
558
+ return True
559
+
560
+ def go_to(self, idx: int) -> bool:
561
+ if not (0 <= idx < len(self._step_pages)):
562
+ return False
563
+ self._stepper.error_step = None
564
+ self._current = idx
565
+ self._sync_ui()
566
+ if self.on_step_change is not None:
567
+ self.on_step_change(self._current)
568
+ return True
569
+
570
+ def _measure_content(self, constraints: Constraints, theme: Theme) -> Size:
571
+ return self._root_col.measure(constraints, theme)
572
+
573
+ def _layout_children(self, content_rect: Rect, theme: Theme) -> None:
574
+ self._root_col.layout(content_rect, theme)
575
+
576
+
577
+ # ---------------------------------------------------------------------------
578
+ # 4. DetailDrawer (`ui.detail_drawer`)
579
+ # ---------------------------------------------------------------------------
580
+
581
+
582
+ class DetailDrawer(Widget):
583
+ """Right-docked Material Design 3 Inspector / Edit Drawer overlay with Save/Cancel footer."""
584
+
585
+ interactive = True
586
+ auto_attach = False
587
+ manages_own_box = True
588
+
589
+ HEADER_H = 68.0
590
+ FOOTER_H = 60.0
591
+
592
+ def __init__(
593
+ self,
594
+ title: str = "Detalle",
595
+ *,
596
+ subtitle: str = "",
597
+ width: float = 400.0,
598
+ save_label: str = "Guardar",
599
+ cancel_label: str = "Cancelar",
600
+ on_save: Callable[[], bool | None] | None = None,
601
+ on_close: Callable[[], None] | None = None,
602
+ window: Any = None,
603
+ ) -> None:
604
+ super().__init__()
605
+ self.title = title
606
+ self.subtitle = subtitle
607
+ self.drawer_width = float(width)
608
+ self.save_label = save_label
609
+ self.cancel_label = cancel_label
610
+ self.on_save = on_save
611
+ self.on_close = on_close
612
+ self._owner_window = window or context.current_window or context.last_window
613
+
614
+ self._panel_rect = Rect(0.0, 0.0, 0.0, 0.0)
615
+ self._close_rect = Rect(0.0, 0.0, 0.0, 0.0)
616
+ self._cancel_rect = Rect(0.0, 0.0, 0.0, 0.0)
617
+ self._save_rect = Rect(0.0, 0.0, 0.0, 0.0)
618
+
619
+ def open(self) -> DetailDrawer:
620
+ win = self._owner_window or context.last_window
621
+ if win is not None:
622
+ self._owner_window = win
623
+ win.open_overlay(self)
624
+ return self
625
+
626
+ def close(self) -> None:
627
+ win = self._owner_window or self.window
628
+ if win is not None:
629
+ win.close_overlay(self)
630
+ if self.on_close is not None:
631
+ self.on_close()
632
+
633
+ def trigger_save(self) -> None:
634
+ if self.on_save is not None:
635
+ res = self.on_save()
636
+ if res is False:
637
+ return
638
+ self.close()
639
+
640
+ def layout(self, rect: Rect, theme: Theme) -> None:
641
+ self.rect = rect
642
+ pw = min(self.drawer_width, max(240.0, rect.width - 48.0))
643
+ self._panel_rect = Rect(rect.right - pw, rect.y, pw, rect.height)
644
+ self._close_rect = Rect(self._panel_rect.right - 44.0, self._panel_rect.y + 14.0, 32.0, 32.0)
645
+
646
+ body_rect = Rect(
647
+ self._panel_rect.x + 20.0,
648
+ self._panel_rect.y + self.HEADER_H + 12.0,
649
+ pw - 40.0,
650
+ max(40.0, rect.height - self.HEADER_H - self.FOOTER_H - 24.0),
651
+ )
652
+ y = body_rect.y
653
+ for child in self.children:
654
+ if not child._visible:
655
+ continue
656
+ sz = child.measure(Constraints(0.0, body_rect.width, 0.0, body_rect.height), theme)
657
+ child.layout(Rect(body_rect.x, y, body_rect.width if child._fill_width else sz.width, sz.height), theme)
658
+ y += sz.height + 12.0
659
+
660
+ fy = self._panel_rect.bottom - self.FOOTER_H
661
+ self._save_rect = Rect(self._panel_rect.right - 116.0, fy + 12.0, 96.0, 36.0)
662
+ self._cancel_rect = Rect(self._save_rect.x - 104.0, fy + 12.0, 94.0, 36.0)
663
+
664
+ def hit_test(self, x: float, y: float) -> Widget | None:
665
+ if not self.rect.contains(x, y):
666
+ return None
667
+ for child in reversed(self.children):
668
+ hit = child.hit_test(x, y)
669
+ if hit is not None:
670
+ return hit
671
+ return self
672
+
673
+ def on_mouse_down(self, event: MouseEvent) -> None:
674
+ super().on_mouse_down(event)
675
+ if not self._panel_rect.contains(event.x, event.y):
676
+ self.close()
677
+ return
678
+ if self._close_rect.contains(event.x, event.y) or self._cancel_rect.contains(event.x, event.y):
679
+ self.close()
680
+ return
681
+ if self._save_rect.contains(event.x, event.y):
682
+ self.trigger_save()
683
+
684
+ def on_key(self, event: KeyEvent) -> None:
685
+ if event.action == glfw.PRESS and event.key == glfw.KEY_ESCAPE:
686
+ self.close()
687
+
688
+ def _paint_self(self, canvas: skia.Canvas, theme: Theme, now: float) -> None:
689
+ c = theme.colors
690
+ pr = self._panel_rect
691
+ # Scrim
692
+ canvas.drawRect(
693
+ skia.Rect.MakeXYWH(self.rect.x, self.rect.y, self.rect.width, self.rect.height),
694
+ skia.Paint(Color=c.scrim.with_alpha(0.32).to_skia()),
695
+ )
696
+ # Panel surface + shadow
697
+ draw_elevation_shadow(canvas, pr, 16.0, 3, c.shadow)
698
+ rrect = skia.RRect()
699
+ rrect.setRectRadii(
700
+ skia.Rect.MakeXYWH(pr.x, pr.y, pr.width, pr.height),
701
+ [(16.0, 16.0), (0.0, 0.0), (0.0, 0.0), (16.0, 16.0)],
702
+ )
703
+ bg = resolve_color(self._bg_override, theme, c.surface) or c.surface
704
+ canvas.drawRRect(rrect, skia.Paint(AntiAlias=True, Color=bg.to_skia()))
705
+
706
+ # Header
707
+ tfont = font_for_style(theme.font_family, theme.typography.title_medium)
708
+ sfont = font_for_style(theme.font_family, theme.typography.body_small)
709
+ draw_text_centered_y(canvas, self.title, pr.x + 20.0, pr.y + (26.0 if self.subtitle else 34.0), tfont, c.on_surface)
710
+ if self.subtitle:
711
+ draw_text_centered_y(canvas, self.subtitle, pr.x + 20.0, pr.y + 46.0, sfont, c.on_surface_variant)
712
+ draw_icon(canvas, "close", self._close_rect.center_x, self._close_rect.center_y, 18.0, c.on_surface_variant)
713
+ div_p = skia.Paint(Color=c.outline_variant.to_skia(), StrokeWidth=1.0)
714
+ canvas.drawLine(pr.x, pr.y + self.HEADER_H, pr.right, pr.y + self.HEADER_H, div_p)
715
+
716
+ # Footer
717
+ fy = pr.bottom - self.FOOTER_H
718
+ canvas.drawLine(pr.x, fy, pr.right, fy, div_p)
719
+ bf = font_for_style(theme.font_family, theme.typography.label_large)
720
+
721
+ # Cancel button
722
+ canvas.drawRRect(
723
+ make_rrect(self._cancel_rect, 18.0),
724
+ skia.Paint(AntiAlias=True, Color=c.outline.to_skia(), Style=skia.Paint.kStroke_Style, StrokeWidth=1.0),
725
+ )
726
+ cw = measure_text(bf, self.cancel_label)
727
+ draw_text_centered_y(canvas, self.cancel_label, self._cancel_rect.center_x - cw * 0.5, self._cancel_rect.center_y, bf, c.primary)
728
+
729
+ # Save button
730
+ canvas.drawRRect(make_rrect(self._save_rect, 18.0), skia.Paint(AntiAlias=True, Color=c.primary.to_skia()))
731
+ sw = measure_text(bf, self.save_label)
732
+ draw_text_centered_y(canvas, self.save_label, self._save_rect.center_x - sw * 0.5, self._save_rect.center_y, bf, c.on_primary)
733
+
734
+
735
+ # ---------------------------------------------------------------------------
736
+ # 5. NotificationCenter (`ui.notification_center`)
737
+ # ---------------------------------------------------------------------------
738
+
739
+ NotifSeverity = Literal["info", "success", "warning", "error"]
740
+
741
+
742
+ @dataclass
743
+ class NotificationItem:
744
+ """Single persistent notification entry in `NotificationCenter`."""
745
+
746
+ id: int
747
+ title: str
748
+ message: str = ""
749
+ severity: NotifSeverity = "info"
750
+ timestamp: str = ""
751
+ read: bool = False
752
+
753
+
754
+ class NotificationCenter(Widget):
755
+ """Persistent Material Design 3 Enterprise Notification Center with unread badge & severity filters."""
756
+
757
+ interactive = True
758
+ manages_own_box = True
759
+
760
+ def __init__(
761
+ self,
762
+ *,
763
+ title: str = "Notificaciones",
764
+ max_items: int = 100,
765
+ height: float = 300.0,
766
+ on_select: Callable[[NotificationItem], None] | None = None,
767
+ ) -> None:
768
+ super().__init__()
769
+ self.title = title
770
+ self.max_items = max(1, int(max_items))
771
+ self.panel_height = float(height)
772
+ self.on_select = on_select
773
+ self._items: list[NotificationItem] = []
774
+ self._next_id: int = 1
775
+ self._severity_filter: NotifSeverity | None = None
776
+ self.unread_state: State[int] = State(0)
777
+ self._fill_width = True
778
+
779
+ self._mark_all_rect = Rect(0.0, 0.0, 0.0, 0.0)
780
+ self._item_rects: list[tuple[NotificationItem, Rect]] = []
781
+
782
+ @property
783
+ def items(self) -> list[NotificationItem]:
784
+ if self._severity_filter is None:
785
+ return list(self._items)
786
+ return [it for it in self._items if it.severity == self._severity_filter]
787
+
788
+ @property
789
+ def unread_count(self) -> int:
790
+ return sum(1 for it in self._items if not it.read)
791
+
792
+ def _sync_unread(self) -> None:
793
+ cnt = self.unread_count
794
+ if self.unread_state.value != cnt:
795
+ self.unread_state.value = cnt
796
+ self.invalidate()
797
+
798
+ def push(
799
+ self,
800
+ title: str,
801
+ message: str = "",
802
+ *,
803
+ severity: NotifSeverity = "info",
804
+ ) -> NotificationItem:
805
+ item = NotificationItem(
806
+ id=self._next_id,
807
+ title=str(title),
808
+ message=str(message),
809
+ severity=severity,
810
+ timestamp=datetime.now(timezone.utc).strftime("%H:%M:%S"),
811
+ read=False,
812
+ )
813
+ self._next_id += 1
814
+ self._items.insert(0, item)
815
+ if len(self._items) > self.max_items:
816
+ self._items.pop()
817
+ self._sync_unread()
818
+ return item
819
+
820
+ def mark_read(self, item_id: int) -> bool:
821
+ for it in self._items:
822
+ if it.id == item_id:
823
+ it.read = True
824
+ self._sync_unread()
825
+ return True
826
+ return False
827
+
828
+ def mark_all_read(self) -> None:
829
+ for it in self._items:
830
+ it.read = True
831
+ self._sync_unread()
832
+
833
+ def set_filter(self, severity: NotifSeverity | None) -> None:
834
+ self._severity_filter = severity
835
+ self.invalidate()
836
+
837
+ def clear(self) -> None:
838
+ self._items.clear()
839
+ self._sync_unread()
840
+
841
+ def _measure_content(self, constraints: Constraints, theme: Theme) -> Size:
842
+ w = constraints.max_width if constraints.max_width != float("inf") else 380.0
843
+ return Size(w, self.panel_height)
844
+
845
+ def on_mouse_down(self, event: MouseEvent) -> None:
846
+ super().on_mouse_down(event)
847
+ if self._mark_all_rect.width > 0 and self._mark_all_rect.contains(event.x, event.y):
848
+ self.mark_all_read()
849
+ return
850
+ for it, rr in self._item_rects:
851
+ if rr.contains(event.x, event.y):
852
+ it.read = True
853
+ self._sync_unread()
854
+ if self.on_select is not None:
855
+ self.on_select(it)
856
+ return
857
+
858
+ def _sev_color(self, sev: NotifSeverity, theme: Theme) -> Color:
859
+ if sev == "success":
860
+ return Color.from_hex("#16A34A")
861
+ if sev == "warning":
862
+ return Color.from_hex("#D97706")
863
+ if sev == "error":
864
+ return theme.colors.error
865
+ return theme.colors.primary
866
+
867
+ def _paint_self(self, canvas: skia.Canvas, theme: Theme, now: float) -> None:
868
+ c = theme.colors
869
+ r = self.rect
870
+ rad_spec = self._shape_override if self._shape_override is not None else "medium"
871
+ rrect = make_rrect_spec(r, rad_spec, theme)
872
+ bg = resolve_color(self._bg_override, theme, c.surface) or c.surface
873
+
874
+ canvas.save()
875
+ canvas.clipRRect(rrect, doAntiAlias=True)
876
+ canvas.drawRRect(rrect, skia.Paint(AntiAlias=True, Color=bg.to_skia()))
877
+
878
+ tfont = font_for_style(theme.font_family, theme.typography.title_small)
879
+ bfont = font_for_style(theme.font_family, theme.typography.body_small)
880
+ sfont = font_for_style(theme.font_family, theme.typography.label_small)
881
+
882
+ # Header
883
+ hdr_h = 44.0
884
+ canvas.drawRect(skia.Rect.MakeXYWH(r.x, r.y, r.width, hdr_h), skia.Paint(Color=c.surface_container_low.to_skia()))
885
+ draw_text_centered_y(canvas, self.title, r.x + 14.0, r.y + hdr_h * 0.5, tfont, c.on_surface)
886
+ unread = self.unread_count
887
+ if unread > 0:
888
+ tw = measure_text(tfont, self.title)
889
+ bt = str(unread)
890
+ bw = max(20.0, measure_text(sfont, bt) + 12.0)
891
+ br = Rect(r.x + 22.0 + tw, r.y + hdr_h * 0.5 - 9.0, bw, 18.0)
892
+ canvas.drawRRect(make_rrect(br, 9.0), skia.Paint(AntiAlias=True, Color=c.error.to_skia()))
893
+ draw_text_centered_y(canvas, bt, br.center_x - measure_text(sfont, bt) * 0.5, br.center_y, sfont, c.on_error)
894
+
895
+ ma_txt = "Marcar leído"
896
+ maw = measure_text(sfont, ma_txt) + 12.0
897
+ self._mark_all_rect = Rect(r.right - maw - 10.0, r.y + 10.0, maw, 24.0)
898
+ draw_text_centered_y(canvas, ma_txt, self._mark_all_rect.x + 6.0, self._mark_all_rect.center_y, sfont, c.primary)
899
+
900
+ div_p = skia.Paint(Color=c.outline_variant.to_skia(), StrokeWidth=1.0)
901
+ canvas.drawLine(r.x, r.y + hdr_h, r.right, r.y + hdr_h, div_p)
902
+
903
+ # Notification list
904
+ self._item_rects = []
905
+ vis = self.items
906
+ if not vis:
907
+ msg = "Sin notificaciones pendientes"
908
+ mw = measure_text(bfont, msg)
909
+ draw_text_centered_y(canvas, msg, r.center_x - mw * 0.5, r.y + hdr_h + (r.height - hdr_h) * 0.5, bfont, c.on_surface_variant)
910
+ else:
911
+ y = r.y + hdr_h
912
+ row_h = 54.0
913
+ for it in vis:
914
+ if y + row_h > r.bottom + 2.0:
915
+ break
916
+ ir = Rect(r.x, y, r.width, row_h)
917
+ self._item_rects.append((it, ir))
918
+ if not it.read:
919
+ canvas.drawRect(
920
+ skia.Rect.MakeXYWH(ir.x, ir.y, ir.width, ir.height),
921
+ skia.Paint(Color=c.primary_container.with_alpha(0.28).to_skia()),
922
+ )
923
+ sc = self._sev_color(it.severity, theme)
924
+ canvas.drawCircle(ir.x + 16.0, ir.center_y, 4.5, skia.Paint(AntiAlias=True, Color=sc.to_skia()))
925
+ draw_text_centered_y(canvas, it.title, ir.x + 30.0, ir.y + 18.0, tfont, c.on_surface)
926
+ if it.message:
927
+ draw_text_centered_y(canvas, it.message, ir.x + 30.0, ir.y + 36.0, bfont, c.on_surface_variant)
928
+ tsw = measure_text(sfont, it.timestamp)
929
+ draw_text_centered_y(canvas, it.timestamp, ir.right - tsw - 12.0, ir.y + 18.0, sfont, c.on_surface_variant)
930
+ canvas.drawLine(ir.x, ir.bottom, ir.right, ir.bottom, div_p)
931
+ y += row_h
932
+
933
+ canvas.restore()
934
+ self._paint_custom_border(canvas, theme, "medium")