Files
buzz/mobile/lib/features/channels/channels_page.dart
Tom Brow e1e1cd50ab fix(mobile): keep Home's header clean under sheets (#9152)
On iOS, opening a sheet over Home (for example a channel's long-press
actions) left a hard horizontal edge and a light glow band under the
filter chips. Home's header keeps a native UIKit soft-edge view behind
its Flutter controls, and the sheet's dim barrier doesn't composite
cleanly over it.

While another route covers Home, the header now switches to its Flutter
backdrop through the existing `FrostedAppBar.nativeViewSuppressed` hook,
the same mechanism other headers use while a backdrop covers them. Home
already hides its native bottom controls under the same condition.

| Before | After |
| --- | --- |
| <img alt="before"
src="https://github.com/user-attachments/assets/a5bf01da-4f88-4055-809d-e347b35408a9"
width="300"> | <img alt="after"
src="https://github.com/user-attachments/assets/6813bb27-9f76-45d5-81c3-b46d8e0df647"
width="300"> |

### Validation

- iPhone 17 Pro simulator (iOS 27), Builderlab test community:
reproduced the artifact on `main` with Home scrolled and the channel
actions sheet open, then confirmed it is gone with this change. Also
opened and dismissed the sheet repeatedly and checked the header before,
during and after.
- Transition timing, frame-stepped from simulator recordings of `main`
(top row of each strip) and this PR (bottom row) on the same Home state:
- The header and the bottom navigation controls switch on the same
frame. A modal sheet doesn't drive Home's secondary animation
(`MaterialPageRoute.canTransitionTo` is false for a sheet route), so the
bottom controls' `secondaryAnimation == 0` check reduces to the same
`isCurrent` gate the header uses.
- Known limitation: while the native header view is swapped out, the
header blanks for about 2 display frames as the sheet opens and about 3
as it closes (about 30 to 50 ms, seen as the missing chips below).
`main` has no blank frames but shows the hard edge.

  Opening:

<img alt="sheet open, main above PR"
src="https://github.com/user-attachments/assets/df8f04f2-da72-4889-b9c8-5c47596fe7e3"
width="900">

  Closing:

<img alt="sheet close, main above PR"
src="https://github.com/user-attachments/assets/aa234a82-773d-4c9f-bba4-469afd158de8"
width="900">
- Extended the iOS Home widget journey: the native header view is
removed while the channel actions sheet is open and restored after it is
dismissed. Without the fix, the journey fails.
- Full mobile Flutter suite passes.

buzz-review-completed

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Signed-off-by: Tom Brow <tomb@squareup.com>
Co-authored-by: Tom Brow <tomb@squareup.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 06:59:08 -08:00

882 lines
34 KiB
Dart
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import 'package:buzz/shared/widgets/feedback_snackbar.dart';
import 'channel_unread.dart';
import '../../shared/widgets/collapsible_section_body.dart';
import '../../shared/me/me_sync.dart';
import '../../shared/hosted/hosted_relay_auth.dart';
import '../../shared/hosted/organization_environment.dart';
import '../../shared/hosted/organization_sign_in.dart';
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:math' show max, min;
import 'dart:ui';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart' show ScrollCacheExtent;
import 'package:flutter/services.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:buzz/shared/theme/buzz_icons.dart';
import '../../shared/auth/auth.dart';
import '../../shared/community/community_icon_provider.dart';
import '../../shared/community/community_avatar.dart';
import '../../shared/community/community_grid.dart';
import '../../shared/community/community_grid_option.dart';
import '../../shared/community/community_grid_add.dart';
import '../../shared/community/paired_community_landing.dart';
import '../../shared/community/community_membership_provider.dart';
import '../../shared/widgets/app_list.dart';
import '../../shared/widgets/app_list_card.dart';
import '../../shared/widgets/app_list_card_item.dart';
import '../../shared/widgets/sheet_action_section.dart';
import '../../shared/relay/relay.dart';
import '../../shared/theme/theme.dart';
import '../../shared/widgets/avatar_image.dart';
import '../../shared/widgets/anchored_popover_menu.dart';
import '../../shared/widgets/bee_refresh_indicator.dart';
import '../../shared/widgets/buzz_loading_indicator.dart';
import '../../shared/widgets/buzz_setting_menu.dart';
import '../../shared/widgets/buzz_titled_sheet_layout.dart';
import '../../shared/widgets/ios_glass_navigation_action.dart';
import '../../shared/widgets/ios_glass_navigation_button.dart';
import '../../shared/widgets/frosted_app_bar.dart';
import '../../shared/widgets/frosted_scaffold.dart';
import '../../shared/widgets/modal_presentation.dart';
import '../../shared/widgets/confirmation_dialog.dart';
import '../../shared/widgets/skeleton.dart';
import '../profile/profile_provider.dart';
import '../profile/presence_cache_provider.dart';
import '../../shared/identity_names/identity_names_provider.dart';
import '../../shared/profile/user_cache_provider.dart';
import '../../onboarding_app_entry.dart';
import '../pairing/pairing_provider.dart';
import 'channel.dart';
import 'ios_create_channel_sheet.dart';
import 'ios_add_members_sheet.dart';
import 'channel_actions_sheet.dart';
import 'channel_detail_page.dart';
import 'channel_management_provider.dart';
import 'mentions/mention_candidates.dart';
import 'mentions/mention_candidates_provider.dart';
import 'mentions/mention_ranking.dart';
import 'mentions/stable_mention_rows.dart';
import 'dm_channel_labels.dart';
import 'ephemeral_channel_display.dart';
import 'channel_mutes/channel_mutes_provider.dart';
import 'channel_sections/channel_sections_provider.dart';
import 'channel_sections/channel_sections_storage.dart';
import 'channel_sort/channel_sort_provider.dart';
import 'channel_sort/channel_sort_storage.dart';
import 'channel_stars/channel_stars_provider.dart';
import 'channels_provider.dart';
import '../../shared/read_state/deferred_read_state_update.dart';
import '../../shared/read_state/read_state_provider.dart';
import '../../shared/read_state/read_state_time.dart';
part 'channels_page/body.dart';
part 'channels_page/sections.dart';
part 'channels_page/channel_tile.dart';
part 'channels_page/sheets.dart';
part 'channels_page/badges.dart';
part 'channels_page/skeleton.dart';
part 'channels_page/community.dart';
part 'channels_page/community_switcher.dart';
part 'channels_page/community_switcher_action.dart';
part 'channels_page/header_actions.dart';
enum _QuickAction { createChannel, newDm }
const double _kChannelSectionInset = Grid.gutter;
const double _kChannelLeadingWidth = 24.0;
const double _kChannelIconSize = 20.0;
const double _kChannelLabelGap = Grid.inventoryLabelGap;
const double _kChannelRowVerticalPadding = Grid.inventoryRowInset;
// Keep section controls at a full touch target without adding a second row
// of vertical padding around their quiet desktop-style label.
const double _kSectionHeaderVerticalPadding = 0;
const double _kChannelLabelInset = _kChannelSectionInset;
/// Compact avatars remain on direct-message rows.
const double _kDmAvatarSize = _kChannelIconSize;
const double _kTopSectionProfileAvatarSize = 36.0;
const double _kTopSectionBottomPadding = Grid.xxs;
/// Inset for the community and profile avatar row.
const double _kTopSectionInset = Grid.twelve;
const double _kHeaderFrostScrollDistance = Grid.xxl;
class ChannelsPage extends HookConsumerWidget {
const ChannelsPage({
required this.settingsPageBuilder,
this.onSearch,
this.messagesFilters,
this.messagesActionsBuilder,
this.messagesActionsWidth = 0,
this.soloSliver,
this.showTeam = true,
this.showTeamHeading = false,
this.newChannelAction,
this.newDmAction,
this.onInbox,
this.communityInvitePageBuilder,
this.communityAppearancePageBuilder,
required this.onSettingsTransitionProgress,
this.tabReselection,
super.key,
});
final WidgetBuilder settingsPageBuilder;
final Widget Function(bool isCollapsed)? messagesFilters;
final List<Widget> Function(VoidCallback openSwitcher, GlobalKey avatarKey)?
messagesActionsBuilder;
/// Width of the trailing controls that collapsed filters must leave clear.
final double messagesActionsWidth;
final Widget? soloSliver;
final bool showTeam;
final bool showTeamHeading;
final ValueNotifier<VoidCallback?>? newChannelAction;
final ValueNotifier<VoidCallback?>? newDmAction;
/// Opens global search from the header.
final VoidCallback? onSearch;
/// Opens the conversation inbox above the channel sections.
final VoidCallback? onInbox;
/// Builds the invite destination opened from the community sheet.
final WidgetBuilder? communityInvitePageBuilder;
/// Builds the appearance destination opened from the community sheet.
final WidgetBuilder? communityAppearancePageBuilder;
/// Reports Settings route progress so its foreground and Home's background
/// render from the same timeline.
final ValueChanged<double> onSettingsTransitionProgress;
/// Notifies this page when its already-selected tab is tapped again.
final ValueListenable<int>? tabReselection;
@override
Widget build(BuildContext context, WidgetRef ref) {
// Resolve permissions before the community menu is opened.
if (communityInvitePageBuilder != null) {
ref.watch(currentCommunityRoleProvider);
}
final channelsAsync = ref.watch(channelsProvider);
final sessionState = ref.watch(relaySessionProvider);
final currentPubkey = ref
.watch(profileProvider)
.whenData((value) => value?.pubkey)
.value;
final headerTitleStyle = context.textTheme.titleMedium?.copyWith(
fontSize: 22,
fontWeight: FontWeight.w600,
color: navigationPrimaryForeground(context),
);
final filterContentHeight = messagesFilters == null
? 0.0
: max(48.0, MediaQuery.textScalerOf(context).scale(16) * 1.4 + 16) +
Grid.xxs;
final topSectionHeight = frostedAppBarHeight(
context,
titleStyle: headerTitleStyle,
bottomHeight: messagesFilters == null
? _kTopSectionBottomPadding
: filterContentHeight,
useNativeNavigation: messagesFilters == null,
);
// A sheet's dim barrier can't composite over Home's native soft edge, so
// use the Flutter backdrop while another route covers this page.
final route = ModalRoute.of(context);
final headerNativeSuppressed = useValueNotifier(false);
headerNativeSuppressed.value =
messagesFilters != null && !(route?.isCurrent ?? true);
final communityAvatarKey = useMemoized(GlobalKey.new);
final nativeCommunityAvatarBounds = useRef<Rect?>(null);
final headerKey = useMemoized(GlobalKey.new);
final nativeHeaderReady = useRef(false);
final bodyReady = useRef(false);
final communityFlightActive = useState(false);
final channelsScrollController = useScrollController();
final reducedMotion = MediaQuery.disableAnimationsOf(context);
final headerFrostProgress = useState(0.0);
final headerCollapse = useState(0.0);
useEffect(
() {
void updateHeaderTreatment() {
final collapse =
messagesFilters == null || !channelsScrollController.hasClients
? 0.0
: channelsScrollController.offset
.clamp(0.0, filterContentHeight)
.toDouble();
if (headerCollapse.value != collapse) headerCollapse.value = collapse;
final nextProgress = !channelsScrollController.hasClients
? 0.0
: (channelsScrollController.offset / _kHeaderFrostScrollDistance)
.clamp(0.0, 1.0)
.toDouble();
if ((headerFrostProgress.value - nextProgress).abs() > 0.001) {
headerFrostProgress.value = nextProgress;
}
}
channelsScrollController.addListener(updateHeaderTreatment);
return () =>
channelsScrollController.removeListener(updateHeaderTreatment);
},
[channelsScrollController, messagesFilters != null, filterContentHeight],
);
useEffect(() {
final tabReselection = this.tabReselection;
if (tabReselection == null) return null;
void scrollToTop() {
if (!channelsScrollController.hasClients) return;
final position = channelsScrollController.position;
if (position.pixels <= position.minScrollExtent + 0.5) return;
if (reducedMotion) {
channelsScrollController.jumpTo(position.minScrollExtent);
return;
}
unawaited(
channelsScrollController.animateTo(
position.minScrollExtent,
duration: const Duration(milliseconds: 260),
curve: Curves.easeOutCubic,
),
);
}
tabReselection.addListener(scrollToTop);
return () => tabReselection.removeListener(scrollToTop);
}, [tabReselection, channelsScrollController, reducedMotion]);
// Cache the last successfully loaded channels so the UI never flashes
// back to a loading state when the provider rebuilds (e.g. reconnect).
// Clear the cache on community switch so we show a full loader instead of
// stale channels from the previous community. unwrapPrevious() ensures the
// selector sees null during loading (not the previous community's ID).
final activeCommunityId = ref.watch(
activeCommunityProvider.select((v) => v.unwrapPrevious().value?.id),
);
final cachedChannels = useRef<List<Channel>?>(null);
final lastCommunityId = useRef<String?>(null);
if (lastCommunityId.value != activeCommunityId) {
cachedChannels.value = null;
lastCommunityId.value = activeCommunityId;
}
if (channelsAsync.asData?.value case final data?) {
cachedChannels.value = data;
}
final soloViewer = ref.watch(myPubkeyProvider);
final personalIds =
ref.watch(meGroupsProvider).asData?.value.channels ?? const <String>[];
final channels = cachedChannels.value
?.where((channel) => !channel.isPersonalChat(soloViewer, personalIds))
.toList();
Future<void> openChannel(Channel channel) async {
if (!context.mounted) return;
await Navigator.of(context).push(
MaterialPageRoute<void>(
builder: (_) => ChannelDetailPage(
channel: channel,
placement: ChannelRoutePlacement.ordinary,
),
),
);
}
// Only surface fetch errors while the relay is stably connected. During a
// reconnect the session owns recovery, so a cancelled in-flight query must
// not turn into a manual Retry page.
final showError = useState(false);
final hasError = channelsAsync.hasError && channels == null;
final canSurfaceError =
hasError &&
sessionState.status != SessionStatus.connecting &&
sessionState.status != SessionStatus.reconnecting;
useEffect(() {
if (!canSurfaceError) {
showError.value = false;
return null;
}
final timer = Timer(const Duration(seconds: 2), () {
showError.value = true;
});
return timer.cancel;
}, [canSurfaceError]);
Rect? measureCommunityAvatar() {
if (messagesFilters == null &&
defaultTargetPlatform == TargetPlatform.iOS) {
final header = headerKey.currentContext?.findRenderObject();
final bounds = nativeCommunityAvatarBounds.value;
return header is RenderBox && bounds != null
? MatrixUtils.transformRect(header.getTransformTo(null), bounds)
: null;
}
final avatar = communityAvatarKey.currentContext?.findRenderObject();
return avatar is RenderBox
? MatrixUtils.transformRect(
avatar.getTransformTo(null),
// The menu keeps a larger touch target around its 36dp avatar.
messagesFilters != null
? Rect.fromCenter(
center: avatar.size.center(Offset.zero),
width: 36,
height: 36,
)
: Offset.zero & avatar.size,
)
: null;
}
Future<Rect?> prepareCommunityLanding() async {
// The list snapshot precedes unread history and DM profile hydration.
// Both can still change weight, labels, and sorting behind the picker.
// A restored list is already usable offline. Refresh its unread state
// and participant profiles behind the page instead of gating navigation.
if (!ref.read(channelsProvider.notifier).hasCachedSnapshot) {
final channels = ref.read(channelsProvider).requireValue;
final dmPubkeys = {
for (final channel in channels)
if (channel.isMember && !channel.isArchived && channel.isDm)
...channel.participantPubkeys,
};
await Future.wait([
ref.read(channelsProvider.notifier).waitForUnreadCatchUp(),
if (dmPubkeys.isNotEmpty)
ref.read(userCacheProvider.notifier).preload(dmPubkeys.toList()),
]);
}
if (!context.mounted || !communityFlightActive.value) return null;
// Settle Home's scale and scroll while the loading backdrop is opaque.
onSettingsTransitionProgress(0);
if (channelsScrollController.hasClients) {
channelsScrollController.jumpTo(
channelsScrollController.position.minScrollExtent,
);
}
Rect? previous;
var stableFrames = 0;
while (context.mounted && communityFlightActive.value) {
await WidgetsBinding.instance.endOfFrame;
if (!context.mounted) return null;
final ready =
ref.read(_communityContentReadyProvider).value == true &&
bodyReady.value &&
(messagesFilters != null ||
defaultTargetPlatform != TargetPlatform.iOS ||
nativeHeaderReady.value);
final bounds = ready ? measureCommunityAvatar() : null;
stableFrames = ready && bounds == previous ? stableFrames + 1 : 0;
previous = bounds;
if (ready && stableFrames >= 2) return bounds;
}
return null;
}
final arrivingCommunity = ref.watch(pairedCommunityLandingProvider);
useEffect(() {
if (arrivingCommunity == null) return null;
var cancelled = false;
Future<void> revealPairedCommunity() async {
// Add-community pairing is a pushed route. Let it finish dismissing
// before placing the loading surface above the destination Home page.
do {
await WidgetsBinding.instance.endOfFrame;
if (cancelled || !context.mounted) return;
} while (ModalRoute.of(context)?.isCurrent == false);
if (ref.read(pairedCommunityLandingProvider)?.id !=
arrivingCommunity.id) {
return;
}
ref.read(pairedCommunityLandingProvider.notifier).clear();
communityFlightActive.value = true;
final completedPairing = ref.read(pairingProvider);
final navigator = Navigator.of(context, rootNavigator: true);
await navigator.push<void>(
PageRouteBuilder<void>(
opaque: false,
transitionDuration: Duration.zero,
reverseTransitionDuration: Duration.zero,
pageBuilder: (_, _, _) => CommunitySwitcherPage(
arrivingCommunity: arrivingCommunity,
destination: measureCommunityAvatar(),
prepareLanding: prepareCommunityLanding,
onFlightChanged: (flying) {
if (context.mounted) communityFlightActive.value = flying;
},
onTransitionProgress: onSettingsTransitionProgress,
),
),
);
if (context.mounted) {
communityFlightActive.value = false;
if (completedPairing.status == PairingStatus.success &&
identical(ref.read(pairingProvider), completedPairing)) {
ref.read(pairingProvider.notifier).reset();
}
}
}
unawaited(revealPairedCommunity());
return () => cancelled = true;
}, [arrivingCommunity]);
void openCommunityGrid() {
if (!context.mounted) return;
ref.invalidate(communityIconProvider);
final destination = measureCommunityAvatar();
late final _CommunitySwitcherRoute route;
route = _CommunitySwitcherRoute(
onTransitionProgress: onSettingsTransitionProgress,
builder: (_) => CommunitySwitcherPage(
destination: destination,
prepareLanding: prepareCommunityLanding,
onFlightChanged: (flying) {
route.flying = flying;
communityFlightActive.value = flying;
},
onTransitionProgress: onSettingsTransitionProgress,
),
);
Navigator.of(context).push(route).whenComplete(() {
if (context.mounted) communityFlightActive.value = false;
});
}
final showImportedCommunities = ref.watch(communityGridLandingProvider);
useEffect(() {
if (!showImportedCommunities) return null;
var cancelled = false;
Future<void> revealImportedCommunities() async {
// Let the hosted sheet and pushed Add route finish dismissing first.
do {
await WidgetsBinding.instance.endOfFrame;
if (cancelled || !context.mounted) return;
} while (ModalRoute.of(context)?.isCurrent == false);
if (!ref.read(communityGridLandingProvider)) return;
ref.read(communityGridLandingProvider.notifier).clear();
openCommunityGrid();
}
unawaited(revealImportedCommunities());
return () => cancelled = true;
}, [showImportedCommunities]);
void openCommunitySwitcher() {
// Freeze the menu shape for this presentation. If a cold permission
// lookup is still pending, the next opening uses its resolved result.
final role = ref.read(currentCommunityRoleProvider).unwrapPrevious();
final canInvite = role.hasError || canManageCommunityInvites(role.value);
unawaited(HapticFeedback.selectionClick());
showBuzzModalBottomSheet<void>(
context: context,
showCloseButton: false,
showDragHandle: true,
builder: (_) => _CommunityMenuSheet(
canInvite: canInvite,
onSwitchCommunity: openCommunityGrid,
invitePageBuilder: communityInvitePageBuilder,
appearancePageBuilder: communityAppearancePageBuilder,
),
);
}
final activeCommunity = ref
.watch(activeCommunityProvider)
.unwrapPrevious()
.value;
final communityRelay = activeCommunity?.relayUrl;
final communityAvatar = communityRelay == null
? null
: ref.watch(communityIconPresentationProvider(communityRelay));
final communityName = activeCommunity?.name.trim() ?? '';
final topSectionGradient = context.appColors.topSectionGradient;
final usesPinnedGradient = topSectionGradient != null;
Future<void> openCreateAction(_QuickAction action) async {
if (!kIsWeb && defaultTargetPlatform == TargetPlatform.iOS) {
Channel? channel;
try {
if (action == _QuickAction.createChannel) {
final actions = ref.read(channelActionsProvider);
channel = await IosCreateChannelSheet.present(
context: context,
onCreate:
({
required name,
required description,
required visibility,
required ttlSeconds,
}) => actions.createChannel(
name: name,
description: description,
visibility: visibility,
channelType: 'stream',
ttlSeconds: ttlSeconds,
),
);
} else {
channel = await showGeneralDialog<Channel>(
context: context,
barrierColor: Colors.transparent,
transitionDuration: Duration.zero,
pageBuilder: (_, _, _) => _NewDirectMessageSheet(
currentPubkey: currentPubkey,
nativePresentation: true,
),
);
}
if (channel != null && context.mounted) await openChannel(channel);
} on PlatformException catch (error) {
if (context.mounted) {
ScaffoldMessenger.of(context).showFeedbackSnackBar(
SnackBar(
content: Text(error.message ?? 'Couldn’t open the form'),
),
kind: ToastKind.error,
);
}
}
return;
}
final channel = await showBuzzModalBottomSheet<Channel>(
context: context,
showCloseButton: false,
constraints: _quickActionSheetConstraints(context),
isScrollControlled: true,
useSafeArea: true,
builder: (_) => SizedBox(
height: double.infinity,
child: action == _QuickAction.createChannel
? const _CreateChannelSheet()
: _NewDirectMessageSheet(currentPubkey: currentPubkey),
),
);
if (channel != null && context.mounted) await openChannel(channel);
}
Future<void> openCreateMenu() async {
final action = await showBuzzModalBottomSheet<_QuickAction>(
context: context,
title: 'Create',
builder: (sheetContext) => Padding(
padding: const EdgeInsets.symmetric(horizontal: Grid.gutter),
child: SheetActionSection(
children: [
ListTile(
leading: const Icon(BuzzIcons.hash),
title: const Text('New channel'),
onTap: () =>
Navigator.pop(sheetContext, _QuickAction.createChannel),
),
ListTile(
leading: const Icon(BuzzIcons.messageSquare),
title: const Text('New DM'),
onTap: () => Navigator.pop(sheetContext, _QuickAction.newDm),
),
],
),
),
);
if (action == null || !context.mounted) return;
await openCreateAction(action);
}
useEffect(() {
var active = true;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!active) return;
newChannelAction?.value = () =>
openCreateAction(_QuickAction.createChannel);
newDmAction?.value = () => openCreateAction(_QuickAction.newDm);
});
return () => active = false;
}, [newChannelAction, newDmAction, currentPubkey]);
return FrostedScaffold(
backgroundColor: usesPinnedGradient
? Colors.transparent
: context.colors.surface,
backgroundGradient: topSectionGradient,
appBar: FrostedAppBar(
key: headerKey,
onNativeReadyChanged: (ready) => nativeHeaderReady.value = ready,
nativeTitle: '',
useNativeNavigation: messagesFilters == null,
nativeViewSuppressed: headerNativeSuppressed,
nativeLeading: messagesFilters != null
? null
: IosNavigationAction(
label: 'Community settings',
onAvatarBoundsChanged: (bounds) {
final header = headerKey.currentContext?.findRenderObject();
if (header is RenderBox) {
// Store native coordinates, then apply the current Home transform
// when measuring the destination immediately before departure.
nativeCommunityAvatarBounds.value =
header.globalToLocal(bounds.topLeft) & bounds.size;
}
},
avatarHidden: communityFlightActive.value,
avatarIdentity: activeCommunity?.id,
symbol: 'building.2.crop.circle',
imageUrl: communityAvatar,
avatarInitial: communityName.isEmpty
? '?'
: communityName.substring(0, 1).toUpperCase(),
onPressed: openCommunitySwitcher,
),
nativeActions: messagesFilters != null
? const []
: [
if (onSearch != null)
IosNavigationAction(
label: 'Search',
symbol: 'magnifyingglass',
sharesBackground: false,
icon: BuzzIcons.search300,
onPressed: onSearch,
),
IosNavigationAction(
label: 'Create',
symbol: 'plus',
sharesBackground: false,
icon: BuzzIcons.plus,
children: [
IosNavigationAction(
label: 'New channel',
symbol: 'number',
onPressed: () =>
openCreateAction(_QuickAction.createChannel),
),
IosNavigationAction(
label: 'New DM',
symbol: 'bubble.left',
onPressed: () => openCreateAction(_QuickAction.newDm),
),
],
),
],
horizontalInset: _kTopSectionInset,
// Let the full Buzz gradient show at rest. Once the list begins to
// move beneath this row, build up blur over the first 64dp of scroll
// without adding the usual white frosted wash. The Buzz list is
// transparent, so the blurred pixels remain a continuation of the
// pinned gradient instead of turning into a white header.
frosted:
messagesFilters != null ||
!usesPinnedGradient ||
headerFrostProgress.value > 0,
alwaysFrosted: messagesFilters != null,
leading: messagesFilters != null
? null
: _CommunityIndicator(
onTap: openCommunitySwitcher,
avatarKey: communityAvatarKey,
hidden: communityFlightActive.value,
),
centerTitle: false,
titleStyle: headerTitleStyle,
automaticallyImplyLeading: messagesFilters == null,
title: messagesFilters == null
? const SizedBox.shrink()
: ExcludeSemantics(
excluding: headerCollapse.value >= filterContentHeight,
child: ShaderMask(
blendMode: BlendMode.dstIn,
shaderCallback: (bounds) => LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
headerCollapse.value == 0
? Colors.white
: Colors.transparent,
Colors.white,
],
stops: [
0,
(headerCollapse.value.clamp(0.0, Grid.sm) / bounds.height)
.clamp(0.0, 1.0),
],
).createShader(bounds),
// Keep the original upward motion, but fade the glyphs at
// status-area boundary instead of the text’s own tight bounds.
child: ClipRect(
child: Opacity(
opacity: 1 - headerCollapse.value / filterContentHeight,
child: SizedBox.expand(
child: Align(
alignment: Alignment.centerLeft,
child: Transform.translate(
offset: Offset(0, -headerCollapse.value),
child: Text('Messages', style: headerTitleStyle),
),
),
),
),
),
),
),
actions: messagesFilters != null
? messagesActionsBuilder?.call(
openCommunityGrid,
communityAvatarKey,
) ??
const []
: [
_ChannelHeaderActions(
onSearch: onSearch,
onCreate: openCreateMenu,
),
],
bottomHeight: messagesFilters == null
? _kTopSectionBottomPadding
: filterContentHeight - headerCollapse.value,
bottomOverlap: messagesFilters == null ? 0 : headerCollapse.value,
bottom: messagesFilters == null
? const SizedBox.expand()
: Padding(
padding: EdgeInsets.only(
// As soon as the rows overlap, keep the entire action
// cluster clear. Interpolating this inset blocks the bell
// during partial collapse even when the final layout fits.
right: headerCollapse.value > 0
? messagesActionsWidth + _kTopSectionInset
: 0,
),
child: ClipRect(
// Native glass paints its shadows outside the viewport, but
// scrolled filters must not paint over the header actions.
clipBehavior: headerCollapse.value > 0
? Clip.hardEdge
: Clip.none,
child: messagesFilters!(
headerCollapse.value >= filterContentHeight,
),
),
),
),
body: _ChannelsBody(
soloSliver: soloSliver,
showTeam: showTeam,
showTeamHeading: showTeamHeading,
onInbox: onInbox,
onReadyChanged: (ready) => bodyReady.value = ready,
channels: channels,
channelsAsync: channelsAsync,
showError: showError.value,
sessionStatus: sessionState.status,
currentPubkey: currentPubkey,
topSectionHeight: topSectionHeight,
usesPinnedGradient: usesPinnedGradient,
scrollController: channelsScrollController,
onRefresh: () {
// Solo has no banner, so pulling must also restart its reader.
if (soloSliver != null) ref.invalidate(meGroupsProvider);
return ref.read(channelsProvider.notifier).refresh();
},
onSelectChannel: openChannel,
),
);
}
}
/// Scale-and-fade route retained for the community switcher.
class _CommunitySurfaceRoute extends PageRouteBuilder<void> {
_CommunitySurfaceRoute({
required WidgetBuilder builder,
required this.onTransitionProgress,
bool? opaque,
}) : super(
pageBuilder: (context, animation, secondaryAnimation) =>
builder(context),
transitionsBuilder: _buildSettingsTransition,
// Stop compositing Home's UIKit controls once Settings has settled.
// Opaque routes still paint the previous page during both transitions.
opaque: opaque ?? defaultTargetPlatform == TargetPlatform.iOS,
allowSnapshotting: false,
transitionDuration: const Duration(milliseconds: 150),
reverseTransitionDuration: const Duration(milliseconds: 150),
);
final ValueChanged<double> onTransitionProgress;
Animation<double>? _progressAnimation;
bool _hasStartedForwardTransition = false;
@override
void install() {
super.install();
_progressAnimation = animation?..addListener(_reportProgress);
}
void _reportProgress() {
final progressAnimation = _progressAnimation;
if (progressAnimation == null) return;
// ProxyAnimation briefly exposes the previous completed value while the
// route installs its new controller. Ignore that handoff notification and
// begin reporting only once the route is genuinely moving forward.
if (!_hasStartedForwardTransition) {
if (progressAnimation.status != AnimationStatus.forward) return;
_hasStartedForwardTransition = true;
}
onTransitionProgress(progressAnimation.value);
}
@override
void dispose() {
_progressAnimation?.removeListener(_reportProgress);
super.dispose();
}
static Widget _buildSettingsTransition(
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
Widget child,
) {
if (MediaQuery.disableAnimationsOf(context)) return child;
final motion = CurvedAnimation(
parent: animation,
// Keep the complete page on one timeline. A gentler forward ease keeps
// the entrance visible without letting scale finish ahead of opacity;
// the existing reverse curve preserves the exit motion.
curve: Curves.easeOutQuad,
reverseCurve: Curves.easeOutCubic,
);
return FadeTransition(
key: const ValueKey('settings-transition-opacity'),
opacity: motion,
child: RepaintBoundary(
key: const ValueKey('settings-transition-layer'),
child: ScaleTransition(
key: const ValueKey('settings-transition-scale'),
scale: Tween<double>(begin: 1.04, end: 1).animate(motion),
alignment: Alignment.center,
child: child,
),
),
);
}
}
BoxConstraints _quickActionSheetConstraints(BuildContext context) {
final mediaQuery = MediaQuery.of(context);
return BoxConstraints(
maxHeight: mediaQuery.size.height - mediaQuery.viewPadding.top,
);
}