feat(app): add native Needs-you bell and sheet over the attention model

This commit is contained in:
2026-10-22 00:07:53 +01:00
parent 261d3a19c5
commit ee93d4f55b
15 changed files with 1952 additions and 0 deletions
@@ -0,0 +1,225 @@
import 'dart:math' as math;
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../ui/adaptive/host.dart';
import '../domain/attention_models.dart';
import 'needs_you_keys.dart';
import 'needs_you_sheet.dart';
/// The reusable `Needs you` bell and its native sheet.
///
/// The widget is told what needs the operator and what each action means; it
/// never reads a socket, a store or the clock. The bell is plain when [entries]
/// is empty and carries the count badge from [attentionBadgeLabel] otherwise.
/// Opening it draws the caller's live list; row and Clear-all callbacks only ever
/// name identities from the list the operator saw.
///
/// [onOpen] is also the caller's invitation to navigate: a Failed row is
/// dismissed first, because opening it is the operator dealing with it. A
/// Decision row is not dismissed here — only answering the decision clears it.
///
/// Pass a new list when the rows change; the bell keeps the list it was given
/// and only redraws an open sheet when the new list draws different rows.
///
/// On Material the action reserves its own end room for the count badge, so it
/// can be placed directly in [AppBar.actions]. The badge paints outside the
/// icon and grows with the text scale; the inset keeps it inside the viewport
/// at narrow widths and doubled text instead of handing a clipping trap to the
/// caller.
class NeedsYouBell extends StatefulWidget {
const NeedsYouBell({
super.key,
required this.entries,
required this.onOpen,
required this.onDismiss,
required this.onClearAll,
this.cupertino,
});
final List<AttentionEntry> entries;
final ValueChanged<AttentionEntry> onOpen;
final ValueChanged<AttentionEntry> onDismiss;
final ValueChanged<List<AttentionEntry>> onClearAll;
/// Forces the native host in tests and fixtures; otherwise the ambient
/// [usesCupertinoHost] decides.
final bool? cupertino;
@override
State<NeedsYouBell> createState() => _NeedsYouBellState();
}
class _NeedsYouBellState extends State<NeedsYouBell> {
/// End room the Material action reserves for the count badge.
///
/// `Badge` places its label 12 logical px past the icon and makes the stadium
/// at least as wide as it is tall, so the label grows with the text scale: at
/// 1x it ends inside the 48 px action, at 2x it reaches 8 logical px beyond it.
/// A Material app bar puts its last action flush at the trailing edge, so a
/// flush bell would have the badge sheared by the viewport at enlarged text.
/// The action reserves the label's own scaled height minus its built-in
/// offset, leaving a 16 logical px margin at every scale and keeping the bell
/// safe to place directly in `AppBar.actions`.
static double _materialBadgeEndRoom(BuildContext context) {
final badgeLabel = MediaQuery.textScalerOf(context).scale(16);
return math.max(8, badgeLabel - 8);
}
/// The live rows the open sheet draws. It changes with the caller's state, so
/// a dismissal redraws the sheet instead of leaving a stale row behind.
late final ValueNotifier<List<AttentionEntry>> _live;
final FocusNode _focus = FocusNode(debugLabel: 'NeedsYouBell');
/// True when the sheet went away because a row was chosen, so focus belongs
/// to whatever the caller opened rather than back on the bell.
bool _openedRun = false;
static List<AttentionEntry> _frozen(List<AttentionEntry> entries) =>
List<AttentionEntry>.unmodifiable(entries);
/// True when two lists would draw the same rows: the same identities in the
/// same order with the same text. A title edit or a new diagnostic keeps the
/// identity but changes what the sheet shows, so it must count as a change.
static bool _sameRows(
List<AttentionEntry> before,
List<AttentionEntry> after,
) {
if (before.length != after.length) return false;
for (var i = 0; i < before.length; i++) {
final previous = before[i];
final next = after[i];
if (previous.key != next.key ||
previous.label != next.label ||
attentionRowDescription(previous) != attentionRowDescription(next)) {
return false;
}
}
return true;
}
@override
void initState() {
super.initState();
_live = ValueNotifier<List<AttentionEntry>>(_frozen(widget.entries));
}
@override
void didUpdateWidget(covariant NeedsYouBell oldWidget) {
super.didUpdateWidget(oldWidget);
if (_sameRows(oldWidget.entries, widget.entries)) return;
final next = _frozen(widget.entries);
// The open sheet is another overlay subtree, not a child of this build, so
// handing it the new rows mid-build would mark it dirty outside the current
// build target. The rows are handed over once the frame is painted.
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) _live.value = next;
});
}
@override
void dispose() {
_live.dispose();
_focus.dispose();
super.dispose();
}
Future<void> _open() async {
_openedRun = false;
await showNeedsYouSheet(
context: context,
entries: _live,
onOpen: _activate,
onDismiss: widget.onDismiss,
onClearAll: widget.onClearAll,
cupertino: widget.cupertino,
);
if (!mounted || _openedRun) return;
// The browser returns focus to the bell after the sheet closes; do the same
// so keyboard and switch users are not dropped at the top of the page.
_focus.requestFocus();
}
void _activate(AttentionEntry entry) {
_openedRun = true;
if (entry.kind == AttentionKind.failed) widget.onDismiss(entry);
widget.onOpen(entry);
}
@override
Widget build(BuildContext context) {
final native = widget.cupertino ?? usesCupertinoHost(context);
final label = attentionBadgeLabel(widget.entries.length);
final action = native ? _cupertino(context) : _material(context, label);
final semantics = Semantics(
label: label,
button: true,
onTap: _open,
excludeSemantics: true,
child: action,
);
if (native) return semantics;
// The reserved badge room is outside the semantics box, so the focus
// rectangle stays the size of the action rather than the empty end room.
return Padding(
padding: EdgeInsetsDirectional.only(end: _materialBadgeEndRoom(context)),
child: semantics,
);
}
Widget _material(BuildContext context, String label) {
return IconButton(
key: attentionBellKey,
focusNode: _focus,
tooltip: label,
onPressed: _open,
icon: _badged(
context,
hostCupertino: false,
icon: const Icon(Icons.notifications_outlined),
),
);
}
Widget _cupertino(BuildContext context) {
final theme = CupertinoTheme.of(context);
return CupertinoButton(
key: attentionBellKey,
focusNode: _focus,
onPressed: _open,
child: _badged(
context,
hostCupertino: true,
icon: const Icon(CupertinoIcons.bell),
textStyle: theme.textTheme.tabLabelTextStyle,
),
);
}
Widget _badged(
BuildContext context, {
required bool hostCupertino,
required Widget icon,
TextStyle? textStyle,
}) {
final count = widget.entries.length;
// No native Cupertino badge exists; the framework Badge is used with the
// host's semantic red and the host's smallest text role.
if (hostCupertino && count > 0) {
return Badge.count(
key: attentionBadgeKey,
count: count,
textStyle: textStyle,
backgroundColor: CupertinoColors.systemRed.resolveFrom(context),
textColor: CupertinoColors.white,
child: icon,
);
}
if (count > 0) {
return Badge.count(key: attentionBadgeKey, count: count, child: icon);
}
return icon;
}
}
@@ -0,0 +1,36 @@
import '../domain/attention_models.dart';
/// The sheet's title and actions, matching the browser's `Needs you` surface.
const attentionSheetTitle = 'Needs you';
const attentionEmptyCopy = 'Nothing needs you right now.';
const attentionClearAllCopy = 'Clear all';
const attentionCloseCopy = 'Close';
/// One row's dismissal name.
///
/// The browser names every destructive control by the row it removes
/// (`Dismiss {label}`), so a sheet with two rows never exposes two identical
/// `Dismiss` actions to VoiceOver, TalkBack or voice control. A repeated label
/// also carries the run id, because the label alone would still be ambiguous.
String attentionDismissLabel(AttentionEntry entry, {bool repeated = false}) {
final label = 'Dismiss ${entry.label}';
return repeated ? '$label (run ${entry.runId})' : label;
}
/// The dismissal names for the rows of one open sheet, keyed by entry identity.
///
/// Only repeated labels get the run id, so the common case stays short and
/// readable, exactly as the browser's `labelCounts` decides.
Map<String, String> attentionDismissLabels(Iterable<AttentionEntry> entries) {
final counts = <String, int>{};
for (final entry in entries) {
counts.update(entry.label, (count) => count + 1, ifAbsent: () => 1);
}
return {
for (final entry in entries)
entry.key: attentionDismissLabel(
entry,
repeated: (counts[entry.label] ?? 0) > 1,
),
};
}
@@ -0,0 +1,24 @@
import 'package:flutter/widgets.dart';
/// The bell action that opens the `Needs you` sheet.
const attentionBellKey = ValueKey<String>('attention-bell');
/// The visible count badge. Absent when nothing needs the operator.
const attentionBadgeKey = ValueKey<String>('attention-badge');
/// The open sheet itself, whichever native host draws it.
const attentionSheetKey = ValueKey<String>('attention-sheet');
/// The honest empty line shown when the open snapshot has no entries.
const attentionEmptyKey = ValueKey<String>('attention-empty');
/// The bulk dismissal action, present only while the snapshot has entries.
const attentionClearAllKey = ValueKey<String>('attention-clear-all');
/// One row, keyed by the run+kind identity it shows.
ValueKey<String> attentionRowKey(String entryKey) =>
ValueKey<String>('attention-row-$entryKey');
/// The per-row dismissal action for one identity.
ValueKey<String> attentionDismissKey(String entryKey) =>
ValueKey<String>('attention-dismiss-$entryKey');
@@ -0,0 +1,57 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import '../../../ui/adaptive/host.dart';
import '../domain/attention_models.dart';
import 'needs_you_sheet_cupertino.dart';
import 'needs_you_sheet_material.dart';
/// Opens the native `Needs you` sheet over the live [entries].
///
/// [entries] is the caller's current list: the sheet redraws when it changes, so
/// dismissing a row updates the open sheet in place, as the browser does. The
/// dismissal snapshot is captured here, when the route opens; Clear all acts
/// only on it, so an entry that arrives while the sheet is open is shown but is
/// never silently cleared.
///
/// The sheet stays open after Dismiss and Clear all, so several rows can be
/// dealt with in one visit. Choosing a row closes it; Escape, the barrier and
/// system back are native route behaviour. The caller supplies the native host
/// explicitly when it already knows it; otherwise the ambient app host decides.
Future<void> showNeedsYouSheet({
required BuildContext context,
required ValueListenable<List<AttentionEntry>> entries,
required ValueChanged<AttentionEntry> onOpen,
required ValueChanged<AttentionEntry> onDismiss,
required ValueChanged<List<AttentionEntry>> onClearAll,
bool? cupertino,
}) {
final snapshot = attentionDismissalSnapshot(entries.value);
final native = cupertino ?? usesCupertinoHost(context);
if (native) {
return showCupertinoModalPopup<void>(
context: context,
builder: (_) => CupertinoNeedsYouSheet(
entries: entries,
snapshot: snapshot,
onOpen: onOpen,
onDismiss: onDismiss,
onClearAll: onClearAll,
),
);
}
return showModalBottomSheet<void>(
context: context,
isScrollControlled: true,
useSafeArea: true,
showDragHandle: true,
builder: (_) => MaterialNeedsYouSheet(
entries: entries,
snapshot: snapshot,
onOpen: onOpen,
onDismiss: onDismiss,
onClearAll: onClearAll,
),
);
}
@@ -0,0 +1,205 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import '../domain/attention_models.dart';
import 'needs_you_copy.dart';
import 'needs_you_keys.dart';
/// The Cupertino popup body of the `Needs you` surface.
///
/// It reads as a native action-sheet style grouped list: an inset-grouped iOS
/// list in a [CupertinoPopupSurface], with a Close action, one grouped row per
/// live entry and a separate Clear-all group. Dismissing and Clear all leave the
/// sheet open and redraw it, matching the browser; [snapshot] is the set Clear
/// all may remove, so a later arrival is shown but never cleared by this visit.
/// Rows use host text roles without a line cap so a long label and description
/// wrap at a narrow, scaled width.
class CupertinoNeedsYouSheet extends StatelessWidget {
const CupertinoNeedsYouSheet({
super.key,
required this.entries,
required this.snapshot,
required this.onOpen,
required this.onDismiss,
required this.onClearAll,
});
/// The caller's current rows; a dismissal removed there redraws the sheet.
final ValueListenable<List<AttentionEntry>> entries;
/// The identities captured when the sheet opened, all Clear all may remove.
final List<AttentionEntry> snapshot;
final ValueChanged<AttentionEntry> onOpen;
final ValueChanged<AttentionEntry> onDismiss;
final ValueChanged<List<AttentionEntry>> onClearAll;
void _close(BuildContext context) => Navigator.of(context).pop();
void _open(BuildContext context, AttentionEntry entry) {
_close(context);
onOpen(entry);
}
@override
Widget build(BuildContext context) {
return ValueListenableBuilder<List<AttentionEntry>>(
valueListenable: entries,
builder: (context, rows, _) => _sheet(context, rows),
);
}
Widget _sheet(BuildContext context, List<AttentionEntry> rows) {
final theme = CupertinoTheme.of(context);
final dismissLabels = attentionDismissLabels(rows);
return SafeArea(
key: attentionSheetKey,
top: false,
child: Padding(
padding: const EdgeInsets.all(8),
child: CupertinoPopupSurface(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(
padding: const EdgeInsetsDirectional.fromSTEB(20, 16, 8, 4),
child: Row(
children: [
Expanded(
child: Semantics(
header: true,
namesRoute: true,
child: Text(
attentionSheetTitle,
style: theme.textTheme.navTitleTextStyle,
),
),
),
CupertinoButton(
padding: EdgeInsets.zero,
onPressed: () => _close(context),
child: const Text(attentionCloseCopy),
),
],
),
),
if (rows.isEmpty)
Padding(
key: attentionEmptyKey,
padding: const EdgeInsetsDirectional.fromSTEB(20, 8, 20, 24),
child: Text(
attentionEmptyCopy,
style: theme.textTheme.textStyle.copyWith(
color: CupertinoColors.secondaryLabel.resolveFrom(
context,
),
),
),
)
else
Flexible(
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
CupertinoListSection.insetGrouped(
children: [
for (final entry in rows)
_AttentionRow(
key: attentionRowKey(entry.key),
entry: entry,
dismissLabel: dismissLabels[entry.key]!,
onOpen: () => _open(context, entry),
onDismiss: () => onDismiss(entry),
),
],
),
CupertinoListSection.insetGrouped(
children: [
CupertinoListTile(
key: attentionClearAllKey,
title: Center(child: Text(attentionClearAllCopy)),
onTap: () => onClearAll(snapshot),
),
],
),
],
),
),
),
],
),
),
),
);
}
}
/// One native grouped row: an open action over the host's text roles and a
/// separate Dismiss control named after the row it removes. It deliberately does
/// not use [CupertinoListTile], whose single-line title/subtitle would truncate a
/// long scaled label.
class _AttentionRow extends StatelessWidget {
const _AttentionRow({
super.key,
required this.entry,
required this.dismissLabel,
required this.onOpen,
required this.onDismiss,
});
final AttentionEntry entry;
final String dismissLabel;
final VoidCallback onOpen;
final VoidCallback onDismiss;
@override
Widget build(BuildContext context) {
final theme = CupertinoTheme.of(context);
final secondary = theme.textTheme.textStyle.copyWith(
color: CupertinoColors.secondaryLabel.resolveFrom(context),
);
return Padding(
padding: const EdgeInsetsDirectional.fromSTEB(16, 10, 8, 10),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.only(top: 4),
child: Icon(
entry.kind == AttentionKind.decision
? CupertinoIcons.time
: CupertinoIcons.exclamationmark_circle,
color: entry.kind == AttentionKind.decision
? CupertinoColors.systemOrange.resolveFrom(context)
: CupertinoColors.systemRed.resolveFrom(context),
),
),
const SizedBox(width: 12),
Expanded(
child: CupertinoButton(
padding: EdgeInsets.zero,
alignment: AlignmentDirectional.centerStart,
onPressed: onOpen,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(entry.label, style: theme.textTheme.textStyle),
const SizedBox(height: 4),
Text(attentionRowDescription(entry), style: secondary),
],
),
),
),
CupertinoButton(
key: attentionDismissKey(entry.key),
padding: EdgeInsets.zero,
onPressed: onDismiss,
child: Icon(CupertinoIcons.xmark, semanticLabel: dismissLabel),
),
],
),
);
}
}
@@ -0,0 +1,129 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import '../domain/attention_models.dart';
import 'needs_you_copy.dart';
import 'needs_you_keys.dart';
/// The Material bottom-sheet body of the `Needs you` surface.
///
/// It draws the live rows it is given: the pure model's order, one native
/// `ListTile` per entry, each row opening its run while its trailing control
/// dismisses only that identity. Dismissing and Clear all leave the sheet open
/// and redraw it, matching the browser; [snapshot] is the set Clear all may
/// remove, so a later arrival is shown but never cleared by this visit. The list
/// stays scrollable so a long label or a large text scale cannot push the
/// actions off the sheet.
class MaterialNeedsYouSheet extends StatelessWidget {
const MaterialNeedsYouSheet({
super.key,
required this.entries,
required this.snapshot,
required this.onOpen,
required this.onDismiss,
required this.onClearAll,
});
/// The caller's current rows; a dismissal removed there redraws the sheet.
final ValueListenable<List<AttentionEntry>> entries;
/// The identities captured when the sheet opened, all Clear all may remove.
final List<AttentionEntry> snapshot;
final ValueChanged<AttentionEntry> onOpen;
final ValueChanged<AttentionEntry> onDismiss;
final ValueChanged<List<AttentionEntry>> onClearAll;
void _open(BuildContext context, AttentionEntry entry) {
Navigator.of(context).pop();
onOpen(entry);
}
@override
Widget build(BuildContext context) {
return ValueListenableBuilder<List<AttentionEntry>>(
valueListenable: entries,
builder: (context, rows, _) => _sheet(context, rows),
);
}
Widget _sheet(BuildContext context, List<AttentionEntry> rows) {
final theme = Theme.of(context);
final dismissLabels = attentionDismissLabels(rows);
return SafeArea(
key: attentionSheetKey,
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(
padding: const EdgeInsetsDirectional.fromSTEB(24, 0, 12, 4),
child: Row(
children: [
Expanded(
child: Semantics(
header: true,
namesRoute: true,
child: Text(
attentionSheetTitle,
style: theme.textTheme.titleLarge,
),
),
),
if (rows.isNotEmpty)
TextButton(
key: attentionClearAllKey,
onPressed: () => onClearAll(snapshot),
child: const Text(attentionClearAllCopy),
),
],
),
),
if (rows.isEmpty)
Padding(
key: attentionEmptyKey,
padding: const EdgeInsetsDirectional.fromSTEB(24, 8, 24, 24),
child: Text(
attentionEmptyCopy,
style: theme.textTheme.bodyMedium?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
),
),
)
else
Flexible(
child: ListView.separated(
shrinkWrap: true,
padding: const EdgeInsets.only(bottom: 8),
itemCount: rows.length,
separatorBuilder: (_, _) => const Divider(height: 1),
itemBuilder: (context, index) {
final entry = rows[index];
return ListTile(
key: attentionRowKey(entry.key),
leading: Icon(
entry.kind == AttentionKind.decision
? Icons.hourglass_top
: Icons.error_outline,
color: entry.kind == AttentionKind.decision
? theme.colorScheme.primary
: theme.colorScheme.error,
),
title: Text(entry.label),
subtitle: Text(attentionRowDescription(entry)),
trailing: IconButton(
key: attentionDismissKey(entry.key),
tooltip: dismissLabels[entry.key],
onPressed: () => onDismiss(entry),
icon: const Icon(Icons.close),
),
onTap: () => _open(context, entry),
);
},
),
),
],
),
);
}
}