From a1604af4d46eea1881d172705b3c5a1e75e13f73 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Fri, 20 Nov 2026 21:43:49 +0000 Subject: [PATCH 1/6] 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 --- documentation/contacts.md | 2 +- documentation/design.md | 6 +- documentation/routing-paths.md | 4 + lib/l10n/app_bg.arb | 2 +- lib/l10n/app_cs.arb | 2 +- lib/l10n/app_de.arb | 2 +- lib/l10n/app_en.arb | 11 +- lib/l10n/app_es.arb | 2 +- lib/l10n/app_fr.arb | 2 +- lib/l10n/app_hu.arb | 2 +- lib/l10n/app_it.arb | 2 +- lib/l10n/app_ja.arb | 2 +- lib/l10n/app_ko.arb | 2 +- lib/l10n/app_localizations.dart | 6 +- lib/l10n/app_localizations_bg.dart | 5 +- lib/l10n/app_localizations_cs.dart | 4 +- lib/l10n/app_localizations_de.dart | 5 +- lib/l10n/app_localizations_en.dart | 7 +- lib/l10n/app_localizations_es.dart | 5 +- lib/l10n/app_localizations_fr.dart | 5 +- lib/l10n/app_localizations_hu.dart | 5 +- lib/l10n/app_localizations_it.dart | 5 +- lib/l10n/app_localizations_ja.dart | 4 +- lib/l10n/app_localizations_ko.dart | 4 +- lib/l10n/app_localizations_nl.dart | 5 +- lib/l10n/app_localizations_pl.dart | 5 +- lib/l10n/app_localizations_pt.dart | 10 +- lib/l10n/app_localizations_ru.dart | 5 +- lib/l10n/app_localizations_sk.dart | 5 +- lib/l10n/app_localizations_sl.dart | 5 +- lib/l10n/app_localizations_sv.dart | 5 +- lib/l10n/app_localizations_uk.dart | 5 +- lib/l10n/app_localizations_zh.dart | 4 +- lib/l10n/app_nl.arb | 2 +- lib/l10n/app_pl.arb | 2 +- lib/l10n/app_pt.arb | 2 +- lib/l10n/app_pt_PT.arb | 2 +- lib/l10n/app_ru.arb | 2 +- lib/l10n/app_sk.arb | 2 +- lib/l10n/app_sl.arb | 2 +- lib/l10n/app_sv.arb | 2 +- lib/l10n/app_uk.arb | 2 +- lib/l10n/app_zh.arb | 2 +- lib/screens/contacts_screen.dart | 43 +- lib/screens/discovery_screen.dart | 37 +- lib/screens/map_screen.dart | 56 +-- lib/utils/contact_search.dart | 56 ++- lib/widgets/path_editor_sheet.dart | 535 +++++++++++++++-------- lib/widgets/share_contact_sheet.dart | 9 +- test/utils/contact_search_test.dart | 109 +++++ test/widgets/path_editor_sheet_test.dart | 199 +++++++++ 51 files changed, 882 insertions(+), 327 deletions(-) create mode 100644 test/utils/contact_search_test.dart create mode 100644 test/widgets/path_editor_sheet_test.dart diff --git a/documentation/contacts.md b/documentation/contacts.md index 69559665..fba26ed9 100644 --- a/documentation/contacts.md +++ b/documentation/contacts.md @@ -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) diff --git a/documentation/design.md b/documentation/design.md index 423b53aa..dee9c2ce 100644 --- a/documentation/design.md +++ b/documentation/design.md @@ -154,7 +154,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 | @@ -165,6 +165,8 @@ 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. +The manual path editor (`path_editor_sheet.dart`) is a fixed-height sheet, not a draggable one. The hop list and the hex path field stay pinned above a scrolling repeater list, including while the keyboard is open. The sheet uses the full height above the keyboard so a newly added hop is not scrolled under the title. + ## 7. 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. @@ -244,7 +246,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`. diff --git a/documentation/routing-paths.md b/documentation/routing-paths.md index 74548258..90202fc4 100644 --- a/documentation/routing-paths.md +++ b/documentation/routing-paths.md @@ -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. 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). diff --git a/lib/l10n/app_bg.arb b/lib/l10n/app_bg.arb index 913a0815..5135e0e4 100644 --- a/lib/l10n/app_bg.arb +++ b/lib/l10n/app_bg.arb @@ -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} неуспешни", diff --git a/lib/l10n/app_cs.arb b/lib/l10n/app_cs.arb index f72e9821..2e05031a 100644 --- a/lib/l10n/app_cs.arb +++ b/lib/l10n/app_cs.arb @@ -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": { diff --git a/lib/l10n/app_de.arb b/lib/l10n/app_de.arb index 40d00f84..1b568750 100644 --- a/lib/l10n/app_de.arb +++ b/lib/l10n/app_de.arb @@ -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", diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index e18f6ed9..c2ed54a6 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -1391,10 +1391,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": { diff --git a/lib/l10n/app_es.arb b/lib/l10n/app_es.arb index 1b0ddb11..a7c49503 100644 --- a/lib/l10n/app_es.arb +++ b/lib/l10n/app_es.arb @@ -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", diff --git a/lib/l10n/app_fr.arb b/lib/l10n/app_fr.arb index de3c1be3..9aa4daa1 100644 --- a/lib/l10n/app_fr.arb +++ b/lib/l10n/app_fr.arb @@ -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", diff --git a/lib/l10n/app_hu.arb b/lib/l10n/app_hu.arb index ba73a0d6..f079dce3 100644 --- a/lib/l10n/app_hu.arb +++ b/lib/l10n/app_hu.arb @@ -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", diff --git a/lib/l10n/app_it.arb b/lib/l10n/app_it.arb index 8d6bd2ec..9e0393bf 100644 --- a/lib/l10n/app_it.arb +++ b/lib/l10n/app_it.arb @@ -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", diff --git a/lib/l10n/app_ja.arb b/lib/l10n/app_ja.arb index 0a3b8931..a7682fd6 100644 --- a/lib/l10n/app_ja.arb +++ b/lib/l10n/app_ja.arb @@ -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": "この経路を使用", diff --git a/lib/l10n/app_ko.arb b/lib/l10n/app_ko.arb index dcaf27a3..1fcb9980 100644 --- a/lib/l10n/app_ko.arb +++ b/lib/l10n/app_ko.arb @@ -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": "이 경로 사용", diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index 53e641fa..800269da 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -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. /// diff --git a/lib/l10n/app_localizations_bg.dart b/lib/l10n/app_localizations_bg.dart index cc0a9670..b89785cf 100644 --- a/lib/l10n/app_localizations_bg.dart +++ b/lib/l10n/app_localizations_bg.dart @@ -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) { diff --git a/lib/l10n/app_localizations_cs.dart b/lib/l10n/app_localizations_cs.dart index 60ad5ee3..112ad4fd 100644 --- a/lib/l10n/app_localizations_cs.dart +++ b/lib/l10n/app_localizations_cs.dart @@ -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) { diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart index 587287f7..f9b79f7c 100644 --- a/lib/l10n/app_localizations_de.dart +++ b/lib/l10n/app_localizations_de.dart @@ -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) { diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index f73db6d1..bba7e7e8 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -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) { diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart index 8dd0aa61..37cf28c6 100644 --- a/lib/l10n/app_localizations_es.dart +++ b/lib/l10n/app_localizations_es.dart @@ -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) { diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart index 9e1cde19..2ef6d2fc 100644 --- a/lib/l10n/app_localizations_fr.dart +++ b/lib/l10n/app_localizations_fr.dart @@ -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) { diff --git a/lib/l10n/app_localizations_hu.dart b/lib/l10n/app_localizations_hu.dart index fae906b6..0cafc066 100644 --- a/lib/l10n/app_localizations_hu.dart +++ b/lib/l10n/app_localizations_hu.dart @@ -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) { diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart index 9d96718d..f0352798 100644 --- a/lib/l10n/app_localizations_it.dart +++ b/lib/l10n/app_localizations_it.dart @@ -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) { diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart index 10908f1e..0aaef47b 100644 --- a/lib/l10n/app_localizations_ja.dart +++ b/lib/l10n/app_localizations_ja.dart @@ -2587,7 +2587,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) { diff --git a/lib/l10n/app_localizations_ko.dart b/lib/l10n/app_localizations_ko.dart index 2ed52089..5b99499f 100644 --- a/lib/l10n/app_localizations_ko.dart +++ b/lib/l10n/app_localizations_ko.dart @@ -2590,7 +2590,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) { diff --git a/lib/l10n/app_localizations_nl.dart b/lib/l10n/app_localizations_nl.dart index cc092841..6d854004 100644 --- a/lib/l10n/app_localizations_nl.dart +++ b/lib/l10n/app_localizations_nl.dart @@ -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) { diff --git a/lib/l10n/app_localizations_pl.dart b/lib/l10n/app_localizations_pl.dart index 62a18751..04bf7d6c 100644 --- a/lib/l10n/app_localizations_pl.dart +++ b/lib/l10n/app_localizations_pl.dart @@ -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) { diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart index 48a93255..feb15cdc 100644 --- a/lib/l10n/app_localizations_pt.dart +++ b/lib/l10n/app_localizations_pt.dart @@ -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) { @@ -10231,8 +10232,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) { diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart index b2d7a486..d0d031c4 100644 --- a/lib/l10n/app_localizations_ru.dart +++ b/lib/l10n/app_localizations_ru.dart @@ -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) { diff --git a/lib/l10n/app_localizations_sk.dart b/lib/l10n/app_localizations_sk.dart index 0c1327b4..deec1017 100644 --- a/lib/l10n/app_localizations_sk.dart +++ b/lib/l10n/app_localizations_sk.dart @@ -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) { diff --git a/lib/l10n/app_localizations_sl.dart b/lib/l10n/app_localizations_sl.dart index 3701f9e0..573c0cd4 100644 --- a/lib/l10n/app_localizations_sl.dart +++ b/lib/l10n/app_localizations_sl.dart @@ -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) { diff --git a/lib/l10n/app_localizations_sv.dart b/lib/l10n/app_localizations_sv.dart index 9aa969ce..fc3c7539 100644 --- a/lib/l10n/app_localizations_sv.dart +++ b/lib/l10n/app_localizations_sv.dart @@ -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) { diff --git a/lib/l10n/app_localizations_uk.dart b/lib/l10n/app_localizations_uk.dart index de2125bc..c0b66621 100644 --- a/lib/l10n/app_localizations_uk.dart +++ b/lib/l10n/app_localizations_uk.dart @@ -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) { diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index 241d78de..d1e28290 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -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) { diff --git a/lib/l10n/app_nl.arb b/lib/l10n/app_nl.arb index 2f192869..93f61445 100644 --- a/lib/l10n/app_nl.arb +++ b/lib/l10n/app_nl.arb @@ -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", diff --git a/lib/l10n/app_pl.arb b/lib/l10n/app_pl.arb index af3783a1..e4850bd4 100644 --- a/lib/l10n/app_pl.arb +++ b/lib/l10n/app_pl.arb @@ -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.", diff --git a/lib/l10n/app_pt.arb b/lib/l10n/app_pt.arb index ad24e07a..51dbc222 100644 --- a/lib/l10n/app_pt.arb +++ b/lib/l10n/app_pt.arb @@ -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", diff --git a/lib/l10n/app_pt_PT.arb b/lib/l10n/app_pt_PT.arb index 80218599..7f093675 100644 --- a/lib/l10n/app_pt_PT.arb +++ b/lib/l10n/app_pt_PT.arb @@ -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", diff --git a/lib/l10n/app_ru.arb b/lib/l10n/app_ru.arb index f5ff336c..c15c5e40 100644 --- a/lib/l10n/app_ru.arb +++ b/lib/l10n/app_ru.arb @@ -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} не доставлено", diff --git a/lib/l10n/app_sk.arb b/lib/l10n/app_sk.arb index c582c8f4..ea09a446 100644 --- a/lib/l10n/app_sk.arb +++ b/lib/l10n/app_sk.arb @@ -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", diff --git a/lib/l10n/app_sl.arb b/lib/l10n/app_sl.arb index 3dcbeb94..40fb0b5b 100644 --- a/lib/l10n/app_sl.arb +++ b/lib/l10n/app_sl.arb @@ -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", diff --git a/lib/l10n/app_sv.arb b/lib/l10n/app_sv.arb index 7ec4e120..7fc55b2e 100644 --- a/lib/l10n/app_sv.arb +++ b/lib/l10n/app_sv.arb @@ -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", diff --git a/lib/l10n/app_uk.arb b/lib/l10n/app_uk.arb index 16d0ca20..e1d60645 100644 --- a/lib/l10n/app_uk.arb +++ b/lib/l10n/app_uk.arb @@ -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} не доставлено", diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb index 6b70ddb0..ce2a3aa8 100644 --- a/lib/l10n/app_zh.arb +++ b/lib/l10n/app_zh.arb @@ -2538,7 +2538,7 @@ "pathEditor_searchRepeaters": "重复搜索", "pathEditor_advancedHex": "高级:原始十六进制路径", "pathEditor_hexLabel": "十六进制前缀", - "pathEditor_hexHelper": "每跳使用两个十六进制字符,用逗号分隔。", + "pathEditor_hexHelper": "每跳使用{count}个十六进制字符,用逗号分隔。", "pathEditor_invalidTokens": "无效:{tokens}", "pathEditor_tooManyHops": "最多 64 跳", "pathEditor_usePath": "请使用此路径", diff --git a/lib/screens/contacts_screen.dart b/lib/screens/contacts_screen.dart index 2d60dd3a..97c439a9 100644 --- a/lib/screens/contacts_screen.dart +++ b/lib/screens/contacts_screen.dart @@ -1201,26 +1201,26 @@ class _ContactsScreenState extends State { }).toList(); } - switch (viewState.contactsSortOption) { - case ContactSortOption.lastSeen: - filtered.sort( - (a, b) => - resolveContactLastSeen(b).compareTo(resolveContactLastSeen(a)), - ); - break; - case ContactSortOption.recentMessages: - final lastMessageAt = { - for (final c in filtered) c: _lastMessageTime(connector, c), - }; - filtered.sort((a, b) => lastMessageAt[b]!.compareTo(lastMessageAt[a]!)); - break; - case ContactSortOption.name: - filtered.sort( - (a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase()), - ); - break; + 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 resolveContactLastSeen(b).compareTo(resolveContactLastSeen(a)); + case ContactSortOption.recentMessages: + return lastMessageAt![b]!.compareTo(lastMessageAt[a]!); + case ContactSortOption.name: + return a.name.toLowerCase().compareTo(b.name.toLowerCase()); + } } + filtered.sort( + (a, b) => + compareContactQueryRank(a, b, viewState.contactsSearchText, tieBreak), + ); + return filtered; } @@ -1409,11 +1409,14 @@ class _ContactsScreenState extends State { 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 diff --git a/lib/screens/discovery_screen.dart b/lib/screens/discovery_screen.dart index 24506563..5c5ad42a 100644 --- a/lib/screens/discovery_screen.dart +++ b/lib/screens/discovery_screen.dart @@ -662,17 +662,32 @@ class _DiscoveryScreenState extends State { 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; diff --git a/lib/screens/map_screen.dart b/lib/screens/map_screen.dart index 018b7ec8..5715fb16 100644 --- a/lib/screens/map_screen.dart +++ b/lib/screens/map_screen.dart @@ -2292,13 +2292,14 @@ class _MapScreenState extends State 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 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 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( diff --git a/lib/utils/contact_search.dart b/lib/utils/contact_search.dart index 7a82c53a..eaad99c2 100644 --- a/lib/utils/contact_search.dart +++ b/lib/utils/contact_search.dart @@ -2,31 +2,55 @@ 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. +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; +} - final hexPrefix = _extractHexPrefix(normalizedQuery); - if (hexPrefix == null) return false; - - 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); } diff --git a/lib/widgets/path_editor_sheet.dart b/lib/widgets/path_editor_sheet.dart index f20aad1c..73a34b31 100644 --- a/lib/widgets/path_editor_sheet.dart +++ b/lib/widgets/path_editor_sheet.dart @@ -1,12 +1,16 @@ -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'; class PathEditorSheet extends StatefulWidget { final List availableContacts; @@ -30,19 +34,25 @@ class PathEditorSheet extends StatefulWidget { 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, + builder: (context) { + final keyboard = MediaQuery.viewInsetsOf(context).bottom; + return Padding( + padding: EdgeInsets.only(bottom: keyboard), + child: Align( + alignment: Alignment.bottomCenter, + child: FractionallySizedBox( + // The keyboard already shrinks the sheet. Use the full band + // above it so the hop list is not clipped under the title. + heightFactor: keyboard > 0 ? 1 : 0.92, + child: PathEditorSheet( + availableContacts: availableContacts, + initialPath: initialPath, + pathHashByteWidth: pathHashByteWidth, + ), + ), ), - ), - ), + ); + }, ); } @@ -62,10 +72,13 @@ class _PathEditorSheetState extends State { final List<_Hop> _hops = []; final _hexController = TextEditingController(); + final _hopScroll = ScrollController(); String? _hexError; bool _syncingHex = false; String _search = ''; int _nextHopId = 0; + int? _highlightedHopId; + Timer? _highlightTimer; @override void initState() { @@ -81,18 +94,25 @@ class _PathEditorSheetState extends State { @override void dispose() { + _highlightTimer?.cancel(); + _hopScroll.dispose(); _hexController.dispose(); super.dispose(); } + int get _hashChars { + final width = widget.pathHashByteWidth.clamp(1, pubKeySize).toInt(); + return width * 2; + } + List 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 +149,7 @@ class _PathEditorSheetState extends State { return; } _hexError = null; + final previous = _hops.length; _hops ..clear() ..addAll( @@ -140,6 +161,9 @@ class _PathEditorSheetState extends State { return _Hop(_nextHopId++, Uint8List.fromList(bytes)); }), ); + if (_hops.length > previous && _hops.isNotEmpty) { + _markHopAdded(_hops.last.id); + } }); } @@ -148,14 +172,38 @@ class _PathEditorSheetState extends State { 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 +230,14 @@ class _PathEditorSheetState extends State { 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 +255,61 @@ class _PathEditorSheetState extends State { : 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 +321,16 @@ class _PathEditorSheetState extends State { 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,13 +338,36 @@ class _PathEditorSheetState extends State { ), 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), ); } + double _hopViewportHeight(double maxHeight, bool tight) { + if (_hops.isEmpty) return 0; + final scaler = MediaQuery.textScalerOf(context); + final rowExtent = tight + ? scaler.scale(56).clamp(56.0, 80.0) + : scaler.scale(76).clamp(72.0, 132.0); + final visibleRows = math.min(_hops.length, tight ? 2 : 3); + final wanted = visibleRows * rowExtent + 4; + // Header, hex field, search field, and the action row stay on screen. + // The hop viewport takes what is left, and never pushes the buttons + // up over the repeater list. + final chrome = tight ? 210.0 : 430.0; + final available = maxHeight - chrome; + if (available >= rowExtent) { + return math.min(wanted, available); + } + return math.max(0.0, available); + } + @override Widget build(BuildContext context) { final l10n = context.l10n; @@ -277,139 +375,208 @@ class _PathEditorSheetState extends State { 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), - ), - ), - 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, - ), + 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 hopHeight = _hopViewportHeight(maxHeight, compact); + + return Column( + children: [ + Padding( + padding: EdgeInsets.fromLTRB(16, compact ? 6 : 10, 16, 0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, 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(), + Center( + child: Container( + width: 36, + height: 4, + decoration: BoxDecoration( + color: scheme.outline, + borderRadius: BorderRadius.circular(2), + ), + ), + ), + SizedBox(height: compact ? 4 : 12), + Text( + l10n.pathEditor_title, + style: theme.textTheme.titleMedium?.copyWith( + fontWeight: FontWeight.w700, + letterSpacing: -0.2, + ), + ), + Semantics( + liveRegion: true, + child: Text( + l10n.pathEditor_hopCounter(_hops.length), + style: theme.textTheme.bodySmall?.copyWith( + color: scheme.onSurfaceVariant, ), ), ), ], ), - ], - ), - ), - SafeArea( - top: false, - child: Padding( - padding: const EdgeInsets.fromLTRB(16, 8, 16, 16), - child: Row( - children: [ - Expanded( - child: TextButton( - style: TextButton.styleFrom( - minimumSize: const Size.fromHeight(48), - ), - onPressed: () => Navigator.pop(context), - child: Text(l10n.common_cancel), - ), - ), - const SizedBox(width: 12), - Expanded( - child: FilledButton( - style: FilledButton.styleFrom( - minimumSize: const Size.fromHeight(48), - ), - onPressed: _hexError != null ? null : _save, - child: Text(l10n.pathEditor_usePath), - ), - ), - ], ), - ), - ), - ], + Padding( + padding: EdgeInsets.fromLTRB(16, compact ? 4 : 10, 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, + ), + ), + ) + : SizedBox( + height: hopHeight, + child: 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), + ), + ), + ), + ), + Padding( + padding: EdgeInsets.fromLTRB(16, compact ? 6 : 16, 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, + 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: 3, + border: const OutlineInputBorder(), + isDense: compact, + ), + ), + ], + ), + ), + Padding( + padding: EdgeInsets.fromLTRB(16, compact ? 6 : 14, 16, 0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (!compact) ...[ + Text( + l10n.pathEditor_addHops, + style: theme.textTheme.titleSmall, + ), + const SizedBox(height: 8), + ], + TextField( + key: const Key('path-editor-search-field'), + onChanged: (value) => setState(() => _search = value), + scrollPadding: EdgeInsets.zero, + decoration: InputDecoration( + labelText: l10n.pathEditor_searchRepeaters, + prefixIcon: const Icon(Icons.search), + border: const OutlineInputBorder(), + isDense: compact, + ), + ), + ], + ), + ), + Expanded( + child: repeaters.isEmpty + ? 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, + ), + ), + ), + ) + : 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]), + ), + ), + SafeArea( + top: false, + child: Padding( + padding: EdgeInsets.fromLTRB( + 16, + compact ? 4 : 8, + 16, + compact ? 4 : 16, + ), + child: Row( + children: [ + Expanded( + child: TextButton( + style: TextButton.styleFrom( + minimumSize: const Size.fromHeight(48), + ), + onPressed: () => Navigator.pop(context), + child: Text(l10n.common_cancel), + ), + ), + const SizedBox(width: 12), + Expanded( + child: FilledButton( + style: FilledButton.styleFrom( + minimumSize: const Size.fromHeight(48), + ), + onPressed: _hexError != null ? null : _save, + child: Text(l10n.pathEditor_usePath), + ), + ), + ], + ), + ), + ), + ], + ); + }, ); } } diff --git a/lib/widgets/share_contact_sheet.dart b/lib/widgets/share_contact_sheet.dart index df0549d7..c38c48d1 100644 --- a/lib/widgets/share_contact_sheet.dart +++ b/lib/widgets/share_contact_sheet.dart @@ -7,6 +7,7 @@ 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,14 +51,10 @@ 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 && diff --git a/test/utils/contact_search_test.dart b/test/utils/contact_search_test.dart new file mode 100644 index 00000000..d2d1cff4 --- /dev/null +++ b/test/utils/contact_search_test.dart @@ -0,0 +1,109 @@ +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 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 _ranked(List 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('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']); + }); +} diff --git a/test/widgets/path_editor_sheet_test.dart b/test/widgets/path_editor_sheet_test.dart new file mode 100644 index 00000000..79ecf6af --- /dev/null +++ b/test/widgets/path_editor_sheet_test.dart @@ -0,0 +1,199 @@ +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 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 _pumpSheet( + WidgetTester tester, { + Size size = const Size(400, 700), + double keyboard = 0, + List 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), + ), + child: Scaffold( + body: SizedBox( + width: size.width, + height: size.height - keyboard, + child: PathEditorSheet( + availableContacts: _contacts, + initialPath: initialPath, + pathHashByteWidth: 2, + ), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); +} + +List _repeaterNames(WidgetTester tester) { + return tester + .widgetList( + find.descendant( + of: find.byKey(const Key('path-editor-repeater-list')), + matching: find.byType(Text), + ), + ) + .map((text) => text.data) + .whereType() + .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(tester.takeException(), isNull); + }); + + 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('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); + }); +} From 3e1c71162de4a0667fbaea8246c030f4d4c64a7f Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Fri, 20 Nov 2026 21:48:17 +0000 Subject: [PATCH 2/6] Shrink the path hop list when hex validation grows An invalid hex path adds error lines under the field. The hop viewport now gives that space back, and a long error scrolls inside its own box instead of overflowing the sheet. Co-authored-by: zjs81 --- lib/widgets/path_editor_sheet.dart | 337 ++++++++++++++--------- test/widgets/path_editor_sheet_test.dart | 26 ++ 2 files changed, 234 insertions(+), 129 deletions(-) diff --git a/lib/widgets/path_editor_sheet.dart b/lib/widgets/path_editor_sheet.dart index 73a34b31..1a57678e 100644 --- a/lib/widgets/path_editor_sheet.dart +++ b/lib/widgets/path_editor_sheet.dart @@ -349,23 +349,59 @@ class _PathEditorSheetState extends State { ); } - double _hopViewportHeight(double maxHeight, bool tight) { - if (_hops.isEmpty) return 0; + /// 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, and the error itself + /// scrolls inside its own box instead of overflowing the sheet. + ({double hop, double hex, double search}) _middleBudget( + double space, + bool compact, + ) { final scaler = MediaQuery.textScalerOf(context); - final rowExtent = tight - ? scaler.scale(56).clamp(56.0, 80.0) - : scaler.scale(76).clamp(72.0, 132.0); - final visibleRows = math.min(_hops.length, tight ? 2 : 3); - final wanted = visibleRows * rowExtent + 4; - // Header, hex field, search field, and the action row stay on screen. - // The hop viewport takes what is left, and never pushes the buttons - // up over the repeater list. - final chrome = tight ? 210.0 : 430.0; - final available = maxHeight - chrome; - if (available >= rowExtent) { - return math.min(wanted, available); + final row = compact + ? scaler.scale(56).clamp(56.0, 96.0) + : scaler.scale(76).clamp(72.0, 140.0); + final gaps = compact ? 16.0 : 40.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 ? 36 : 48); + final wantedHop = _hops.isEmpty + ? math.min(scaler.scale(compact ? 64 : 80), 140.0) + : math.min(_hops.length, compact ? 2 : 3) * row + 4; + final minHop = _hops.isEmpty + ? 0.0 + : math.min(row, math.max(0.0, space - gaps)); + + var hopH = wantedHop; + var hexH = baseHex + errorExtra; + final used = hopH + hexH + searchH + gaps; + if (used > space) { + var overflow = used - space; + final hopCut = math.min(overflow, math.max(0.0, hopH - minHop)); + hopH -= hopCut; + overflow -= hopCut; + if (overflow > 0) { + final hexFloor = math.min( + baseHex, + math.max(0.0, space - searchH - gaps - hopH), + ); + final hexCut = math.min(overflow, math.max(0.0, hexH - hexFloor)); + hexH -= hexCut; + overflow -= hexCut; + } + if (overflow > 0) { + hopH = math.max(0.0, hopH - overflow); + } } - return math.max(0.0, available); + return ( + hop: math.max(0.0, hopH), + hex: math.max(0.0, hexH), + search: searchH, + ); } @override @@ -383,7 +419,6 @@ class _PathEditorSheetState extends State { // 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 hopHeight = _hopViewportHeight(maxHeight, compact); return Column( children: [ @@ -422,123 +457,167 @@ class _PathEditorSheetState extends State { ], ), ), - Padding( - padding: EdgeInsets.fromLTRB(16, compact ? 4 : 10, 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, - ), - ), - ) - : SizedBox( - height: hopHeight, - child: 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), - ), - ), - ), - ), - Padding( - padding: EdgeInsets.fromLTRB(16, compact ? 6 : 16, 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, - 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: 3, - border: const OutlineInputBorder(), - isDense: compact, - ), - ), - ], - ), - ), - Padding( - padding: EdgeInsets.fromLTRB(16, compact ? 6 : 14, 16, 0), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - if (!compact) ...[ - Text( - l10n.pathEditor_addHops, - style: theme.textTheme.titleSmall, - ), - const SizedBox(height: 8), - ], - TextField( - key: const Key('path-editor-search-field'), - onChanged: (value) => setState(() => _search = value), - scrollPadding: EdgeInsets.zero, - decoration: InputDecoration( - labelText: l10n.pathEditor_searchRepeaters, - prefixIcon: const Icon(Icons.search), - border: const OutlineInputBorder(), - isDense: compact, - ), - ), - ], - ), - ), Expanded( - child: repeaters.isEmpty - ? 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, + child: LayoutBuilder( + builder: (context, inner) { + final budget = _middleBudget(inner.maxHeight, compact); + return Column( + children: [ + SizedBox( + height: budget.hop, + child: budget.hop < 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, + ), + ), + ), + ), + ), + SizedBox( + height: budget.hex, + 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, + 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, + ), + ), + ], ), ), ), - ) - : 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]), - ), + SizedBox( + height: budget.search, + child: Padding( + padding: EdgeInsets.fromLTRB( + 16, + compact ? 6 : 12, + 16, + 0, + ), + child: TextField( + key: const Key('path-editor-search-field'), + onChanged: (value) => + setState(() => _search = value), + scrollPadding: EdgeInsets.zero, + decoration: InputDecoration( + labelText: l10n.pathEditor_searchRepeaters, + prefixIcon: const Icon(Icons.search), + border: const OutlineInputBorder(), + isDense: compact, + ), + ), + ), + ), + Expanded( + child: repeaters.isEmpty + ? 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, + ), + ), + ), + ) + : 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]), + ), + ), + ], + ); + }, + ), ), SafeArea( top: false, diff --git a/test/widgets/path_editor_sheet_test.dart b/test/widgets/path_editor_sheet_test.dart index 79ecf6af..972b0562 100644 --- a/test/widgets/path_editor_sheet_test.dart +++ b/test/widgets/path_editor_sheet_test.dart @@ -165,6 +165,32 @@ void main() { 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('action buttons stay below the repeater list on a short sheet', ( tester, ) async { From c4675d810ed163cbebec7e3831fa5d7295d24c90 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Fri, 20 Nov 2026 22:30:35 +0000 Subject: [PATCH 3/6] Seat the path sheet header with the other sheets The sheet background was taller than its content, leaving an empty band above the drag handle. Use the shared sheet header, and rank the share sheet's own contact with the same name and hash matcher. Co-authored-by: zjs81 --- documentation/design.md | 2 +- lib/utils/contact_search.dart | 41 ++++++++- lib/widgets/path_editor_sheet.dart | 68 +++++---------- lib/widgets/share_contact_sheet.dart | 102 +++++++++++++++-------- test/utils/contact_search_test.dart | 39 +++++++++ test/widgets/path_editor_sheet_test.dart | 40 +++++++++ 6 files changed, 203 insertions(+), 89 deletions(-) diff --git a/documentation/design.md b/documentation/design.md index dee9c2ce..85ade038 100644 --- a/documentation/design.md +++ b/documentation/design.md @@ -165,7 +165,7 @@ 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. -The manual path editor (`path_editor_sheet.dart`) is a fixed-height sheet, not a draggable one. The hop list and the hex path field stay pinned above a scrolling repeater list, including while the keyboard is open. The sheet uses the full height above the keyboard so a newly added hop is not scrolled under the title. +The manual path editor (`path_editor_sheet.dart`) uses `showMeshSheet` and `BottomSheetHeader`, the same top padding, drag handle, and title row as the other sheets. The hop list and the hex path field stay pinned under that header, including while the keyboard is open. ## 7. App bars diff --git a/lib/utils/contact_search.dart b/lib/utils/contact_search.dart index eaad99c2..9101bc9a 100644 --- a/lib/utils/contact_search.dart +++ b/lib/utils/contact_search.dart @@ -9,19 +9,54 @@ enum ContactQueryRank { namePrefix, nameContains, keyPrefix } /// /// 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 name = contact.name.toLowerCase(); - if (name.startsWith(normalized)) return ContactQueryRank.namePrefix; - if (name.contains(normalized)) return ContactQueryRank.nameContains; + final byName = rankNameQuery(contact.name, normalized); + if (byName != null) return byName; if (_publicKeyPrefixMatches(contact, normalized)) { return ContactQueryRank.keyPrefix; } return null; } +/// 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 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; +} + bool matchesContactQuery(Contact contact, String query) { return rankContactQuery(contact, query) != null; } diff --git a/lib/widgets/path_editor_sheet.dart b/lib/widgets/path_editor_sheet.dart index 1a57678e..cbed8317 100644 --- a/lib/widgets/path_editor_sheet.dart +++ b/lib/widgets/path_editor_sheet.dart @@ -11,6 +11,7 @@ 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 availableContacts; @@ -30,27 +31,26 @@ class PathEditorSheet extends StatefulWidget { List initialPath = const [], int pathHashByteWidth = pathHashSize, }) { - return showModalBottomSheet( - context: context, - isScrollControlled: true, - useSafeArea: true, + // 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( + context, builder: (context) { - final keyboard = MediaQuery.viewInsetsOf(context).bottom; - return Padding( - padding: EdgeInsets.only(bottom: keyboard), - child: Align( - alignment: Alignment.bottomCenter, - child: FractionallySizedBox( - // The keyboard already shrinks the sheet. Use the full band - // above it so the hop list is not clipped under the title. - heightFactor: keyboard > 0 ? 1 : 0.92, + 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, ), - ), - ), + ); + }, ); }, ); @@ -422,39 +422,11 @@ class _PathEditorSheetState extends State { return Column( children: [ - Padding( - padding: EdgeInsets.fromLTRB(16, compact ? 6 : 10, 16, 0), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Center( - child: Container( - width: 36, - height: 4, - decoration: BoxDecoration( - color: scheme.outline, - borderRadius: BorderRadius.circular(2), - ), - ), - ), - SizedBox(height: compact ? 4 : 12), - Text( - l10n.pathEditor_title, - style: theme.textTheme.titleMedium?.copyWith( - fontWeight: FontWeight.w700, - letterSpacing: -0.2, - ), - ), - Semantics( - liveRegion: true, - child: Text( - l10n.pathEditor_hopCounter(_hops.length), - style: theme.textTheme.bodySmall?.copyWith( - color: scheme.onSurfaceVariant, - ), - ), - ), - ], + Semantics( + liveRegion: true, + child: BottomSheetHeader( + title: l10n.pathEditor_title, + subtitle: l10n.pathEditor_hopCounter(_hops.length), ), ), Expanded( diff --git a/lib/widgets/share_contact_sheet.dart b/lib/widgets/share_contact_sheet.dart index c38c48d1..88828c11 100644 --- a/lib/widgets/share_contact_sheet.dart +++ b/lib/widgets/share_contact_sheet.dart @@ -2,6 +2,7 @@ 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'; @@ -56,12 +57,14 @@ class _ShareContactSheetState extends State<_ShareContactSheet> { .toList() ..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( @@ -83,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 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, diff --git a/test/utils/contact_search_test.dart b/test/utils/contact_search_test.dart index d2d1cff4..19937868 100644 --- a/test/utils/contact_search_test.dart +++ b/test/utils/contact_search_test.dart @@ -88,6 +88,45 @@ void main() { 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, diff --git a/test/widgets/path_editor_sheet_test.dart b/test/widgets/path_editor_sheet_test.dart index 972b0562..d98d3217 100644 --- a/test/widgets/path_editor_sheet_test.dart +++ b/test/widgets/path_editor_sheet_test.dart @@ -208,6 +208,46 @@ void main() { 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( From cd211da0efa739e45b860757cf066087469a0f44 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Fri, 20 Nov 2026 22:53:06 +0000 Subject: [PATCH 4/6] Scroll the path sheet when the keyboard leaves no room A landscape keyboard can leave less than the search field under the header. The pinned column overflowed there, so that band now scrolls the hops, hex field, search field, and repeater list together. Co-authored-by: zjs81 --- documentation/design.md | 2 +- documentation/routing-paths.md | 2 +- lib/widgets/path_editor_sheet.dart | 455 +++++++++++++++-------- test/widgets/path_editor_sheet_test.dart | 88 +++++ 4 files changed, 388 insertions(+), 159 deletions(-) diff --git a/documentation/design.md b/documentation/design.md index 85ade038..021a67e3 100644 --- a/documentation/design.md +++ b/documentation/design.md @@ -165,7 +165,7 @@ 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. -The manual path editor (`path_editor_sheet.dart`) uses `showMeshSheet` and `BottomSheetHeader`, the same top padding, drag handle, and title row as the other sheets. The hop list and the hex path field stay pinned under that header, including while the keyboard is open. +The manual path editor (`path_editor_sheet.dart`) uses `showMeshSheet` and `BottomSheetHeader`, the same top padding, drag handle, and title row as the other sheets. The hop list and the hex path field stay pinned under that 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. App bars diff --git a/documentation/routing-paths.md b/documentation/routing-paths.md index 90202fc4..e053e11b 100644 --- a/documentation/routing-paths.md +++ b/documentation/routing-paths.md @@ -64,6 +64,6 @@ Contacts/messages persist hop count, path bytes, and width. Legacy contact recor ## 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. 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. +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). diff --git a/lib/widgets/path_editor_sheet.dart b/lib/widgets/path_editor_sheet.dart index cbed8317..6cc623df 100644 --- a/lib/widgets/path_editor_sheet.dart +++ b/lib/widgets/path_editor_sheet.dart @@ -355,7 +355,12 @@ class _PathEditorSheetState extends State { /// An invalid hex path grows the error text. That growth comes out of the /// hop viewport first, keeping one row when it fits, and the error itself /// scrolls inside its own box instead of overflowing the sheet. - ({double hop, double hex, double search}) _middleBudget( + /// + /// [scroll] is set when that band is shorter than the search field, which + /// happens when a landscape keyboard leaves only the header and the action + /// buttons. The pinned column would overflow, so the caller lays the same + /// blocks out in one scroll view instead. + ({double hop, double hex, double search, bool scroll}) _middleBudget( double space, bool compact, ) { @@ -372,12 +377,13 @@ class _PathEditorSheetState extends State { 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 : math.min(row, math.max(0.0, space - gaps)); var hopH = wantedHop; - var hexH = baseHex + errorExtra; + var hexH = wantedHex; final used = hopH + hexH + searchH + gaps; if (used > space) { var overflow = used - space; @@ -397,18 +403,294 @@ class _PathEditorSheetState extends State { hopH = math.max(0.0, hopH - overflow); } } + hopH = math.max(0.0, hopH); + hexH = math.max(0.0, hexH); + // The search field stays at its full height in the pinned column. When + // the band cannot hold it, scrolling is the only way to reach it and the + // repeater list. + final scroll = hopH + hexH + searchH > space; return ( - hop: math.max(0.0, hopH), - hex: math.max(0.0, hexH), + hop: scroll ? wantedHop : hopH, + hex: scroll ? wantedHex : hexH, 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, + 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'), + 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 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]), + ); + } + + /// 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 repeaters, + }) { + final l10n = context.l10n; + final theme = Theme.of(context); + final scheme = theme.colorScheme; + return CustomScrollView( + key: const Key('path-editor-scroll-fallback'), + keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag, + slivers: [ + 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]), + ), + ), + ], + ); + } + + 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, + 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'), + 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 LayoutBuilder( @@ -433,159 +715,18 @@ class _PathEditorSheetState extends State { child: LayoutBuilder( builder: (context, inner) { final budget = _middleBudget(inner.maxHeight, compact); + if (budget.scroll) { + return _scrollingMiddle( + compact: compact, + repeaters: repeaters, + ); + } return Column( children: [ - SizedBox( - height: budget.hop, - child: budget.hop < 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, - ), - ), - ), - ), - ), - SizedBox( - height: budget.hex, - 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, - 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, - ), - ), - ], - ), - ), - ), - SizedBox( - height: budget.search, - child: Padding( - padding: EdgeInsets.fromLTRB( - 16, - compact ? 6 : 12, - 16, - 0, - ), - child: TextField( - key: const Key('path-editor-search-field'), - onChanged: (value) => - setState(() => _search = value), - scrollPadding: EdgeInsets.zero, - decoration: InputDecoration( - labelText: l10n.pathEditor_searchRepeaters, - prefixIcon: const Icon(Icons.search), - border: const OutlineInputBorder(), - isDense: compact, - ), - ), - ), - ), - Expanded( - child: repeaters.isEmpty - ? 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, - ), - ), - ), - ) - : 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]), - ), - ), + _hopViewport(compact, budget.hop), + _hexViewport(compact, budget.hex), + _searchViewport(compact, budget.search), + Expanded(child: _repeaterViewport(repeaters)), ], ); }, diff --git a/test/widgets/path_editor_sheet_test.dart b/test/widgets/path_editor_sheet_test.dart index d98d3217..29aa1ee8 100644 --- a/test/widgets/path_editor_sheet_test.dart +++ b/test/widgets/path_editor_sheet_test.dart @@ -67,6 +67,29 @@ Future _pumpSheet( await tester.pumpAndSettle(); } +Future _revealInFallback( + WidgetTester tester, + Finder scrollable, + Finder target, +) async { + final state = tester.state(scrollable); + final view = tester.getRect( + find.byKey(const Key('path-editor-scroll-fallback')), + ); + for (var i = 0; i < 40; i++) { + final rect = tester.getRect(target); + if (rect.center.dy >= view.top && rect.center.dy <= view.bottom) return; + final next = (state.position.pixels + 48).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 the path sheet'); +} + List _repeaterNames(WidgetTester tester) { return tester .widgetList( @@ -162,6 +185,7 @@ void main() { find.byKey(const Key('path-editor-hex-field')).hitTestable(), findsOneWidget, ); + expect(find.byKey(const Key('path-editor-scroll-fallback')), findsNothing); expect(tester.takeException(), isNull); }); @@ -191,6 +215,70 @@ void main() { 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, + ); + // The hop list has its own scrollable. The fallback is the scrollable + // that also contains the hex field. + final scrollable = 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; + }); + 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('action buttons stay below the repeater list on a short sheet', ( tester, ) async { From 52be39e4e8dfec479abdec79bb863e94fba5005e Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Fri, 20 Nov 2026 22:54:58 +0000 Subject: [PATCH 5/6] Document sheet layout and shared node search The design reference now says new sheets use the shared header flush with the top of the sheet, and that contact, repeater, room and user search share one prefix, substring, then hash ranking. Co-authored-by: zjs81 --- documentation/design.md | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/documentation/design.md b/documentation/design.md index 021a67e3..d7905230 100644 --- a/documentation/design.md +++ b/documentation/design.md @@ -165,9 +165,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. -The manual path editor (`path_editor_sheet.dart`) uses `showMeshSheet` and `BottomSheetHeader`, the same top padding, drag handle, and title row as the other sheets. The hop list and the hex path field stay pinned under that 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. +**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. -## 7. App bars +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. @@ -176,7 +184,7 @@ The manual path editor (`path_editor_sheet.dart`) uses `showMeshSheet` and `Bott - 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 | |---|---| @@ -199,7 +207,7 @@ The manual path editor (`path_editor_sheet.dart`) uses `showMeshSheet` and `Bott 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. @@ -213,7 +221,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. @@ -221,13 +229,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: From f85dbee51e3480b0a0086a5dc8739be47eae41e0 Mon Sep 17 00:00:00 2001 From: zjs81 <30362347+zjs81@users.noreply.github.com> Date: Fri, 20 Nov 2026 23:31:55 -0700 Subject: [PATCH 6/6] Scroll path editor sheet whenever pinned fields cannot fit --- lib/widgets/path_editor_sheet.dart | 234 ++++++++++++----------- test/widgets/path_editor_sheet_test.dart | 199 +++++++++++++++++-- 2 files changed, 300 insertions(+), 133 deletions(-) diff --git a/lib/widgets/path_editor_sheet.dart b/lib/widgets/path_editor_sheet.dart index 6cc623df..443e2dc4 100644 --- a/lib/widgets/path_editor_sheet.dart +++ b/lib/widgets/path_editor_sheet.dart @@ -72,6 +72,8 @@ class _PathEditorSheetState extends State { final List<_Hop> _hops = []; final _hexController = TextEditingController(); + final _hexFocus = FocusNode(); + final _searchFocus = FocusNode(); final _hopScroll = ScrollController(); String? _hexError; bool _syncingHex = false; @@ -96,6 +98,8 @@ class _PathEditorSheetState extends State { void dispose() { _highlightTimer?.cancel(); _hopScroll.dispose(); + _hexFocus.dispose(); + _searchFocus.dispose(); _hexController.dispose(); super.dispose(); } @@ -353,13 +357,10 @@ class _PathEditorSheetState extends State { /// 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, and the error itself - /// scrolls inside its own box instead of overflowing the sheet. - /// - /// [scroll] is set when that band is shorter than the search field, which - /// happens when a landscape keyboard leaves only the header and the action - /// buttons. The pinned column would overflow, so the caller lays the same - /// blocks out in one scroll view instead. + /// 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, @@ -368,53 +369,31 @@ class _PathEditorSheetState extends State { final row = compact ? scaler.scale(56).clamp(56.0, 96.0) : scaler.scale(76).clamp(72.0, 140.0); - final gaps = compact ? 16.0 : 40.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 ? 36 : 48); + : 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 - : math.min(row, math.max(0.0, space - gaps)); + final minHop = _hops.isEmpty ? 0.0 : row; + final scroll = minHop + wantedHex + searchH > space; var hopH = wantedHop; - var hexH = wantedHex; - final used = hopH + hexH + searchH + gaps; - if (used > space) { - var overflow = used - space; - final hopCut = math.min(overflow, math.max(0.0, hopH - minHop)); - hopH -= hopCut; - overflow -= hopCut; - if (overflow > 0) { - final hexFloor = math.min( - baseHex, - math.max(0.0, space - searchH - gaps - hopH), - ); - final hexCut = math.min(overflow, math.max(0.0, hexH - hexFloor)); - hexH -= hexCut; - overflow -= hexCut; - } - if (overflow > 0) { - hopH = math.max(0.0, hopH - overflow); + 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)); } } - hopH = math.max(0.0, hopH); - hexH = math.max(0.0, hexH); - // The search field stays at its full height in the pinned column. When - // the band cannot hold it, scrolling is the only way to reach it and the - // repeater list. - final scroll = hopH + hexH + searchH > space; - return ( - hop: scroll ? wantedHop : hopH, - hex: scroll ? wantedHex : hexH, - search: searchH, - scroll: scroll, - ); + return (hop: hopH, hex: wantedHex, search: searchH, scroll: scroll); } Widget _hopViewport(bool compact, double height) { @@ -479,6 +458,7 @@ class _PathEditorSheetState extends State { TextField( key: const Key('path-editor-hex-field'), controller: _hexController, + focusNode: _hexFocus, onChanged: _onHexChanged, textCapitalization: TextCapitalization.characters, style: MeshTheme.mono(fontSize: 14), @@ -509,6 +489,7 @@ class _PathEditorSheetState extends State { 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( @@ -549,6 +530,42 @@ class _PathEditorSheetState extends State { ); } + List _middleSlivers({ + required bool compact, + required List 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 @@ -558,39 +575,10 @@ class _PathEditorSheetState extends State { required bool compact, required List repeaters, }) { - final l10n = context.l10n; - final theme = Theme.of(context); - final scheme = theme.colorScheme; return CustomScrollView( key: const Key('path-editor-scroll-fallback'), keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag, - slivers: [ - 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]), - ), - ), - ], + slivers: _middleSlivers(compact: compact, repeaters: repeaters), ); } @@ -649,6 +637,7 @@ class _PathEditorSheetState extends State { TextField( key: const Key('path-editor-hex-field'), controller: _hexController, + focusNode: _hexFocus, onChanged: _onHexChanged, textCapitalization: TextCapitalization.characters, style: MeshTheme.mono(fontSize: 14), @@ -676,6 +665,7 @@ class _PathEditorSheetState extends State { 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( @@ -701,16 +691,67 @@ class _PathEditorSheetState extends State { // 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), + ), + ); + final actions = SafeArea( + top: false, + child: Padding( + padding: EdgeInsets.fromLTRB( + 16, + compact ? 4 : 8, + 16, + compact ? 4 : 16, + ), + child: Row( + children: [ + Expanded( + child: TextButton( + style: TextButton.styleFrom( + minimumSize: const Size.fromHeight(48), + ), + onPressed: () => Navigator.pop(context), + child: Text(l10n.common_cancel), + ), + ), + const SizedBox(width: 12), + Expanded( + child: FilledButton( + style: FilledButton.styleFrom( + minimumSize: const Size.fromHeight(48), + ), + onPressed: _hexError != null ? null : _save, + child: Text(l10n.pathEditor_usePath), + ), + ), + ], + ), + ), + ); + + // 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: [ - Semantics( - liveRegion: true, - child: BottomSheetHeader( - title: l10n.pathEditor_title, - subtitle: l10n.pathEditor_hopCounter(_hops.length), - ), - ), + header, Expanded( child: LayoutBuilder( builder: (context, inner) { @@ -732,40 +773,7 @@ class _PathEditorSheetState extends State { }, ), ), - SafeArea( - top: false, - child: Padding( - padding: EdgeInsets.fromLTRB( - 16, - compact ? 4 : 8, - 16, - compact ? 4 : 16, - ), - child: Row( - children: [ - Expanded( - child: TextButton( - style: TextButton.styleFrom( - minimumSize: const Size.fromHeight(48), - ), - onPressed: () => Navigator.pop(context), - child: Text(l10n.common_cancel), - ), - ), - const SizedBox(width: 12), - Expanded( - child: FilledButton( - style: FilledButton.styleFrom( - minimumSize: const Size.fromHeight(48), - ), - onPressed: _hexError != null ? null : _save, - child: Text(l10n.pathEditor_usePath), - ), - ), - ], - ), - ), - ), + actions, ], ); }, diff --git a/test/widgets/path_editor_sheet_test.dart b/test/widgets/path_editor_sheet_test.dart index 29aa1ee8..d94e90b1 100644 --- a/test/widgets/path_editor_sheet_test.dart +++ b/test/widgets/path_editor_sheet_test.dart @@ -35,6 +35,7 @@ Future _pumpSheet( WidgetTester tester, { Size size = const Size(400, 700), double keyboard = 0, + double textScale = 1.0, List initialPath = const [], }) async { tester.view.physicalSize = size; @@ -49,12 +50,14 @@ Future _pumpSheet( 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, @@ -67,6 +70,24 @@ Future _pumpSheet( 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 _revealInFallback( WidgetTester tester, Finder scrollable, @@ -76,10 +97,11 @@ Future _revealInFallback( final view = tester.getRect( find.byKey(const Key('path-editor-scroll-fallback')), ); - for (var i = 0; i < 40; i++) { + 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 + 48).clamp( + final next = (state.position.pixels + step).clamp( 0.0, state.position.maxScrollExtent, ); @@ -87,7 +109,9 @@ Future _revealInFallback( state.position.jumpTo(next); await tester.pump(); } - fail('Could not scroll $target into the path sheet'); + fail( + 'Could not scroll $target into $view (last rect=${tester.getRect(target)}, pixels=${state.position.pixels})', + ); } List _repeaterNames(WidgetTester tester) { @@ -215,6 +239,61 @@ void main() { 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(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 { @@ -229,23 +308,7 @@ void main() { find.byKey(const Key('path-editor-scroll-fallback')), findsOneWidget, ); - // The hop list has its own scrollable. The fallback is the scrollable - // that also contains the hex field. - final scrollable = 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; - }); + final scrollable = _fallbackScrollable(); await tester.scrollUntilVisible( find.byKey(const Key('path-editor-hex-field')), 40, @@ -279,6 +342,102 @@ void main() { 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(_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 {