merge(app): land notification capability after a retained deadline

This commit is contained in:
2026-10-22 02:05:36 +01:00
19 changed files with 2882 additions and 0 deletions
@@ -0,0 +1,30 @@
import 'notification_bridge_stub.dart'
if (dart.library.js_interop) 'notification_bridge_web.dart'
as impl;
import 'notification_models.dart';
/// Where the notification capability actually posts.
///
/// The controller depends on this, not on any platform, so the dedupe, the
/// permission rules and the content are all testable without a browser. A bridge
/// answers the platform's real facts and never guesses: [environment] returns
/// what the platform says (including "unsupported"), [requestPermission] is only
/// called from an explicit gesture, and [show] reports whether the platform
/// accepted the notification.
abstract interface class NotificationBridge {
/// The platform's own facts: support, secure context and permission word.
NotificationEnvironment environment();
/// Asks the platform, from an explicit operator gesture, and returns its own
/// answer word. Never a guess, and never called by the controller on its own.
Future<String> requestPermission();
/// Shows one notification, attaching [onTap] as its tap intent when given.
/// Returns whether the platform accepted it.
bool show(NotificationMessage message, {void Function()? onTap});
}
/// The bridge for the current platform: the browser `Notification` on the web,
/// an honest "unsupported" elsewhere.
NotificationBridge createNotificationBridge() =>
impl.createNotificationBridge();
@@ -0,0 +1,27 @@
import 'notification_bridge.dart';
import 'notification_models.dart';
/// The non-web bridge: there is no browser Notification API to reach.
///
/// It reports `unsupported` honestly rather than pretending a notification was
/// shown, so the surface falls back to the in-app `Needs you` channel. A native
/// platform notifier would replace this through the same seam.
class UnsupportedNotificationBridge implements NotificationBridge {
const UnsupportedNotificationBridge();
@override
NotificationEnvironment environment() => const NotificationEnvironment(
supported: false,
secureContext: false,
permission: 'default',
);
@override
Future<String> requestPermission() async => 'default';
@override
bool show(NotificationMessage message, {void Function()? onTap}) => false;
}
NotificationBridge createNotificationBridge() =>
const UnsupportedNotificationBridge();
@@ -0,0 +1,95 @@
import 'dart:js_interop';
import 'dart:js_interop_unsafe';
import 'notification_bridge.dart';
import 'notification_models.dart';
/// The browser's `Notification` constructor.
///
/// Declared with `dart:js_interop` rather than `dart:html`, so the same source
/// compiles for the JavaScript and WebAssembly web targets. Every member is
/// reached only after [_supported] has confirmed the global exists, so an
/// unsupported browser never touches it.
@JS('Notification')
extension type _Notification._(JSObject _) implements JSObject {
external factory _Notification(JSString title, _NotificationOptions options);
external static JSString get permission;
external static JSPromise<JSString> requestPermission();
external set onclick(JSFunction? handler);
}
/// The `{ body, tag }` options object one notification is created with.
extension type _NotificationOptions._(JSObject _) implements JSObject {
external factory _NotificationOptions({JSString body, JSString tag});
}
/// Whether `globalThis.Notification` is really a constructor right now.
bool _supported() =>
globalContext.getProperty<JSAny?>('Notification'.toJS).isA<JSFunction>();
/// The browser's own secure-context flag; anything but a real boolean is false.
bool _secureContext() {
final value = globalContext.getProperty<JSAny?>('isSecureContext'.toJS);
return value.isA<JSBoolean>() && (value as JSBoolean).toDart;
}
/// The browser bridge: the real `Notification` API, reached through
/// `dart:js_interop`.
///
/// Nothing is fabricated. [environment] reports the constructor's own
/// `permission` word and the page's own `isSecureContext`; an unsupported
/// browser is reported as unsupported rather than as a default grant.
class WebNotificationBridge implements NotificationBridge {
const WebNotificationBridge();
@override
NotificationEnvironment environment() {
if (!_supported()) {
return const NotificationEnvironment(
supported: false,
secureContext: false,
permission: 'default',
);
}
final raw = _Notification.permission.toDart;
return NotificationEnvironment(
supported: true,
secureContext: _secureContext(),
permission: raw == 'granted' || raw == 'denied' ? raw : 'default',
);
}
@override
Future<String> requestPermission() async {
if (!_supported()) return 'default';
try {
return (await _Notification.requestPermission().toDart).toDart;
} catch (_) {
// A browser that refuses the request keeps the honest fallback wording.
return 'default';
}
}
@override
bool show(NotificationMessage message, {void Function()? onTap}) {
if (!_supported()) return false;
try {
final notification = _Notification(
message.title.toJS,
_NotificationOptions(body: message.body.toJS, tag: message.tag.toJS),
);
final open = onTap;
if (open != null) notification.onclick = (() => open()).toJS;
return true;
} catch (_) {
// Some browsers can throw even with permission granted; the in-app Needs
// you surface remains the only honest channel and nothing is faked.
return false;
}
}
}
NotificationBridge createNotificationBridge() => const WebNotificationBridge();
@@ -0,0 +1,250 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import '../domain/attention_transitions.dart';
import 'notification_bridge.dart';
import 'notification_ledger.dart';
import 'notification_models.dart';
import 'notification_store.dart';
/// The live notification capability behind the `Needs you` surface.
///
/// It never invents a permission: [permission] is the platform's own answer,
/// read from the [NotificationBridge], and `granted` is only ever reported when
/// the platform said so. Nothing asks for permission on its own —
/// [requestPermission] is the one explicit call — and a denied answer is never
/// re-asked.
///
/// Only live attention transitions raise a notification: the caller publishes
/// the transitions the attention model raised (never the initial seed), and one
/// identity is posted at most once per entry into its run's qualifying state,
/// including across a reconnect, because the ledger records the identity before
/// the platform is asked to show it. A dismissed identity is recorded but never
/// shown.
///
/// The manager wires it: set [onOpenRun] to open a run, call [load] once, and
/// after *every* authoritative read and pushed frame call [publishTransitions]
/// with the attention controller's accumulated transitions, its current rows
/// (through [notificationQualifyingKeys]) and its dismissed set. Publishing the
/// frame that leaves a state is what forgets the old identity, so the next gate
/// or retry is a new announcement. The call is idempotent, so passing the whole
/// accumulated list is safe.
class NotificationController extends ChangeNotifier {
NotificationController({required this.store, NotificationBridge? bridge})
: bridge = bridge ?? createNotificationBridge();
/// The most notifications one publish posts, so a burst cannot flood the tray.
static const maxNotificationsPerBatch = 5;
final NotificationStore store;
final NotificationBridge bridge;
/// The tap seam: the manager sets this to open a run. Nothing here navigates.
void Function(int runId)? onOpenRun;
NotificationLedger _ledger = const NotificationLedger();
NotificationPermissionState _permission =
NotificationPermissionState.unsupported;
bool _loaded = false;
bool _disposed = false;
int _posted = 0;
/// The transition instance announced this session for each identity: a new
/// instance means the run entered the state again.
final Map<String, AttentionTransition> _announced = {};
/// The queued ledger writes, so an older snapshot cannot land after a newer one.
Future<void> _writes = Future<void>.value();
/// The platform's own permission state for this page.
NotificationPermissionState get permission => _permission;
/// True once the persisted ledger and the platform facts have been read.
bool get loaded => _loaded;
/// Whether the operator has ever been asked for permission.
bool get asked => _ledger.asked;
/// A copy of the transition identities this client has already announced.
/// Returned unmodifiable, so a caller cannot mutate the ledger behind
/// [publishTransitions]' back.
Set<String> get notified => Set<String>.unmodifiable(_ledger.notified);
/// True only when the platform itself reported `granted`.
bool get canNotify => _permission == NotificationPermissionState.granted;
/// How many notifications this session has actually posted.
int get postedCount => _posted;
/// Reads the persisted ledger and the platform's real permission facts once.
Future<void> load() async {
NotificationLedger ledger;
try {
ledger = decodeNotificationLedger(await store.read());
} catch (_) {
ledger = const NotificationLedger();
}
if (_disposed) return;
_ledger = ledger;
_announced.clear();
_permission = notificationStateOf(bridge.environment());
_loaded = true;
notifyListeners();
}
/// Re-reads the platform's facts without asking anything, for example after
/// the browser's site settings changed and the page regained focus.
void refreshPermission() {
if (_disposed) return;
final next = notificationStateOf(bridge.environment());
if (next == _permission) return;
_permission = next;
notifyListeners();
}
/// The one explicit request, only ever called from an operator gesture.
///
/// A supported, secure page that has not decided is asked, and every other
/// state answers with the platform's own word instead of prompting again. The
/// request is issued before any await, so it stays inside the gesture that
/// triggered it.
Future<NotificationPermissionState> requestPermission() async {
if (_disposed) return _permission;
final environment = bridge.environment();
_permission = notificationStateOf(environment);
if (_permission != NotificationPermissionState.notRequested) {
notifyListeners();
return _permission;
}
// The operator was asked, whatever the answer; persisted without awaiting so
// the platform request stays in this gesture's frame.
_ledger = _ledger.withAsked(true);
unawaited(_persist(_ledger));
notifyListeners();
String answer;
try {
answer = await bridge.requestPermission();
} catch (_) {
answer = '';
}
if (_disposed) return _permission;
final word = answer.trim().toLowerCase();
_permission = notificationStateOf(
NotificationEnvironment(
supported: environment.supported,
secureContext: environment.secureContext,
permission: word == 'granted' || word == 'denied'
? word
: environment.permission,
),
);
notifyListeners();
return _permission;
}
/// Posts one notification per live transition, in order.
///
/// [qualifying] is [notificationQualifyingKeys] for the *same* snapshot as
/// [transitions]: a transition whose run has left the state is stale and
/// neither posts nor records anything, then every recorded identity outside
/// [qualifying] is forgotten so the next gate can notify. Only the latest
/// entry per run+kind in a backlog is announced.
///
/// A caller that misses the leaving frame still gets the new transition: the
/// detector creates one instance per genuine transition, so an identity
/// announced earlier this session with a different instance is a new
/// occurrence; the same instance, and an identity loaded from the store before
/// this session, stay silent.
///
/// The initial seed raises no transition. A transition the operator dismissed,
/// one already recorded and one past [maxNotificationsPerBatch] post nothing.
/// Returns how many notifications the platform accepted.
int publishTransitions(
Iterable<AttentionTransition> transitions, {
required Set<String> qualifying,
Set<String> dismissed = const {},
}) {
if (_disposed) return 0;
var posted = 0;
var changed = false;
// A backlog may hold several entries for one run+kind; only the latest one
// describes the state that is current, so a coalesced burst notifies once.
final latest = <String, AttentionTransition>{};
for (final transition in transitions) {
latest[notificationIdentity(transition)] = transition;
}
for (final transition in latest.values) {
if (posted >= maxNotificationsPerBatch) break;
final identity = notificationIdentity(transition);
// Older than the snapshot: the run already left this state.
if (!qualifying.contains(identity)) continue;
final announced = _announced[identity];
if (identical(announced, transition)) continue;
if (announced == null && _ledger.hasNotified(identity)) {
// Restored from the store before this session: adopt the instance so a
// republish is recognized, but do not announce it again.
_announced[identity] = transition;
continue;
}
// A new instance for an identity announced this session is a later entry.
if (!_ledger.hasNotified(identity)) {
_ledger = _ledger.recording(identity);
changed = true;
}
_announced[identity] = transition;
if (dismissed.contains(identity)) continue;
if (!canNotify) continue;
final open = onOpenRun;
final message = NotificationMessage(
runId: transition.runId,
title: notificationAlertTitle(transition.kind),
body: notificationAlertBody(transition.entry),
tag: identity,
);
var shown = false;
try {
shown = bridge.show(
message,
onTap: open == null ? null : () => open(transition.runId),
);
} catch (_) {
shown = false;
}
if (shown) {
posted++;
_posted++;
}
}
final pruned = _ledger.pruning(qualifying);
if (!identical(pruned, _ledger)) {
_ledger = pruned;
changed = true;
}
if (changed) unawaited(_persist(_ledger));
return posted;
}
/// Writes the ledger without ever throwing into the caller's frame, one write
/// at a time so their order matches the calls.
Future<void> _persist(NotificationLedger ledger) {
final encoded = encodeNotificationLedger(ledger);
final write = _writes.then((_) async {
if (_disposed) return;
try {
await store.write(encoded);
} catch (_) {
// The in-memory ledger still applies for this session.
}
});
_writes = write;
return write;
}
@override
void dispose() {
_disposed = true;
super.dispose();
}
}
@@ -0,0 +1,122 @@
import 'dart:convert';
import '../../../core/api_gateway.dart';
import '../domain/attention_models.dart';
import '../domain/attention_transitions.dart';
/// This client's own storage key for the notification ledger, namespaced like
/// the rest of the app. It is deliberately not the legacy web key, so neither
/// client rewrites the other's local state on a shared origin.
const notificationStorageKey = 'pipelines.next.notify.v1';
/// The identity of one announced transition: the run and kind, exactly the
/// attention surface's own key and the browser's `alertKey`.
///
/// It is deliberately *not* keyed by a timestamp. A waiting run has no
/// `finished_at`, and its creation time never changes, so a marker derived from
/// them cannot tell a run's first decision gate from a later one. Instead the
/// ledger only holds identities for the runs that are qualifying *right now*:
/// [notificationQualifyingKeys] supplies that set, and an identity is forgotten
/// as soon as its run leaves the qualifying state (see [NotificationLedger.pruning]).
/// The next entry into the same state is therefore a new announcement, exactly
/// as in `web/src/notify.js`.
String notificationIdentity(AttentionTransition transition) => transition.key;
/// The `{runId}:{Kind}` identities of the runs currently in a qualifying state,
/// built from the same rows the attention surface draws.
///
/// Dismissals and the local-day window are deliberately ignored: a dismissal
/// does not stop a run qualifying, and an old failure is still the same
/// announced transition rather than a new one.
Set<String> notificationQualifyingKeys(Iterable<JsonMap>? runs) {
final keys = <String>{};
for (final run in runs ?? const <JsonMap>[]) {
final runId = attentionRunId(run['run_id']) ?? attentionRunId(run['id']);
final kind = attentionKindForRun(run);
if (runId == null || kind == null) continue;
keys.add(attentionKey(runId, kind));
}
return keys;
}
/// What this client has already announced, plus whether the operator has ever
/// been asked.
///
/// The ledger is pure: it records identities, decides whether one is new and
/// drops the ones whose run no longer qualifies. Persistence is the store's job.
///
/// An identity lives only while its run is in the qualifying state it announced:
/// publishing the same list again is idempotent, a reconnect cannot repeat a
/// notification, and a genuinely new transition (a second decision gate, or a
/// later failure of a new run id) notifies once more because leaving the state
/// dropped the old identity. This is the browser's `forget` model; unlike a
/// timestamp marker it can tell two decision gates of one run apart.
class NotificationLedger {
const NotificationLedger({
this.notified = const <String>{},
this.asked = false,
});
/// The transition identities already recorded, in no particular order.
final Set<String> notified;
/// Whether the operator has ever been asked for permission.
final bool asked;
bool hasNotified(String identity) => notified.contains(identity);
/// The ledger with [identity] recorded.
NotificationLedger recording(String identity) =>
NotificationLedger(notified: {...notified, identity}, asked: asked);
NotificationLedger withAsked(bool value) =>
NotificationLedger(notified: notified, asked: value);
/// The ledger with every identity outside [qualifying] dropped.
///
/// A run that is no longer failed or waiting has left its announced state, so
/// a later entry is a new event and must be able to notify again. Keeping only
/// the current qualifying identities also bounds the ledger to the runs the
/// surface currently holds instead of growing with every event ever seen.
NotificationLedger pruning(Set<String> qualifying) {
final kept = notified.where(qualifying.contains).toSet();
if (kept.length == notified.length) return this;
return NotificationLedger(notified: kept, asked: asked);
}
}
/// The one-line JSON the ledger is stored as. The identities are sorted so an
/// unchanged ledger always encodes to the same bytes.
String encodeNotificationLedger(NotificationLedger ledger) {
final identities = ledger.notified.where((id) => id.isNotEmpty).toList()
..sort();
return jsonEncode({'asked': ledger.asked, 'notified': identities});
}
/// Decodes a stored value into a ledger. Total: blank text, unreadable JSON, a
/// non-map, a non-boolean `asked` and non-string members all decode to the
/// members that can be read, and a malformed value never throws.
///
/// A value written by an older build may still contain timestamped identities;
/// they simply stop matching [notificationQualifyingKeys] and are dropped on the
/// next publish, so no migration step is needed.
NotificationLedger decodeNotificationLedger(String? stored) {
final text = (stored ?? '').trim();
if (text.isEmpty) return const NotificationLedger();
dynamic parsed;
try {
parsed = jsonDecode(text);
} catch (_) {
return const NotificationLedger();
}
if (parsed is! Map) return const NotificationLedger();
final raw = parsed['notified'];
return NotificationLedger(
notified: {
if (raw is List)
for (final value in raw)
if (value is String && value.isNotEmpty) value,
},
asked: parsed['asked'] == true,
);
}
@@ -0,0 +1,169 @@
import '../domain/attention_models.dart';
/// The permission state the notification surface reports.
///
/// The Dart names are this client's; [wireName] is the browser model's own word
/// (`unsupported` | `insecure` | `default` | `granted` | `denied`) so the two
/// clients' vocabularies stay traceable. [notRequested] is the Notification
/// API's `default`: supported and secure, but the operator has not decided yet.
enum NotificationPermissionState {
unsupported('unsupported'),
needsSecureContext('insecure'),
notRequested('default'),
granted('granted'),
denied('denied');
const NotificationPermissionState(this.wireName);
/// The browser model's own word for this state (`web/src/notify.js`).
final String wireName;
}
/// The platform's own notification facts, as the bridge answers them.
///
/// [permission] is the Notification API's raw word; anything unrecognised is
/// read as `default` rather than guessed, exactly as the browser does.
class NotificationEnvironment {
const NotificationEnvironment({
required this.supported,
required this.secureContext,
required this.permission,
});
final bool supported;
final bool secureContext;
final String permission;
}
/// The permission state for one environment.
///
/// Only the platform's own answers decide it: an unsupported API and an
/// insecure page are reported before the permission word, and `granted` is never
/// assumed — a page that has not been granted stays [notRequested].
NotificationPermissionState notificationStateOf(
NotificationEnvironment environment,
) {
if (!environment.supported) return NotificationPermissionState.unsupported;
if (!environment.secureContext) {
return NotificationPermissionState.needsSecureContext;
}
switch (environment.permission) {
case 'granted':
return NotificationPermissionState.granted;
case 'denied':
return NotificationPermissionState.denied;
default:
return NotificationPermissionState.notRequested;
}
}
/// Android's NOTIFICATION_RATIONALE, verbatim (`RunAlerts.kt`, `notify.js`).
const notificationRationale =
'Pipelines can notify you when a run is waiting for your decision or has '
'failed. Without it, those runs still appear in the in-app Needs you '
'surface.';
/// The Settings section heading and the explicit-gesture action label.
const notificationSectionTitle = 'Notifications';
const notificationRequestLabel = 'Enable notifications';
/// The honest wording for every state, verbatim from `web/src/notify.js`; each
/// says plainly that the in-app `Needs you` surface is the only channel when the
/// platform cannot notify.
const notificationUnsupportedCopy =
'This browser does not support notifications. The in-app Needs you surface '
'is the only channel.';
const notificationInsecureCopy =
'Notifications need a secure context (https or localhost). This page is not '
'secure, so the in-app Needs you surface is the only channel.';
const notificationGrantedCopy =
'Notifications are on. Failed and waiting runs will raise a browser '
'notification.';
const notificationDeniedCopy =
'Notifications are blocked for this site. Allow them in the browser\'s site '
'settings to use them; until then the in-app Needs you surface is the only '
'channel.';
const notificationDefaultCopy =
'Notifications are off. Enable them to be told when a run fails or needs '
'your decision.';
const notificationDefaultAskedCopy =
'Notifications are still off. Your browser did not grant permission when '
'asked; you can ask again, or the in-app Needs you surface remains the only '
'channel.';
/// The total permission view for the Settings tile.
///
/// Only a supported, secure page whose permission is still `default` offers the
/// request control, and [asked] only changes the honest wording — nothing here
/// asks for permission on its own.
class NotificationPermissionView {
const NotificationPermissionView({
required this.state,
required this.body,
required this.canRequest,
required this.actionLabel,
required this.asked,
});
final NotificationPermissionState state;
final String body;
final bool canRequest;
final String? actionLabel;
final bool asked;
}
/// The view for one state, with the browser's own copy for it.
NotificationPermissionView notificationPermissionView(
NotificationPermissionState state, {
bool asked = false,
}) {
final canRequest = state == NotificationPermissionState.notRequested;
final body = switch (state) {
NotificationPermissionState.unsupported => notificationUnsupportedCopy,
NotificationPermissionState.needsSecureContext => notificationInsecureCopy,
NotificationPermissionState.granted => notificationGrantedCopy,
NotificationPermissionState.denied => notificationDeniedCopy,
NotificationPermissionState.notRequested =>
asked ? notificationDefaultAskedCopy : notificationDefaultCopy,
};
return NotificationPermissionView(
state: state,
body: body,
canRequest: canRequest,
actionLabel: canRequest ? notificationRequestLabel : null,
asked: asked,
);
}
/// The short headline one kind shows; the browser's `alertTitle` verbatim.
String notificationAlertTitle(AttentionKind kind) => switch (kind) {
AttentionKind.decision => 'A run needs your decision',
AttentionKind.failed => 'A run failed',
};
/// The line naming the run: its label, then the pipeline it belongs to.
///
/// The words are the entry's own — a blank or equal pipeline is never repeated,
/// so there is no trailing separator and nothing is invented.
String notificationAlertBody(AttentionEntry entry) {
final pipeline = entry.pipeline;
final label = entry.label;
if (pipeline.isEmpty || pipeline == label) return label;
return '$label \u00b7 $pipeline';
}
/// One notification the platform is asked to show: the entry's own words, plus
/// the stable identity used as the browser's coalescing tag.
class NotificationMessage {
const NotificationMessage({
required this.runId,
required this.title,
required this.body,
required this.tag,
});
final int runId;
final String title;
final String body;
final String tag;
}
@@ -0,0 +1,83 @@
import 'package:shared_preferences/shared_preferences.dart';
import 'notification_ledger.dart';
/// The persistence seam for the notification ledger.
///
/// The controller only ever hands over the exact string produced by
/// [encodeNotificationLedger], so a store cannot invent a different format.
/// Both directions are allowed to fail: a caller treats a null read as "nothing
/// recorded yet" and a false write as "this session only".
abstract interface class NotificationStore {
Future<String?> read();
Future<bool> write(String value);
}
/// `shared_preferences` storage under the ledger's own key.
///
/// Reads and writes are total: an unavailable plugin, a disabled store or a full
/// disk returns null/false instead of throwing into the caller's frame. Only the
/// documented [notificationStorageKey] is touched, never the attention key or the
/// legacy web key.
class SharedPreferencesNotificationStore implements NotificationStore {
const SharedPreferencesNotificationStore();
Future<SharedPreferences?> _preferences() async {
try {
return await SharedPreferences.getInstance();
} catch (_) {
return null;
}
}
@override
Future<String?> read() async {
final preferences = await _preferences();
if (preferences == null) return null;
try {
return preferences.getString(notificationStorageKey);
} catch (_) {
return null;
}
}
@override
Future<bool> write(String value) async {
final preferences = await _preferences();
if (preferences == null) return false;
try {
return await preferences.setString(notificationStorageKey, value);
} catch (_) {
return false;
}
}
}
/// An in-memory store for tests and isolated fixtures.
///
/// It never touches the platform store, so a probe or widget test cannot mutate
/// a real operator's persisted ledger. [failReads] and [failWrites] reproduce an
/// unavailable store without throwing.
class MemoryNotificationStore implements NotificationStore {
MemoryNotificationStore({this.stored});
String? stored;
bool failReads = false;
bool failWrites = false;
int writes = 0;
@override
Future<String?> read() async {
if (failReads) throw StateError('notification store unavailable');
return stored;
}
@override
Future<bool> write(String value) async {
writes++;
if (failWrites) throw StateError('notification store is read-only');
stored = value;
return true;
}
}
@@ -0,0 +1,127 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../ui/adaptive/host.dart';
import '../notify/notification_models.dart';
/// The permission tile's root, so a caller can find it whichever host draws it.
const notificationTileKey = ValueKey<String>('notification-permission-tile');
/// The explicit-gesture Enable action, present only when a request is possible.
const notificationEnableKey = ValueKey<String>(
'notification-permission-enable',
);
/// The honest state line, which says plainly when the in-app surface is the
/// only channel.
const notificationStateKey = ValueKey<String>('notification-permission-state');
/// The reusable Notifications permission tile for Settings.
///
/// It renders the platform's own [state] with the browser's own copy, shows the
/// Android rationale verbatim, and offers the [notificationRequestLabel] action
/// only while a request is still possible. Nothing here asks for permission on
/// its own — [onRequest] is the caller's explicit-gesture handler, and the tile
/// never guesses a grant.
///
/// The caller owns the surrounding section/card and passes the live state; the
/// tile reads no store, bridge or clock.
class NotificationPermissionTile extends StatelessWidget {
const NotificationPermissionTile({
super.key,
required this.state,
this.asked = false,
this.onRequest,
this.cupertino,
});
final NotificationPermissionState state;
/// Whether the operator has already been asked; only changes the wording.
final bool asked;
/// The explicit-gesture handler. Absent means no action is drawn even when a
/// request would be possible.
final VoidCallback? onRequest;
/// Forces the native host in tests and fixtures; otherwise the ambient
/// [usesCupertinoHost] decides.
final bool? cupertino;
@override
Widget build(BuildContext context) {
final view = notificationPermissionView(state, asked: asked);
final native = cupertino ?? usesCupertinoHost(context);
final action = view.canRequest && onRequest != null
? _action(native, view.actionLabel!, onRequest!)
: null;
final bodyStyle = native
? CupertinoTheme.of(context).textTheme.textStyle.copyWith(
color: CupertinoColors.secondaryLabel.resolveFrom(context),
)
: Theme.of(context).textTheme.bodyMedium?.copyWith(
color: Theme.of(context).colorScheme.onSurfaceVariant,
);
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
native
? CupertinoListTile(
key: notificationTileKey,
leading: const Icon(CupertinoIcons.bell),
title: const Text(notificationSectionTitle),
)
: ListTile(
key: notificationTileKey,
leading: const Icon(Icons.notifications_outlined),
title: const Text(notificationSectionTitle),
),
Padding(
padding: const EdgeInsetsDirectional.fromSTEB(16, 0, 16, 12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(notificationRationale, style: bodyStyle),
const SizedBox(height: 8),
Semantics(
liveRegion: true,
child: Text(
view.body,
key: notificationStateKey,
style: bodyStyle,
),
),
// The action sits on its own row, as the browser's settings
// section does: a native button in a row's trailing slot would
// squeeze the section title to one character per line at large
// text, and its label is too long to share the row.
if (action != null) ...[
const SizedBox(height: 8),
Align(
alignment: AlignmentDirectional.centerStart,
child: action,
),
],
],
),
),
],
);
}
Widget _action(bool native, String label, VoidCallback onRequest) {
if (native) {
return CupertinoButton(
key: notificationEnableKey,
padding: EdgeInsets.zero,
onPressed: onRequest,
child: Text(label),
);
}
return TextButton(
key: notificationEnableKey,
onPressed: onRequest,
child: Text(label),
);
}
}