Files
buzz/mobile/lib/features/activity/activity_page/inbox_row.dart
Logan Johnson 82656ffea0 fix(mobile): standardize public-key identity display on npub (#7493)
🤖

## Summary

In the mobile app, anyone who hasn't set a display name shows up as a
raw 64-character hex key (e.g. `3a5d4f9c…`) — unreadable, and
unrecognizable as the same identity across screens. Profile and Settings
also let you copy that raw hex. Nostr public keys have a standard
readable form — `npub1…`, the same encoding other Nostr apps and our
desktop app already display. This PR makes every mobile identity surface
render npub instead:

- **Unnamed people everywhere** — message and thread authors, reactions,
typing indicators, member lists, channel details, DM headers and tiles,
inbox, search, forum cards, Pulse notes and reply context, mention
suggestions, and invite rows — now show a compact npub label: first 8 +
last 4 characters of the full npub joined by an ellipsis
(`npub1abcd…wxyz`), the same truncation desktop uses. Previously these
showed truncated raw hex.
- **DM fallback avatars and blank names** — 1:1 DM tiles and headers key
their fallback avatar to the same non-self counterpart the label names,
including self-first participant order; a self-DM keeps its
hex-key-derived initial. Blank or whitespace-only display names fall
back to the compact npub instead of rendering empty, while nonblank
authored names render verbatim (padding included).
- **Profile sheet → "Copy public key"** now copies the full canonical
npub — never raw hex. When the identity string isn't a valid public key,
the copy tile is disabled, so a malformed key never reaches the
clipboard.
- **Settings → Identity (pubkey)** displays and copies the full npub; an
invalid identity reads "Identity unavailable" with copy disabled.
- **Invalid identities never leak truncated raw hex** into the UI
anywhere — they render a neutral "Unknown identity" label.
- **Unchanged on purpose:** display names and verified handles (NIP-05 —
the `name@domain` badge) still render as before. Unnamed avatars keep
distinct per-key initials, derived from the underlying hex key rather
than the npub — otherwise every unnamed key would render the same "N"
initial. Event IDs are not public keys, so they keep their hex
truncation (in Pulse's "Replying to", the parent author shows npub while
an event-id fallback still shows hex). The nevent share link, private
keys, and internal hex storage are untouched. Inputs that accept a key
(invite/member entry) accept both hex and npub and keep working in hex
internally.

### Related issue

N/A. Searched open issues/PRs for npub identity display on mobile —
closest related: none found. Desktop's parallel npub standardization
lives in the stacked desktop PRs (#7488 foundation, #7489 controls,
#7495 display surfaces); this is the independent mobile slice (based
directly on `main`, not on those branches).

### Testing

At exact head `5a620e420a1fd57d9d8011ac26434eed32fcf765` (base: `main`
`44316ff72`; 40 files, +1,345/−154):

- Full mobile suite: 2,098 tests passing (`cd mobile && flutter test`);
`flutter analyze` clean; `dart format --set-exit-if-changed .` clean —
the same checks CI runs.
- Widget/unit coverage at production seams: compact labels and hex-keyed
avatar initials for DM headers/tiles, member rows, mention suggestions,
and Pulse reply context; DM fallback avatars keyed to the labeled
counterpart (self-first order and self-DMs); blank/whitespace
display-name npub fallback with nonblank authored labels verbatim,
including the Activity inbox sender and profile-sheet heading (each with
its own empty/whitespace production-seam regression); full-npub copy and
disabled-copy semantics in profile and settings; invalid-key
suppression; and hex↔npub input round-trips.

Verified via unit and widget tests — no device/simulator validation is
claimed.

### Task provenance

Buzz channel: `1f0e4a3d-7e01-4efe-bb16-843b357f85c9`

Task:
buzz://message?channel=1f0e4a3d-7e01-4efe-bb16-843b357f85c9&id=86b34eb4bd84a1472419e9af22636c011c0fe273e3c196f967d7a36996e149b6

---------

Signed-off-by: Logan Johnson <loganj@squareup.com>
Co-authored-by: Larry <627498bd4bd1f281a16431e3c6cce3b5c25b6692798c78672298aefbf2f8f8b5@buzz.block.builderlab.xyz>
2026-09-09 14:08:24 -04:00

490 lines
19 KiB
Dart

part of '../activity_page.dart';
const _inboxSwipeActionInset = Grid.half;
const _inboxSwipeActionLabelMinWidth = Grid.xxl;
const _inboxSwipeLabelRevealWidth =
_inboxSwipeActionLabelMinWidth + (_inboxSwipeActionInset * 2);
/// "New" boundary between unread and previously read rows.
class _NewBoundaryDivider extends StatelessWidget {
const _NewBoundaryDivider();
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(
horizontal: Grid.gutter,
vertical: Grid.half,
),
child: Row(
children: [
Expanded(
child: Divider(color: context.colors.error.withValues(alpha: 0.5)),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: Grid.xxs),
child: Text(
'New',
style: context.textTheme.labelSmall?.copyWith(
color: context.colors.error,
fontWeight: FontWeight.w600,
),
),
),
Expanded(
child: Divider(color: context.colors.error.withValues(alpha: 0.5)),
),
],
),
);
}
}
/// One conversation row, matching desktop's inbox item hierarchy:
/// avatar | sender + unread dot + time | contextual label | preview.
///
/// Swiping left reveals the row's read-state action. Opening remains a tap or
/// long-press action, so the swipe has one clear, easily recoverable outcome.
class _InboxRow extends HookConsumerWidget {
final InboxItem item;
final Channel? channel;
final String? currentPubkey;
final bool isDone;
final VoidCallback onTap;
final VoidCallback onMarkRead;
final VoidCallback onMarkUnread;
const _InboxRow({
super.key,
required this.item,
required this.channel,
required this.currentPubkey,
required this.isDone,
required this.onTap,
required this.onMarkRead,
required this.onMarkUnread,
});
@override
Widget build(BuildContext context, WidgetRef ref) {
const restingRevealWidth = 132.0;
const commitThreshold = 0.58;
final revealAmount = useState(0.0);
final isDragging = useState(false);
final labelHapticFired = useRef(false);
final senderPubkey = item.item.pubkey.toLowerCase();
final mentionPubkeys = mentionedPubkeysFromTags(item.item.tags);
final relevantPubkeys = {senderPubkey, ...mentionPubkeys};
final profiles = <String, UserProfile?>{
for (final pubkey in relevantPubkeys)
pubkey: ref.watch(userCacheProvider.select((cache) => cache[pubkey])),
};
final profile = profiles[senderPubkey];
// The shared label contract: blank cached names (empty or whitespace-only
// are relay-valid) fall back to the compact npub, never a blank sender.
final senderLabel = profile?.label ?? shortPubkey(item.item.pubkey);
final profileMentionNames = {
for (final pubkey in mentionPubkeys)
if (profiles[pubkey]?.displayName?.trim().isNotEmpty == true)
pubkey: profiles[pubkey]!.displayName!.trim(),
};
final knownAgentPubkeys = channel == null
? ref.watch(knownAgentPubkeysProvider)
: ref.watch(agentMentionPubkeysProvider(channel!.id));
final isAgent =
knownAgentPubkeys.contains(senderPubkey) ||
profile?.ownerPubkey != null;
final agentMentionPubkeys = agentPubkeysWithProfileOwners(
knownAgentPubkeys: knownAgentPubkeys,
profileOwnedAgentPubkeys: [
for (final pubkey in mentionPubkeys)
if (profiles[pubkey]?.ownerPubkey != null) pubkey,
],
);
final mentionNames = mentionNamesWithDirectoryLabels(
mentionPubkeys: mentionPubkeys,
profileMentionNames: profileMentionNames,
directoryDisplayNames: ref.watch(agentDirectoryDisplayNamesProvider),
agentMentionPubkeys: agentMentionPubkeys,
);
final isDm = channel?.isDm ?? false;
final channelName = channel != null && !isDm
? (channel!.name.isNotEmpty ? channel!.name : null)
: null;
final label = inboxTypeLabel(
item,
channelName: channelName,
isDm: isDm,
senderLabel: senderLabel,
);
final mutedColor = context.colors.onSurfaceVariant;
final labelColor = item.isActionRequired && !isDone
? context.colors.tertiary
: mutedColor;
final reducedMotion = MediaQuery.of(context).disableAnimations;
final swipeDirection = Directionality.of(context) == TextDirection.ltr
? 1.0
: -1.0;
void closeActions() => revealAmount.value = 0;
void toggleReadState() {
closeActions();
isDone ? onMarkUnread() : onMarkRead();
}
return LayoutBuilder(
builder: (context, constraints) {
final actionExtent = constraints.maxWidth;
final revealedWidth = revealAmount.value
.clamp(0, actionExtent)
.toDouble();
final actionColor = isDone
? context.colors.primary
: context.appColors.success;
return ClipRect(
child: Stack(
children: [
if (revealedWidth > 0)
PositionedDirectional(
top: 0,
end: 0,
bottom: 0,
width: revealedWidth,
child: Padding(
key: ValueKey('inbox-swipe-background-${item.id}'),
padding: const EdgeInsets.all(_inboxSwipeActionInset),
child: _InboxSwipeAction(
key: ValueKey('inbox-swipe-read-${item.id}'),
color: actionColor,
foregroundColor: contrastForeground(actionColor),
icon: isDone ? LucideIcons.mail : LucideIcons.mailOpen,
label: isDone ? 'Mark unread' : 'Mark as read',
onTap: toggleReadState,
),
),
),
AnimatedSlide(
offset: Offset(
-swipeDirection * revealAmount.value / constraints.maxWidth,
0,
),
duration: reducedMotion || isDragging.value
? Duration.zero
: const Duration(milliseconds: 160),
curve: Curves.easeOutCubic,
child: GestureDetector(
behavior: HitTestBehavior.opaque,
onHorizontalDragStart: (_) {
isDragging.value = true;
labelHapticFired.value = false;
},
onHorizontalDragUpdate: (details) {
isDragging.value = true;
final previous = revealAmount.value;
final next =
(previous - (details.delta.dx * swipeDirection))
.clamp(0, actionExtent)
.toDouble();
if (!labelHapticFired.value &&
previous < _inboxSwipeLabelRevealWidth &&
next >= _inboxSwipeLabelRevealWidth) {
labelHapticFired.value = true;
unawaited(HapticFeedback.selectionClick());
}
revealAmount.value = next;
},
onHorizontalDragEnd: (details) {
isDragging.value = false;
final velocity = details.primaryVelocity ?? 0;
final shouldCommit =
(velocity * swipeDirection) < -900 ||
revealAmount.value >= actionExtent * commitThreshold;
if (shouldCommit) {
toggleReadState();
} else {
revealAmount.value =
(velocity * swipeDirection) < -200 ||
revealAmount.value >= restingRevealWidth / 2
? restingRevealWidth
: 0;
}
},
child: Material(
color: context.colors.surface,
child: InkWell(
key: ValueKey('inbox-row-${item.id}'),
onTap: onTap,
onLongPress: () => _showRowActions(context),
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: Grid.gutter,
vertical: Grid.twelve,
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_RowAvatar(
pubkey: item.item.pubkey,
profile: profile,
isAgent: isAgent,
),
const SizedBox(width: messageAvatarContentGap),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Sender + unread dot + timestamp.
Row(
children: [
Expanded(
child: MessageAuthorMeta(
displayName: senderLabel,
username: messageUsernameLabel(
profile,
),
timestamp: _inboxTimestamp(
item.latestActivityAt,
),
nameColor: context.colors.onSurface,
metadataColor: mutedColor,
nameStyle: activityUsernameTextStyle,
timestampStyle:
activityTimestampTextStyle,
displayNameKey: ValueKey(
'activity-author-${item.id}',
),
usernameKey: ValueKey(
'activity-username-${item.id}',
),
timestampKey: ValueKey(
'activity-timestamp-${item.id}',
),
),
),
if (!isDone) ...[
const SizedBox(width: Grid.xxs),
Container(
key: ValueKey(
'inbox-unread-dot-${item.id}',
),
width: 6,
height: 6,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: context.colors.primary,
),
),
],
],
),
const SizedBox(height: Grid.quarter),
// Contextual label: "Mentioned in #channel" etc.
Row(
children: [
Flexible(
child: Text(
label.text,
style: activityContextTextStyle
.copyWith(color: labelColor),
overflow: TextOverflow.ellipsis,
),
),
if (label.channelLabel != null) ...[
const SizedBox(width: Grid.half),
Flexible(
child: Container(
padding: const EdgeInsets.symmetric(
horizontal:
Grid.half + Grid.quarter,
vertical: Grid.quarter / 2,
),
decoration: BoxDecoration(
color: context
.colors
.surfaceContainerHighest,
borderRadius:
BorderRadius.circular(
Grid.half,
),
),
child: Text(
'#${label.channelLabel}',
style: activityContextTextStyle
.copyWith(color: mutedColor),
overflow: TextOverflow.ellipsis,
),
),
),
],
],
),
const SizedBox(height: Grid.half),
// Message preview.
MessageContent(
content: item.item.displayContent,
mentionNames: mentionNames,
agentMentionPubkeys: agentMentionPubkeys,
tags: item.item.tags,
maxLines: 2,
baseStyle: activityPreviewTextStyle
.copyWith(
color: context.colors.onSurface,
),
),
],
),
),
],
),
),
),
),
),
),
],
),
);
},
);
}
void _showRowActions(BuildContext context) {
showBuzzModalBottomSheet<void>(
context: context,
builder: (sheetContext) => SafeArea(
child: Padding(
padding: const EdgeInsets.fromLTRB(
Grid.gutter,
0,
Grid.gutter,
Grid.xs,
),
child: IconTheme.merge(
data: const IconThemeData(size: 18),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
ListTile(
leading: Icon(
isDone ? LucideIcons.mail : LucideIcons.mailOpen,
),
title: Text(isDone ? 'Mark unread' : 'Mark as read'),
onTap: () {
Navigator.of(sheetContext).pop();
isDone ? onMarkUnread() : onMarkRead();
},
),
ListTile(
leading: const Icon(LucideIcons.externalLink),
title: const Text('Open conversation'),
onTap: () {
Navigator.of(sheetContext).pop();
onTap();
},
),
],
),
),
),
),
);
}
}
class _InboxSwipeAction extends StatelessWidget {
final Color color;
final Color foregroundColor;
final IconData icon;
final String label;
final VoidCallback onTap;
const _InboxSwipeAction({
super.key,
required this.color,
required this.foregroundColor,
required this.icon,
required this.label,
required this.onTap,
});
@override
Widget build(BuildContext context) => Material(
color: color,
borderRadius: BorderRadius.circular(Radii.full),
clipBehavior: Clip.antiAlias,
child: InkWell(
onTap: onTap,
borderRadius: BorderRadius.circular(Radii.full),
child: Semantics(
button: true,
label: label,
child: LayoutBuilder(
builder: (context, constraints) {
if (constraints.maxWidth < Grid.lg) {
return const SizedBox.shrink();
}
final showLabel =
constraints.maxWidth >= _inboxSwipeActionLabelMinWidth;
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(icon, size: 18, color: foregroundColor),
if (showLabel) ...[
const SizedBox(height: Grid.quarter),
Padding(
padding: const EdgeInsets.symmetric(horizontal: Grid.xxs),
child: Text(
label,
maxLines: 2,
softWrap: true,
textAlign: TextAlign.center,
style: context.textTheme.labelSmall?.copyWith(
color: foregroundColor,
fontWeight: FontWeight.w600,
),
),
),
],
],
);
},
),
),
),
);
}
class _RowAvatar extends StatelessWidget {
final String pubkey;
final UserProfile? profile;
final bool isAgent;
const _RowAvatar({
required this.pubkey,
required this.profile,
required this.isAgent,
});
@override
Widget build(BuildContext context) {
final initial =
profile?.initial ?? (pubkey.isNotEmpty ? pubkey[0].toUpperCase() : '?');
return AvatarImage(
imageUrl: profile?.avatarUrl,
radius: activityAvatarSize / 2,
backgroundColor: context.colors.primaryContainer,
fallback: Text(
initial,
style: TextStyle(
fontSize: 14,
fontWeight: FontWeight.w600,
color: context.colors.onPrimaryContainer,
),
),
isAgent: isAgent,
);
}
}