import 'dart:async'; import 'package:flutter/widgets.dart'; import '../../../core/api_gateway.dart'; import '../domain/attention_models.dart'; import '../runtime/attention_controller.dart'; import '../runtime/attention_store.dart'; import 'needs_you_bell.dart'; /// The `Needs you` bell as it appears in the Runs list heading. /// /// It owns the live attention state for this destination: [rows] are the /// already-loaded `list_runs` summaries and [frames] is the shared gateway's /// unsolicited stream, so it never polls or issues an attention request. The /// bell has no built-in host choice; the ambient app host (or [cupertino] in a /// fixture) selects the native Material or Cupertino action and sheet. class NeedsYouRunsHeading extends StatefulWidget { const NeedsYouRunsHeading({ super.key, required this.rows, required this.frames, required this.onOpen, this.syncToken = 0, this.store = const SharedPreferencesAttentionStore(), this.now, this.cupertino, }); /// The run summaries the Runs destination already holds. final List rows; /// The shared gateway's frames; only `run_event` envelopes are folded. final Stream frames; /// Opens an entry's run. A Failed entry is dismissed by the bell first. final ValueChanged onOpen; /// Advances when the shared socket is replaced. The detector rebaselines /// without replaying a transition that happened during the gap. final int syncToken; final AttentionStore store; /// Injected clock for deterministic local-day windows. final DateTime Function()? now; /// Forces the native host in tests and fixtures. final bool? cupertino; @override State createState() => _NeedsYouRunsHeadingState(); } class _NeedsYouRunsHeadingState extends State { late final AttentionController _attention = AttentionController( store: widget.store, now: widget.now, ); StreamSubscription? _frames; @override void initState() { super.initState(); _attention.seedRows(widget.rows); unawaited(_attention.load()); _listen(); } void _listen() { _frames = widget.frames .where((frame) => frame['type'] == 'run_event') .listen(_attention.observeFrame); } @override void didUpdateWidget(covariant NeedsYouRunsHeading oldWidget) { super.didUpdateWidget(oldWidget); if (!identical(oldWidget.frames, widget.frames)) { unawaited(_frames?.cancel()); _frames = null; _listen(); } if (oldWidget.syncToken != widget.syncToken) { _attention.resetForReconnect(); _attention.seedRows(widget.rows, reconnect: true); return; } if (!identical(oldWidget.rows, widget.rows)) { _attention.seedRows(widget.rows); } } @override void dispose() { unawaited(_frames?.cancel()); _attention.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return AnimatedBuilder( animation: _attention, builder: (context, _) => NeedsYouBell( entries: _attention.entries, cupertino: widget.cupertino, onOpen: widget.onOpen, onDismiss: (entry) { unawaited(_attention.dismiss(entry)); }, onClearAll: (snapshot) { unawaited(_attention.clearAll(snapshot)); }, ), ); } }