layerman 1.0.1
layerman: ^1.0.1 copied to clipboard
Headless overlay queue orchestrator: serial one-at-a-time queueing with priority, replace, overlap, conditions, cooldown and two-phase close; renders through any UI backend (showDialog / GetX / bot_to [...]
1.0.1 #
- Docs only: README gains the
gate:(OverlayGate/OverlayVerdict) chapter, a 0.x → 1.0 migration table with before/after examples, and thevisible-confirmed cooldown wording; CHANGELOG 1.0.0 listsPresentedOverlay.visible,gateandOverlayVisibility. - Example: new gate demos, a fix for the live-data demo wrapping
PositionedinsideValueListenableBuilder, and a real example README.
1.0.0 #
Breaking
| 0.x | 1.0.0 |
|---|---|
replace: true |
mode: OverlayMode.replace |
overlap: true |
mode: OverlayMode.overlap |
| Both omitted / false | Omit mode or use mode: OverlayMode.queue |
replace: true, overlap: true |
No equivalent: select exactly one mode. |
route: '/home' |
route: const RouteMatcher.exact('/home') |
route: ['/home', '/promo'] |
route: const RouteMatcher.anyOf(['/home', '/promo']) |
route: RegExp(r'^/promo') |
route: RouteMatcher.regex(RegExp(r'^/promo')) |
pauseOnRoutes: ['/checkout', RegExp(r'^/pay')] |
pauseOnRoutes: [const RouteMatcher.exact('/checkout'), RouteMatcher.regex(RegExp(r'^/pay'))] |
A list pattern inside pauseOnRoutes |
Wrap that pattern with RouteMatcher.anyOf(...). |
record.phase == 'open' |
record.phase == OverlayPhase.open |
requiresAuth: true |
auth: (ctx) => ctx['auth'] == true |
requiresAuth: false (guests only) |
auth: (ctx) => ctx['auth'] != true |
| Fixed login boolean | Custom policy, e.g. auth: (ctx) => ctx['role'] == 'admin'; read any setContext keys. |
when overrides route/auth |
route, auth, when combine with AND; remove unwanted conditions explicitly. |
Layerman(now: callback) |
Layerman(clock: clock) with an OverlayClock providing both now() and createTimer(...); default OverlayClock.system. |
PresentedOverlay(dismissed:, dismiss:) |
visible: is required: a Future<void> that completes after the first painted frame (error => failed). shown events and cooldown counting happen only after it succeeds. Use presentRoute (ModalRoute confirms automatically; other TransitionRoutes pass visible:) or wrap your content in OverlayVisibility; headless tests may pass Future<void>.value(). |
PresentContext |
PresentContext<T>, with close([T? result]) through beforeClose, bound to this submission. |
DialogManager(key, manager: manager) / BottomSheetManager(key, manager: manager) |
Remove manager:; builder close always uses ctx.close and its guard. |
openandsubmitreplace thereplace/overlapbooleans withmode(defaultOverlayMode.queue).affixremains independent.routeis nowRouteMatcher?;pauseOnRoutesisList<RouteMatcher>. Chooseexact,anyOforregex; weakly typed patterns are no longer accepted.PresentedOverlay.visibleis required. Waiting for it keeps the entry inOverlayPhase.openand occupies its slot (durationalready runs); an earlier end has noshownand no cooldown count; a failed signal ends asfailed.OverlayRecord.phaseis nowOverlayPhase, withpending,resolving,openandclosingvalues, instead of strings.
Fixed
-
Reject mutations during when/auth/clearWhere tests before state changes; preserve holds on rejected release.
-
Settle reentrant submissions during dispose as disposed without entering containers.
-
Bind serial delay to its queued owner and reschedule when it leaves; enforce maxQueued after activation, including build deferral.
-
Revalidate resolve data after synchronous listeners; preserve string-keyed Map types on update.
-
Use local calendar buckets with UTC clocks; isolate and preserve malformed cooldown records (a valid record written later for the same id replaces the malformed one).
-
Keep queued → shown → ended ordering when present synchronously ends; failed presentation has no shown.
-
Remove routes with internal history instead of consuming a LocalHistoryEntry; retain Flutter 3.27 compatibility.
-
Clarify delay, targeted dismiss and open-only close/dismiss contracts; document all lib declarations in Chinese.
-
Example: fix the Pause page, ShadSheet, toast inspector and update demos; card close buttons go through
ctx.closeand keep their exit animation; refresh stale guidance. -
Complete the 0.3.0 exhausted-cap behavior: serial entries already blocked by session/total settle as
cappedat submission and after hydration, even with an occupied slot or while paused; they no longer wait for a scheduling scan. -
Overlap now honors
delay, judging now-or-never eligibility after waiting; remove, clear, same-id reopen and dispose cancel the wait. -
Cancel duration when backend dismissal enters exit grace. Clean up a handle returned after synchronous
ctx.close()during present, without starting duration. -
Request backend
dismissat most once per entry. Randomized sequence tests found thatclosefollowed byremove,clearor a dismiss timeout could request dismissal again. Non-idempotent backends such aspopUntilorGet.back()could then close another overlay. ThedismissRequestedguard prevents retries, including after a failing dismiss; targeted handles remain required. -
openduringbuild()defers presentation and manager notifications until after the frame instead of presenting and notifying synchronously. -
Batch manager notifications per public operation so listeners see completed synchronous changes rather than multiple intermediate notifications.
-
Reclaim empty runtime slots once they have no occupant, queued entries, pending gap or gap/delay/cooldown timers.
Changed (behavior)
- Every submission with
cooldownnow waits for storage hydration, including session-only and emptyconst OverlayCooldown()configurations, because suppress is persisted. Submissions without cooldown are unaffected. Migration: code relying on session-only entries appearing beforeready()now waits for one storage read.
Added
-
Layerman.suppress(String id, {Duration? duration})for result-based timed or permanent suppression of cooldown submissions; repeated calls only extend it.resetCooldown/clearCooldownsclear suppression together with counters. -
OverlayEndReason.suppressedandOverlayCooldownStatus.suppressedexpose suppression outcomes and current state. -
OverlaySlotOptions.blockedBy(emptySet<String>by default) holds new activations while listed slots have serial active entries or active overlaps; already activated entries continue. Unblocking runs at the outermost batch end. -
Debug invariants (i), (j), (k): no permanently blocked serial queue entries after hydration is applied, no missed unblock scheduling, and no releasable held overlaps.
-
gate:onopen/submitwithOverlayGate,OverlayVerdict.pass / waitUntil / dropandOverlayEndReason.gated: business eligibility evaluated after route/auth/when and before activation.waitUntilworks for serial entries and overlaps; computeretryAtfrommanager.clock.now(). -
OverlayVisibilitywidget andpresentRoute(..., visible:)for first-frame visibility confirmation. -
OverlayClockunifies current time and timers.package:layerman/testing.dartexportsFakeOverlayClockfor ordinary Darttest()without Flutter bindings. -
Automatic debug invariant validation after every outermost batch via
debugCheckInvariants(); explicit calls also work in release. -
Randomized coverage for slow/failing hydration, build-time open, cooldown inspection/reset, tags, overlap delay, auth predicates and
ctx.close. -
cooldownStatusreturningOverlayCooldownStatus,resetCooldownandclearCooldownsfor inspecting and resetting session and persisted counters. -
Copied, read-only
tagson records andclearTagfor grouped removal. -
OverlayMode,RouteMatcherandOverlayPhasetyped public contracts. -
Randomized sequence invariant tests (
test/fuzz_invariants_test.dart), regression coverage for batched notifications, build deferral and slot reclamation. -
Example demonstrations for the new modes, route matchers, cooldown inspection and reset, tags and build-time submission.
0.3.0 #
Fixed
- Reopening an active serial id takes over its slot when eligible and unpaused,
instead of losing it to a higher-priority queued entry. Old results settle as
null(superseded); old tickets cannot affect the new submission. PresentContext.dataListenablemakesupdate()data available to backends;dataremains a presentation-time snapshot.- Queue insertion now preserves replace / priority / FIFO ordering;
queuedIdsreflects that order within each slot. Predicate context views are cached.
Changed (behavior)
LayermanNavigatorObservernow tracks onlyPageRouteby default. Dialogs and bottom sheets no longer overwrite page context, dismiss their own route-gated overlays, or release no-overlay zones. To restore 0.2.x tracking of every route, passrouteFilter: (r) => true. UsecontextKeyfor nested navigators;route:andpauseOnRoutesstill read only the defaultroutekey.- Exhausted
session/totalcaps discard serial entries when checked by scheduling, completing withnull(capped) instead of waiting forever. Use time-based caps for retryable waits, or a new id for a new campaign. - Waiting is bounded by default:
dismissTimeoutis 10 seconds andresolveTimeoutis 30 seconds. Constructornulldisables either limit; per-entryresolveTimeout: nullinherits, andDuration.zerodisables that entry's resolve limit. Timeouts report errors and free the slot; a dismiss timeout preserves the already-delivered outcome. Backend work is not cancelled. - Route recipes now recommend
DialogManager, created once with a navigator key, instead of a hand-written shared dialog helper. Bindmanager:to route builder close calls throughbeforeClose; custom routes/pages usepresentRoute.
Added
DialogManager,BottomSheetManagerandpresentRoute: targeted Route presenters waiting for exit completion; per-call configuration overrides.submit<T>()returningOverlayTicket<T>with typed close, update, removal, live data, result and outcome;OverlayOutcome,OverlayEndReason, and async broadcastevents(OverlayEvent,OverlayEventType).resolvingIds,records,recordOffor complete entry inspection.- Independent pause tokens via
hold()/OverlayHold,holdCount, andLayermanLifecyclefor automatic background pause. - Serial queue expiration via
expireAfterand per-slotOverlaySlotOptions(gap,maxQueued), withqueueExpired/queueFulloutcomes. .pubignoreexcludesCLAUDE.mdand.claude/from the published package.- Example Android platform and a “v0.3 Features” demo page. The 26 example integration tests pass on a real phone (Huawei STG-AL00, Android 12); the 199 unit tests pass on Flutter 3.47 and on the minimum supported Flutter 3.27.4.
0.2.2 #
Fixed
close(id, result)with aresultthat isn't aT?of itsopen<T>()used to throw aTypeErrorhalfway through the close and leave theopen()future pending forever. It now throws anArgumentErrorbefore touching any state, so the overlay can still be closed normally afterwards.- Cooldown hydration race: an entry gated on a persisted cap (
total/day/hour/minute/minGap) opened beforeready()was checked against empty counters, and its write-back overwrote every other id's counters in storage (hydration then overwrote the new count). Such entries now wait until the store has hydrated (anoverlapone is held, not dropped); hydration merges instead of overwriting; writes are serialized (one in flight, then the latest snapshot); read/write failures are reported viaFlutterError.reportErrorinstead of being swallowed.ready()now completes after the queue has been re-scheduled, and awaiting it beforeopen()is no longer required. A persisted-capreplacethat arrives before hydration therefore queues at the front instead of preempting. - An async
beforeCloseguard no longer runs twice whenclose()/dismiss()is called again while it is pending; the repeated calls are ignored. - A throwing
whenpredicate no longer escapesopen()/setContext()/ timer callbacks: it is reported once per overlay and treated as unmet. open()afterdispose()no longer presents the overlay: it asserts in debug and returnsnullin release. Every other mutator is a no-op afterdispose().
Changed
cooldownwithout an explicitidnow asserts in debug — counters are keyed by id, and an auto-generated id changes on every open, so the cap never applied.- README route recipes now push a
Routeobject, useroute.completed(completes after the exit animation, carrying the pop result) asdismissed, and close it withpopwhen on top orremoveRoutewhen buried. The previous name-basedpopUntil/Get.untilrecipes silently did nothing when the dialog wasn't the topmost route (e.g. under anoverlapdialog), leaving the entry stuck inclosing. Also corrected the docs onupdate(),activeIds/isShowing, andreplacepreempting a resolving entry. - Minimum SDK is now Dart 3.6 / Flutter 3.27 — the first release with
NavigatorObserver.didChangeTop. The previousflutter: ">=1.17.0"bound was wrong, andsdk: ^3.12.2was needlessly high. ARCHITECTURE.md/ARCHITECTURE.svgrewritten from the actual code.
0.2.1 #
Fixed
- A throwing
present/dismissno longer wedges the queue: the error is reported viaFlutterError.reportError, the entry is dropped (resultnull, no cooldown counted) and the queue advances. durationexpiry bypassesbeforeClose(it gates only an explicitclose()).resolvenow also runs foroverlap: trueentries; aresolvethat finishes while paused is held untilresumeAll(resolver is not re-run).- Reopening the same id from a listener while the old entry is closing no longer
unregisters the new entry; moving an id to another slot (or to
overlap) re-schedules the slot it vacated. clearWhereremoves everything before advancing, so a matching queued entry is never briefly shown;clear()also resets a pending transition gap / delay.- Day/hour/minute cooldown wake-ups use calendar boundaries (DST-safe).
Changed
- Internal engine simplified (dead code removed); the example's
presentShadToastnow owns the toast lifetime (hide timer, completes onhide()), so hover or a late exit animation can't advance the queue under a visible toast.
0.2.0 #
Breaking — the manager is now headless (UI-agnostic). The self-rendering
builder: path is gone; present: is the sole rendering hook. The core no
longer owns an Overlay, imports no package:flutter/widgets.dart, and mirrors
the headless TS sister package.
Why: the whole point is an orchestrator that doesn't care what renders. As long
as builder: existed, the manager had to own an Overlay layer and be attached
to an OverlayState — that is a UI responsibility, and it contradicted the
goal. The present:/PresentedOverlay handle model is a strict superset: a
backend that owns its own OverlayEntry covers everything builder: did, so
nothing is lost. See the README's "Why there is no builder:" section for the
migration recipe.
Renamed (to match the package name)
OverlayManager→Layerman;OverlayNavigatorObserver→LayermanNavigatorObserver.- Everything else keeps its
Overlay*name on purpose —OverlayPredicate,OverlayCooldown,OverlayCooldownStorage,OverlayRecord,PresentedOverlaydescribe the overlay being managed, not the manager itself, so renaming those toLayerman*would misdescribe what they are (e.g.PresentedOverlayis "the overlay that got presented", not "a presented orchestrator").
Removed
open(builder: ...)and theOverlayContentBuildertypedef — useopen(present: ...).OverlayManagerScope,Layerman.attach/detach/isAttached— the manager attaches to nothing now.OverlayHandle,OverlayPhase, and the handle'sphase/phaseListenable/isClosing—open()returns itsFuture<T?>directly; a backend drives its own exit animation and reports completion viaPresentedOverlay.dismissed.barrierColor/barrierDismissibleonopen()— the backend renders its own barrier.Layerman(exitDuration:)constructor default —exitDurationis now a per-open()grace only (null ⇒ advance immediately).
Behavior
replacenow always closes the preempted overlay (resultnull); it is never sent back to the queue to re-show. A dismissed backend can't be faithfully re-presented (that would re-run its side effects), so the old self-rendered "displace + resume" semantics no longer applied and were dropped along with theirwasDisplaced/replaceBandmachinery.
Unchanged: slots, priority, affix, overlap, conditions (when / route
/ requiresAuth / setContext / dismissWhenUnmet), cooldown (+ pluggable
storage), resolve, beforeClose, duration, delay, gap, pauseAll /
resumeAll / pause / resume, update, clearWhere, LayermanNavigatorObserver,
currentRoute, pauseOnRoutes.
0.1.1 #
Docs only — no code changes.
- README now links the live interactive demo.
0.1.0 #
OverlayNavigatorObserver— aNavigatorObserverthat feeds real navigation intosetContext'sroutekey automatically (deferred to a post-frame callback, safe even if navigation happens mid-build). Works under vanillaNavigator, GetX and go_router alike; purely observational, never touches navigation itself. Removes the need to callsetContext({'route': ...})by hand in every page's lifecycle.OverlayManager.currentRoute— reads the trackedroutecontext value back, so hosts don't need to maintain their own route mirror.OverlayManager({pauseOnRoutes: [...]})— declares "no-overlay zone" route patterns: entering a match freezes the whole queue (likepauseAll), leaving resumes it (likeresumeAll). Composes correctly with manualpauseAll/resumeAll— neither one overrides the other; the queue only actually thaws once both are clear.- README: new "Auto route awareness" section and a "navigated page as a queue
entry" recipe (wrapping
Navigator.pushinpresent:— a page route is just another external presenter, nobuilder:needed).
0.0.1 #
Initial public release.
A Flutter-native overlay queue manager that renders real OverlayEntrys and
can also orchestrate overlays rendered by other libraries (showDialog, GetX,
bot_toast, fluttertoast, …).
Core
OverlayManager— serial one-at-a-time queueing per namedslot, with an optionalgap;open<T>()returns aFuture<T?>(likeshowDialog).- Ordering:
priority(desc, FIFO ties),replace(preempt the current overlay — which is sent back to the queue and re-shows after the replacer closes; front-bands ahead of queued entries; skips a pending gap),affix(protect the current overlay fromreplace),overlap(bypass the queue and stack immediately, now-or-never). - Two-phase close (
OverlayPhase.open→closing→ removed) for exit animations, driven byOverlayHandle.phaseListenable. - Per-overlay
delay/duration(auto-close) and an optional modal barrier (barrierColor/barrierDismissible).
Conditions & cooldown
- Conditions:
when(ctx)predicate (sole authority),route(String/List/RegExp) +requiresAuthsugar,setContext({...})push-model re-evaluation, anddismissWhenUnmet(default true) auto-dismissal. - Cooldown:
OverlayCooldown(session/total/day/hour/minute/minGap)— AND semantics, counts on real open, local calendar buckets, rollingminGap; persisted via a pluggableOverlayCooldownStorage(defaultMemoryCooldownStorage);ready()awaits hydration; injectablenow. A time-based cap (minGap/ bucket rollover) auto-shows the queued entry the moment it expires.
Lifecycle & data
- Backend-driven
resolve(fetch payload only when granted;nullskips without counting cooldown; slot committed while resolving). beforeCloseguard (sync/async;falseor throw vetoesclose;remove/clearbypass it).pauseAll/resumeAllfull freeze and per-idpause/resume.update(id, patch)(shallow-merge + rebuild) andclearWhere(test)(selective mass removal overOverlayRecords).- Introspection:
activeIds,queuedIds,isShowing,isPaused,isAttached;OverlayManageris aChangeNotifier.
Rendering & orchestration
OverlayManagerScope— a dedicatedOverlaylayer above your app (independent of theNavigator), withof/maybeOfand automatic re-attach when the manager is swapped. Orattach/detachan ambientOverlayyourself.- External presenter:
open(present: ...)withPresent/PresentContext/PresentedOverlay— one queue overshowDialog/ GetX (dialog + snackbar) /bot_toast/fluttertoast. README has copy-paste recipes and the orchestration rules of engagement.
Zero third-party runtime dependencies.