Files
meshcore-open/lib/utils/contact_search.dart
T
Cursor Agentandzjs81 a1604af4d4 Fix manual path search ranking, hash matching, and layout
Rank name prefixes ahead of other substring matches, match hop hashes
in the path builder and contact search, and keep the hop list and hex
field on screen while the keyboard is open.

Co-authored-by: zjs81 <zjs81@users.noreply.github.com>
2026-11-20 21:43:49 +00:00

70 lines
2.4 KiB
Dart

import '../models/contact.dart';
export 'contact_filter_types.dart';
/// How closely a contact matches a search query. Lower ranks sort first.
enum ContactQueryRank { namePrefix, nameContains, keyPrefix }
/// Rank for [query], or null when the contact does not match.
///
/// Names that start with the query come before other substring matches.
/// A public-key / hop-hash prefix matches only when the name does not.
ContactQueryRank? rankContactQuery(Contact contact, String query) {
final normalized = query.trim().toLowerCase();
if (normalized.isEmpty) return ContactQueryRank.namePrefix;
final name = contact.name.toLowerCase();
if (name.startsWith(normalized)) return ContactQueryRank.namePrefix;
if (name.contains(normalized)) return ContactQueryRank.nameContains;
if (_publicKeyPrefixMatches(contact, normalized)) {
return ContactQueryRank.keyPrefix;
}
return null;
}
bool matchesContactQuery(Contact contact, String query) {
return rankContactQuery(contact, query) != null;
}
bool matchesDiscoveryContactQuery(Contact contact, String query) {
return matchesContactQuery(contact, query);
}
/// Sorts prefix matches ahead of other substring matches, then key matches.
///
/// [tieBreak] orders contacts that share a rank. With an empty query every
/// contact shares the top rank, so [tieBreak] is the whole order.
int compareContactQueryRank(
Contact a,
Contact b,
String query, [
int Function(Contact a, Contact b)? tieBreak,
]) {
final left = rankContactQuery(a, query);
final right = rankContactQuery(b, query);
final byRank = (left?.index ?? 3).compareTo(right?.index ?? 3);
if (byRank != 0) return byRank;
return tieBreak?.call(a, b) ??
a.name.toLowerCase().compareTo(b.name.toLowerCase());
}
bool _publicKeyPrefixMatches(Contact contact, String normalizedQuery) {
final hexPrefix = _extractHexPrefix(normalizedQuery);
if (hexPrefix == null || contact.publicKey.isEmpty) return false;
return contact.publicKeyHex.toLowerCase().startsWith(hexPrefix);
}
String? _extractHexPrefix(String query) {
var cleaned = query;
if (cleaned.startsWith('<')) {
cleaned = cleaned.substring(1).replaceAll(">", "");
}
if (cleaned.startsWith('0x')) {
cleaned = cleaned.substring(2);
}
cleaned = cleaned.replaceAll(' ', '');
if (cleaned.length < 2) return null;
if (!RegExp(r'^[0-9a-f]+$').hasMatch(cleaned)) return null;
return cleaned;
}