diff --git a/mobile/lib/features/channels/default_agent_launcher.dart b/mobile/lib/features/channels/default_agent_launcher.dart index 6461c2c482..c75cc4bba9 100644 --- a/mobile/lib/features/channels/default_agent_launcher.dart +++ b/mobile/lib/features/channels/default_agent_launcher.dart @@ -7,6 +7,8 @@ import 'package:flutter/services.dart'; import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; +import '../../shared/agents/owned_agent_directory.dart'; +import '../../shared/agents/remote_agents.dart'; import '../../shared/me/default_agent.dart'; import '../../shared/animated_avatar.dart'; import '../../shared/me/me_sync.dart'; @@ -17,6 +19,8 @@ import '../../shared/widgets/agent_navigation_icon.dart'; import '../../shared/widgets/avatar_image.dart'; import '../../shared/widgets/preset_agent_avatar.dart'; import '../../shared/widgets/navigation_button_surface.dart'; +import '../../shared/widgets/buzz_callout.dart'; +import 'first_agent_callout.dart'; import 'empty_bestie_avatar.dart'; import 'channel.dart'; import 'channel_detail_page.dart'; @@ -36,12 +40,36 @@ class DefaultAgentLauncher extends HookConsumerWidget { final profile = profiles[pubkey]; final opening = useState(false); final resolving = useState(false); + final remoteAgents = ref.watch(remoteAgentsEnabledProvider); + // Only someone with no agents at all is invited to make a first one. + // Cheap checks come first, so the rest are watched only when relevant. + final showCallout = + remoteAgents && + pubkey == null && + !preference.isLoading && + !preference.hasError && + !ref.watch(firstAgentCalloutSeenProvider) && + ref + .watch(ownedAgentDirectoryProvider) + .unwrapPrevious() + .value + ?.isEmpty == + true; useEffect(() { if (pubkey != null) { ref.read(userCacheProvider.notifier).preload([pubkey]); } + // Having a Bestie, however it was chosen, retires the tip for good. A + // failed read can still hold the previous community's Bestie, so only + // current data counts. + if (pubkey != null && + !preference.hasError && + remoteAgents && + !ref.read(firstAgentCalloutSeenProvider)) { + dismissFirstAgentCallout(ref); + } return null; - }, [pubkey]); + }, [pubkey, preference.hasError, remoteAgents]); final label = pubkey != null ? 'Chat with ${profile?.label ?? 'your Bestie'}' : preference.hasError @@ -61,6 +89,7 @@ class DefaultAgentLauncher extends HookConsumerWidget { return; } if (pubkey == null) { + if (remoteAgents) dismissFirstAgentCallout(ref); onChooseAgent(); return; } @@ -118,36 +147,53 @@ class DefaultAgentLauncher extends HookConsumerWidget { } } - return NavigationButtonSurface( - child: SizedBox.square( - dimension: 56, - child: IconButton( - tooltip: label, - padding: EdgeInsets.zero, - onPressed: opening.value || preference.isLoading ? null : open, - icon: ExcludeSemantics( - child: resolving.value - ? const SizedBox.square( - dimension: 22, - child: CircularProgressIndicator(strokeWidth: 2), - ) - : pubkey == null - ? preference.isLoading || preference.hasError - ? const AgentNavigationIcon(size: 24) - : const EmptyBestieAvatar() - : usesInsetAgentArtwork(profile?.avatarUrl) - ? PresetAgentAvatar( - imageUrl: profile!.avatarUrl!, - size: 47.88, - fallback: Center(child: Text(profile.initial)), - ) - : AvatarImage( - imageUrl: profile?.avatarUrl, - radius: 18, - isAgent: true, - backgroundColor: context.controlSurface, - fallback: Center(child: Text(profile?.initial ?? 'A')), - ), + return BuzzCallout( + message: 'Create your first agent', + visible: showCallout, + // Give people a moment with Home before inviting them. + delay: const Duration(seconds: 3), + onTap: open, + onDismiss: () => dismissFirstAgentCallout(ref), + artwork: [ + for (final character in emptyBestieCharacters.take(6)) + AvatarImageContent( + imageUrl: character.url, + preferThumbnail: true, + fit: BoxFit.contain, + fallback: const AgentNavigationIcon(size: 24), + ), + ], + child: NavigationButtonSurface( + child: SizedBox.square( + dimension: 56, + child: IconButton( + tooltip: label, + padding: EdgeInsets.zero, + onPressed: opening.value || preference.isLoading ? null : open, + icon: ExcludeSemantics( + child: resolving.value + ? const SizedBox.square( + dimension: 22, + child: CircularProgressIndicator(strokeWidth: 2), + ) + : pubkey == null + ? preference.isLoading || preference.hasError + ? const AgentNavigationIcon(size: 24) + : const EmptyBestieAvatar() + : usesInsetAgentArtwork(profile?.avatarUrl) + ? PresetAgentAvatar( + imageUrl: profile!.avatarUrl!, + size: 47.88, + fallback: Center(child: Text(profile.initial)), + ) + : AvatarImage( + imageUrl: profile?.avatarUrl, + radius: 18, + isAgent: true, + backgroundColor: context.controlSurface, + fallback: Center(child: Text(profile?.initial ?? 'A')), + ), + ), ), ), ), diff --git a/mobile/lib/features/channels/empty_bestie_avatar.dart b/mobile/lib/features/channels/empty_bestie_avatar.dart index daca2a0d93..6a0f3f5e4a 100644 --- a/mobile/lib/features/channels/empty_bestie_avatar.dart +++ b/mobile/lib/features/channels/empty_bestie_avatar.dart @@ -7,7 +7,8 @@ import '../../shared/agents/agent_avatar_catalog.dart'; import '../../shared/widgets/agent_navigation_icon.dart'; import '../../shared/widgets/avatar_image.dart'; -final _characters = [ +/// The agent pictures new people are invited with, in the order shown. +final emptyBestieCharacters = [ for (var i = 0; i < AgentAvatarPack.gloopies.indices.length; i++) for (final pack in [ AgentAvatarPack.fuzzies, @@ -33,16 +34,18 @@ class EmptyBestieAvatar extends HookWidget { useEffect(() { if (reducedMotion || !visible) return null; final timer = Timer.periodic(const Duration(seconds: 5), (_) { - index.value = (index.value + 1) % _characters.length; + index.value = (index.value + 1) % emptyBestieCharacters.length; }); return timer.cancel; }, [reducedMotion, visible]); - final character = _characters[index.value]; + final character = emptyBestieCharacters[index.value]; useEffect(() { var cancelled = false; if (visible && !reducedMotion) { final nextPoster = - _characters[(index.value + 1) % _characters.length].url; + emptyBestieCharacters[(index.value + 1) % + emptyBestieCharacters.length] + .url; // precacheImage reads inherited configuration; do so after hook setup. WidgetsBinding.instance.addPostFrameCallback((_) { if (cancelled || !context.mounted) return; diff --git a/mobile/lib/features/channels/first_agent_callout.dart b/mobile/lib/features/channels/first_agent_callout.dart new file mode 100644 index 0000000000..9d111d96f9 --- /dev/null +++ b/mobile/lib/features/channels/first_agent_callout.dart @@ -0,0 +1,34 @@ +import 'dart:async'; + +import 'package:hooks_riverpod/hooks_riverpod.dart'; + +import '../../shared/me/me_sync.dart'; +import '../../shared/theme/theme_provider.dart'; + +/// The first-agent tip is dismissed once per account and community. +String firstAgentCalloutKey(MeSync scope) => + 'buzz-first-agent-callout.v1:${Uri.encodeComponent(scope.community)}:' + '${scope.pubkey}'; + +/// Whether this account has already dismissed the tip in this community. +/// Without an identity there is nothing to scope it to, so it stays hidden. +final firstAgentCalloutSeenProvider = Provider.autoDispose((ref) { + final scope = ref.watch(meSyncProvider); + if (scope.config.nsec == null) return true; + return ref.watch(savedPrefsProvider).getBool(firstAgentCalloutKey(scope)) ?? + false; +}); + +/// Hides the tip for good. Preferences update in memory at once, so a failed +/// disk write only means the tip may return on the next launch. +void dismissFirstAgentCallout(WidgetRef ref) { + final scope = ref.read(meSyncProvider); + if (scope.config.nsec == null) return; + unawaited( + ref + .read(savedPrefsProvider) + .setBool(firstAgentCalloutKey(scope), true) + .catchError((Object _) => false), + ); + ref.invalidate(firstAgentCalloutSeenProvider); +} diff --git a/mobile/lib/shared/widgets/anchored_popover_menu.dart b/mobile/lib/shared/widgets/anchored_popover_menu.dart index 60fb9d55e7..55abd5615b 100644 --- a/mobile/lib/shared/widgets/anchored_popover_menu.dart +++ b/mobile/lib/shared/widgets/anchored_popover_menu.dart @@ -5,9 +5,11 @@ import 'package:flutter/material.dart'; import '../theme/theme.dart'; -const _popoverEnterDuration = Duration(milliseconds: 150); +/// How app popovers enter: a quick fade while scaling up from slightly small. +const appPopoverEnterDuration = Duration(milliseconds: 150); +const appPopoverEnterCurve = Curves.easeOutCubic; +const appPopoverStartScale = 0.96; const _popoverExitDuration = Duration(milliseconds: 110); -const _popoverStartScale = 0.96; /// Elevation shared by anchored menus and composer popover surfaces. const appPopoverElevation = 8.0; @@ -142,7 +144,7 @@ class _AnchoredPopoverRoute extends PopupRoute { @override Duration get transitionDuration => - reducedMotion ? Duration.zero : _popoverEnterDuration; + reducedMotion ? Duration.zero : appPopoverEnterDuration; @override Duration get reverseTransitionDuration => @@ -155,10 +157,10 @@ class _AnchoredPopoverRoute extends PopupRoute { Animation secondaryAnimation, ) { final curvedAnimation = animation.drive( - CurveTween(curve: Curves.easeOutCubic), + CurveTween(curve: appPopoverEnterCurve), ); final scaleAnimation = Tween( - begin: _popoverStartScale, + begin: appPopoverStartScale, end: 1, ).animate(curvedAnimation); final transformOrigin = switch (alignment) { diff --git a/mobile/lib/shared/widgets/buzz_callout.dart b/mobile/lib/shared/widgets/buzz_callout.dart new file mode 100644 index 0000000000..d5e7e341a4 --- /dev/null +++ b/mobile/lib/shared/widgets/buzz_callout.dart @@ -0,0 +1,375 @@ +import 'dart:async'; +import 'dart:math' as math; + +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter_hooks/flutter_hooks.dart'; + +import '../theme/buzz_icons.dart'; +import '../theme/theme.dart'; +import 'anchored_popover_menu.dart'; + +const _arrowHeight = Grid.xxs; +const _arrowWidth = Grid.xs; +const _targetGap = Grid.half; +const _cardMaxWidth = Grid.xxxl * 6; + +/// A non-blocking callout card that points down at [child] while [visible]. +/// +/// It floats above everything else on the current route without a scrim, so +/// the screen underneath stays usable, and hides while another route covers +/// this one. With a [delay], it waits that long on screen before popping up +/// from [child], and the wait restarts whenever it's covered. +/// +/// The card spans a phone, with [artwork] scattered around a centered +/// message. Tapping it calls [onTap]; only its close button, or a screen +/// reader's dismiss action, calls [onDismiss]. +class BuzzCallout extends HookWidget { + const BuzzCallout({ + required this.message, + required this.visible, + required this.onTap, + required this.onDismiss, + required this.child, + this.artwork = const [], + this.delay = Duration.zero, + super.key, + }); + + final String message; + final bool visible; + final VoidCallback onTap; + final VoidCallback onDismiss; + + /// Up to six pictures scattered around the card's edges. + final List artwork; + final Duration delay; + final Widget child; + + @override + Widget build(BuildContext context) { + final eligible = visible && (ModalRoute.of(context)?.isCurrent ?? true); + final waited = useState(false); + useEffect(() { + waited.value = false; + if (!eligible || delay == Duration.zero) return null; + return Timer(delay, () => waited.value = true).cancel; + }, [eligible, delay]); + final showing = eligible && (delay == Duration.zero || waited.value); + final reducedMotion = MediaQuery.disableAnimationsOf(context); + final entrance = useAnimationController(duration: appPopoverEnterDuration); + final controller = useMemoized(OverlayPortalController.new); + useEffect(() { + if (!showing) { + entrance.value = 0; + } else if (reducedMotion) { + entrance.value = 1; + } else { + unawaited(entrance.forward(from: 0)); + } + // The controller can't change during a build, so it follows a frame + // behind; the builder below hides the callout in the meantime. + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!context.mounted || showing == controller.isShowing) return; + showing ? controller.show() : controller.hide(); + }); + return null; + }, [showing]); + return OverlayPortal.overlayChildLayoutBuilder( + controller: controller, + overlayChildBuilder: (context, info) { + if (!showing) return const SizedBox.shrink(); + final target = MatrixUtils.transformRect( + info.childPaintTransform, + Offset.zero & info.childSize, + ); + final padding = MediaQuery.paddingOf(context); + final placement = _CalloutPlacement( + target: target, + margin: EdgeInsets.only( + left: padding.left + Grid.xs, + right: padding.right + Grid.xs, + top: padding.top + Grid.xs, + ), + color: _calloutColors(context).$1, + shadowColor: appPopoverShadowColor(context), + child: _Card( + message: message, + artwork: artwork, + onTap: onTap, + onDismiss: onDismiss, + ), + ); + // Pops up from the target: a fade and a short rise while scaling up + // around the arrow's tip. + return AnimatedBuilder( + animation: entrance, + builder: (context, placement) { + final t = appPopoverEnterCurve.transform(entrance.value); + return Opacity( + opacity: t, + child: Transform.translate( + offset: Offset(0, (1 - t) * Grid.xxs), + child: Transform.scale( + scale: appPopoverStartScale + (1 - appPopoverStartScale) * t, + alignment: Alignment.topLeft, + origin: Offset(target.center.dx, target.top), + child: placement, + ), + ), + ); + }, + child: placement, + ); + }, + child: child, + ); + } +} + +/// The callout's background and foreground. Inverse colors set it apart from +/// menus and the page; in dark mode, whose inverse is a flat light gray, it +/// uses the raised dark surface instead, as toasts do. +(Color, Color) _calloutColors(BuildContext context) { + final colors = context.colors; + return Theme.of(context).brightness == Brightness.dark + ? (colors.surfaceContainer, colors.onSurface) + : (colors.inverseSurface, colors.onInverseSurface); +} + +/// Where the card's artwork sits, after desktop's empty Agents tile: each +/// picture hangs partly off an edge, tilted, clear of the close button. The +/// message sits on top where they meet. +const _scatter = [ + (Alignment(-1.12, -1.3), -0.21), + (Alignment(-0.42, -1.45), 0.12), + (Alignment(-0.78, 1.4), -0.17), + (Alignment(0.12, 1.5), 0.08), + (Alignment(0.45, -1.4), -0.1), + (Alignment(1.12, 1.25), 0.21), +]; + +class _Card extends StatelessWidget { + const _Card({ + required this.message, + required this.artwork, + required this.onTap, + required this.onDismiss, + }); + + final String message; + final List artwork; + final VoidCallback onTap; + final VoidCallback onDismiss; + + @override + Widget build(BuildContext context) { + // Not a live region: it reappears on every return to Home, and would be + // announced each time. It stays in traversal with its actions. + return Semantics( + container: true, + button: true, + label: message, + onTap: onTap, + onDismiss: onDismiss, + child: GestureDetector( + behavior: HitTestBehavior.opaque, + excludeFromSemantics: true, + onTap: onTap, + child: ClipRRect( + borderRadius: BorderRadius.circular(Radii.popover), + child: Stack( + children: [ + for (final (index, picture) + in artwork.take(_scatter.length).indexed) + Positioned.fill( + child: Align( + alignment: _scatter[index].$1, + child: Transform.rotate( + angle: _scatter[index].$2, + child: SizedBox.square( + dimension: Grid.xxxl, + child: ExcludeSemantics(child: picture), + ), + ), + ), + ), + // The message sets the card's height, keeping a close-button + // row above it at any text size. Where large text outgrows the + // room above the target, it scrolls instead of clipping. The + // card itself carries the message for screen readers. + ExcludeSemantics( + child: SingleChildScrollView( + primary: false, + padding: const EdgeInsets.symmetric( + horizontal: Grid.xs, + vertical: Grid.xxl, + ), + child: Center( + heightFactor: 1, + child: Text( + message, + textAlign: TextAlign.center, + style: context.textTheme.titleLarge?.copyWith( + color: _calloutColors(context).$2, + ), + ), + ), + ), + ), + Positioned( + top: Grid.half, + right: Grid.half, + child: IconButton( + tooltip: 'Dismiss', + onPressed: onDismiss, + color: _calloutColors(context).$2, + icon: const Icon(BuzzIcons.x), + ), + ), + ], + ), + ), + ), + ); + } +} + +/// Fills the overlay, placing its child above [target] inside [margin] and +/// painting one surface for the bubble and its arrow. Only the bubble is +/// hit-testable, so the rest of the screen keeps receiving touches. +class _CalloutPlacement extends SingleChildRenderObjectWidget { + const _CalloutPlacement({ + required this.target, + required this.margin, + required this.color, + required this.shadowColor, + required super.child, + }); + + final Rect target; + final EdgeInsets margin; + final Color color; + final Color shadowColor; + + @override + _RenderCalloutPlacement createRenderObject(BuildContext context) => + _RenderCalloutPlacement(target, margin, color, shadowColor); + + @override + void updateRenderObject( + BuildContext context, + _RenderCalloutPlacement renderObject, + ) { + renderObject + ..target = target + ..margin = margin + ..color = color + ..shadowColor = shadowColor; + } +} + +class _RenderCalloutPlacement extends RenderShiftedBox { + _RenderCalloutPlacement( + this._target, + this._margin, + this._color, + this._shadowColor, + ) : super(null); + + Rect _target; + set target(Rect value) { + if (value == _target) return; + _target = value; + markNeedsLayout(); + } + + EdgeInsets _margin; + set margin(EdgeInsets value) { + if (value == _margin) return; + _margin = value; + markNeedsLayout(); + } + + Color _color; + set color(Color value) { + if (value == _color) return; + _color = value; + markNeedsPaint(); + } + + Color _shadowColor; + set shadowColor(Color value) { + if (value == _shadowColor) return; + _shadowColor = value; + markNeedsPaint(); + } + + Path _path = Path(); + + @override + void performLayout() { + size = constraints.biggest; + final child = this.child; + if (child == null) return; + final bottom = _target.top - _targetGap - _arrowHeight; + final room = math.max(0.0, size.width - _margin.horizontal); + // The card spans a phone; on wider screens it stays phone-sized. + final width = math.min(room, _cardMaxWidth); + child.layout( + BoxConstraints( + minWidth: width, + maxWidth: width, + maxHeight: math.max(0, bottom - _margin.top), + ), + parentUsesSize: true, + ); + final left = (_target.center.dx - child.size.width / 2) + .clamp( + _margin.left, + math.max(_margin.left, size.width - _margin.right - child.size.width), + ) + .toDouble(); + final offset = Offset(left, bottom - child.size.height); + (child.parentData! as BoxParentData).offset = offset; + + final bubble = offset & child.size; + final radius = math.min(Radii.popover, bubble.shortestSide / 2); + // Keep the arrow's base clear of the rounded corners. + final arrowX = _target.center.dx + .clamp( + bubble.left + radius + _arrowWidth / 2, + math.max( + bubble.left + radius + _arrowWidth / 2, + bubble.right - radius - _arrowWidth / 2, + ), + ) + .toDouble(); + // One outline, so the shadow doesn't cross where the arrow joins. + _path = Path.combine( + PathOperation.union, + Path() + ..addRRect(RRect.fromRectAndRadius(bubble, Radius.circular(radius))), + Path()..addPolygon([ + Offset(arrowX - _arrowWidth / 2, bubble.bottom - 1), + Offset(arrowX, bubble.bottom + _arrowHeight), + Offset(arrowX + _arrowWidth / 2, bubble.bottom - 1), + ], true), + ); + } + + @override + void paint(PaintingContext context, Offset offset) { + final child = this.child; + if (child == null) return; + final path = _path.shift(offset); + final canvas = context.canvas; + canvas.drawShadow(path, _shadowColor, appPopoverElevation, _color.a < 1); + canvas.drawPath(path, Paint()..color = _color); + super.paint(context, offset); + } + + @override + bool hitTest(BoxHitTestResult result, {required Offset position}) => + hitTestChildren(result, position: position); +} diff --git a/mobile/test/features/agents/agents_sheet_test.dart b/mobile/test/features/agents/agents_sheet_test.dart index 521b99af4c..044ff982b1 100644 --- a/mobile/test/features/agents/agents_sheet_test.dart +++ b/mobile/test/features/agents/agents_sheet_test.dart @@ -3,6 +3,7 @@ import 'package:buzz/shared/widgets/app_list_card.dart'; import 'package:buzz/shared/agents/remote_agents.dart'; import 'package:buzz/shared/me/me_sync.dart'; import 'package:buzz/shared/me/default_agent.dart'; +import 'package:buzz/shared/theme/theme_provider.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:buzz/features/channels/default_agent_launcher.dart'; import 'package:buzz/features/agents/agents_page.dart'; @@ -11,6 +12,7 @@ import 'package:buzz/features/profile/user_profile_sheet.dart'; import 'package:flutter/material.dart'; import 'package:buzz/features/home/home_page.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; import 'agents_harness.dart'; import '../../helpers/remote_agents_fixture.dart'; @@ -37,7 +39,12 @@ void main() { addTearDown(tester.view.resetDevicePixelRatio); addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue); final h = await AgentsHarness.create(); - await h.open(tester, directory: [existing, otherAgentKeys.public]); + final prefs = await SharedPreferences.getInstance(); + await h.open( + tester, + directory: [existing, otherAgentKeys.public], + overrides: [savedPrefsProvider.overrideWithValue(prefs)], + ); expect(find.byKey(ValueKey(otherAgentKeys.public)), findsNothing); expect(find.byKey(ValueKey(oldAppAgentKeys.public)), findsNothing); if (!supportsRemoteAgents(h.community)) { @@ -270,6 +277,7 @@ void main() { await h.open( tester, directory: [existing], + overrides: [savedPrefsProvider.overrideWithValue(prefs)], home: HomePage( onAgents: showAgents, defaultAgentBuilder: (context) => DefaultAgentLauncher( diff --git a/mobile/test/features/channels/default_agent_launcher_test.dart b/mobile/test/features/channels/default_agent_launcher_test.dart index bf5904f375..eed8736cc1 100644 --- a/mobile/test/features/channels/default_agent_launcher_test.dart +++ b/mobile/test/features/channels/default_agent_launcher_test.dart @@ -1,6 +1,8 @@ import 'dart:async'; import 'package:buzz/features/channels/default_agent_launcher.dart'; +import 'package:buzz/features/channels/first_agent_callout.dart'; +import 'package:buzz/shared/agents/remote_agents.dart'; import 'package:buzz/shared/me/default_agent.dart'; import 'package:buzz/shared/me/default_agent_writer.dart'; import 'package:buzz/shared/me/me_sync.dart'; @@ -10,6 +12,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:nostr/nostr.dart' as nostr; +import 'package:shared_preferences/shared_preferences.dart'; import '../../shared/me/me_sync_test.dart' show FakeRelay; @@ -37,10 +40,14 @@ void main() { final pending = Completer>(); relayB.pendingRead = pending.future; var choices = 0; + SharedPreferences.setMockInitialValues({}); + final prefs = await SharedPreferences.getInstance(); Widget app(MeSync scope) => ProviderScope( overrides: [ + savedPrefsProvider.overrideWithValue(prefs), meSyncProvider.overrideWithValue(scope), relaySessionProvider.overrideWith(() => relayA), + remoteAgentsEnabledProvider.overrideWithValue(true), ], child: MaterialApp( theme: AppTheme.light(), @@ -63,8 +70,17 @@ void main() { await tester.pumpAndSettle(); expect(choices, 0); expect(relayB.writes, 0); - pending.complete([]); + // A failed read can keep A's Bestie as B's value. That must not retire + // the first-agent card in B, which has no Bestie. + pending.completeError(StateError('offline')); await tester.pumpAndSettle(); + expect(container.read(defaultAgentProvider).hasError, isTrue); + expect(prefs.getBool(firstAgentCalloutKey(b)), isNot(true)); + relayB.pendingRead = null; + await tester.tap(button); + await tester.pumpAndSettle(); + expect(choices, 0); + expect(prefs.getBool(firstAgentCalloutKey(b)), isNot(true)); await tester.tap(button); expect(choices, 1); expect(tester.takeException(), isNull); diff --git a/mobile/test/features/channels/first_agent_callout_test.dart b/mobile/test/features/channels/first_agent_callout_test.dart new file mode 100644 index 0000000000..01d77786e3 --- /dev/null +++ b/mobile/test/features/channels/first_agent_callout_test.dart @@ -0,0 +1,307 @@ +import 'dart:async'; +import 'dart:ui' show SemanticsAction; + +import 'package:buzz/features/channels/default_agent_launcher.dart'; +import 'package:buzz/features/channels/first_agent_callout.dart'; +import 'package:buzz/shared/agents/owned_agent_directory.dart'; +import 'package:buzz/shared/agents/remote_agents.dart'; +import 'package:buzz/shared/me/default_agent.dart'; +import 'package:buzz/shared/me/me_sync.dart'; +import 'package:buzz/shared/relay/relay.dart'; +import 'package:buzz/shared/theme/theme.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:hooks_riverpod/hooks_riverpod.dart'; +import 'package:nostr/nostr.dart' as nostr; +import 'package:shared_preferences/shared_preferences.dart'; + +import '../../shared/me/me_sync_test.dart' show FakeRelay; + +const _card = 'Create your first agent'; +const _delay = Duration(seconds: 3); + +void main() { + final nsec = nostr.Nip19.encode( + prefix: nostr.Nip19Prefix.nsec, + data: '0' * 63 + '1', + ); + late SharedPreferences prefs; + late StreamController bestie; + late int choices; + late int otherTaps; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + prefs = await SharedPreferences.getInstance(); + bestie = StreamController.broadcast(); + choices = 0; + otherTaps = 0; + }); + tearDown(() => bestie.close()); + + Future pumpHome( + WidgetTester tester, { + String community = 'https://a.test', + bool remoteAgents = true, + List owned = const [], + String? initialBestie, + bool reducedMotion = false, + bool waitForCard = true, + }) async { + final relay = FakeRelay(); + final scope = MeSync( + relay, + RelayConfig(baseUrl: community, nsec: nsec), + prefs: prefs, + ); + await tester.pumpWidget( + ProviderScope( + // A new key per call rebuilds the providers, like a fresh launch. + key: UniqueKey(), + overrides: [ + savedPrefsProvider.overrideWithValue(prefs), + meSyncProvider.overrideWithValue(scope), + relaySessionProvider.overrideWith(() => relay), + remoteAgentsEnabledProvider.overrideWithValue(remoteAgents), + ownedAgentDirectoryProvider.overrideWith((ref) async => owned), + defaultAgentProvider.overrideWith((ref) async* { + yield initialBestie; + yield* bestie.stream; + }), + ], + child: MaterialApp( + theme: AppTheme.light(), + builder: (context, child) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(disableAnimations: reducedMotion), + child: child!, + ), + home: Scaffold( + body: Center( + child: TextButton( + onPressed: () => otherTaps++, + child: const Text('Channel'), + ), + ), + bottomNavigationBar: Align( + alignment: Alignment.centerRight, + heightFactor: 1, + child: DefaultAgentLauncher(onChooseAgent: () => choices++), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + if (waitForCard) { + await tester.pump(_delay); + await tester.pumpAndSettle(); + } + } + + bool seen(String community) => + prefs.getBool( + firstAgentCalloutKey( + MeSync(FakeRelay(), RelayConfig(baseUrl: community, nsec: nsec)), + ), + ) == + true; + + testWidgets('shows above the empty Bestie slot without blocking Home', ( + tester, + ) async { + final semantics = tester.ensureSemantics(); + await pumpHome(tester); + expect(find.text(_card), findsOneWidget); + expect( + tester.getBottomLeft(find.text(_card)).dy, + lessThan(tester.getTopLeft(find.byTooltip('Bestie')).dy), + ); + expect( + tester.getSemantics(find.text(_card)), + matchesSemantics( + label: _card, + isButton: true, + hasDismissAction: true, + hasTapAction: true, + ), + ); + // The screen underneath still takes taps, and they leave the card up. + await tester.tap(find.text('Channel')); + await tester.pumpAndSettle(); + expect(otherTaps, 1); + expect(find.text(_card), findsOneWidget); + expect(seen('https://a.test'), isFalse); + semantics.dispose(); + }); + + testWidgets('activating the slot dismisses it and starts creation', ( + tester, + ) async { + await pumpHome(tester); + // Screen readers and keyboards activate the slot without a touch. + tester + .widget( + find.ancestor( + of: find.byTooltip('Bestie'), + matching: find.byType(IconButton), + ), + ) + .onPressed!(); + await tester.pumpAndSettle(); + expect(choices, 1); + expect(find.text(_card), findsNothing); + expect(seen('https://a.test'), isTrue); + }); + + testWidgets('tapping the card starts creation and retires it', ( + tester, + ) async { + await pumpHome(tester); + await tester.tap(find.text(_card)); + await tester.pumpAndSettle(); + expect(choices, 1); + expect(find.text(_card), findsNothing); + expect(seen('https://a.test'), isTrue); + }); + + testWidgets('the close button dismisses it without creating', (tester) async { + await pumpHome(tester); + await tester.tap(find.byTooltip('Dismiss')); + await tester.pumpAndSettle(); + expect(choices, 0); + expect(find.text(_card), findsNothing); + expect(seen('https://a.test'), isTrue); + }); + + testWidgets('a screen reader can dismiss it', (tester) async { + final semantics = tester.ensureSemantics(); + await pumpHome(tester); + tester.semantics.performAction( + find.semantics.byLabel(_card), + SemanticsAction.dismiss, + ); + await tester.pumpAndSettle(); + expect(find.text(_card), findsNothing); + expect(seen('https://a.test'), isTrue); + semantics.dispose(); + }); + + testWidgets('a Bestie retires it, even if the Bestie is later cleared', ( + tester, + ) async { + await pumpHome(tester); + expect(find.text(_card), findsOneWidget); + bestie.add('a' * 64); + await tester.pumpAndSettle(); + expect(find.text(_card), findsNothing); + expect(seen('https://a.test'), isTrue); + bestie.add(null); + await tester.pumpAndSettle(); + expect(find.text(_card), findsNothing); + }); + + testWidgets('once dismissed it never returns in that community', ( + tester, + ) async { + await pumpHome(tester); + await tester.tap(find.byTooltip('Dismiss')); + await tester.pumpAndSettle(); + await pumpHome(tester); + expect(find.text(_card), findsNothing); + // Another community is its own first run. + await pumpHome(tester, community: 'https://b.test'); + expect(find.text(_card), findsOneWidget); + }); + + testWidgets('stays hidden for anyone who already has agents', (tester) async { + await pumpHome(tester, owned: [OwnedAgentDirectoryEntry(pubkey: 'b' * 64)]); + expect(find.text(_card), findsNothing); + await pumpHome(tester, remoteAgents: false); + expect(find.text(_card), findsNothing); + // None of these count as dismissing it. + await pumpHome(tester); + expect(find.text(_card), findsOneWidget); + }); + + testWidgets('hides while anything covers Home, then returns', (tester) async { + await pumpHome(tester); + final navigator = tester.state(find.byType(Navigator)); + // A sheet leaves Home painted underneath, so only the route check hides + // the tip there. + unawaited( + showModalBottomSheet( + context: navigator.context, + builder: (_) => const Text('Sheet'), + ), + ); + await tester.pumpAndSettle(); + expect(find.text('Channel'), findsOneWidget); + expect(find.text(_card), findsNothing); + navigator.pop(); + await tester.pumpAndSettle(); + // Coming back restarts the wait. + expect(find.text(_card), findsNothing); + await tester.pump(_delay); + await tester.pumpAndSettle(); + expect(find.text(_card), findsOneWidget); + expect(seen('https://a.test'), isFalse); + }); + + testWidgets('waits three seconds on Home, then pops up', (tester) async { + await pumpHome(tester, waitForCard: false); + await tester.pump(_delay - const Duration(milliseconds: 100)); + expect(find.text(_card), findsNothing); + await tester.pump(const Duration(milliseconds: 100)); + await tester.pump(); + expect(find.text(_card), findsOneWidget); + // It starts faint and fades in. + expect(_opacity(tester), lessThan(1)); + await tester.pumpAndSettle(); + expect(_opacity(tester), 1); + }); + + testWidgets('with reduced motion it still waits, then appears at once', ( + tester, + ) async { + await pumpHome(tester, reducedMotion: true, waitForCard: false); + await tester.pump(_delay - const Duration(milliseconds: 100)); + expect(find.text(_card), findsNothing); + await tester.pump(const Duration(milliseconds: 100)); + await tester.pump(); + expect(find.text(_card), findsOneWidget); + expect(_opacity(tester), 1); + }); + + testWidgets('leaving Home during the wait keeps it from popping up', ( + tester, + ) async { + await pumpHome(tester, waitForCard: false); + await tester.pump(const Duration(seconds: 2)); + final navigator = tester.state(find.byType(Navigator)); + unawaited( + navigator.push( + MaterialPageRoute(builder: (_) => const Text('Elsewhere')), + ), + ); + await tester.pumpAndSettle(); + await tester.pump(_delay); + await tester.pumpAndSettle(); + expect(find.text(_card), findsNothing); + navigator.pop(); + await tester.pumpAndSettle(); + // Back on Home, the full wait starts over. + await tester.pump(const Duration(seconds: 2)); + expect(find.text(_card), findsNothing); + await tester.pump(const Duration(seconds: 1)); + await tester.pumpAndSettle(); + expect(find.text(_card), findsOneWidget); + }); +} + +double _opacity(WidgetTester tester) => tester + .widget( + find.ancestor(of: find.text(_card), matching: find.byType(Opacity)).first, + ) + .opacity; diff --git a/mobile/test/shared/widgets/buzz_callout_test.dart b/mobile/test/shared/widgets/buzz_callout_test.dart new file mode 100644 index 0000000000..c9bbf7d538 --- /dev/null +++ b/mobile/test/shared/widgets/buzz_callout_test.dart @@ -0,0 +1,154 @@ +import 'package:buzz/shared/theme/theme.dart'; +import 'package:buzz/shared/widgets/buzz_callout.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + Future pumpCard( + WidgetTester tester, { + required double width, + double height = 700, + String message = 'Make one', + double scale = 1, + VoidCallback? onTap, + VoidCallback? onDismiss, + VoidCallback? onPage, + }) async { + tester.view.physicalSize = Size(width, height); + tester.view.devicePixelRatio = 1; + tester.platformDispatcher.textScaleFactorTestValue = scale; + addTearDown(tester.view.reset); + addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue); + await tester.pumpWidget( + MaterialApp( + theme: AppTheme.light(), + home: Scaffold( + body: Stack( + children: [ + Center( + child: TextButton( + onPressed: onPage ?? () {}, + child: const Text('Page'), + ), + ), + Align( + alignment: Alignment.bottomRight, + child: BuzzCallout( + message: message, + visible: true, + onTap: onTap ?? () {}, + onDismiss: onDismiss ?? () {}, + artwork: const [Text('Art')], + child: const SizedBox.square( + key: Key('target'), + dimension: 56, + ), + ), + ), + ], + ), + ), + ), + ); + await tester.pumpAndSettle(); + final card = tester.getRect( + find.ancestor(of: find.text(message), matching: find.byType(Stack)).first, + ); + expect( + card.bottom, + lessThan(tester.getRect(find.byKey(const Key('target'))).top), + ); + return card; + } + + testWidgets('a card spans a phone between the margins', (tester) async { + final card = await pumpCard(tester, width: 320); + expect(card.left, Grid.xs); + expect(card.right, 320 - Grid.xs); + }); + + testWidgets('a card grows to fit large text below its close button', ( + tester, + ) async { + final card = await pumpCard(tester, width: 320, scale: 3); + final message = tester.getRect(find.text('Make one')); + final close = tester.getRect(find.byTooltip('Dismiss')); + expect(card.contains(message.topLeft), isTrue); + expect(card.contains(message.bottomRight), isTrue); + expect(message.top, greaterThanOrEqualTo(close.bottom)); + }); + + testWidgets('a card scrolls large text that outgrows a short screen', ( + tester, + ) async { + const message = 'Create your first agent'; + final card = await pumpCard( + tester, + width: 568, + height: 320, + message: message, + scale: 3, + ); + expect(tester.takeException(), isNull); + final close = tester.getRect(find.byTooltip('Dismiss')); + expect(card.contains(close.topLeft), isTrue); + expect(card.contains(close.bottomRight), isTrue); + final scrollable = find.descendant( + of: find.byType(BuzzCallout), + matching: find.byType(Scrollable), + ); + expect( + tester.state(scrollable).position.maxScrollExtent, + greaterThan(0), + ); + await tester.drag(scrollable, const Offset(0, -1000)); + await tester.pumpAndSettle(); + expect( + tester.getRect(find.text(message)).bottom, + lessThanOrEqualTo(card.bottom), + ); + }); + + testWidgets('a card stays phone-sized on a wide screen', (tester) async { + final card = await pumpCard(tester, width: 1024); + expect(card.width, Grid.xxxl * 6); + expect(card.right, lessThanOrEqualTo(1024 - Grid.xs)); + }); + + testWidgets('a card opens on tap and closes only from its close button', ( + tester, + ) async { + var taps = 0; + var dismissals = 0; + var pageTaps = 0; + await pumpCard( + tester, + width: 390, + onTap: () => taps++, + onDismiss: () => dismissals++, + onPage: () => pageTaps++, + ); + expect(find.text('Art'), findsOneWidget); + final semantics = tester.ensureSemantics(); + // The close button stays its own control inside the tappable card. + expect( + tester.getSemantics(find.byTooltip('Dismiss')), + matchesSemantics( + tooltip: 'Dismiss', + isButton: true, + hasTapAction: true, + hasEnabledState: true, + isEnabled: true, + isFocusable: true, + hasFocusAction: true, + ), + ); + semantics.dispose(); + await tester.tap(find.text('Page')); + expect((pageTaps, taps, dismissals), (1, 0, 0)); + await tester.tap(find.text('Make one')); + expect((pageTaps, taps, dismissals), (1, 1, 0)); + await tester.tap(find.byTooltip('Dismiss')); + expect((pageTaps, taps, dismissals), (1, 1, 1)); + }); +}