flet-stacked 1.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,17 @@
1
+ from .stacked import (
2
+ Direction,
3
+ GuardCallback,
4
+ RouteChangeCallback,
5
+ RouteChangeEvent,
6
+ RouteSource,
7
+ Stacked,
8
+ )
9
+
10
+ __all__ = [
11
+ "Stacked",
12
+ "RouteChangeEvent",
13
+ "RouteSource",
14
+ "RouteChangeCallback",
15
+ "GuardCallback",
16
+ "Direction",
17
+ ]
@@ -0,0 +1,549 @@
1
+ #!/usr/bin/python3
2
+ # -*- coding: utf-8 -*-
3
+
4
+ from __future__ import annotations
5
+
6
+ import asyncio
7
+ import inspect
8
+ from dataclasses import dataclass, field
9
+ from typing import Any, Awaitable, Callable, Literal, Optional, Union
10
+
11
+ import flet as ft
12
+
13
+ RouteSource = Union[ft.Control, Callable[..., ft.Control]]
14
+ Direction = Literal["initial", "forward", "backward", "replace"]
15
+ RouteChangeCallback = Callable[["RouteChangeEvent"], Union[None, Awaitable[None]]]
16
+ GuardCallback = Callable[[str, str], Union[bool, Awaitable[bool]]]
17
+
18
+
19
+ @dataclass
20
+ class RouteChangeEvent:
21
+ from_route: Optional[str]
22
+ to_route: str
23
+ direction: Direction
24
+ source: str
25
+ params: dict[str, Any] = field(default_factory=dict)
26
+ previous_index: Optional[int] = None
27
+ current_index: Optional[int] = None
28
+
29
+ def __str__(self) -> str:
30
+ arrow = {
31
+ "initial": "·",
32
+ "forward": "→",
33
+ "backward": "←",
34
+ "replace": "↺",
35
+ }[self.direction]
36
+ src = self.from_route or "(none)"
37
+ return f"{src} {arrow} {self.to_route} [{self.source}]"
38
+
39
+
40
+ class Stacked(ft.AnimatedSwitcher):
41
+ def __init__(
42
+ self,
43
+ routes: dict[str, RouteSource],
44
+ index: Union[str, int] = 0,
45
+ *,
46
+ on_route_change: Optional[RouteChangeCallback] = None,
47
+ on_before_leave: Optional[GuardCallback] = None,
48
+ max_history: int = 50,
49
+ cache_lazy_routes: bool = True,
50
+ forward_transition: Optional[ft.AnimatedSwitcherTransition] = None,
51
+ backward_transition: Optional[ft.AnimatedSwitcherTransition] = None,
52
+ **kwargs: Any,
53
+ ) -> None:
54
+ if not routes:
55
+ raise ValueError("Stacked requires at least one route.")
56
+
57
+ self._routes: dict[str, RouteSource] = dict(routes)
58
+ self._resolved: dict[str, ft.Control] = {}
59
+ self._history: list[str] = []
60
+ self._forward_stack: list[str] = []
61
+ self._max_history = max(0, int(max_history))
62
+ self._cache_lazy_routes = bool(cache_lazy_routes)
63
+ self._on_route_change = on_route_change
64
+ self._on_before_leave = on_before_leave
65
+ self._forward_transition = forward_transition
66
+ self._backward_transition = backward_transition
67
+
68
+ self._index: str = self._parse_route(index)
69
+ if self._index not in self._routes:
70
+ raise KeyError(
71
+ f"Initial route {self._index!r} is not registered. "
72
+ f"Available routes: {list(self._routes)}"
73
+ )
74
+
75
+ kwargs.setdefault("transition", ft.AnimatedSwitcherTransition.FADE)
76
+ kwargs.setdefault("duration", 150)
77
+ kwargs.setdefault("reverse_duration", 50)
78
+ kwargs.setdefault("switch_in_curve", ft.AnimationCurve.LINEAR)
79
+ kwargs.setdefault("switch_out_curve", ft.AnimationCurve.EASE_IN_CUBIC)
80
+ kwargs.pop("content", None)
81
+
82
+ initial = self._resolve(self._index, {})
83
+ super().__init__(initial, **kwargs)
84
+ self._default_transition = self.transition
85
+
86
+ def _parse_route(self, route: Union[str, int]) -> str:
87
+ if isinstance(route, bool):
88
+ raise TypeError(f"Route must be str or int, got bool ({route!r}).")
89
+ if isinstance(route, int):
90
+ keys = tuple(self._routes.keys())
91
+ try:
92
+ return keys[route]
93
+ except IndexError:
94
+ raise KeyError(
95
+ f"Route index {route} out of range "
96
+ f"(valid: -{len(keys)}..{len(keys) - 1})."
97
+ ) from None
98
+ if isinstance(route, str):
99
+ return route
100
+ raise TypeError(f"Route must be str or int, got {type(route).__name__}.")
101
+
102
+ def _resolve(
103
+ self, key: str, params: dict[str, Any], *, fresh: bool = False
104
+ ) -> ft.Control:
105
+ source = self._routes[key]
106
+ if isinstance(source, ft.Control):
107
+ return source
108
+ if not callable(source):
109
+ raise TypeError(
110
+ f"Route {key!r} must be an ft.Control or a callable returning one, "
111
+ f"got {type(source).__name__}."
112
+ )
113
+ if not fresh and self._cache_lazy_routes and key in self._resolved:
114
+ return self._resolved[key]
115
+ ctrl = source(**params) if params else source()
116
+ if not isinstance(ctrl, ft.Control):
117
+ raise TypeError(
118
+ f"Route factory for {key!r} returned {type(ctrl).__name__}, "
119
+ "expected an ft.Control."
120
+ )
121
+ if self._cache_lazy_routes:
122
+ self._resolved[key] = ctrl
123
+ return ctrl
124
+
125
+ def _index_of(self, key: Optional[str]) -> Optional[int]:
126
+ if key is None:
127
+ return None
128
+ try:
129
+ return tuple(self._routes.keys()).index(key)
130
+ except ValueError:
131
+ return None
132
+
133
+ def _push_history(self, route: str) -> None:
134
+ if self._max_history <= 0:
135
+ return
136
+ self._history.append(route)
137
+ if len(self._history) > self._max_history:
138
+ del self._history[0]
139
+
140
+ def _safe_update(self) -> None:
141
+ try:
142
+ self.update()
143
+ except AssertionError:
144
+ pass
145
+
146
+ def _infer_direction(
147
+ self, previous: Optional[str], target: str, source: str
148
+ ) -> Direction:
149
+ if source in ("go_next", "go_forward"):
150
+ return "forward"
151
+ if source in ("go_prev", "go_back"):
152
+ return "backward"
153
+ if previous is None:
154
+ return "initial"
155
+ keys = tuple(self._routes.keys())
156
+ try:
157
+ pi, ti = keys.index(previous), keys.index(target)
158
+ except ValueError:
159
+ return "replace"
160
+ if pi == ti:
161
+ return "replace"
162
+ return "forward" if ti > pi else "backward"
163
+
164
+ def _switch_prepare(
165
+ self,
166
+ route: Union[str, int],
167
+ direction: Optional[Direction],
168
+ source: str,
169
+ ) -> tuple[str, Optional[str], Direction]:
170
+ target = self._parse_route(route)
171
+ if target not in self._routes:
172
+ raise KeyError(
173
+ f"The route {route!r} is not registered yet. "
174
+ f"Available routes: {list(self._routes)}"
175
+ )
176
+ previous = self._index
177
+ if direction is None:
178
+ direction = self._infer_direction(previous, target, source)
179
+ return target, previous, direction
180
+
181
+ def _switch_commit(
182
+ self,
183
+ target: str,
184
+ previous: Optional[str],
185
+ direction: Direction,
186
+ params: dict[str, Any],
187
+ source: str,
188
+ record_history: bool,
189
+ force: bool,
190
+ ) -> tuple[tuple[str, ft.Control], Optional[RouteChangeEvent]]:
191
+ if target == previous and not force:
192
+ return (target, self.content), None
193
+
194
+ if record_history and previous is not None and target != previous:
195
+ self._push_history(previous)
196
+ self._forward_stack.clear()
197
+
198
+ if direction == "forward" and self._forward_transition is not None:
199
+ self.transition = self._forward_transition
200
+ elif direction == "backward" and self._backward_transition is not None:
201
+ self.transition = self._backward_transition
202
+ elif self._default_transition is not None:
203
+ self.transition = self._default_transition
204
+
205
+ self._index = target
206
+ ctrl = self._resolve(target, params, fresh=force)
207
+ self.content = ctrl
208
+ self._safe_update()
209
+
210
+ event = RouteChangeEvent(
211
+ from_route=previous,
212
+ to_route=target,
213
+ direction=direction,
214
+ source=source,
215
+ params=params,
216
+ previous_index=self._index_of(previous),
217
+ current_index=self._index_of(target),
218
+ )
219
+ return (target, ctrl), event
220
+
221
+ def _emit_change_sync(self, event: RouteChangeEvent) -> None:
222
+ cb = self._on_route_change
223
+ if cb is None:
224
+ return
225
+ result = cb(event)
226
+ if inspect.isawaitable(result):
227
+ try:
228
+ asyncio.ensure_future(result)
229
+ except RuntimeError:
230
+ close = getattr(result, "close", None)
231
+ if close:
232
+ close()
233
+
234
+ def switch(
235
+ self,
236
+ route: Union[str, int] = 0,
237
+ *,
238
+ params: Optional[dict[str, Any]] = None,
239
+ source: str = "switch",
240
+ direction: Optional[Direction] = None,
241
+ record_history: bool = True,
242
+ force: bool = False,
243
+ ) -> tuple[str, ft.Control]:
244
+ target, previous, direction = self._switch_prepare(route, direction, source)
245
+
246
+ if (
247
+ self._on_before_leave is not None
248
+ and previous is not None
249
+ and target != previous
250
+ ):
251
+ allowed = self._on_before_leave(previous, target)
252
+ if inspect.isawaitable(allowed):
253
+ close = getattr(allowed, "close", None)
254
+ if close:
255
+ close()
256
+ raise RuntimeError(
257
+ "Async on_before_leave guards are not supported by the sync "
258
+ "switch(); use switch_async() or make the guard synchronous."
259
+ )
260
+ if allowed is False:
261
+ return (previous, self.content)
262
+
263
+ result, event = self._switch_commit(
264
+ target, previous, direction, params or {}, source, record_history, force
265
+ )
266
+ if event is not None:
267
+ self._emit_change_sync(event)
268
+ return result
269
+
270
+ def go(self, route: Union[str, int] = 0, **kwargs: Any) -> tuple[str, ft.Control]:
271
+ kwargs.setdefault("source", "go")
272
+ return self.switch(route, **kwargs)
273
+
274
+ def go_next(self, **kwargs: Any) -> Optional[tuple[str, ft.Control]]:
275
+ keys = tuple(self._routes.keys())
276
+ cur = keys.index(self._index)
277
+ if cur < len(keys) - 1:
278
+ kwargs.setdefault("source", "go_next")
279
+ kwargs.setdefault("direction", "forward")
280
+ return self.switch(keys[cur + 1], **kwargs)
281
+ return None
282
+
283
+ def go_prev(self, **kwargs: Any) -> Optional[tuple[str, ft.Control]]:
284
+ keys = tuple(self._routes.keys())
285
+ cur = keys.index(self._index)
286
+ if cur > 0:
287
+ kwargs.setdefault("source", "go_prev")
288
+ kwargs.setdefault("direction", "backward")
289
+ return self.switch(keys[cur - 1], **kwargs)
290
+ return None
291
+
292
+ def go_back(self, **kwargs: Any) -> Optional[tuple[str, ft.Control]]:
293
+ if not self._history:
294
+ return None
295
+ target = self._history.pop()
296
+ self._forward_stack.append(self._index)
297
+ kwargs.setdefault("source", "go_back")
298
+ kwargs.setdefault("direction", "backward")
299
+ kwargs["record_history"] = False
300
+ return self.switch(target, **kwargs)
301
+
302
+ def go_forward(self, **kwargs: Any) -> Optional[tuple[str, ft.Control]]:
303
+ if not self._forward_stack:
304
+ return None
305
+ target = self._forward_stack.pop()
306
+ self._push_history(self._index)
307
+ kwargs.setdefault("source", "go_forward")
308
+ kwargs.setdefault("direction", "forward")
309
+ kwargs["record_history"] = False
310
+ return self.switch(target, **kwargs)
311
+
312
+ async def switch_async(
313
+ self,
314
+ route: Union[str, int] = 0,
315
+ *,
316
+ params: Optional[dict[str, Any]] = None,
317
+ source: str = "switch",
318
+ direction: Optional[Direction] = None,
319
+ record_history: bool = True,
320
+ force: bool = False,
321
+ ) -> tuple[str, ft.Control]:
322
+ target, previous, direction = self._switch_prepare(route, direction, source)
323
+
324
+ if (
325
+ self._on_before_leave is not None
326
+ and previous is not None
327
+ and target != previous
328
+ ):
329
+ allowed = self._on_before_leave(previous, target)
330
+ if inspect.isawaitable(allowed):
331
+ allowed = await allowed
332
+ if allowed is False:
333
+ return (previous, self.content)
334
+
335
+ result, event = self._switch_commit(
336
+ target, previous, direction, params or {}, source, record_history, force
337
+ )
338
+ if event is not None and self._on_route_change is not None:
339
+ cb_result = self._on_route_change(event)
340
+ if inspect.isawaitable(cb_result):
341
+ await cb_result
342
+ return result
343
+
344
+ async def go_async(
345
+ self, route: Union[str, int] = 0, **kwargs: Any
346
+ ) -> tuple[str, ft.Control]:
347
+ kwargs.setdefault("source", "go")
348
+ return await self.switch_async(route, **kwargs)
349
+
350
+ async def go_next_async(self, **kwargs: Any) -> Optional[tuple[str, ft.Control]]:
351
+ keys = tuple(self._routes.keys())
352
+ cur = keys.index(self._index)
353
+ if cur < len(keys) - 1:
354
+ kwargs.setdefault("source", "go_next")
355
+ kwargs.setdefault("direction", "forward")
356
+ return await self.switch_async(keys[cur + 1], **kwargs)
357
+ return None
358
+
359
+ async def go_prev_async(self, **kwargs: Any) -> Optional[tuple[str, ft.Control]]:
360
+ keys = tuple(self._routes.keys())
361
+ cur = keys.index(self._index)
362
+ if cur > 0:
363
+ kwargs.setdefault("source", "go_prev")
364
+ kwargs.setdefault("direction", "backward")
365
+ return await self.switch_async(keys[cur - 1], **kwargs)
366
+ return None
367
+
368
+ async def go_back_async(self, **kwargs: Any) -> Optional[tuple[str, ft.Control]]:
369
+ if not self._history:
370
+ return None
371
+ target = self._history.pop()
372
+ self._forward_stack.append(self._index)
373
+ kwargs.setdefault("source", "go_back")
374
+ kwargs.setdefault("direction", "backward")
375
+ kwargs["record_history"] = False
376
+ return await self.switch_async(target, **kwargs)
377
+
378
+ async def go_forward_async(self, **kwargs: Any) -> Optional[tuple[str, ft.Control]]:
379
+ if not self._forward_stack:
380
+ return None
381
+ target = self._forward_stack.pop()
382
+ self._push_history(self._index)
383
+ kwargs.setdefault("source", "go_forward")
384
+ kwargs.setdefault("direction", "forward")
385
+ kwargs["record_history"] = False
386
+ return await self.switch_async(target, **kwargs)
387
+
388
+ def current_route(self) -> str:
389
+ return self._index
390
+
391
+ def current_index(self) -> int:
392
+ return tuple(self._routes.keys()).index(self._index)
393
+
394
+ def current_control(self) -> ft.Control:
395
+ return self.content
396
+
397
+ def history(self) -> tuple[str, ...]:
398
+ return tuple(self._history)
399
+
400
+ def forward_history(self) -> tuple[str, ...]:
401
+ return tuple(self._forward_stack)
402
+
403
+ def can_go_back(self) -> bool:
404
+ return bool(self._history)
405
+
406
+ def can_go_forward(self) -> bool:
407
+ return bool(self._forward_stack)
408
+
409
+ def can_go_next(self) -> bool:
410
+ return self.current_index() < len(self._routes) - 1
411
+
412
+ def can_go_prev(self) -> bool:
413
+ return self.current_index() > 0
414
+
415
+ def get_routes(self) -> dict[str, RouteSource]:
416
+ return dict(self._routes)
417
+
418
+ def get_route_keys(self) -> tuple[str, ...]:
419
+ return tuple(self._routes.keys())
420
+
421
+ def has_route(self, route: Union[str, int]) -> bool:
422
+ try:
423
+ return self._parse_route(route) in self._routes
424
+ except (KeyError, TypeError):
425
+ return False
426
+
427
+ def get_route(
428
+ self,
429
+ route: Union[str, int],
430
+ default: Optional[RouteSource] = None,
431
+ ) -> Optional[RouteSource]:
432
+ try:
433
+ key = self._parse_route(route)
434
+ except (KeyError, TypeError):
435
+ return default
436
+ return self._routes.get(key, default)
437
+
438
+ def add_route(
439
+ self,
440
+ key: str,
441
+ source: RouteSource,
442
+ *,
443
+ position: Optional[int] = None,
444
+ switch_to: bool = False,
445
+ **switch_kwargs: Any,
446
+ ) -> Optional[tuple[str, ft.Control]]:
447
+ if key in self._routes:
448
+ raise KeyError(f"Route {key!r} already exists.")
449
+ items = list(self._routes.items())
450
+ if position is None:
451
+ items.append((key, source))
452
+ else:
453
+ items.insert(position, (key, source))
454
+ self._routes = dict(items)
455
+ if switch_to:
456
+ switch_kwargs.setdefault("source", "add_route")
457
+ return self.switch(key, **switch_kwargs)
458
+ return None
459
+
460
+ def remove_route(
461
+ self,
462
+ key: str,
463
+ *,
464
+ fallback: Optional[Union[str, int]] = None,
465
+ **switch_kwargs: Any,
466
+ ) -> Optional[tuple[str, ft.Control]]:
467
+ if key not in self._routes:
468
+ raise KeyError(f"Route {key!r} does not exist.")
469
+ if len(self._routes) == 1:
470
+ raise ValueError("Cannot remove the last remaining route.")
471
+
472
+ was_current = key == self._index
473
+ del self._routes[key]
474
+ self._resolved.pop(key, None)
475
+ self._history = [r for r in self._history if r != key]
476
+ self._forward_stack = [r for r in self._forward_stack if r != key]
477
+
478
+ if not was_current:
479
+ return None
480
+
481
+ target = (
482
+ self._parse_route(fallback)
483
+ if fallback is not None
484
+ else next(iter(self._routes))
485
+ )
486
+ if target not in self._routes:
487
+ raise KeyError(f"Fallback route {fallback!r} is not registered.")
488
+ switch_kwargs.setdefault("source", "remove_route")
489
+ return self.switch(target, force=True, **switch_kwargs)
490
+
491
+ def rename_route(self, old: str, new: str) -> None:
492
+ if old not in self._routes:
493
+ raise KeyError(f"Route {old!r} does not exist.")
494
+ if new in self._routes:
495
+ raise KeyError(f"Route {new!r} already exists.")
496
+ self._routes = {(new if k == old else k): v for k, v in self._routes.items()}
497
+ if old in self._resolved:
498
+ self._resolved[new] = self._resolved.pop(old)
499
+ if self._index == old:
500
+ self._index = new
501
+ self._history = [new if r == old else r for r in self._history]
502
+ self._forward_stack = [new if r == old else r for r in self._forward_stack]
503
+
504
+ def set_routes(
505
+ self,
506
+ routes: dict[str, RouteSource],
507
+ *,
508
+ fallback: Optional[Union[str, int]] = None,
509
+ **switch_kwargs: Any,
510
+ ) -> Optional[tuple[str, ft.Control]]:
511
+ if not routes:
512
+ raise ValueError("Stacked requires at least one route.")
513
+ self._routes = dict(routes)
514
+ self._resolved = {k: v for k, v in self._resolved.items() if k in self._routes}
515
+ self._history = [r for r in self._history if r in self._routes]
516
+ self._forward_stack = [r for r in self._forward_stack if r in self._routes]
517
+ if self._index in self._routes:
518
+ return None
519
+ target = (
520
+ self._parse_route(fallback)
521
+ if fallback is not None
522
+ else next(iter(self._routes))
523
+ )
524
+ if target not in self._routes:
525
+ raise KeyError(f"Fallback route {fallback!r} is not registered.")
526
+ switch_kwargs.setdefault("source", "set_routes")
527
+ return self.switch(target, force=True, **switch_kwargs)
528
+
529
+ def clear_history(self) -> None:
530
+ self._history.clear()
531
+ self._forward_stack.clear()
532
+
533
+ def refresh_current(self) -> ft.Control:
534
+ ctrl = self._resolve(self._index, {}, fresh=True)
535
+ self.content = ctrl
536
+ self._safe_update()
537
+ return ctrl
538
+
539
+ def __len__(self) -> int:
540
+ return len(self._routes)
541
+
542
+ def __contains__(self, route: object) -> bool:
543
+ return self.has_route(route) # type: ignore[arg-type]
544
+
545
+ def __iter__(self):
546
+ return iter(self._routes)
547
+
548
+ def __repr__(self) -> str:
549
+ return f"Stacked(current={self._index!r}, routes={list(self._routes)!r})"
@@ -0,0 +1,293 @@
1
+ Metadata-Version: 2.4
2
+ Name: flet-stacked
3
+ Version: 1.2.0
4
+ Summary: a custom Flet control for managing multiple pages with smooth animations.
5
+ Author-email: Osama Mohammed <osamalzabidi@gmail.com>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/osamalzabidi/flet-3d
8
+ Project-URL: Repository, https://github.com/osamalzabidi/flet-3d
9
+ Project-URL: Issues, https://github.com/osamalzabidi/flet-3d/issues
10
+ Keywords: flet,toolkit,tools,route,pages,navigation
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Classifier: Programming Language :: Python :: 3.14
17
+ Classifier: Topic :: Multimedia :: Graphics :: 3D Rendering
18
+ Requires-Python: >=3.12
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Requires-Dist: flet>=1.1
22
+ Requires-Dist: numpy>=1.26.0
23
+ Dynamic: license-file
24
+
25
+ # Flet Stacked v2.0.0
26
+
27
+ `Stacked` is a custom Flet control for managing multiple routes with smooth, animated transitions. Navigate by key or index, walk route order (`go_next`/`go_prev`), or use browser-style history (`go_back`/`go_forward`). Routes can be plain controls or lazy factories, navigation can be vetoed by async guards, and transitions can differ by direction — all backed by `ft.AnimatedSwitcher`.
28
+
29
+ ## Features
30
+
31
+ - **Smooth transitions** — every switch is animated by `ft.AnimatedSwitcher`; duration, curve and transition type are fully customizable per instance.
32
+ - **Direction-aware animation** — use one transition for forward navigation (`SCALE`, `SLIDE`, …) and another for going back (`FADE`, …); `Stacked` picks the right one automatically.
33
+ - **Flexible navigation** — switch by key or index, walk route order with `go_next` / `go_prev`, or use **browser-style history** with `go_back` / `go_forward` and a configurable `max_history`.
34
+ - **Lazy routes with params** — register a zero-arg factory (or a factory that accepts `**params`) instead of an eager control. Pass `params={"user_id": 42}` to `switch()` and the factory receives them.
35
+ - **Async guards** — an `on_before_leave(from_route, to_route)` callback can veto navigation. If it's `async`, use the `*_async` navigation methods (the sync ones raise a clear `RuntimeError`).
36
+ - **Rich route events** — `on_route_change` receives a `RouteChangeEvent` with `from_route`, `to_route`, `direction`, `source`, `params`, and previous/current indices.
37
+ - **Dynamic routes** — `add_route`, `remove_route`, `rename_route`, and `set_routes` keep history and the current route consistent.
38
+ - **Full async API** — `switch_async`, `go_async`, `go_next_async`, `go_prev_async`, `go_back_async`, `go_forward_async`.
39
+ - **Rich introspection** — `current_route`, `current_control`, `history`, `forward_history`, `can_go_back`, `can_go_forward`, `can_go_next`, `can_go_prev`, `has_route`, `get_route_keys`, plus `len()`, `in`, and iteration support.
40
+
41
+ ## Installation
42
+
43
+ ### Install from the source
44
+ ```bash
45
+ pip install git+https://github.com/osamalzabidi/flet-stacked.git
46
+ ```
47
+
48
+ ### Install from PyPi
49
+ ```bash
50
+ pip install flet-stacked
51
+ ```
52
+
53
+ Requires Python **3.12+** and **Flet 1.1+**.
54
+
55
+ ## Quick start
56
+
57
+ ```python
58
+ import flet as ft
59
+ from flet_stacked import Stacked
60
+
61
+
62
+ def main(page: ft.Page):
63
+ page.title = "Flet Stacked"
64
+
65
+ page.vertical_alignment = ft.MainAxisAlignment.CENTER
66
+ page.horizontal_alignment = ft.CrossAxisAlignment.CENTER
67
+ page.window.width = page.window.height = 600
68
+
69
+ routes = {
70
+ "home": ft.Text("Home Page", size=30),
71
+ "about": ft.Text("About Page", size=30),
72
+ "contact": ft.Text("Contact Page", size=30),
73
+ }
74
+
75
+ stacked = Stacked(
76
+ routes,
77
+ index="home",
78
+ on_route_change=lambda event: print(event), # "home → about [switch]"
79
+ )
80
+
81
+ page.add(
82
+ stacked,
83
+ ft.Row(
84
+ [
85
+ ft.Button("About", on_click=lambda e: stacked.switch("about")),
86
+ ft.Button("Next", on_click=lambda e: stacked.go_next()),
87
+ ft.Button("Prev", on_click=lambda e: stacked.go_prev()),
88
+ ],
89
+ alignment=ft.MainAxisAlignment.CENTER,
90
+ ),
91
+ )
92
+
93
+
94
+ if __name__ == "__main__":
95
+ ft.run(main)
96
+ ```
97
+
98
+ ## Output of the above code
99
+
100
+ ![Example 2](media/screenshot.gif)
101
+
102
+ ## Advanced features
103
+
104
+ ### Browser-style history
105
+
106
+ ```python
107
+ back = ft.IconButton(ft.Icons.ARROW_BACK, disabled=True)
108
+ forward = ft.IconButton(ft.Icons.ARROW_FORWARD, disabled=True)
109
+
110
+ stacked = Stacked(routes, index="home", max_history=30)
111
+
112
+ def on_change(event):
113
+ back.disabled = not stacked.can_go_back()
114
+ forward.disabled = not stacked.can_go_forward()
115
+ page.update()
116
+
117
+ back.on_click = lambda e: page.run_task(stacked.go_back_async)
118
+ forward.on_click = lambda e: page.run_task(stacked.go_forward_async)
119
+ ```
120
+
121
+ `go_back()` pops the bounded `_history` stack; `go_forward()` re-applies routes you walked away from. Call `clear_history()` to reset both stacks.
122
+
123
+ ### Lazy routes with parameters
124
+
125
+ ```python
126
+ def user_page(user_id: int = 0, **_):
127
+ return ft.Column([ft.Text(f"User #{user_id}", size=28)])
128
+
129
+ stacked = Stacked(
130
+ {"home": ft.Text("Home", size=30), "user": user_page},
131
+ index="home",
132
+ cache_lazy_routes=False, # fresh control per visit
133
+ )
134
+
135
+ page.run_task(stacked.switch_async, "user", params={"user_id": 42})
136
+ ```
137
+
138
+ With `cache_lazy_routes=True` (the default), factory-produced controls are cached, so returning to a route restores the same instance and its state. Set `force=True` on `switch` to bypass the cache for a single call.
139
+
140
+ ### Async guards
141
+
142
+ ```python
143
+ async def guard(from_route: str, to_route: str) -> bool:
144
+ if from_route == "editor" and editor_is_dirty():
145
+ return await confirm_discard()
146
+ return True
147
+
148
+ stacked = Stacked(routes, index="home", on_before_leave=guard)
149
+
150
+ # All navigation must go through the async API:
151
+ page.run_task(stacked.switch_async, "settings")
152
+ page.run_task(stacked.go_back_async)
153
+ ```
154
+
155
+ Returning `False` from the guard cancels navigation and leaves the current route untouched. Sync `def` guards work with both APIs; `async def` guards require the `*_async` methods.
156
+
157
+ ### Direction-aware transitions
158
+
159
+ ```python
160
+ stacked = Stacked(
161
+ routes,
162
+ index="home",
163
+ forward_transition=ft.AnimatedSwitcherTransition.SCALE, # go_next / go_forward
164
+ backward_transition=ft.AnimatedSwitcherTransition.FADE, # go_prev / go_back
165
+ )
166
+ ```
167
+
168
+ `Stacked` infers direction from the source (`go_next`, `go_back`, …) or from the positional indices of the routes. Pass `direction="forward" | "backward" | "replace"` explicitly to override.
169
+
170
+ ### Rich route events
171
+
172
+ ```python
173
+ from flet_stacked import RouteChangeEvent
174
+
175
+ def on_change(event: RouteChangeEvent):
176
+ print(
177
+ f"{event.from_route!r} -> {event.to_route!r} "
178
+ f"dir={event.direction} source={event.source} "
179
+ f"params={event.params}"
180
+ )
181
+ ```
182
+
183
+ `RouteChangeEvent` fields:
184
+
185
+ | Field | Type | Description |
186
+ |---|---|---|
187
+ | `from_route` | `str \| None` | Previous route name (`None` on first render). |
188
+ | `to_route` | `str` | Route being navigated to. |
189
+ | `direction` | `"initial" \| "forward" \| "backward" \| "replace"` | Inferred or explicit direction. |
190
+ | `source` | `str` | One of `"switch"`, `"go"`, `"go_next"`, `"go_prev"`, `"go_back"`, `"go_forward"`, `"add_route"`, `"remove_route"`, `"set_routes"`. |
191
+ | `params` | `dict` | Passed through from `switch(..., params=...)`. |
192
+ | `previous_index` | `int \| None` | Index of `from_route`. |
193
+ | `current_index` | `int \| None` | Index of `to_route`. |
194
+
195
+ ### Dynamic routes
196
+
197
+ ```python
198
+ stacked.add_route("new_tab", factory, switch_to=True)
199
+ stacked.rename_route("new_tab", "renamed_tab")
200
+ stacked.remove_route("renamed_tab", fallback="home")
201
+ stacked.set_routes({...}, fallback="home")
202
+ ```
203
+
204
+ All four keep `_history`, `_forward_stack`, the resolved cache, and the current route consistent — if the current route is removed, `Stacked` switches to `fallback` (or the first remaining route) automatically.
205
+
206
+ ## Examples
207
+
208
+ | Example | What it shows |
209
+ |---|---|
210
+ | [`examples/package_browser.py`](examples/package_browser.py) | Grid → detail navigation with `switch_async(params=...)`, direction-aware transitions, and a header driven by `RouteChangeEvent`. |
211
+ | [`examples/flip_card.py`](examples/flip_card.py) | Visa / Mastercard / Amex cards that flip on tap — each card wraps a small `Stacked` whose face is swapped at the 90° point of the flip animation. |
212
+ | [`examples/guarded_form.py`](examples/guarded_form.py) | Unsaved-changes confirmation dialog wired through an async `on_before_leave` guard. |
213
+ | [`examples/dynamic_tabs.py`](examples/dynamic_tabs.py) | Add / close tabs with `add_route` and `remove_route`. |
214
+
215
+ ## API reference
216
+
217
+ ### `Stacked(routes, index=0, *, ...)`
218
+
219
+ | Parameter | Type | Default | Description |
220
+ |---|---|---|---|
221
+ | `routes` | `dict[str, ft.Control \| Callable]` | — | Route name → control or factory. |
222
+ | `index` | `str \| int` | `0` | Initial route (name or positional int). |
223
+ | `on_route_change` | `Callable[[RouteChangeEvent], ...]` | `None` | Called after every successful transition. May be async. |
224
+ | `on_before_leave` | `Callable[[str, str], bool \| Awaitable[bool]]` | `None` | Guard: return `False` to veto. |
225
+ | `max_history` | `int` | `50` | Bounded history for `go_back`. `0` disables history. |
226
+ | `cache_lazy_routes` | `bool` | `True` | Cache factory-produced controls. |
227
+ | `forward_transition` | `ft.AnimatedSwitcherTransition \| None` | `None` | Used for `go_next` / `go_forward`. |
228
+ | `backward_transition` | `ft.AnimatedSwitcherTransition \| None` | `None` | Used for `go_prev` / `go_back`. |
229
+ | `**kwargs` | | | Forwarded to `ft.AnimatedSwitcher`. Defaults: `FADE`, 150 ms in, 50 ms out, `LINEAR` / `EASE_IN_CUBIC` curves. |
230
+
231
+ ### Navigation
232
+
233
+ | Method | Sync / Async | Returns |
234
+ |---|---|---|
235
+ | `switch(route, *, params=None, source="switch", direction=None, record_history=True, force=False)` | sync | `(name, control)` |
236
+ | `switch_async(...)` | async | `(name, control)` |
237
+ | `go(route, **kw)` / `go_async(route, **kw)` | both | `(name, control)` |
238
+ | `go_next(**kw)` / `go_next_async(**kw)` | both | `(name, control) \| None` |
239
+ | `go_prev(**kw)` / `go_prev_async(**kw)` | both | `(name, control) \| None` |
240
+ | `go_back(**kw)` / `go_back_async(**kw)` | both | `(name, control) \| None` |
241
+ | `go_forward(**kw)` / `go_forward_async(**kw)` | both | `(name, control) \| None` |
242
+
243
+ ### Introspection
244
+
245
+ | Method | Returns |
246
+ |---|---|
247
+ | `current_route()` | `str` |
248
+ | `current_index()` | `int` |
249
+ | `current_control()` | `ft.Control` |
250
+ | `history()` | `tuple[str, ...]` |
251
+ | `forward_history()` | `tuple[str, ...]` |
252
+ | `can_go_back()` / `can_go_forward()` | `bool` |
253
+ | `can_go_next()` / `can_go_prev()` | `bool` |
254
+ | `has_route(route)` | `bool` |
255
+ | `get_route_keys()` | `tuple[str, ...]` |
256
+ | `get_routes()` | `dict[str, RouteSource]` |
257
+ | `get_route(route, default=None)` | `RouteSource \| None` |
258
+ | `len(stacked)`, `route in stacked`, `for r in stacked` | — |
259
+
260
+ ### Mutation
261
+
262
+ | Method | Description |
263
+ |---|---|
264
+ | `add_route(key, source, *, position=None, switch_to=False)` | Register a new route, optionally switching to it. |
265
+ | `remove_route(key, *, fallback=None)` | Remove a route; navigates to `fallback` if it was current. |
266
+ | `rename_route(old, new)` | Rename in place, preserving history and current route. |
267
+ | `set_routes(routes, *, fallback=None)` | Replace the route table; navigates to `fallback` if the current route disappears. |
268
+ | `clear_history()` | Clear both history and forward stacks. |
269
+ | `refresh_current()` | Re-resolve the current route (fresh factory call) and re-render. |
270
+
271
+ ## Migrating from v1.2.0
272
+
273
+ 1. **`on_route_change` signature changed.** It now receives a `RouteChangeEvent` instead of `(route, *args, **kwargs)`:
274
+
275
+ ```python
276
+ # before
277
+ on_route_change=lambda route, *a, **k: print(route)
278
+ # after
279
+ on_route_change=lambda event: print(event.to_route)
280
+ ```
281
+
282
+ 2. **`go_back()` is now history pop**, not an alias for `go_prev()`. Use `go_prev()` for route-order navigation.
283
+ 3. **`current_control()` returns the resolved control** (from a factory if applicable), not the raw entry in `routes`.
284
+ 4. **Unknown routes raise `KeyError`** at construction and on `switch`, rather than silently setting `content=None`.
285
+ 5. **`set_routes` auto-navigates** to `fallback` (or the first route) when the current route is removed, keeping the switcher consistent.
286
+
287
+ ## Contributing
288
+
289
+ Pull requests and suggestions are welcome! Open an issue first to discuss any major changes.
290
+
291
+ ## License
292
+
293
+ Apache-2.0
@@ -0,0 +1,7 @@
1
+ flet_stacked/__init__.py,sha256=GAinYpAZq5ZdFiCTuwyiErtaC1VeFuoT9V9gKrBdSQo,274
2
+ flet_stacked/stacked.py,sha256=K2Cvr6aF6GEp6afPeSAq8v5O1MOlS4rLCrYg07Lttks,19607
3
+ flet_stacked-1.2.0.dist-info/licenses/LICENSE,sha256=el6cYxfQVLlU_3MjZdEQ4GIJsCtMY_JncjKKWprjZgo,11362
4
+ flet_stacked-1.2.0.dist-info/METADATA,sha256=DbMQTSt6bUVah6SckB7NtSCpGw_4D8dx0F0tPhoxc1Y,12585
5
+ flet_stacked-1.2.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
6
+ flet_stacked-1.2.0.dist-info/top_level.txt,sha256=4fURPt_UDMEnA2ogO6TNPPcaEY6h25eCvftFmNbrAqc,13
7
+ flet_stacked-1.2.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [2026] [Osama Mohammed @osamalzabidi]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1 @@
1
+ flet_stacked