Merge pull request #673 from zjs81/cursor/fix-manual-path-builder-ux-63c1

Fix manual path builder search and keep hops visible
This commit is contained in:
zjs81 authored and GitHub committed 2026-11-21 07:38:55 -07:00
commit cd84855c15
51 files changed
+1545 -362

No files matched your search

+538 -171
View File
@@ -1,12 +1,17 @@
import 'dart:typed_data';
import 'dart:async';
import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../connector/meshcore_protocol.dart';
import '../helpers/path_helper.dart';
import '../l10n/contact_localization.dart';
import '../l10n/l10n.dart';
import '../models/contact.dart';
import '../theme/mesh_theme.dart';
import '../utils/contact_search.dart';
import 'mesh_ui.dart';
class PathEditorSheet extends StatefulWidget {
final List<Contact> availableContacts;
@@ -26,23 +31,28 @@ class PathEditorSheet extends StatefulWidget {
List<int> initialPath = const [],
int pathHashByteWidth = pathHashSize,
}) {
return showModalBottomSheet<Uint8List>(
context: context,
isScrollControlled: true,
useSafeArea: true,
builder: (context) => Padding(
padding: EdgeInsets.only(
bottom: MediaQuery.of(context).viewInsets.bottom,
),
child: FractionallySizedBox(
heightFactor: 0.9,
child: PathEditorSheet(
availableContacts: availableContacts,
initialPath: initialPath,
pathHashByteWidth: pathHashByteWidth,
),
),
),
// Same container as the other sheets: safe area on the top and sides,
// keyboard inset on the bottom, and the header at the top of the sheet.
// A fraction inside an expanding align left an empty band above the handle.
return showMeshSheet<Uint8List>(
context,
builder: (context) {
return LayoutBuilder(
builder: (context, constraints) {
final height = constraints.maxHeight.isFinite
? constraints.maxHeight
: MediaQuery.sizeOf(context).height;
return SizedBox(
height: height,
child: PathEditorSheet(
availableContacts: availableContacts,
initialPath: initialPath,
pathHashByteWidth: pathHashByteWidth,
),
);
},
);
},
);
}
@@ -62,10 +72,15 @@ class _PathEditorSheetState extends State<PathEditorSheet> {
final List<_Hop> _hops = [];
final _hexController = TextEditingController();
final _hexFocus = FocusNode();
final _searchFocus = FocusNode();
final _hopScroll = ScrollController();
String? _hexError;
bool _syncingHex = false;
String _search = '';
int _nextHopId = 0;
int? _highlightedHopId;
Timer? _highlightTimer;
@override
void initState() {
@@ -81,18 +96,27 @@ class _PathEditorSheetState extends State<PathEditorSheet> {
@override
void dispose() {
_highlightTimer?.cancel();
_hopScroll.dispose();
_hexFocus.dispose();
_searchFocus.dispose();
_hexController.dispose();
super.dispose();
}
int get _hashChars {
final width = widget.pathHashByteWidth.clamp(1, pubKeySize).toInt();
return width * 2;
}
List<Contact> get _repeaters {
final query = _search.trim().toLowerCase();
final query = _search.trim();
return widget.availableContacts
.where((c) => c.type == advTypeRepeater || c.type == advTypeRoom)
.where((c) => c.publicKey.isNotEmpty)
.where((c) => query.isEmpty || c.name.toLowerCase().contains(query))
.where((c) => rankContactQuery(c, query) != null)
.toList()
..sort((a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase()));
..sort((a, b) => compareContactQueryRank(a, b, query));
}
void _syncHexFromHops() {
@@ -129,6 +153,7 @@ class _PathEditorSheetState extends State<PathEditorSheet> {
return;
}
_hexError = null;
final previous = _hops.length;
_hops
..clear()
..addAll(
@@ -140,6 +165,9 @@ class _PathEditorSheetState extends State<PathEditorSheet> {
return _Hop(_nextHopId++, Uint8List.fromList(bytes));
}),
);
if (_hops.length > previous && _hops.isNotEmpty) {
_markHopAdded(_hops.last.id);
}
});
}
@@ -148,14 +176,38 @@ class _PathEditorSheetState extends State<PathEditorSheet> {
final width = widget.pathHashByteWidth
.clamp(1, contact.publicKey.length)
.toInt();
HapticFeedback.selectionClick();
setState(() {
_hops.add(
_Hop(
_nextHopId++,
Uint8List.fromList(contact.publicKey.sublist(0, width)),
),
final hop = _Hop(
_nextHopId++,
Uint8List.fromList(contact.publicKey.sublist(0, width)),
);
_hops.add(hop);
_syncHexFromHops();
_markHopAdded(hop.id);
});
}
void _markHopAdded(int id) {
_highlightedHopId = id;
_highlightTimer?.cancel();
_highlightTimer = Timer(const Duration(milliseconds: 1400), () {
if (!mounted) return;
setState(() {
if (_highlightedHopId == id) _highlightedHopId = null;
});
});
_revealLatestHop();
}
void _revealLatestHop() {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted || !_hopScroll.hasClients) return;
_hopScroll.animateTo(
_hopScroll.position.maxScrollExtent,
duration: const Duration(milliseconds: 180),
curve: Curves.easeOut,
);
});
}
@@ -182,7 +234,14 @@ class _PathEditorSheetState extends State<PathEditorSheet> {
Navigator.pop(context, Uint8List.fromList(bytes));
}
Widget _hopTile(BuildContext context, int index) {
String _contactHopHex(Contact contact) {
final width = widget.pathHashByteWidth
.clamp(1, contact.publicKey.length)
.toInt();
return PathHelper.formatHopHex(contact.publicKey.sublist(0, width));
}
Widget _hopTile(BuildContext context, int index, {required bool singleLine}) {
final l10n = context.l10n;
final scheme = Theme.of(context).colorScheme;
final hop = _hops[index];
@@ -200,41 +259,61 @@ class _PathEditorSheetState extends State<PathEditorSheet> {
: matches.length == 1
? matches.first.name
: matches.map((c) => c.name).join(' | ');
final highlighted = hop.id == _highlightedHopId;
return ListTile(
final label = name ?? l10n.pathEditor_unknownHop;
final hash = Text(hex, style: MeshTheme.mono(fontSize: 12));
return Material(
key: ValueKey(hop.id),
contentPadding: EdgeInsets.zero,
leading: CircleAvatar(
radius: 14,
backgroundColor: scheme.primaryContainer,
child: Text(
'${index + 1}',
style: TextStyle(fontSize: 12, color: scheme.onPrimaryContainer),
color: highlighted ? scheme.primaryContainer : scheme.surfaceContainerLow,
child: ListTile(
contentPadding: const EdgeInsets.symmetric(horizontal: 8),
visualDensity: singleLine
? VisualDensity.compact
: VisualDensity.standard,
minVerticalPadding: singleLine ? 0 : 4,
leading: CircleAvatar(
radius: 16,
backgroundColor: scheme.primary,
child: Text(
'${index + 1}',
style: TextStyle(fontSize: 12, color: scheme.onPrimary),
),
),
),
title: Text(
name ?? l10n.pathEditor_unknownHop,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
subtitle: Text(hex),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
IconButton(
icon: const Icon(Icons.remove_circle_outline),
tooltip: l10n.pathEditor_removeHop,
constraints: const BoxConstraints(minWidth: 44, minHeight: 44),
onPressed: () => _removeHop(index),
),
ReorderableDragStartListener(
index: index,
child: const Padding(
padding: EdgeInsets.symmetric(horizontal: 10, vertical: 12),
child: Icon(Icons.drag_handle),
title: singleLine
? Row(
children: [
Expanded(
child: Text(
label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
const SizedBox(width: 8),
hash,
],
)
: Text(label, maxLines: 1, overflow: TextOverflow.ellipsis),
subtitle: singleLine ? null : hash,
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
IconButton(
icon: const Icon(Icons.remove_circle_outline),
tooltip: l10n.pathEditor_removeHop,
onPressed: () => _removeHop(index),
),
),
],
ReorderableDragStartListener(
index: index,
child: const SizedBox(
width: 48,
height: 48,
child: Icon(Icons.drag_handle),
),
),
],
),
),
);
}
@@ -246,16 +325,16 @@ class _PathEditorSheetState extends State<PathEditorSheet> {
final full = _hops.length >= _maxHops;
return ListTile(
contentPadding: EdgeInsets.zero,
contentPadding: const EdgeInsets.symmetric(vertical: 4),
enabled: !full,
leading: CircleAvatar(
radius: 16,
radius: 18,
backgroundColor: isRepeater
? scheme.primaryContainer
: scheme.secondaryContainer,
child: Icon(
isRepeater ? Icons.router : Icons.meeting_room,
size: 16,
size: 18,
color: isRepeater
? scheme.onPrimaryContainer
: scheme.onSecondaryContainer,
@@ -263,127 +342,372 @@ class _PathEditorSheetState extends State<PathEditorSheet> {
),
title: Text(contact.name, maxLines: 1, overflow: TextOverflow.ellipsis),
subtitle: Text(
'${contact.typeLabel(l10n)} • ${PathHelper.formatHopHex(contact.publicKey.sublist(0, widget.pathHashByteWidth.clamp(1, contact.publicKey.length).toInt()))}',
'${contact.typeLabel(l10n)} • ${_contactHopHex(contact)}',
style: MeshTheme.mono(fontSize: 12),
),
trailing: Icon(
Icons.add_circle_outline,
color: full ? scheme.outline : scheme.primary,
),
trailing: const Icon(Icons.add_circle_outline),
onTap: full ? null : () => _addHop(contact),
);
}
/// Heights for the hop list, hex field, and search field inside the
/// measured band between the title and the action buttons.
///
/// An invalid hex path grows the error text. That growth comes out of the
/// hop viewport first, keeping one row when it fits. When even one hop row,
/// the hex field with any active error, and the search field cannot fit,
/// [scroll] switches the middle band to a single scroll view so nothing is
/// crushed or overflows and all controls stay reachable.
({double hop, double hex, double search, bool scroll}) _middleBudget(
double space,
bool compact,
) {
final scaler = MediaQuery.textScalerOf(context);
final row = compact
? scaler.scale(56).clamp(56.0, 96.0)
: scaler.scale(76).clamp(72.0, 140.0);
final minRepeater = compact ? 56.0 : 80.0;
final searchH = scaler.scale(compact ? 48 : 56) + 20;
final baseHex = scaler.scale(compact ? 48 : 64) + (compact ? 16 : 44);
final errorExtra = _hexError == null
? 0.0
: scaler.scale(compact ? 56 : 52);
final wantedHop = _hops.isEmpty
? math.min(scaler.scale(compact ? 64 : 80), 140.0)
: math.min(_hops.length, compact ? 2 : 3) * row + 4;
final wantedHex = baseHex + errorExtra;
final minHop = _hops.isEmpty ? 0.0 : row;
final scroll = minHop + wantedHex + searchH > space;
var hopH = wantedHop;
if (!scroll) {
final targetMax = math.max(
minHop + wantedHex + searchH,
space - minRepeater,
);
final used = hopH + wantedHex + searchH;
if (used > targetMax) {
hopH -= math.min(used - targetMax, math.max(0.0, hopH - minHop));
}
}
return (hop: hopH, hex: wantedHex, search: searchH, scroll: scroll);
}
Widget _hopViewport(bool compact, double height) {
final l10n = context.l10n;
final theme = Theme.of(context);
final scheme = theme.colorScheme;
return SizedBox(
height: height,
child: height < 8
? const SizedBox.shrink()
: Padding(
padding: const EdgeInsets.fromLTRB(16, 4, 16, 0),
child: DecoratedBox(
decoration: BoxDecoration(
color: scheme.surfaceContainerLow,
borderRadius: BorderRadius.circular(MeshRadii.md),
border: Border.all(color: scheme.outlineVariant),
),
child: _hops.isEmpty
? SingleChildScrollView(
padding: const EdgeInsets.all(12),
child: Text(
l10n.pathEditor_noHops,
style: theme.textTheme.bodyMedium?.copyWith(
color: scheme.onSurfaceVariant,
),
),
)
: ReorderableListView.builder(
scrollController: _hopScroll,
buildDefaultDragHandles: false,
padding: EdgeInsets.symmetric(
vertical: compact ? 0 : 4,
),
itemCount: _hops.length,
onReorderItem: _reorderHop,
itemBuilder: (context, index) =>
_hopTile(context, index, singleLine: compact),
),
),
),
);
}
Widget _hexViewport(bool compact, double height) {
final l10n = context.l10n;
final theme = Theme.of(context);
return SizedBox(
height: height,
child: SingleChildScrollView(
padding: EdgeInsets.fromLTRB(16, compact ? 6 : 12, 16, 0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (!compact) ...[
Text(
l10n.pathEditor_advancedHex,
style: theme.textTheme.titleSmall,
),
const SizedBox(height: 8),
],
TextField(
key: const Key('path-editor-hex-field'),
controller: _hexController,
focusNode: _hexFocus,
onChanged: _onHexChanged,
textCapitalization: TextCapitalization.characters,
style: MeshTheme.mono(fontSize: 14),
scrollPadding: EdgeInsets.zero,
decoration: InputDecoration(
labelText: l10n.pathEditor_hexLabel,
helperText: compact || _hexError != null
? null
: l10n.pathEditor_hexHelper(_hashChars),
helperMaxLines: 3,
errorText: _hexError,
errorMaxLines: compact ? 4 : 3,
border: const OutlineInputBorder(),
isDense: compact,
),
),
],
),
),
);
}
Widget _searchViewport(bool compact, double height) {
final l10n = context.l10n;
return SizedBox(
height: height,
child: Padding(
padding: EdgeInsets.fromLTRB(16, compact ? 6 : 12, 16, 0),
child: TextField(
key: const Key('path-editor-search-field'),
focusNode: _searchFocus,
onChanged: (value) => setState(() => _search = value),
scrollPadding: EdgeInsets.zero,
decoration: InputDecoration(
labelText: l10n.pathEditor_searchRepeaters,
prefixIcon: const Icon(Icons.search),
border: const OutlineInputBorder(),
isDense: compact,
),
),
),
);
}
Widget _repeaterViewport(List<Contact> repeaters) {
final l10n = context.l10n;
final theme = Theme.of(context);
final scheme = theme.colorScheme;
if (repeaters.isEmpty) {
return Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 8),
child: Align(
alignment: Alignment.topLeft,
child: Text(
l10n.path_noRepeatersFound,
style: theme.textTheme.bodyMedium?.copyWith(
color: scheme.onSurfaceVariant,
),
),
),
);
}
return ListView.builder(
key: const Key('path-editor-repeater-list'),
keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
padding: const EdgeInsets.fromLTRB(16, 8, 16, 8),
itemCount: repeaters.length,
itemBuilder: (context, index) => _repeaterTile(context, repeaters[index]),
);
}
List<Widget> _middleSlivers({
required bool compact,
required List<Contact> repeaters,
}) {
final l10n = context.l10n;
final theme = Theme.of(context);
final scheme = theme.colorScheme;
return [
SliverToBoxAdapter(child: _scrollHopBlock(compact)),
SliverToBoxAdapter(child: _scrollHexBlock(compact)),
SliverToBoxAdapter(child: _scrollSearchBlock(compact)),
if (repeaters.isEmpty)
SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 8),
child: Text(
l10n.path_noRepeatersFound,
style: theme.textTheme.bodyMedium?.copyWith(
color: scheme.onSurfaceVariant,
),
),
),
)
else
SliverPadding(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 8),
sliver: SliverList.builder(
key: const Key('path-editor-repeater-list'),
itemCount: repeaters.length,
itemBuilder: (context, index) =>
_repeaterTile(context, repeaters[index]),
),
),
];
}
/// One scrollable for the hop list, hex field, search field, and repeaters.
///
/// The blocks are intrinsic height with no nested scrolling, so a drag
/// anywhere in the band moves the search field and the repeater list into
/// view. The pinned layout keeps its own viewports.
Widget _scrollingMiddle({
required bool compact,
required List<Contact> repeaters,
}) {
return CustomScrollView(
key: const Key('path-editor-scroll-fallback'),
keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
slivers: _middleSlivers(compact: compact, repeaters: repeaters),
);
}
Widget _scrollHopBlock(bool compact) {
final l10n = context.l10n;
final theme = Theme.of(context);
final scheme = theme.colorScheme;
return Padding(
padding: const EdgeInsets.fromLTRB(16, 4, 16, 0),
child: DecoratedBox(
decoration: BoxDecoration(
color: scheme.surfaceContainerLow,
borderRadius: BorderRadius.circular(MeshRadii.md),
border: Border.all(color: scheme.outlineVariant),
),
child: _hops.isEmpty
? Padding(
padding: const EdgeInsets.all(12),
child: Text(
l10n.pathEditor_noHops,
style: theme.textTheme.bodyMedium?.copyWith(
color: scheme.onSurfaceVariant,
),
),
)
: ReorderableListView.builder(
scrollController: _hopScroll,
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
buildDefaultDragHandles: false,
padding: EdgeInsets.symmetric(vertical: compact ? 0 : 4),
itemCount: _hops.length,
onReorderItem: _reorderHop,
itemBuilder: (context, index) =>
_hopTile(context, index, singleLine: compact),
),
),
);
}
Widget _scrollHexBlock(bool compact) {
final l10n = context.l10n;
final theme = Theme.of(context);
return Padding(
padding: EdgeInsets.fromLTRB(16, compact ? 6 : 12, 16, 0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (!compact) ...[
Text(
l10n.pathEditor_advancedHex,
style: theme.textTheme.titleSmall,
),
const SizedBox(height: 8),
],
TextField(
key: const Key('path-editor-hex-field'),
controller: _hexController,
focusNode: _hexFocus,
onChanged: _onHexChanged,
textCapitalization: TextCapitalization.characters,
style: MeshTheme.mono(fontSize: 14),
scrollPadding: EdgeInsets.zero,
decoration: InputDecoration(
labelText: l10n.pathEditor_hexLabel,
helperText: compact || _hexError != null
? null
: l10n.pathEditor_hexHelper(_hashChars),
helperMaxLines: 3,
errorText: _hexError,
errorMaxLines: compact ? 4 : 3,
border: const OutlineInputBorder(),
isDense: compact,
),
),
],
),
);
}
Widget _scrollSearchBlock(bool compact) {
final l10n = context.l10n;
return Padding(
padding: EdgeInsets.fromLTRB(16, compact ? 6 : 12, 16, 0),
child: TextField(
key: const Key('path-editor-search-field'),
focusNode: _searchFocus,
onChanged: (value) => setState(() => _search = value),
scrollPadding: EdgeInsets.zero,
decoration: InputDecoration(
labelText: l10n.pathEditor_searchRepeaters,
prefixIcon: const Icon(Icons.search),
border: const OutlineInputBorder(),
isDense: compact,
),
),
);
}
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
final theme = Theme.of(context);
final scheme = theme.colorScheme;
final repeaters = _repeaters;
return Column(
children: [
const SizedBox(height: 8),
Container(
width: 32,
height: 4,
decoration: BoxDecoration(
color: scheme.outlineVariant,
borderRadius: BorderRadius.circular(2),
return LayoutBuilder(
builder: (context, constraints) {
final maxHeight = constraints.maxHeight.isFinite
? constraints.maxHeight
: 640.0;
// Phone sheets and a keyboard-shrunk window use the shorter hop rows
// so the action buttons stay below the repeater list.
final compact = maxHeight < 680;
final scaler = MediaQuery.textScalerOf(context);
final header = Semantics(
liveRegion: true,
child: BottomSheetHeader(
title: l10n.pathEditor_title,
subtitle: l10n.pathEditor_hopCounter(_hops.length),
),
),
Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(l10n.pathEditor_title, style: theme.textTheme.titleLarge),
Text(
l10n.pathEditor_hopCounter(_hops.length),
style: theme.textTheme.bodySmall?.copyWith(
color: scheme.onSurfaceVariant,
),
),
],
),
),
Expanded(
child: ListView(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 8),
children: [
if (_hops.isEmpty)
Padding(
padding: const EdgeInsets.symmetric(vertical: 12),
child: Text(
l10n.pathEditor_noHops,
style: theme.textTheme.bodySmall?.copyWith(
color: scheme.onSurfaceVariant,
),
),
)
else
ReorderableListView.builder(
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
buildDefaultDragHandles: false,
itemCount: _hops.length,
onReorderItem: _reorderHop,
itemBuilder: _hopTile,
),
const Divider(),
const SizedBox(height: 8),
Text(l10n.pathEditor_addHops, style: theme.textTheme.titleSmall),
const SizedBox(height: 8),
TextField(
onChanged: (value) => setState(() => _search = value),
decoration: InputDecoration(
labelText: l10n.pathEditor_searchRepeaters,
prefixIcon: const Icon(Icons.search),
border: const OutlineInputBorder(),
isDense: true,
),
),
const SizedBox(height: 4),
if (repeaters.isEmpty)
Padding(
padding: const EdgeInsets.symmetric(vertical: 12),
child: Text(
l10n.path_noRepeatersFound,
style: theme.textTheme.bodySmall?.copyWith(
color: scheme.onSurfaceVariant,
),
),
)
else
...repeaters.map((c) => _repeaterTile(context, c)),
ExpansionTile(
tilePadding: EdgeInsets.zero,
title: Text(
l10n.pathEditor_advancedHex,
style: theme.textTheme.titleSmall,
),
children: [
Padding(
padding: const EdgeInsets.only(bottom: 12),
child: TextField(
controller: _hexController,
onChanged: _onHexChanged,
textCapitalization: TextCapitalization.characters,
decoration: InputDecoration(
labelText: l10n.pathEditor_hexLabel,
helperText: _hexError == null
? l10n.pathEditor_hexHelper
: null,
errorText: _hexError,
border: const OutlineInputBorder(),
),
),
),
],
),
],
),
),
SafeArea(
);
final actions = SafeArea(
top: false,
child: Padding(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 16),
padding: EdgeInsets.fromLTRB(
16,
compact ? 4 : 8,
16,
compact ? 4 : 16,
),
child: Row(
children: [
Expanded(
@@ -408,8 +732,51 @@ class _PathEditorSheetState extends State<PathEditorSheet> {
],
),
),
),
],
);
// When scaled header and action buttons leave less than one row for
// the middle band, scroll the whole sheet so nothing clips or crowds
// the viewport.
if (maxHeight < scaler.scale(150) + 28) {
return CustomScrollView(
key: const Key('path-editor-scroll-fallback'),
keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
slivers: [
SliverToBoxAdapter(child: header),
..._middleSlivers(compact: compact, repeaters: repeaters),
SliverToBoxAdapter(child: actions),
],
);
}
return Column(
children: [
header,
Expanded(
child: LayoutBuilder(
builder: (context, inner) {
final budget = _middleBudget(inner.maxHeight, compact);
if (budget.scroll) {
return _scrollingMiddle(
compact: compact,
repeaters: repeaters,
);
}
return Column(
children: [
_hopViewport(compact, budget.hop),
_hexViewport(compact, budget.hex),
_searchViewport(compact, budget.search),
Expanded(child: _repeaterViewport(repeaters)),
],
);
},
),
),
actions,
],
);
},
);
}
}
+68 -43
View File
@@ -2,11 +2,13 @@ import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../connector/meshcore_connector.dart';
import '../connector/meshcore_protocol.dart';
import '../helpers/contact_share_message.dart';
import '../l10n/contact_localization.dart';
import '../l10n/l10n.dart';
import '../models/contact.dart';
import '../theme/mesh_theme.dart';
import '../utils/contact_search.dart';
import 'mesh_ui.dart';
/// Lets the user pick a saved contact (or themself) and appends the encoded
@@ -50,21 +52,19 @@ class _ShareContactSheetState extends State<_ShareContactSheet> {
final contacts =
connector.contacts
.where(
(c) =>
c.publicKey.length == 32 &&
(needle.isEmpty || c.name.toLowerCase().contains(needle)),
(c) => c.publicKey.length == 32 && matchesContactQuery(c, needle),
)
.toList()
..sort(
(a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase()),
);
..sort((a, b) => compareContactQueryRank(a, b, needle));
final selfName = connector.selfName ?? '';
final showSelf =
selfKey != null &&
selfKey.length == 32 &&
(needle.isEmpty ||
selfName.toLowerCase().contains(needle) ||
l10n.contactShare_myContact.toLowerCase().contains(needle));
final selfRank = selfKey != null && selfKey.length == 32
? rankLabeledKeyQuery(
name: selfName.isEmpty ? l10n.contactShare_myContact : selfName,
publicKeyHex: pubKeyToHex(selfKey),
query: needle,
aliases: [l10n.contactShare_myContact],
)
: null;
return SafeArea(
child: ConstrainedBox(
@@ -86,43 +86,68 @@ class _ShareContactSheetState extends State<_ShareContactSheet> {
onChanged: (value) => setState(() => _query = value),
),
),
Flexible(
child: ListView(
shrinkWrap: true,
children: [
if (showSelf)
_tile(
context,
name: selfName.isEmpty
? l10n.contactShare_myContact
: selfName,
subtitle: l10n.contactShare_myContact,
token: encodeContactShare(
publicKey: selfKey,
type: 1,
name: selfName,
),
),
for (final c in contacts) _contactTile(context, c),
if (!showSelf && contacts.isEmpty)
Padding(
padding: const EdgeInsets.all(24),
child: Center(
child: Text(
l10n.contactShare_noContacts,
style: const TextStyle(fontSize: 14),
),
),
),
],
),
),
Flexible(child: _shareList(context, contacts, selfRank)),
],
),
),
);
}
Widget _shareList(
BuildContext context,
List<Contact> contacts,
ContactQueryRank? selfRank,
) {
final l10n = context.l10n;
final connector = widget.connector;
final selfKey = connector.selfPublicKey;
final selfName = connector.selfName ?? '';
final rows =
<({int rank, String name, Widget tile})>[
for (final contact in contacts)
(
rank: rankContactQuery(contact, _query)?.index ?? 3,
name: contact.name.toLowerCase(),
tile: _contactTile(context, contact),
),
if (selfRank != null && selfKey != null)
(
rank: selfRank.index,
name: (selfName.isEmpty ? l10n.contactShare_myContact : selfName)
.toLowerCase(),
tile: _tile(
context,
name: selfName.isEmpty ? l10n.contactShare_myContact : selfName,
subtitle: l10n.contactShare_myContact,
token: encodeContactShare(
publicKey: selfKey,
type: 1,
name: selfName,
),
),
),
]..sort((a, b) {
final byRank = a.rank.compareTo(b.rank);
if (byRank != 0) return byRank;
return a.name.compareTo(b.name);
});
if (rows.isEmpty) {
return Padding(
padding: const EdgeInsets.all(24),
child: Center(
child: Text(
l10n.contactShare_noContacts,
style: const TextStyle(fontSize: 14),
),
),
);
}
return ListView(
shrinkWrap: true,
children: [for (final row in rows) row.tile],
);
}
Widget _contactTile(BuildContext context, Contact c) {
return _tile(
context,