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

+1 -1
View File
@@ -40,7 +40,7 @@ Pull-to-refresh re-fetches the full contact list from the device. Telemetry loca
A toolbar at the top provides:
**Search**: Matches contact name (case-insensitive) or public key hex prefix. Debounced at 300ms.
**Search**: Matches contact name (case-insensitive) or public key hex prefix. Names that start with the query are listed before other name matches, then key-prefix matches. Within each group the selected sort still applies. Debounced at 300ms.
**Sort options**:
- Latest Messages (by most recent message)
+19 -8
View File
@@ -191,7 +191,7 @@ What the code does:
| Container | Call | Used for | Examples |
|---|---|---|---|
| Bottom sheet | `showMeshSheet` + `BottomSheetHeader` (28 calls in 17 files) | Choosing from a list, an item's actions, quick tools tied to the current screen | Language picker, notification mode, add contact/channel options, emoji and GIF pickers, node info, share contact, image actions |
| Draggable sheet | `showModalBottomSheet` + `DraggableScrollableSheet` | Tall, scrollable panels that need a drag size | `ContactRoutingSheet` (`routing_sheet.dart`), path editor, image send preview |
| Draggable sheet | `showModalBottomSheet` + `DraggableScrollableSheet` | Tall, scrollable panels that need a drag size | `ContactRoutingSheet` (`routing_sheet.dart`), image send preview |
| Dialog | `showDialog` + `AlertDialog` (72 calls in 35 files) | Confirming an action, a short input (one to three fields), a short message | Disconnect (`showDisconnectDialog`), clear (`showConfirmClearDialog`), unsaved changes, edit node name, rename point |
| Page | `Navigator.push(MaterialPageRoute(...))` | Anything with sections, many fields, its own save, or that the user stays in | App Settings, Repeater Settings, Themes, Theme editor, Message filter, Region management |
@@ -202,7 +202,17 @@ Rules for new UI:
3. **Forms with sections, live remote values, or anything that needs Save/Discard → page.** Guard unsaved changes with `PopScope` and a discard dialog, as `repeater_settings_screen.dart` does.
4. Never stack a dialog on a sheet on a dialog. Close the sheet first, or move the flow to a page.
## 7. App bars
**Sheet layout.** `showMeshSheet` is the sheet: safe area on the top and sides, and the keyboard or navigation-bar inset on the bottom. Start the content with `BottomSheetHeader`. That widget is the handle and the title row (padding 20, 8, 8, 4 and a 36×4 handle, section 4). Do not add space above it, draw a second handle, or size the sheet with a fraction inside an `Align`; that leaves an empty band over the handle. The status-bar inset stays outside the sheet.
The manual path editor (`path_editor_sheet.dart`) uses that layout. The hop list and the hex path field stay pinned under the header, including while the keyboard is open. When the band under the header is shorter than the search field, as on a landscape phone with the keyboard open, those blocks and the repeater list scroll together instead of overflowing.
## 7. Node search
Contact, repeater, room and user search all use `lib/utils/contact_search.dart`. Sort with `compareContactQueryRank`: names that start with the query, then other substring matches, then a public-key / hop-hash prefix. Use `rankLabeledKeyQuery` for a label that is not itself a contact, such as "my contact" on the share sheet. Do not filter with a separate name `contains`.
That is the Contacts list and its group member picker, Discovery, Map node search, Map "send to contact", Share contact, and the Build Path repeater and room list. Channel names, chat messages, repeater CLI commands and the path-trace hex field are not this search. The map key-prefix setting is a filter, not a ranked search.
## 8. App bars
- Title: a plain localized string, ellipsized on one line. Use `AppBarTitle` on top-level and settings screens; it adds the connected node name as a subtitle and battery/SNR indicators when there is room, dropping them in that order on narrow widths. Use `AdaptiveAppBarTitle` for a plain one-line title.
- Centre the title (`centerTitle: true`, `AGENTS.md`); 31 screens set it explicitly because the theme default is `false`. Chat screens (`chat_screen.dart`, `channel_chat_screen.dart`) deliberately use `centerTitle: false` for their two-line name + route title.
@@ -211,7 +221,7 @@ Rules for new UI:
- Search: tapping search swaps the title for the field and hides all actions (`actions: _searching ? null : [...]`). The leading back arrow and the system back gesture close the search (`PopScope(canPop: !_searching)`) instead of leaving the screen.
- Long operations: show progress as the app bar `bottom` (`SyncProgressAppBarBottom`, or a 4px `LinearProgressIndicator` for Refresh all in `repeater_settings_screen.dart`).
## 8. States
## 9. States
| State | How to show it |
|---|---|
@@ -234,7 +244,7 @@ Rules for new UI:
Follow the same pattern for any new remote-value screen.
## 9. Text and localization
## 10. Text and localization
- All user-facing strings go through `context.l10n` (`lib/l10n/l10n.dart`). Add keys to `lib/l10n/app_en.arb` first. No string literals in widgets, including fallbacks.
- Keep strings short: labels are a few words, subtitles one sentence.
@@ -248,7 +258,7 @@ Follow the same pattern for any new remote-value screen.
- Upper-casing is done in code (`SectionHeader`, `StatTile`, `RouteChip`); keep the ARB strings in normal case.
- Test with a long locale (German, Portuguese) and a large system font (at least 1.3×, ideally 2.0×) on a narrow phone (320dp). `test/screens/small_screen_layout_test.dart` checks many screens at 320×568 at 1.0, 1.3 and 2.0× in English; add new screens to it.
## 10. Checklist for a UI change
## 11. Checklist for a UI change
- [ ] Colours from `colorScheme` or theme extensions; no raw `Colors.*` or `MeshPalette.ink/bg/line` in chrome.
- [ ] Text styles from `textTheme` or `MeshTheme.mono`; nothing below 12.
@@ -257,13 +267,14 @@ Follow the same pattern for any new remote-value screen.
- [ ] Popup menu rows use `MeshMenuItemRow`; segmented buttons use `MeshSegmentLabel`; destructive menu items last, in `scheme.error`.
- [ ] Every `IconButton` and FAB has a localized `tooltip`.
- [ ] Tap targets at least 48×48.
- [ ] Right container: dialog for confirm/short input, `showMeshSheet` + `BottomSheetHeader` for choices and item actions, page for forms.
- [ ] Right container: dialog for confirm/short input, `showMeshSheet` + `BottomSheetHeader` for choices and item actions, page for forms. No gap above the sheet handle.
- [ ] Contact, repeater, room and user search uses `compareContactQueryRank`: prefix, then substring, then hop hash.
- [ ] Loading, empty, error, offline and unknown-value states handled.
- [ ] All strings in `app_en.arb`; checked in German or Portuguese at 1.3× and 2.0× on a narrow screen.
- [ ] Light, dark and one custom theme checked.
- [ ] This page updated if you introduced or changed a pattern.
## 11. Known inconsistencies
## 12. Known inconsistencies
The current code does not yet follow this page everywhere:
@@ -282,7 +293,7 @@ The current code does not yet follow this page everywhere:
- **Large forms in dialogs.** `RadioSettingsDialog` (`widgets/radio_settings_dialog.dart`, nine inputs) and the contact settings dialog in `chat_screen.dart` are dialogs although they behave like forms.
- **Dialog buttons.** `showDisconnectDialog` (`utils/dialog_utils.dart`) uses two `TextButton`s with no emphasis; `showConfirmClearDialog` uses a red `FilledButton`.
- **Snackbars.** A few places still call `ScaffoldMessenger.showSnackBar` directly (`discovery_screen.dart`, `app_settings_screen.dart`, `message_filter_settings_screen.dart`, `region_management_screen.dart`, `helpers/image_send_flow.dart`) and so miss tap-to-dismiss and replace-instead-of-queue.
- **Small tap targets.** `FeatureToggleRow` refresh (32px) and 40px buttons in `chat_screen.dart`, `channel_chat_screen.dart`, `reaction_chips.dart`, `snr_indicator.dart`, `path_map_ui.dart`; 44px in `routing_sheet.dart`, `path_editor_sheet.dart`.
- **Small tap targets.** `FeatureToggleRow` refresh (32px) and 40px buttons in `chat_screen.dart`, `channel_chat_screen.dart`, `reaction_chips.dart`, `snr_indicator.dart`, `path_map_ui.dart`; 44px in `routing_sheet.dart`.
- **Unknown placeholders.** Repeater and companion stats screens use `—`; `line_of_sight_map_screen.dart` uses `--`.
- **Missing tooltip.** The Contacts FAB (`contacts_screen.dart`) has no tooltip; about 18 of 111 `IconButton`s have no tooltip nearby.
- **Stale doc comments.** `SectionHeader` is described as "mono" but uses the sans `accentLabel`; the `StatusChip` comment sits above `meshContrastRatio`.
+4
View File
@@ -62,4 +62,8 @@ Contacts/messages persist hop count, path bytes, and width. Legacy contact recor
`resolvePathSelection` uses a route picked from history even when the radio itself holds no path for the contact, so repeater logins and commands use proven routes instead of flooding.
## Building a path by hand
Chat → Routing → Manual opens the Build Path sheet. The hops you have added stay pinned at the top, including while the keyboard is open, and the one just added is highlighted. Under that list is the hex field, so a path can be typed without scrolling past every repeater. On a very short sheet, such as landscape with the keyboard open, the hop list, hex field, search field, and repeater list scroll together so the search field stays reachable. Search matches repeater and room names and hop hashes (the public-key prefix). Names that start with the query are listed before other substring matches, then hash-only matches.
For message-path actions, trace maps, and retry behavior, see [chat](chat-and-messaging.md), [channels](channels.md), and [map](map-and-location.md).
+1 -1
View File
@@ -2625,7 +2625,7 @@
"pathEditor_searchRepeaters": "Търсене на повторители",
"pathEditor_advancedHex": "Разширено: суров шестнадесетичен път",
"pathEditor_hexLabel": "Шестнадесетични префикси",
"pathEditor_hexHelper": "Два шестнадесетични идентификатора на скок, разделени със запетаи",
"pathEditor_hexHelper": "{count} шестнадесетични идентификатора на скок, разделени със запетаи",
"pathEditor_invalidTokens": "Невалидни: {tokens}",
"routing_lastWorked": "последно работил {when}",
"routing_deliveryCounts": "{successes} доставени, {failures} неуспешни",
+1 -1
View File
@@ -1243,7 +1243,7 @@
"pathEditor_searchRepeaters": "Hledat opakovače",
"pathEditor_advancedHex": "Pokročilé: surová hex cesta",
"pathEditor_hexLabel": "Hex prefixy",
"pathEditor_hexHelper": "Dva hex znaky na skok, oddělené čárkami",
"pathEditor_hexHelper": "{count} hex znaky na skok, oddělené čárkami",
"pathEditor_invalidTokens": "Neplatné: {tokens}",
"@pathEditor_invalidTokens": {
"placeholders": {
+1 -1
View File
@@ -2791,7 +2791,7 @@
"pathEditor_searchRepeaters": "Repeater suchen",
"pathEditor_advancedHex": "Erweitert: roher Hex-Pfad",
"pathEditor_hexLabel": "Hex-Präfixe",
"pathEditor_hexHelper": "Zwei Hex-Zeichen pro Sprung, durch Kommas getrennt",
"pathEditor_hexHelper": "{count} Hex-Zeichen pro Sprung, durch Kommas getrennt",
"pathEditor_invalidTokens": "Ungültig: {tokens}",
"pathEditor_tooManyHops": "Maximal 64 Sprünge",
"pathEditor_usePath": "Diesen Pfad verwenden",
+9 -2
View File
@@ -1386,10 +1386,17 @@
},
"pathEditor_noHops": "No hops yet. Tap repeaters below to add them in order, or save with no hops to send direct.",
"pathEditor_addHops": "Add hops in order",
"pathEditor_searchRepeaters": "Search repeaters",
"pathEditor_searchRepeaters": "Search name or hash",
"pathEditor_advancedHex": "Advanced: raw hex path",
"pathEditor_hexLabel": "Hex prefixes",
"pathEditor_hexHelper": "Two hex characters per hop, separated by commas",
"pathEditor_hexHelper": "{count} hex characters per hop, separated by commas",
"@pathEditor_hexHelper": {
"placeholders": {
"count": {
"type": "int"
}
}
},
"pathEditor_invalidTokens": "Invalid: {tokens}",
"@pathEditor_invalidTokens": {
"placeholders": {
+1 -1
View File
@@ -2675,7 +2675,7 @@
"pathEditor_searchRepeaters": "Buscar repetidores",
"pathEditor_advancedHex": "Avanzado: ruta hexadecimal sin procesar",
"pathEditor_hexLabel": "Prefijos hexadecimales",
"pathEditor_hexHelper": "Dos caracteres hexadecimales por salto, separados por comas.",
"pathEditor_hexHelper": "{count} caracteres hexadecimales por salto, separados por comas.",
"pathEditor_invalidTokens": "Inválido: {tokens}",
"pathEditor_tooManyHops": "Máximo 64 saltos",
"pathEditor_usePath": "Usar esta ruta",
+1 -1
View File
@@ -2675,7 +2675,7 @@
"pathEditor_searchRepeaters": "Rechercher des répétiteurs",
"pathEditor_advancedHex": "Avancé : chemin hexadécimal brut",
"pathEditor_hexLabel": "Préfixes hexadécimaux",
"pathEditor_hexHelper": "Deux caractères hexadécimaux par saut, séparés par des virgules.",
"pathEditor_hexHelper": "{count} caractères hexadécimaux par saut, séparés par des virgules.",
"pathEditor_invalidTokens": "Invalide : {tokens}",
"pathEditor_tooManyHops": "Maximum 64 sauts",
"pathEditor_usePath": "Utiliser ce chemin",
+1 -1
View File
@@ -2663,7 +2663,7 @@
"pathEditor_searchRepeaters": "Ismétlő keresése",
"pathEditor_advancedHex": "Haladó: nyers hexadecimális útvonal",
"pathEditor_hexLabel": "Hexadecimális előtagok",
"pathEditor_hexHelper": "Két hexadecimális karakter ugrásonként, vesszővel elválasztva",
"pathEditor_hexHelper": "{count} hexadecimális karakter ugrásonként, vesszővel elválasztva",
"pathEditor_invalidTokens": "Érvénytelen: {tokens}",
"routing_lastWorked": "dolgozott {when}",
"routing_deliveryCounts": "{successes} kézbesítve, {failures} sikertelen",
+1 -1
View File
@@ -2680,7 +2680,7 @@
"pathEditor_searchRepeaters": "Cerca ripetitori",
"pathEditor_advancedHex": "Avanzato: percorso esadecimale grezzo",
"pathEditor_hexLabel": "Prefissi esadecimali",
"pathEditor_hexHelper": "Due caratteri esadecimali per ogni salto, separati da virgole.",
"pathEditor_hexHelper": "{count} caratteri esadecimali per ogni salto, separati da virgole.",
"pathEditor_invalidTokens": "Non valido: {tokens}",
"routing_lastWorked": "ha funzionato {when}",
"pathEditor_tooManyHops": "Massimo 64 salti",
+1 -1
View File
@@ -2675,7 +2675,7 @@
"pathEditor_searchRepeaters": "リピータを検索",
"pathEditor_advancedHex": "詳細: 生の 16 進経路",
"pathEditor_hexLabel": "16 進接頭辞",
"pathEditor_hexHelper": "ホップごとに 16 進数 2 文字をカンマ区切りで入力します",
"pathEditor_hexHelper": "ホップごとに 16 進数 {count} 文字をカンマ区切りで入力します",
"pathEditor_invalidTokens": "無効: {tokens}",
"pathEditor_tooManyHops": "最大 64 ホップ",
"pathEditor_usePath": "この経路を使用",
+1 -1
View File
@@ -2579,7 +2579,7 @@
"pathEditor_searchRepeaters": "리피터 검색",
"pathEditor_advancedHex": "고급: 원시 HEX 경로",
"pathEditor_hexLabel": "HEX 접두사",
"pathEditor_hexHelper": "각 홉마다 2개의 16진수 바이트, 쉼표로 구분",
"pathEditor_hexHelper": "각 홉마다 {count}개의 16진수 문자, 쉼표로 구분",
"pathEditor_invalidTokens": "유효하지 않음: {tokens}",
"pathEditor_tooManyHops": "최대 64개의 홉",
"pathEditor_usePath": "이 경로 사용",
+3 -3
View File
@@ -4720,7 +4720,7 @@ abstract class AppLocalizations {
/// No description provided for @pathEditor_searchRepeaters.
///
/// In en, this message translates to:
/// **'Search repeaters'**
/// **'Search name or hash'**
String get pathEditor_searchRepeaters;
/// No description provided for @pathEditor_advancedHex.
@@ -4738,8 +4738,8 @@ abstract class AppLocalizations {
/// No description provided for @pathEditor_hexHelper.
///
/// In en, this message translates to:
/// **'Two hex characters per hop, separated by commas'**
String get pathEditor_hexHelper;
/// **'{count} hex characters per hop, separated by commas'**
String pathEditor_hexHelper(int count);
/// No description provided for @pathEditor_invalidTokens.
///
+3 -2
View File
@@ -2714,8 +2714,9 @@ class AppLocalizationsBg extends AppLocalizations {
String get pathEditor_hexLabel => 'Шестнадесетични префикси';
@override
String get pathEditor_hexHelper =>
'Два шестнадесетични идентификатора на скок, разделени със запетаи';
String pathEditor_hexHelper(int count) {
return '$count шестнадесетични идентификатора на скок, разделени със запетаи';
}
@override
String pathEditor_invalidTokens(String tokens) {
+3 -1
View File
@@ -2706,7 +2706,9 @@ class AppLocalizationsCs extends AppLocalizations {
String get pathEditor_hexLabel => 'Hex prefixy';
@override
String get pathEditor_hexHelper => 'Dva hex znaky na skok, oddělené čárkami';
String pathEditor_hexHelper(int count) {
return '$count hex znaky na skok, oddělené čárkami';
}
@override
String pathEditor_invalidTokens(String tokens) {
+3 -2
View File
@@ -2717,8 +2717,9 @@ class AppLocalizationsDe extends AppLocalizations {
String get pathEditor_hexLabel => 'Hex-Präfixe';
@override
String get pathEditor_hexHelper =>
'Zwei Hex-Zeichen pro Sprung, durch Kommas getrennt';
String pathEditor_hexHelper(int count) {
return '$count Hex-Zeichen pro Sprung, durch Kommas getrennt';
}
@override
String pathEditor_invalidTokens(String tokens) {
+4 -3
View File
@@ -2661,7 +2661,7 @@ class AppLocalizationsEn extends AppLocalizations {
String get pathEditor_addHops => 'Add hops in order';
@override
String get pathEditor_searchRepeaters => 'Search repeaters';
String get pathEditor_searchRepeaters => 'Search name or hash';
@override
String get pathEditor_advancedHex => 'Advanced: raw hex path';
@@ -2670,8 +2670,9 @@ class AppLocalizationsEn extends AppLocalizations {
String get pathEditor_hexLabel => 'Hex prefixes';
@override
String get pathEditor_hexHelper =>
'Two hex characters per hop, separated by commas';
String pathEditor_hexHelper(int count) {
return '$count hex characters per hop, separated by commas';
}
@override
String pathEditor_invalidTokens(String tokens) {
+3 -2
View File
@@ -2707,8 +2707,9 @@ class AppLocalizationsEs extends AppLocalizations {
String get pathEditor_hexLabel => 'Prefijos hexadecimales';
@override
String get pathEditor_hexHelper =>
'Dos caracteres hexadecimales por salto, separados por comas.';
String pathEditor_hexHelper(int count) {
return '$count caracteres hexadecimales por salto, separados por comas.';
}
@override
String pathEditor_invalidTokens(String tokens) {
+3 -2
View File
@@ -2711,8 +2711,9 @@ class AppLocalizationsFr extends AppLocalizations {
String get pathEditor_hexLabel => 'Préfixes hexadécimaux';
@override
String get pathEditor_hexHelper =>
'Deux caractères hexadécimaux par saut, séparés par des virgules.';
String pathEditor_hexHelper(int count) {
return '$count caractères hexadécimaux par saut, séparés par des virgules.';
}
@override
String pathEditor_invalidTokens(String tokens) {
+3 -2
View File
@@ -2704,8 +2704,9 @@ class AppLocalizationsHu extends AppLocalizations {
String get pathEditor_hexLabel => 'Hexadecimális előtagok';
@override
String get pathEditor_hexHelper =>
'Két hexadecimális karakter ugrásonként, vesszővel elválasztva';
String pathEditor_hexHelper(int count) {
return '$count hexadecimális karakter ugrásonként, vesszővel elválasztva';
}
@override
String pathEditor_invalidTokens(String tokens) {
+3 -2
View File
@@ -2711,8 +2711,9 @@ class AppLocalizationsIt extends AppLocalizations {
String get pathEditor_hexLabel => 'Prefissi esadecimali';
@override
String get pathEditor_hexHelper =>
'Due caratteri esadecimali per ogni salto, separati da virgole.';
String pathEditor_hexHelper(int count) {
return '$count caratteri esadecimali per ogni salto, separati da virgole.';
}
@override
String pathEditor_invalidTokens(String tokens) {
+3 -1
View File
@@ -2588,7 +2588,9 @@ class AppLocalizationsJa extends AppLocalizations {
String get pathEditor_hexLabel => '16 進接頭辞';
@override
String get pathEditor_hexHelper => 'ホップごとに 16 進数 2 文字をカンマ区切りで入力します';
String pathEditor_hexHelper(int count) {
return 'ホップごとに 16 進数 $count 文字をカンマ区切りで入力します';
}
@override
String pathEditor_invalidTokens(String tokens) {
+3 -1
View File
@@ -2591,7 +2591,9 @@ class AppLocalizationsKo extends AppLocalizations {
String get pathEditor_hexLabel => 'HEX 접두사';
@override
String get pathEditor_hexHelper => '각 홉마다 2개의 16진수 바이트, 쉼표로 구분';
String pathEditor_hexHelper(int count) {
return '각 홉마다 $count개의 16진수 문자, 쉼표로 구분';
}
@override
String pathEditor_invalidTokens(String tokens) {
+3 -2
View File
@@ -2696,8 +2696,9 @@ class AppLocalizationsNl extends AppLocalizations {
String get pathEditor_hexLabel => 'Hex-prefixen';
@override
String get pathEditor_hexHelper =>
'Twee hex-tekens per hop, gescheiden door komma\'s';
String pathEditor_hexHelper(int count) {
return '$count hex-tekens per hop, gescheiden door komma\'s';
}
@override
String pathEditor_invalidTokens(String tokens) {
+3 -2
View File
@@ -2738,8 +2738,9 @@ class AppLocalizationsPl extends AppLocalizations {
String get pathEditor_hexLabel => 'Prefiksy heksadecymalne';
@override
String get pathEditor_hexHelper =>
'Dwa znaki szesnastkowe na każdym kroku, oddzielone przecinkami';
String pathEditor_hexHelper(int count) {
return '$count znaki szesnastkowe na każdym kroku, oddzielone przecinkami';
}
@override
String pathEditor_invalidTokens(String tokens) {
+6 -4
View File
@@ -2706,8 +2706,9 @@ class AppLocalizationsPt extends AppLocalizations {
String get pathEditor_hexLabel => 'Prefixos hexadecimais';
@override
String get pathEditor_hexHelper =>
'Dois caracteres hexadecimais por salto, separados por vírgulas.';
String pathEditor_hexHelper(int count) {
return '$count caracteres hexadecimais por salto, separados por vírgulas.';
}
@override
String pathEditor_invalidTokens(String tokens) {
@@ -10298,8 +10299,9 @@ class AppLocalizationsPtPt extends AppLocalizationsPt {
String get pathEditor_hexLabel => 'Prefixos hex';
@override
String get pathEditor_hexHelper =>
'Dois caracteres hex por hop, separados por vírgulas';
String pathEditor_hexHelper(int count) {
return '$count caracteres hex por hop, separados por vírgulas';
}
@override
String pathEditor_invalidTokens(String tokens) {
+3 -2
View File
@@ -2717,8 +2717,9 @@ class AppLocalizationsRu extends AppLocalizations {
String get pathEditor_hexLabel => 'Префиксы шестнадцатеричной системы';
@override
String get pathEditor_hexHelper =>
'Два шестнадцатеричных символа на каждом шаге, разделенные запятыми.';
String pathEditor_hexHelper(int count) {
return '$count шестнадцатеричных символа на каждом шаге, разделенные запятыми.';
}
@override
String pathEditor_invalidTokens(String tokens) {
+3 -2
View File
@@ -2708,8 +2708,9 @@ class AppLocalizationsSk extends AppLocalizations {
String get pathEditor_hexLabel => 'Prefiksy pre hexadecimálne čísla';
@override
String get pathEditor_hexHelper =>
'Dve hexové čísla na každý krok, oddelené čiarkami';
String pathEditor_hexHelper(int count) {
return '$count hexové čísla na každý krok, oddelené čiarkami';
}
@override
String pathEditor_invalidTokens(String tokens) {
+3 -2
View File
@@ -2705,8 +2705,9 @@ class AppLocalizationsSl extends AppLocalizations {
String get pathEditor_hexLabel => 'Predfiks za heksadecimalno šifro';
@override
String get pathEditor_hexHelper =>
'Dva šestbitna znaka na vsak skok, ločena z vejico';
String pathEditor_hexHelper(int count) {
return '$count šestnajstiških znakov na vsak skok, ločenih z vejico';
}
@override
String pathEditor_invalidTokens(String tokens) {
+3 -2
View File
@@ -2684,8 +2684,9 @@ class AppLocalizationsSv extends AppLocalizations {
String get pathEditor_hexLabel => 'Hex-prefikser';
@override
String get pathEditor_hexHelper =>
'Två hextecken per hopp, separerade med kommatecken';
String pathEditor_hexHelper(int count) {
return '$count hextecken per hopp, separerade med kommatecken';
}
@override
String pathEditor_invalidTokens(String tokens) {
+3 -2
View File
@@ -2715,8 +2715,9 @@ class AppLocalizationsUk extends AppLocalizations {
'Префікси для шестнадцяткової системи числення';
@override
String get pathEditor_hexHelper =>
'Два шестизначні символи на кожний крок, розділені комами';
String pathEditor_hexHelper(int count) {
return '$count шістнадцяткові символи на кожний крок, розділені комами';
}
@override
String pathEditor_invalidTokens(String tokens) {
+3 -1
View File
@@ -2546,7 +2546,9 @@ class AppLocalizationsZh extends AppLocalizations {
String get pathEditor_hexLabel => '十六进制前缀';
@override
String get pathEditor_hexHelper => '每跳使用两个十六进制字符,用逗号分隔。';
String pathEditor_hexHelper(int count) {
return '每跳使用$count个十六进制字符,用逗号分隔。';
}
@override
String pathEditor_invalidTokens(String tokens) {
+1 -1
View File
@@ -2682,7 +2682,7 @@
"pathEditor_searchRepeaters": "Repeaters zoeken",
"pathEditor_advancedHex": "Geavanceerd: ruwe hex-pad",
"pathEditor_hexLabel": "Hex-prefixen",
"pathEditor_hexHelper": "Twee hex-tekens per hop, gescheiden door komma's",
"pathEditor_hexHelper": "{count} hex-tekens per hop, gescheiden door komma's",
"pathEditor_invalidTokens": "Ongeldig: {tokens}",
"pathEditor_tooManyHops": "Maximaal 64 hops",
"pathEditor_usePath": "Dit pad gebruiken",
+1 -1
View File
@@ -2658,7 +2658,7 @@
"pathEditor_searchRepeaters": "Funkcje powtarzania",
"pathEditor_advancedHex": "Zaawansowane: ścieżka w formacie szesnastkowym",
"pathEditor_hexLabel": "Prefiksy heksadecymalne",
"pathEditor_hexHelper": "Dwa znaki szesnastkowe na każdym kroku, oddzielone przecinkami",
"pathEditor_hexHelper": "{count} znaki szesnastkowe na każdym kroku, oddzielone przecinkami",
"pathEditor_invalidTokens": "Nieprawidłowe: {tokens}",
"pathEditor_tooManyHops": "Maksymalnie 64 hopów",
"pathEditor_usePath": "Użyj tej ścieżki.",
+1 -1
View File
@@ -2540,7 +2540,7 @@
"pathEditor_searchRepeaters": "Encontrar repetidores",
"pathEditor_advancedHex": "Avançado: caminho hexadecimal bruto",
"pathEditor_hexLabel": "Prefixos hexadecimais",
"pathEditor_hexHelper": "Dois caracteres hexadecimais por salto, separados por vírgulas.",
"pathEditor_hexHelper": "{count} caracteres hexadecimais por salto, separados por vírgulas.",
"pathEditor_invalidTokens": "Inválido: {tokens}",
"routing_lastWorked": "funcionou {when}",
"pathEditor_tooManyHops": "Máximo de 64 saltos",
+1 -1
View File
@@ -758,7 +758,7 @@
"pathEditor_searchRepeaters": "Pesquisar repetidores",
"pathEditor_advancedHex": "Avançado: caminho hex em bruto",
"pathEditor_hexLabel": "Prefixos hex",
"pathEditor_hexHelper": "Dois caracteres hex por hop, separados por vírgulas",
"pathEditor_hexHelper": "{count} caracteres hex por hop, separados por vírgulas",
"pathEditor_invalidTokens": "Inválido: {tokens}",
"pathEditor_tooManyHops": "Máximo de 64 hops",
"pathEditor_usePath": "Usar este caminho",
+1 -1
View File
@@ -1922,7 +1922,7 @@
"pathEditor_searchRepeaters": "Поиск повторителей",
"pathEditor_advancedHex": "Продвинутый уровень: прямой путь в шестнадцатеричном формате",
"pathEditor_hexLabel": "Префиксы шестнадцатеричной системы",
"pathEditor_hexHelper": "Два шестнадцатеричных символа на каждом шаге, разделенные запятыми.",
"pathEditor_hexHelper": "{count} шестнадцатеричных символа на каждом шаге, разделенные запятыми.",
"pathEditor_invalidTokens": "Неверно: {tokens}",
"routing_lastWorked": "работал {when}",
"routing_deliveryCounts": "{successes} доставлено, {failures} не доставлено",
+1 -1
View File
@@ -2625,7 +2625,7 @@
"pathEditor_searchRepeaters": "Hľadať opakované",
"pathEditor_advancedHex": "Pokročilé: pôvodná hexová cesta",
"pathEditor_hexLabel": "Prefiksy pre hexadecimálne čísla",
"pathEditor_hexHelper": "Dve hexové čísla na každý krok, oddelené čiarkami",
"pathEditor_hexHelper": "{count} hexové čísla na každý krok, oddelené čiarkami",
"routing_lastWorked": "fungovala {when}",
"pathEditor_invalidTokens": "Neplatné: {tokens}",
"routing_deliveryCounts": "{successes} doručených, {failures} neúspešných",
+1 -1
View File
@@ -2534,7 +2534,7 @@
"pathEditor_searchRepeaters": "Iskanje ponovitev",
"pathEditor_advancedHex": "Napredno: surovi šestnajstni pot",
"pathEditor_hexLabel": "Predfiks za heksadecimalno šifro",
"pathEditor_hexHelper": "Dva šestbitna znaka na vsak skok, ločena z vejico",
"pathEditor_hexHelper": "{count} šestnajstiških znakov na vsak skok, ločenih z vejico",
"pathEditor_invalidTokens": "Neveljaven: {tokens}",
"pathEditor_tooManyHops": "Največ 64 hopov",
"pathEditor_usePath": "Uporabite to poto",
+1 -1
View File
@@ -2529,7 +2529,7 @@
"pathEditor_searchRepeaters": "Sök repeaters",
"pathEditor_advancedHex": "Avancerat: rå rutt i hexformat",
"pathEditor_hexLabel": "Hex-prefikser",
"pathEditor_hexHelper": "Två hextecken per hopp, separerade med kommatecken",
"pathEditor_hexHelper": "{count} hextecken per hopp, separerade med kommatecken",
"pathEditor_invalidTokens": "Ogiltigt: {tokens}",
"pathEditor_tooManyHops": "Maximalt 64 hopp",
"pathEditor_usePath": "Använd den här rutten",
+1 -1
View File
@@ -2598,7 +2598,7 @@
"pathEditor_searchRepeaters": "Пошук повторювачів",
"pathEditor_advancedHex": "Просунутий рівень: пряма шлях у форматі шестнадцяткової системи.",
"pathEditor_hexLabel": "Префікси для шестнадцяткової системи числення",
"pathEditor_hexHelper": "Два шестизначні символи на кожний крок, розділені комами",
"pathEditor_hexHelper": "{count} шістнадцяткові символи на кожний крок, розділені комами",
"pathEditor_invalidTokens": "Неправильно: {tokens}",
"routing_lastWorked": "працював {when}",
"routing_deliveryCounts": "{successes} доставлено, {failures} не доставлено",
+1 -1
View File
@@ -2538,7 +2538,7 @@
"pathEditor_searchRepeaters": "重复搜索",
"pathEditor_advancedHex": "高级:原始十六进制路径",
"pathEditor_hexLabel": "十六进制前缀",
"pathEditor_hexHelper": "每跳使用两个十六进制字符,用逗号分隔。",
"pathEditor_hexHelper": "每跳使用{count}个十六进制字符,用逗号分隔。",
"pathEditor_invalidTokens": "无效:{tokens}",
"pathEditor_tooManyHops": "最多 64 跳",
"pathEditor_usePath": "请使用此路径",
+33 -26
View File
@@ -1243,34 +1243,38 @@ class _ContactsScreenState extends State<ContactsScreen> {
}).toList();
}
switch (viewState.contactsSortOption) {
case ContactSortOption.lastSeen:
final lastSeenAt = {
for (final c in filtered)
c: resolveContactLastSeen(
c,
addedAt: connector.contactAddedAt(c.publicKeyHex),
),
};
filtered.sort((a, b) => lastSeenAt[b]!.compareTo(lastSeenAt[a]!));
break;
case ContactSortOption.recentMessages:
final lastMessageAt = {
for (final c in filtered) c: _lastMessageTime(connector, c),
};
filtered.sort((a, b) {
final timeCompare = lastMessageAt[b]!.compareTo(lastMessageAt[a]!);
final lastSeenAt =
viewState.contactsSortOption == ContactSortOption.lastSeen
? {
for (final c in filtered)
c: resolveContactLastSeen(
c,
addedAt: connector.contactAddedAt(c.publicKeyHex),
),
}
: null;
final lastMessageAt =
viewState.contactsSortOption == ContactSortOption.recentMessages
? {for (final c in filtered) c: _lastMessageTime(connector, c)}
: null;
int tieBreak(Contact a, Contact b) {
switch (viewState.contactsSortOption) {
case ContactSortOption.lastSeen:
return lastSeenAt![b]!.compareTo(lastSeenAt[a]!);
case ContactSortOption.recentMessages:
final timeCompare = lastMessageAt![b]!.compareTo(lastMessageAt[a]!);
if (timeCompare != 0) return timeCompare;
return a.name.toLowerCase().compareTo(b.name.toLowerCase());
});
break;
case ContactSortOption.name:
filtered.sort(
(a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase()),
);
break;
case ContactSortOption.name:
return a.name.toLowerCase().compareTo(b.name.toLowerCase());
}
}
filtered.sort(
(a, b) =>
compareContactQueryRank(a, b, viewState.contactsSearchText, tieBreak),
);
return filtered;
}
@@ -1459,11 +1463,14 @@ class _ContactsScreenState extends State<ContactsScreen> {
builder: (builderContext, setDialogState) {
final filteredContacts = filterQuery.isEmpty
? sortedContacts
: sortedContacts
: (sortedContacts
.where(
(contact) => matchesContactQuery(contact, filterQuery),
)
.toList();
.toList()
..sort(
(a, b) => compareContactQueryRank(a, b, filterQuery),
));
return AlertDialog(
title: Text(
isEditing
+26 -11
View File
@@ -662,17 +662,32 @@ class _DiscoveryScreenState extends State<DiscoveryScreen> {
return _matchesTypeFilter(contact);
}).toList();
switch (sortOption) {
case ContactSortOption.lastSeen:
filtered.sort((a, b) => b.lastSeen.compareTo(a.lastSeen));
break;
case ContactSortOption.name:
filtered.sort(
(a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase()),
);
break;
default:
break;
int tieBreak(Contact a, Contact b) {
switch (sortOption) {
case ContactSortOption.lastSeen:
return b.lastSeen.compareTo(a.lastSeen);
case ContactSortOption.name:
return a.name.toLowerCase().compareTo(b.name.toLowerCase());
default:
return a.name.toLowerCase().compareTo(b.name.toLowerCase());
}
}
if (searchQuery.trim().isEmpty) {
switch (sortOption) {
case ContactSortOption.lastSeen:
filtered.sort((a, b) => b.lastSeen.compareTo(a.lastSeen));
case ContactSortOption.name:
filtered.sort(
(a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase()),
);
default:
break;
}
} else {
filtered.sort(
(a, b) => compareContactQueryRank(a, b, searchQuery, tieBreak),
);
}
return filtered;
+30 -26
View File
@@ -2292,13 +2292,14 @@ class _MapScreenState extends State<MapScreen> with WidgetsBindingObserver {
) {
final query = _searchQuery.trim().toLowerCase();
final matches =
allContacts.where((c) => matchesContactQuery(c, query)).toList()
..sort((a, b) {
allContacts.where((c) => matchesContactQuery(c, query)).toList()..sort(
(a, b) => compareContactQueryRank(a, b, query, (a, b) {
if (a.hasLocation != b.hasLocation) {
return a.hasLocation ? -1 : 1;
}
return b.lastHeard.compareTo(a.lastHeard);
});
}),
);
final results = matches.take(8).toList();
return Container(
margin: const EdgeInsets.only(top: 6),
@@ -3464,6 +3465,15 @@ class _MapScreenState extends State<MapScreen> with WidgetsBindingObserver {
contact.type != advTypeRoom,
)
.toList();
final people = allContacts
.where(
(contact) =>
query.isEmpty || matchesContactQuery(contact, query),
)
.toList();
if (query.isNotEmpty) {
people.sort((a, b) => compareContactQueryRank(a, b, query));
}
return SafeArea(
child: SingleChildScrollView(
child: Column(
@@ -3499,29 +3509,23 @@ class _MapScreenState extends State<MapScreen> with WidgetsBindingObserver {
},
),
),
...allContacts
.where(
(contact) =>
query.isEmpty ||
matchesContactQuery(contact, query),
)
.map((contact) {
return ListTile(
leading: const Icon(Icons.person),
title: Text(contact.name),
onTap: () {
Navigator.pop(sheetContext);
if (!_markerFits(
context,
markerText,
maxContactMessageBytes(),
)) {
return;
}
liveConnector.sendMessage(contact, markerText);
},
);
}),
...people.map((contact) {
return ListTile(
leading: const Icon(Icons.person),
title: Text(contact.name),
onTap: () {
Navigator.pop(sheetContext);
if (!_markerFits(
context,
markerText,
maxContactMessageBytes(),
)) {
return;
}
liveConnector.sendMessage(contact, markerText);
},
);
}),
Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 4),
child: Text(
+74 -15
View File
@@ -2,31 +2,90 @@ import '../models/contact.dart';
export 'contact_filter_types.dart';
bool matchesContactQuery(Contact contact, String query) {
final normalizedQuery = query.trim().toLowerCase();
if (normalizedQuery.isEmpty) return true;
/// How closely a contact matches a search query. Lower ranks sort first.
enum ContactQueryRank { namePrefix, nameContains, keyPrefix }
if (contact.name.toLowerCase().contains(normalizedQuery)) {
return true;
/// 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.
/// Name-only half of [rankContactQuery], for a label that is not itself a
/// contact (for example the "my contact" alias on the share sheet).
ContactQueryRank? rankNameQuery(String name, String query) {
final normalized = query.trim().toLowerCase();
if (normalized.isEmpty) return ContactQueryRank.namePrefix;
final label = name.toLowerCase();
if (label.startsWith(normalized)) return ContactQueryRank.namePrefix;
if (label.contains(normalized)) return ContactQueryRank.nameContains;
return null;
}
ContactQueryRank? rankContactQuery(Contact contact, String query) {
final normalized = query.trim().toLowerCase();
if (normalized.isEmpty) return ContactQueryRank.namePrefix;
final byName = rankNameQuery(contact.name, normalized);
if (byName != null) return byName;
if (_publicKeyPrefixMatches(contact, normalized)) {
return ContactQueryRank.keyPrefix;
}
return null;
}
final hexPrefix = _extractHexPrefix(normalizedQuery);
if (hexPrefix == null) return false;
/// Whether [name], any [aliases], or [publicKeyHex] matches [query] with the
/// same prefix, substring, then hash order as [rankContactQuery].
ContactQueryRank? rankLabeledKeyQuery({
required String name,
required String publicKeyHex,
required String query,
List<String> aliases = const [],
}) {
final normalized = query.trim().toLowerCase();
if (normalized.isEmpty) return ContactQueryRank.namePrefix;
ContactQueryRank? best = rankNameQuery(name, normalized);
for (final alias in aliases) {
final rank = rankNameQuery(alias, normalized);
if (rank != null && (best == null || rank.index < best.index)) {
best = rank;
}
}
if (best != null) return best;
final hexPrefix = _extractHexPrefix(normalized);
if (hexPrefix != null && publicKeyHex.toLowerCase().startsWith(hexPrefix)) {
return ContactQueryRank.keyPrefix;
}
return null;
}
return contact.publicKeyHex.toLowerCase().startsWith(hexPrefix);
bool matchesContactQuery(Contact contact, String query) {
return rankContactQuery(contact, query) != null;
}
bool matchesDiscoveryContactQuery(Contact contact, String query) {
final normalizedQuery = query.trim().toLowerCase();
if (normalizedQuery.isEmpty) return true;
return matchesContactQuery(contact, query);
}
if (contact.name.toLowerCase().contains(normalizedQuery)) {
return true;
}
/// 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) return false;
if (hexPrefix == null || contact.publicKey.isEmpty) return false;
return contact.publicKeyHex.toLowerCase().startsWith(hexPrefix);
}
+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,
+148
View File
@@ -0,0 +1,148 @@
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/connector/meshcore_protocol.dart';
import 'package:meshcore_open/models/contact.dart';
import 'package:meshcore_open/utils/contact_search.dart';
Contact _contact(
String name,
List<int> key, {
int type = advTypeRepeater,
DateTime? lastSeen,
}) {
return Contact(
publicKey: Uint8List.fromList(key),
name: name,
type: type,
pathLength: -1,
path: Uint8List(0),
lastSeen: lastSeen ?? DateTime.fromMillisecondsSinceEpoch(0),
);
}
List<String> _ranked(List<Contact> contacts, String query) {
final matches = contacts.where((c) => matchesContactQuery(c, query)).toList()
..sort((a, b) => compareContactQueryRank(a, b, query));
return matches.map((c) => c.name).toList();
}
void main() {
final contacts = [
_contact('100 Acre', [0x11, 0x22, 0x33, 0x44]),
_contact('Acreage North', [0x33, 0x44, 0x55, 0x66]),
_contact('My Acre Site', [0x55, 0x66, 0x77, 0x88]),
_contact('2E0HQR-R', [0x2E, 0x0A, 0x1B, 0x2C]),
_contact('CR1', [0x60, 0x60, 0xAB, 0xCD]),
_contact('Node 6060', [0x01, 0x02, 0x03, 0x04]),
_contact('6060 Hub', [0x0A, 0x0B, 0x0C, 0x0D]),
];
test('name prefixes rank before other substring matches', () {
expect(_ranked(contacts, 'acre'), [
'Acreage North',
'100 Acre',
'My Acre Site',
]);
});
test('prefix matches stay alphabetical among themselves', () {
final extra = [
_contact('Acreage North', [0x01]),
_contact('Acre Beacon', [0x02]),
];
expect(_ranked(extra, 'acre'), ['Acre Beacon', 'Acreage North']);
});
test('a hop hash matches when the name does not', () {
expect(matchesContactQuery(contacts[4], '6060'), isTrue);
expect(matchesContactQuery(contacts[4], '60'), isTrue);
expect(matchesContactQuery(contacts[4], '6060abcd'), isTrue);
expect(matchesContactQuery(contacts[4], '6061'), isFalse);
expect(_ranked(contacts, '6060'), ['6060 Hub', 'Node 6060', 'CR1']);
});
test('hash search accepts 0x, spaces, and angle brackets', () {
expect(_ranked(contacts, '0x6060'), ['CR1']);
expect(_ranked(contacts, '60 60'), ['CR1']);
expect(_ranked(contacts, '<6060>'), ['CR1']);
});
test('a single hex digit does not match every key', () {
expect(matchesContactQuery(contacts[4], '6'), isFalse);
});
test('an empty query matches every contact and keeps the tie-break', () {
final timed = [
_contact('B', [0x01], lastSeen: DateTime.utc(2024, 1, 2)),
_contact('A', [0x02], lastSeen: DateTime.utc(2024, 1, 3)),
];
timed.sort(
(a, b) => compareContactQueryRank(
a,
b,
'',
(a, b) => b.lastSeen.compareTo(a.lastSeen),
),
);
expect(timed.map((c) => c.name), ['A', 'B']);
});
test('a labeled key uses the same prefix, substring, then hash order', () {
expect(
rankLabeledKeyQuery(
name: 'Review Radio',
publicKeyHex: '6060abcd',
query: 'my',
aliases: ['My contact'],
),
ContactQueryRank.namePrefix,
);
expect(
rankLabeledKeyQuery(
name: 'Review Radio',
publicKeyHex: '6060abcd',
query: 'radio',
aliases: ['My contact'],
),
ContactQueryRank.nameContains,
);
expect(
rankLabeledKeyQuery(
name: 'Review Radio',
publicKeyHex: '6060abcd',
query: '6060',
aliases: ['My contact'],
),
ContactQueryRank.keyPrefix,
);
expect(
rankLabeledKeyQuery(
name: 'Review Radio',
publicKeyHex: '6060abcd',
query: 'zzzz',
aliases: ['My contact'],
),
isNull,
);
});
test('tie-break applies inside a rank, not across ranks', () {
final olderPrefix = _contact('Acre Older', [
0x01,
], lastSeen: DateTime.utc(2020));
final newerSubstring = _contact('My Acre', [
0x02,
], lastSeen: DateTime.utc(2024));
final ranked = [newerSubstring, olderPrefix]
..sort(
(a, b) => compareContactQueryRank(
a,
b,
'acre',
(a, b) => b.lastSeen.compareTo(a.lastSeen),
),
);
expect(ranked.map((c) => c.name), ['Acre Older', 'My Acre']);
});
}
+512
View File
@@ -0,0 +1,512 @@
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/connector/meshcore_protocol.dart';
import 'package:meshcore_open/l10n/app_localizations.dart';
import 'package:meshcore_open/models/contact.dart';
import 'package:meshcore_open/widgets/path_editor_sheet.dart';
Contact _repeater(String name, List<int> prefix) {
final key = Uint8List(32);
for (var i = 0; i < prefix.length; i++) {
key[i] = prefix[i];
}
return Contact(
publicKey: key,
name: name,
type: advTypeRepeater,
pathLength: -1,
path: Uint8List(0),
lastSeen: DateTime.fromMillisecondsSinceEpoch(0),
);
}
final _contacts = [
_repeater('100 Acre', [0x11, 0x22]),
_repeater('Acreage North', [0x33, 0x44]),
_repeater('My Acre Site', [0x55, 0x66]),
_repeater('2E0HQR-R', [0x2E, 0x0A]),
_repeater('CR1', [0x60, 0x60]),
for (var i = 0; i < 24; i++) _repeater('Repeater $i', [0xA0, i]),
];
Future<void> _pumpSheet(
WidgetTester tester, {
Size size = const Size(400, 700),
double keyboard = 0,
double textScale = 1.0,
List<int> initialPath = const [],
}) async {
tester.view.physicalSize = size;
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
await tester.pumpWidget(
MaterialApp(
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: MediaQuery(
data: MediaQueryData(
size: size,
viewInsets: EdgeInsets.only(bottom: keyboard),
textScaler: TextScaler.linear(textScale),
),
child: Scaffold(
body: SizedBox(
width: size.width,
height: size.height - keyboard,
child: PathEditorSheet(
key: UniqueKey(),
availableContacts: _contacts,
initialPath: initialPath,
pathHashByteWidth: 2,
),
),
),
),
),
);
await tester.pumpAndSettle();
}
Finder _fallbackScrollable() {
return find.byElementPredicate((element) {
if (element.widget is! Scrollable) return false;
var hasHex = false;
void visit(Element node) {
node.visitChildren((child) {
if (child.widget.key == const Key('path-editor-hex-field')) {
hasHex = true;
}
visit(child);
});
}
visit(element);
return hasHex;
});
}
Future<void> _revealInFallback(
WidgetTester tester,
Finder scrollable,
Finder target,
) async {
final state = tester.state<ScrollableState>(scrollable);
final view = tester.getRect(
find.byKey(const Key('path-editor-scroll-fallback')),
);
final step = (view.height / 2).clamp(2.0, 24.0);
for (var i = 0; i < 400; i++) {
final rect = tester.getRect(target);
if (rect.center.dy >= view.top && rect.center.dy <= view.bottom) return;
final next = (state.position.pixels + step).clamp(
0.0,
state.position.maxScrollExtent,
);
expect(next, greaterThan(state.position.pixels));
state.position.jumpTo(next);
await tester.pump();
}
fail(
'Could not scroll $target into $view (last rect=${tester.getRect(target)}, pixels=${state.position.pixels})',
);
}
List<String> _repeaterNames(WidgetTester tester) {
return tester
.widgetList<Text>(
find.descendant(
of: find.byKey(const Key('path-editor-repeater-list')),
matching: find.byType(Text),
),
)
.map((text) => text.data)
.whereType<String>()
.where((text) => !text.contains('•'))
.toList();
}
void main() {
testWidgets('prefix matches are listed before other substring matches', (
tester,
) async {
await _pumpSheet(tester);
await tester.enterText(
find.byKey(const Key('path-editor-search-field')),
'acre',
);
await tester.pumpAndSettle();
final visible = _repeaterNames(tester);
expect(visible.first, 'Acreage North');
expect(visible[1], '100 Acre');
await tester.scrollUntilVisible(
find.text('My Acre Site'),
80,
scrollable: find.descendant(
of: find.byKey(const Key('path-editor-repeater-list')),
matching: find.byType(Scrollable),
),
);
expect(find.text('My Acre Site'), findsOneWidget);
});
testWidgets('search matches a hop hash the name does not contain', (
tester,
) async {
await _pumpSheet(tester);
await tester.enterText(
find.byKey(const Key('path-editor-search-field')),
'6060',
);
await tester.pumpAndSettle();
expect(find.text('No repeaters or room servers found.'), findsNothing);
expect(_repeaterNames(tester), ['CR1']);
});
testWidgets('hex entry is reachable without scrolling the repeater list', (
tester,
) async {
await _pumpSheet(tester, size: const Size(400, 900));
expect(
find.byKey(const Key('path-editor-hex-field')).hitTestable(),
findsOneWidget,
);
expect(find.text('Hex prefixes'), findsOneWidget);
expect(
find.text('4 hex characters per hop, separated by commas'),
findsOneWidget,
);
});
testWidgets('an added hop stays fully visible with the keyboard open', (
tester,
) async {
await _pumpSheet(
tester,
size: const Size(390, 640),
keyboard: 320,
initialPath: [0x60, 0x60],
);
final tile = find.ancestor(
of: find.byIcon(Icons.remove_circle_outline),
matching: find.byType(ListTile),
);
expect(tile.hitTestable(), findsOneWidget);
final title = tester.getRect(find.text('Build Path'));
final hopRect = tester.getRect(tile);
final sheet = tester.getRect(find.byType(PathEditorSheet));
expect(hopRect.top, greaterThanOrEqualTo(title.bottom));
expect(hopRect.bottom, lessThanOrEqualTo(sheet.bottom));
expect(hopRect.height, greaterThanOrEqualTo(48));
expect(find.text('CR1').hitTestable(), findsWidgets);
expect(find.text('6060').hitTestable(), findsWidgets);
expect(
find.byKey(const Key('path-editor-hex-field')).hitTestable(),
findsOneWidget,
);
expect(find.byKey(const Key('path-editor-scroll-fallback')), findsNothing);
expect(tester.takeException(), isNull);
});
testWidgets('an invalid hex path does not overflow a keyboard-height sheet', (
tester,
) async {
await _pumpSheet(
tester,
size: const Size(390, 640),
keyboard: 320,
initialPath: [0x60, 0x60, 0x11, 0x22],
);
await tester.enterText(
find.byKey(const Key('path-editor-hex-field')),
'ZZ',
);
await tester.pumpAndSettle();
expect(find.textContaining('Invalid'), findsOneWidget);
expect(tester.takeException(), isNull);
expect(
find.byIcon(Icons.remove_circle_outline).hitTestable(),
findsWidgets,
);
final button = tester.getRect(find.text('Use this path'));
final sheet = tester.getRect(find.byType(PathEditorSheet));
expect(button.bottom, lessThanOrEqualTo(sheet.bottom + 1));
});
testWidgets(
'3-line hex error on a 320px keyboard sheet keeps controls scrollable',
(tester) async {
await _pumpSheet(
tester,
size: const Size(390, 640),
keyboard: 320,
initialPath: [0x60, 0x60, 0x11, 0x22],
);
await tester.enterText(
find.byKey(const Key('path-editor-hex-field')),
'AA, BB, CC, DD, EE, FF, GG, HH, II, JJ, KK',
);
await tester.pumpAndSettle();
expect(tester.takeException(), isNull);
expect(
find.byKey(const Key('path-editor-scroll-fallback')),
findsOneWidget,
);
expect(
tester
.widget<TextField>(find.byKey(const Key('path-editor-hex-field')))
.focusNode
?.hasFocus,
isTrue,
);
final scrollable = _fallbackScrollable();
await _revealInFallback(
tester,
scrollable,
find.textContaining('Invalid', skipOffstage: false),
);
expect(find.textContaining('Invalid').hitTestable(), findsOneWidget);
await _revealInFallback(
tester,
scrollable,
find.byKey(const Key('path-editor-search-field'), skipOffstage: false),
);
expect(
find.byKey(const Key('path-editor-search-field')).hitTestable(),
findsOneWidget,
);
await _revealInFallback(
tester,
scrollable,
find.text('Acreage North', skipOffstage: false),
);
expect(find.text('Acreage North').hitTestable(), findsOneWidget);
final button = tester.getRect(find.text('Use this path'));
final sheet = tester.getRect(find.byType(PathEditorSheet));
expect(button.bottom, lessThanOrEqualTo(sheet.bottom + 1));
},
);
testWidgets('a landscape keyboard sheet scrolls instead of overflowing', (
tester,
) async {
await _pumpSheet(
tester,
size: const Size(800, 180),
initialPath: [0x60, 0x60, 0x11, 0x22],
);
expect(tester.takeException(), isNull);
expect(
find.byKey(const Key('path-editor-scroll-fallback')),
findsOneWidget,
);
final scrollable = _fallbackScrollable();
await tester.scrollUntilVisible(
find.byKey(const Key('path-editor-hex-field')),
40,
scrollable: scrollable,
);
await tester.enterText(
find.byKey(const Key('path-editor-hex-field')),
'ZZ',
);
await tester.pumpAndSettle();
expect(tester.takeException(), isNull);
expect(find.textContaining('Invalid'), findsOneWidget);
await _revealInFallback(
tester,
scrollable,
find.byKey(const Key('path-editor-search-field'), skipOffstage: false),
);
expect(
find.byKey(const Key('path-editor-search-field')).hitTestable(),
findsOneWidget,
);
await _revealInFallback(
tester,
scrollable,
find.text('Acreage North', skipOffstage: false),
);
expect(find.text('Acreage North').hitTestable(), findsOneWidget);
final button = tester.getRect(find.text('Use this path'));
final sheet = tester.getRect(find.byType(PathEditorSheet));
expect(button.bottom, lessThanOrEqualTo(sheet.bottom + 1));
});
testWidgets('an empty landscape keyboard sheet scrolls cleanly at 180px', (
tester,
) async {
for (final size in [const Size(800, 180), const Size(640, 220)]) {
await _pumpSheet(tester, size: size);
expect(tester.takeException(), isNull);
expect(
find.byKey(const Key('path-editor-scroll-fallback')),
findsOneWidget,
);
final scrollable = _fallbackScrollable();
await _revealInFallback(
tester,
scrollable,
find.byKey(const Key('path-editor-hex-field'), skipOffstage: false),
);
expect(
find.byKey(const Key('path-editor-hex-field')).hitTestable(),
findsOneWidget,
);
await _revealInFallback(
tester,
scrollable,
find.byKey(const Key('path-editor-search-field'), skipOffstage: false),
);
expect(
find.byKey(const Key('path-editor-search-field')).hitTestable(),
findsOneWidget,
);
await _revealInFallback(
tester,
scrollable,
find.text('Acreage North', skipOffstage: false),
);
expect(find.text('Acreage North').hitTestable(), findsOneWidget);
final button = tester.getRect(find.text('Use this path'));
final sheet = tester.getRect(find.byType(PathEditorSheet));
expect(button.bottom, lessThanOrEqualTo(sheet.bottom + 1));
}
});
testWidgets('320dp width fits at 1.3x and 2.0x text scale without overflow', (
tester,
) async {
for (final scale in [1.3, 2.0]) {
for (final keyboard in [0.0, 320.0]) {
await _pumpSheet(
tester,
size: const Size(320, 640),
keyboard: keyboard,
textScale: scale,
initialPath: [0x60, 0x60, 0x11, 0x22],
);
expect(tester.takeException(), isNull);
if (find
.byKey(const Key('path-editor-scroll-fallback'))
.evaluate()
.isNotEmpty) {
await _revealInFallback(
tester,
_fallbackScrollable(),
find.byKey(const Key('path-editor-hex-field'), skipOffstage: false),
);
}
await tester.enterText(
find.byKey(const Key('path-editor-hex-field')),
'AA, BB, CC, DD, EE, FF, GG, HH, II, JJ',
);
await tester.pumpAndSettle();
expect(tester.takeException(), isNull);
if (find
.byKey(const Key('path-editor-scroll-fallback'))
.evaluate()
.isNotEmpty) {
await _revealInFallback(
tester,
_fallbackScrollable(),
find.textContaining('Invalid', skipOffstage: false),
);
}
expect(find.textContaining('Invalid').hitTestable(), findsOneWidget);
if (find.text('Use this path').evaluate().isEmpty) {
final state = tester.state<ScrollableState>(_fallbackScrollable());
state.position.jumpTo(state.position.maxScrollExtent);
await tester.pumpAndSettle();
}
final button = tester.getRect(find.text('Use this path'));
final sheet = tester.getRect(find.byType(PathEditorSheet));
expect(button.bottom, lessThanOrEqualTo(sheet.bottom + 1));
}
}
});
testWidgets('action buttons stay below the repeater list on a short sheet', (
tester,
) async {
await _pumpSheet(
tester,
size: const Size(400, 560),
initialPath: [0x60, 0x60, 0x11, 0x22],
);
expect(tester.takeException(), isNull);
final button = tester.getRect(find.text('Use this path'));
final list = tester.getRect(
find.byKey(const Key('path-editor-repeater-list')),
);
expect(button.top, greaterThanOrEqualTo(list.bottom - 1));
});
testWidgets('the title sits at the top of the sheet', (tester) async {
tester.view.physicalSize = const Size(400, 800);
tester.view.devicePixelRatio = 1;
// A phone status bar. The sheet may pad for it, and must not add another
// empty band above the handle.
tester.view.padding = const FakeViewPadding(top: 47);
tester.view.viewPadding = const FakeViewPadding(top: 47);
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
addTearDown(tester.view.resetPadding);
addTearDown(tester.view.resetViewPadding);
await tester.pumpWidget(
MaterialApp(
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: Builder(
builder: (context) => Scaffold(
body: TextButton(
onPressed: () => PathEditorSheet.show(
context,
availableContacts: _contacts,
pathHashByteWidth: 2,
),
child: const Text('open'),
),
),
),
),
);
await tester.tap(find.text('open'));
await tester.pumpAndSettle();
final sheetTop = tester.getTopLeft(find.byType(BottomSheet)).dy;
final titleTop = tester.getTopLeft(find.text('Build Path')).dy;
// Header only: 8px padding, a 4px handle, and a 10px gap. The status-bar
// inset stays outside the sheet, and there is no extra empty band.
expect(titleTop - sheetTop, inInclusiveRange(16, 36));
});
testWidgets('tapping a repeater adds a visible hop', (tester) async {
await _pumpSheet(tester);
await tester.enterText(
find.byKey(const Key('path-editor-search-field')),
'6060',
);
await tester.pumpAndSettle();
await tester.tap(find.widgetWithText(ListTile, 'CR1'));
await tester.pumpAndSettle();
expect(find.text('1 of 64 hops'), findsOneWidget);
expect(find.byIcon(Icons.remove_circle_outline), findsOneWidget);
expect(find.text('CR1').hitTestable(), findsWidgets);
});
}