From 6994846f8608e90932698083cd6f070db8227652 Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Sun, 6 Dec 2026 14:10:22 +0300 Subject: [PATCH] Add incremental file filtering and match navigation --- README.md | 8 +- docs/acceptance.md | 7 + docs/spec-matrix.md | 13 + docs/testing.md | 7 + docs/tui-design-guidelines.md | 8 + .../add-file-search-and-filter/.openspec.yaml | 2 + .../add-file-search-and-filter/design.md | 105 ++++ .../add-file-search-and-filter/proposal.md | 31 ++ .../specs/file-filtering/spec.md | 103 ++++ .../specs/terminal-ui/spec.md | 48 ++ .../add-file-search-and-filter/tasks.md | 40 ++ src/app/filtering.rs | 269 ++++++++++ src/app/help.rs | 74 ++- src/app/mod.rs | 136 ++++- src/domain/filter.rs | 62 +++ src/domain/mod.rs | 2 + src/input/mod.rs | 43 +- src/session.rs | 1 + src/tui.rs | 9 +- src/ui/layout.rs | 36 +- src/ui/render.rs | 101 +++- tests/app_navigation.rs | 3 +- tests/file_filter.rs | 144 ++++++ tests/filter_input.rs | 87 ++++ tests/filter_navigation.rs | 481 ++++++++++++++++++ tests/filter_runtime.rs | 62 +++ tests/filter_ui.rs | 107 ++++ tests/help_inventory.rs | 30 ++ tests/pty_smoke.rs | 43 ++ tests/selection_clipboard.rs | 10 +- .../ui_overlays__snapshot_help_120x40.snap | 8 +- tests/ui_accessibility.rs | 2 +- tests/workspace_panes.rs | 8 +- 33 files changed, 2043 insertions(+), 47 deletions(-) create mode 100644 openspec/changes/add-file-search-and-filter/.openspec.yaml create mode 100644 openspec/changes/add-file-search-and-filter/design.md create mode 100644 openspec/changes/add-file-search-and-filter/proposal.md create mode 100644 openspec/changes/add-file-search-and-filter/specs/file-filtering/spec.md create mode 100644 openspec/changes/add-file-search-and-filter/specs/terminal-ui/spec.md create mode 100644 openspec/changes/add-file-search-and-filter/tasks.md create mode 100644 src/app/filtering.rs create mode 100644 src/domain/filter.rs create mode 100644 tests/file_filter.rs create mode 100644 tests/filter_input.rs create mode 100644 tests/filter_navigation.rs create mode 100644 tests/filter_runtime.rs create mode 100644 tests/filter_ui.rs diff --git a/README.md b/README.md index daec08e..89d38b7 100644 --- a/README.md +++ b/README.md @@ -62,6 +62,8 @@ Yazi-подобные и mc-команды доступны одновремен | Действие | Клавиши | |---|---| | Перемещение | `j` / `k`, `Down` / `Up` | +| Фильтр/поиск текущего каталога | `/`; `Enter` Apply, `Esc` Cancel/Clear | +| Следующее / предыдущее совпадение | `n` / `N` | | Родительский каталог | `h`, `Left` | | Открыть каталог | `l`, `Right`, `Enter` | | Первая / последняя строка | `gg` / `G`, `Home` / `End` | @@ -92,6 +94,8 @@ Yazi-подобные и mc-команды доступны одновремен В HostPicker текст вводится в фильтр, `Up`/`Down` меняют выбор, `Enter` подключает хост, `Esc` закрывает без изменения панели. В prompts текст редактируется до глобальных aliases; `Esc` отменяет без mutation. +`/` открывает incremental filter уже загруженного каталога без нового listing I/O. Ввод использует lowercase-based substring, сохраняет совпадающий EntryId и иначе выбирает первый match. `Enter` применяет draft, `Esc` откатывает его; после Apply `n`/`N` циклически переходят по совпадениям. `Ctrl-u` очищает ввод, а `Esc` вне visual mode очищает applied filter. Status показывает `visible/total`, NO MATCHES и число скрытых query marked entries; фильтры панелей независимы и переживают same-location refresh, но очищаются после accepted navigation/reconnect. + Help содержит шесть категорий: **Navigation, Selection, Files, Tasks, SSH, General**. `h`/`Left`/`Shift-Tab` и `l`/`Right`/`Tab` переключают их с wrap; `j`/`k`, `Up`/`Down`, `PageUp`/`PageDown`, `Ctrl-b`/`Ctrl-f` и `Ctrl-u`/`Ctrl-d` прокручивают содержимое. На 40×8 полный tab strip заменяется на `< N/6 Category >`, а все команды остаются достижимыми постранично. `Esc`, `q`, `?` или F1 закрывают Help без изменения workspace; Enter ничего не выполняет, F10 выходит через обычный quit path. В Task Details те же вертикальные aliases прокручивают именно подробности и не меняют выбор задачи за overlay. Clipboard `y`/`x` сохраняет исходный snapshot: после multi-select можно перейти в другой каталог или на другую панель перед `p`. Paste создаёт новый plan для исходных источников и актуального destination; missing source/stale SSH epoch по-прежнему отклоняются. После committed copy/move затронутые панели обновляются автоматически, включая partial/cancelled результат. @@ -134,13 +138,13 @@ Copy/move сначала выполняют read-only preflight и показы - Copy использует unique sibling `.rcom-part-*`, flush/close, size/collision recheck и commit rename; каталоги собираются в staging root без merge существующих каталогов. - Move удаляет source только после подтверждённого commit и fingerprint-проверки; timeout/disconnect даёт `Unknown`, без automatic retry или rollback-обещания. - Trash создаёт unique restore records на исходном endpoint. Permanent delete явно не undoable; undo работает только в текущей сессии для полностью успешных create/rename/move/trash и проверяет fingerprints/epochs. Copy, permanent delete и редактирование не добавляются в undo journal. -- Windows SSH backend, архивы, плагины, tabs и search остаются следующими changes. Kitty и real tmux прошли visual acceptance; iTerm2/Sixel не заявляются без отдельной real-terminal matrix и не выводятся из headless tests. +- Windows SSH backend, архивы, плагины и tabs остаются следующими changes. Kitty и real tmux прошли visual acceptance; iTerm2/Sixel не заявляются без отдельной real-terminal matrix и не выводятся из headless tests. ## Roadmap Icons/colors, 20 themes, categorized Help и preview debounce реализованы и архивированы в `openspec/changes/archive/2026-12-06-*`. Image preview реализован в `add-image-previews`; его technical verdict 0 findings, а внешний iTerm2/Sixel и real-SSH visual gate явно остаётся открытым. Общий стандарт: `docs/tui-design-guidelines.md`; дизайнерский/проверочный skill: `.agents/skills/rcom-tui-design/SKILL.md`. -Далее в roadmap остаются search/filter, workspace tabs, archive preview и plugin API. +Текущий `add-file-search-and-filter` добавляет поиск/фильтр текущего каталога. Далее в roadmap остаются рекурсивный поиск, workspace tabs, archive preview и plugin API. ## Разработка diff --git a/docs/acceptance.md b/docs/acceptance.md index 7944a96..499486a 100644 --- a/docs/acceptance.md +++ b/docs/acceptance.md @@ -290,3 +290,10 @@ cargo test --test ssh_hermesvm -- --ignored --nocapture - Пользовательский реальный запуск выявил, что прежний fix скрывал loading только до deadline. Selection-origin running request теперь остаётся quiet до current response: никаких `LOADING PREVIEW`, `Reading…` или `NO PREVIEW`; initial/F3 loading не изменён. - Directory preview получил typed bounded rows и semantic icons для вложенных generic/special folders и files; icons-off сохраняет имена. - Новые regressions закрывают кадр после deadline и nested directory rows, включая U+2028/U+2029 sanitization. Полный suite: **652 passed, 0 failed, 4 ignored**; strict Clippy/fmt — PASS. Финальный independent verdict: **0 findings**; пользовательский visual verdict остаётся открытым. + +## Change `add-file-search-and-filter` + +- `/` открывает incremental lowercase-based filter/search canonical successful listing без нового listing I/O. Draft/applied разделены, Apply/Cancel восстанавливают EntryId, n/N используют wrap, visual mode имеет приоритет для Esc. +- Same-location refresh и hidden toggle используют атомарную проекцию; failed navigation сохраняет query/draft, accepted Location/SourceId/new SessionEpoch очищает их без затирания Quit. +- Status показывает sanitized query и eligible `visible/total`, NO MATCHES и query-only hidden-marked count. SelectionSet сохраняется, пустая видимая проекция блокирует source-действия, clipboard paste сохраняет собственные guards. +- Полный Buffer покрывает 40×8/80×24/120×40, NO_COLOR/ASCII/icons-off и Unicode sanitization. Help получил Filter context; PTY подтверждает incremental/Apply/n/F10 и draft cancel lifecycle. Общий suite: **680 passed, 0 failed, 4 ignored** в 83 suites; strict Clippy/fmt/doc — PASS. Финальный independent verdict: **0 findings** после accepted-epoch, projected foreground/background fallback, responsive suffix и operation coverage fixes; пользовательский visual review остаётся перед archive. diff --git a/docs/spec-matrix.md b/docs/spec-matrix.md index bb5bd40..4788dcd 100644 --- a/docs/spec-matrix.md +++ b/docs/spec-matrix.md @@ -283,6 +283,19 @@ | file-navigation | Initial/F3 loading сохраняется | `tests/preview_debounce.rs::initial_f3_and_pure_selection_effects_keep_their_distinct_modes`; `tests/ui_states.rs::loading_empty_error_and_stale_warning_are_distinct_states` | | terminal-ui | Nested generic/special directory и file icons, icons-off | `tests/file_type_rendering.rs::directory_preview_shows_icons_for_nested_folders_and_files` | +## Change: add-file-search-and-filter + +| Capability | Scenario / contract | Текущие тесты | +|---|---|---| +| file-filtering | Canonical snapshot, lowercase literal matching, non-UTF-8 и large listing | `tests/file_filter.rs::snapshot_keeps_the_complete_canonical_order_and_parallel_folded_names`, `query_is_a_literal_substring_not_a_regular_expression`, `unicode_lowercase_does_not_promise_full_case_folding`, `non_utf8_names_match_lossy_display_text_without_changing_the_entry`, `twenty_thousand_entries_support_repeated_precomputed_matching` | +| file-filtering | Apply/Cancel EntryId, n/N wrap, visual/Esc и empty source guard | `tests/filter_navigation.rs::filter_apply_cancel_and_match_navigation_preserve_entry_identity`, `visual_escape_precedes_filter_clear_and_no_active_match_is_inert`, `no_matches_blocks_source_actions_and_notices_do_not_mutate_listing` | +| file-filtering | Eligible/total, query-only hidden marks и canonical hidden toggle | `tests/filter_navigation.rs::hidden_policy_and_query_have_separate_marked_counts`, `hidden_toggle_uses_canonical_snapshot_without_a_listing_effect` | +| file-filtering | Failed/accepted navigation, same-home new epoch и background preview | `tests/filter_navigation.rs::failed_navigation_preserves_filter_and_accepted_navigation_resets_draft`, `same_home_reconnect_resets_filter_only_after_accepted_new_epoch`, `background_refresh_preserves_draft_or_immediately_reloads_changed_selection` | +| terminal-ui | Literal input Press/Repeat и responsive filter/status/NO MATCHES | `tests/filter_input.rs::filter_input_captures_aliases_and_press_repeat_policy`; `tests/filter_ui.rs::filter_editor_and_applied_status_fit_every_supported_layout`, `no_matches_and_hidden_marked_are_textual_in_monochrome_and_icons_off`, `cancel_restores_workspace_geometry_and_unicode_input_is_sanitized` | +| terminal-ui | Help Filter inventory | `tests/help_inventory.rs::independently_enumerated_input_contexts_match_every_inventory_action_and_alias`, `context_specific_bindings_execute_only_their_documented_handler`; `tests/ui_accessibility.rs::every_help_category_alias_and_context_is_reachable_at_wide_and_minimum_sizes` | +| file-filtering | PTY incremental/Apply/n/F10 и draft cancel lifecycle | `tests/pty_smoke.rs::filter_input_apply_match_clear_and_f10_restore_terminal`, `filter_no_matches_cancel_and_quit_restore_workspace` | + + ## Change: redesign-help-and-remove-hints diff --git a/docs/testing.md b/docs/testing.md index 452b191..c772551 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -89,6 +89,13 @@ cargo test --test ssh_action_acceptance --locked -- --ignored --nocapture - `tests/operation_ui.rs::task_details_vertical_aliases_scroll_without_selecting_behind_overlay` перебирает `j/k`, Up/Down, PageUp/PageDown и Ctrl aliases на Press/Repeat, доказывая неизменный selected task. `tests/pty_smoke.rs::help_close_reopen_aliases_preserve_terminal_lifecycle` проверяет Esc/`q`/`?`/F1, reopen, F10 и восстановление terminal. - `tests/ui_layout.rs::hints_row_is_gone_and_help_affordance_never_consumes_status_or_workspace` закрепляет отсутствие persistent hints, дополнительную workspace row, status и `? Help` на узких/широких кадрах. Snapshots обновляются только в affected UI suites с последующим `INSTA_UPDATE=no` контролем. +### File filter/search + +- `tests/file_filter.rs` проверяет canonical order, folded lowercase matching, regex literals, ß/SS/sigma limits, non-UTF-8 и 20 000 entries с повторными projections. +- `tests/filter_navigation.rs` покрывает Apply/Cancel, n/N wrap, visual/Esc, eligible/total и hidden-marked, full source/clipboard paste, F10/dual, failed/accepted navigation, same-home same/new SessionEpoch, foreground/background projected fallback и hidden toggle без listing. `tests/filter_runtime.rs` подтверждает Local RecordingFs zero listing I/O/один current preview read и общий Local/fake-SSH projection. +- `tests/filter_input.rs` фиксирует literal aliases и Press/Repeat/Release policy. `tests/filter_ui.rs` проверяет полный Buffer editor/status/NO MATCHES на 40×8/80×24/120×40, NO_COLOR/ASCII/icons-off, Unicode sanitization и geometry restore. +- PTY `filter_input_apply_match_clear_and_f10_restore_terminal` подтверждает incremental ввод/Apply/n/F10, а `filter_no_matches_cancel_and_quit_restore_workspace` — draft/cancel/quit lifecycle. Raw terminal output не заменяет full-Buffer text assertions. + ### Image preview - `tests/image_preview.rs` генерирует PNG/JPEG/GIF/BMP/WebP в памяти и проверяет content magic, corrupt/truncated/exact cap/cap+1, checked dimensions/allocations, static aspect-fit, no-probe disabled/tmux gates, bounded cache и реальные halfblock RGB на TestBackend. Kitty/iTerm2/Sixel имеют только structural shape checks без wire snapshots. diff --git a/docs/tui-design-guidelines.md b/docs/tui-design-guidelines.md index 7d6326e..761f417 100644 --- a/docs/tui-design-guidelines.md +++ b/docs/tui-design-guidelines.md @@ -90,6 +90,14 @@ Selection не должен оставлять произвольный icon for Постоянная нижняя строка key hints не нужна. Освобождённое место принадлежит содержимому. Discoverability обеспечивается документированными `?` и `F1`, а не постоянным списком сокращений. +### Filter/search текущего каталога + +- `/` открывает transient двухстрочный editor над status; applied filter не занимает постоянную строку. Renderer и page size используют общую geometry, на 40×8 остаётся хотя бы одна entry row. +- Draft и applied query разделены: Enter применяет, Esc откатывает, F10→Stay не оставляет скрытый editor. После Apply `n/N` используют wrap, обычные `j/k` — clamp. +- Matching выполняется над canonical successful listing после hidden-policy без дополнительного I/O. Status показывает sanitized query и `visible/total`, где total — eligible после hidden-policy. +- NO MATCHES не выдаётся за пустой успешный каталог и не оставляет старый preview. Скрытые именно query marked entries имеют текстовый count; source review сохраняет полный immutable set. +- Query использует lowercase-based substring, а не полный Unicode case folding. Control/U+2028/U+2029 экранируются, non-UTF-8 EntryId не изменяются. + ## 5. Help и overlays Help — спокойный читаемый слой, а не перегруженная таблица всех команд одновременно. diff --git a/openspec/changes/add-file-search-and-filter/.openspec.yaml b/openspec/changes/add-file-search-and-filter/.openspec.yaml new file mode 100644 index 0000000..1edded0 --- /dev/null +++ b/openspec/changes/add-file-search-and-filter/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-12-06 diff --git a/openspec/changes/add-file-search-and-filter/design.md b/openspec/changes/add-file-search-and-filter/design.md new file mode 100644 index 0000000..1503bf3 --- /dev/null +++ b/openspec/changes/add-file-search-and-filter/design.md @@ -0,0 +1,105 @@ +# Design + +## Context + +См. `proposal.md`, новый `file-filtering` и ADDED `terminal-ui`. Сейчас `PaneState.entries` одновременно является успешным listing и видимым списком; `finish_listing` применяет hidden filter и restore_selection. SelectionSet уже хранит EntryId и сохраняет скрытые элементы. Input/Help, preview debounce и responsive layout независимы от backend, поэтому фильтр можно реализовать как чистую проекцию без нового executor. + +## Goals / Non-Goals + +**Goals:** + +- Один canonical successful listing и детерминированная видимая проекция. +- Явное разделение applied query и transient draft с откатом по EntryId. +- Повторное использование selection, preview, refresh и operation guards. + +**Non-Goals:** + +- Рекурсивный/content/regex/fuzzy поиск, persistent history и индексация на диске. +- Watcher, новый async worker или дополнительные FS запросы на каждый ввод. +- Изменение clipboard snapshot и существующих mutation protocols. + +## Decisions + +### 1. Canonical listing и видимая проекция + +`PaneState` получает `listing: Option`; `Some` существует даже для пустого успешного каталога, `None` обозначает отсутствие canonical данных в synthetic fixtures или до первого listing. Snapshot хранит отсортированные полные entries и параллельные folded display names для matching. + +Существующее `entries` остаётся видимой проекцией, поэтому preview, selection movement, planners и renderer не получают второй источник истины. `rebuild_projection` сначала строит `eligible` после show_hidden, затем применяет query и обновляет `entries`/selection. `total` всегда равен `eligible.len()`, а не размеру полного canonical listing. Существующие fixtures с `listing=None` и пустым query сохраняют прежнее поведение. + +Query нормализуется через `to_string_lossy().to_lowercase()` один раз для snapshot и один раз для draft; спецсимволы regex не интерпретируются. Это сознательно lowercase-based matching, а не полный Unicode case folding: `ß`/`SS` и варианты sigma фиксируются отдельными tests. На refresh folded names пересоздаются, на keystroke выполняется только bounded scan текущего listing без I/O. В качестве альтернативы рассматривались indices вместо Vec; они уменьшили бы клонирование, но потребовали бы широкого rewrite всех consumers и отложены. + +### 2. Selection fallback зависит от причины проекции + +Projection принимает прежние EntryId/index и явный fallback mode: + +- ввод query: сохранить текущий EntryId если видим, иначе первый match; +- refresh/hidden toggle: сохранить EntryId, иначе ближайший прежний index в новой проекции; +- cancel draft: восстановить baseline EntryId, если существует, иначе ближайший baseline index. + +Preview обновляется только при изменении selected EntryId. Пользовательские query/cancel/hidden/`n/N` используют существующий `debounce_preview` при новом выборе; изменение query с неизменным выбором не создаёт read. Background same EntryId сохраняет pending/существующий background path, а background changed/removed selection использует immediate current load либо invalidation согласно main `file-navigation`, без дополнительного debounce. При отсутствии выбора preview invalidates generation и guards отбрасывают старый response. + +### 3. Applied filter и отдельный editor + +Каждая панель хранит только applied query и небольшой filter notice. `AppState.filter_editor: Option` содержит pane, draft, baseline query/EntryId/index. Пока editor открыт, проекция использует draft; applied query остаётся неизменным. + +Enter копирует draft в applied и закрывает editor. Esc восстанавливает baseline и закрывает его. F10 сначала выполняет тот же rollback, затем существующий request_quit, поэтому Quit→Stay не раскрывает скрытый transient state. Открытие `/` при существующем фильтре начинает draft с текущего query. + +В workspace Esc сначала выходит из visual mode. Если visual mode не активен и applied query непуст, Esc очищает query; иначе сохраняется прежний no-op. Reset вычисляется только на accepted listing из фактического delta: изменился Location/SourceId либо confirmed SessionEpoch для того же host/home. Same-location refresh и cached same-epoch reconnect не очищают фильтр. `SynchronizeSshEpoch` очищает query/editor всех подтверждённых панелей затронутого host при фактической смене epoch. Editor удаляется только для затронутой панели; Overlay::None устанавливается только при активном Overlay::Filter, поэтому Quit/другой overlay не затирается. Failed/superseded/wrong-host navigation не имеет pending reset intent и сохраняет applied/draft. + +### 4. Refresh и hidden policy + +`finish_listing` сначала проверяет существующие generation/target/epoch guards, затем атомарно заменяет snapshot. SelectionSet.retain_existing получает полный набор EntryId до hidden/query projection, поэтому скрытые маркеры не удаляются. При открытом editor background response пересчитывает draft view, но не меняет applied baseline. + +ToggleHidden использует локальный snapshot и rebuild без LoadListing. При `listing=None` сохраняется существующий request_listing fallback для старых synthetic состояний. Same-location refresh без новой navigation identity сохраняет applied/draft; accepted Location/SourceId/SessionEpoch change очищает оба по фактическому delta. Для background с непустым query прежние projected EntryId/index сохраняются до скрытого restore и используются непосредственно на итоговой hidden+query projection, поэтому Nearest не смещается к промежуточному hidden-only соседу. + +### 5. Match navigation + +`n`/`N` вызывают отдельный wrap movement по уже видимой проекции только для непустого applied query вне editor. `j/k` и paging продолжают clamped move_selection. Отсутствие query/matches не меняет entries и создаёт маленький sanitized filter notice, который очищается следующим содержательным действием; ошибка панели не используется как notice. + +Все реальные selection changes проходят общий debounce. Filter input и `n/N` не создают listing effects или новые worker queues. + +### 6. SelectionSet и source-действия + +Ctrl-a и invert продолжают получать только `pane.entries`, поэтому изменяют видимые IDs и сохраняют остальные. `U` остаётся явной полной очисткой. + +Status показывает `hidden_marked = SelectionSet ∩ eligible − visible`; marked dotfile, исключённый только show_hidden, в этот count не входит. Operation review по-прежнему перечисляет полный immutable source set, включая policy/query-hidden IDs, который не заменяется видимой проекцией. Центральный active_operation_sources возвращает пустой набор, если видимая проекция пуста, блокируя y/x/F5/F6 и связанные source actions при NO MATCHES. Clipboard paste использует отдельный snapshot path и не блокируется этим правилом. + +### 7. Layout и rendering + +`frame_layout_with_filter` добавляет transient editor высотой 2 над status только во время редактирования; production render и active_page_size используют одну geometry. Существующий frame_layout делегирует с `editing=false`, сохраняя snapshots applied/обычного workspace. + +Editor содержит sanitized query и отдельные Enter/Esc controls. При 40×8 обе строки помещаются, workspace сохраняет хотя бы одну entry row. Applied filter не занимает дополнительную строку: status в приоритетном порядке показывает query/`visible/total`, NO MATCHES и hidden-marked count раньше вторичных сегментов. Query обрезается по display width, counts не обрезаются. + +Help получает HelpContext::Filter и entries для `/`, `n/N`, printable/Backspace/Ctrl-u, Enter/Esc, clear и F10. `?` внутри editor является литералом, а не открывает Help. + +### 8. Input policy + +Filter Char и Backspace принимают Press/Repeat; Ctrl-u, Enter, Esc и F10 — Press only; Release игнорируется. Все printable aliases, включая `j`, `q`, `/`, `?` и `n`, остаются текстом. В workspace `/` — Press only open, `n/N` поддерживают Press/Repeat. + +### 9. Проверки + +- Pure matcher/property tests: lowercase Unicode, `ß/SS` и sigma limits, substring, спецсимволы, non-UTF-8, пустой query и порядок. +- Reducer tests: Apply/Cancel/F10 Stay, selection fallback, n/N wrap/Repeat, clear/visual precedence, accepted/failed navigation во время draft и same-home new epoch. +- Refresh matrix: applied/draft × same/new listing × preserved/removed selection; same/changed/removed background preview во время active debounce; hidden toggle без backend calls. +- Selection/operation tests: eligible/total и combined dotfile+query count, hidden marks, select-all/invert/clear, NO MATCHES no plan/mutation, clipboard paste сохранён. +- Полный Buffer: query/count/no-match/hidden marked, 40×8/80×24/120×40, NO_COLOR/ASCII/icons-off; geometry/page size стабильны. +- PTY: ввод буквальных aliases, incremental search, Enter/Esc, n/N, quit/terminal restore; fake Local/SSH подтверждают одинаковый typed path и отсутствие дополнительного listing I/O. + +## Risks / Trade-offs + +- [Два Vec entries увеличивают память на больших каталогах] → один bounded canonical snapshot на панель, folded names переиспользуются; future indices не смешиваются с этим change. +- [Draft и background response разойдутся] → editor хранит baseline по EntryId, projection fallback явный, guards остаются до mutation snapshot. +- [Скрытые маркеры приведут к неожиданной операции] → текстовый count и полный source review; пустая проекция блокирует source-действия. +- [Фильтрация на каждый keystroke будет O(n)] → FS не читается, query/folded names нормализуются заранее; synthetic large-listing tests обязательны. +- [Transient layout изменит paging] → одна geometry функция для renderer/input и отдельные 40×8 tests. + +## Migration Plan + +1. Добавить matcher/snapshot/projection и failing pure tests. +2. Ввести applied/editor reducer и input context, затем refresh/navigation lifecycle. +3. Подключить status/transient layout/Help и operation visibility guards. +4. Добавить full-Buffer/PTY/large-listing tests и обновить docs/matrix. +5. Прогнать полный suite, independent design verify и пользовательский visual acceptance. +6. Синхронизировать новый `file-filtering` и ADDED `terminal-ui`, затем архивировать change. + +Откат удаляет projection/editor и возвращает прямой listing; файловые данные и config не затрагиваются. diff --git a/openspec/changes/add-file-search-and-filter/proposal.md b/openspec/changes/add-file-search-and-filter/proposal.md new file mode 100644 index 0000000..8a56825 --- /dev/null +++ b/openspec/changes/add-file-search-and-filter/proposal.md @@ -0,0 +1,31 @@ +# Proposal + +## Why + +В больших Local/SSH-каталогах сейчас можно лишь линейно листать элементы: нет способа быстро сузить список или перейти между совпадениями. Нужен одинаковый для обеих панелей keyboard-only фильтр без повторных filesystem запросов и без потери selection/operation identity. + +## What Changes + +- Добавить `/` для incremental filter/search текущего каталога: ввод сразу сужает видимые entries, сохраняет текущий EntryId если он совпадает и иначе выбирает первое совпадение; `Enter` применяет draft, `Esc` откатывает редактирование. +- После применения фильтра поддержать циклические `n`/`N` для следующего/предыдущего совпадения; обычные `j/k` остаются clamped. `Esc` вне редактирования очищает применённый фильтр после выхода из visual mode. +- Использовать документированный lowercase-based substring по display name без regex/fuzzy в первом этапе; это не полный Unicode default caseless matching (`ß`/`SS` и варианты sigma не обязаны совпадать). Non-UTF-8 имена сохраняются и сопоставляются через документированное lossy представление. +- Сохранять фильтр независимо для каждой панели и при same-location refresh; очищать его только после успешной смены location/endpoint. Failed navigation сохраняет прежний фильтр. +- Показывать query, `visible/total`, явное `NO MATCHES`, скрытые фильтром marked count и актуальные input controls на 40×8, NO_COLOR, ASCII и icons-off. +- Сохранять стабильные EntryId, multi-select и безопасность операций: фильтр сам не выполняет mutations; скрытые фильтром marked entries не теряются и явно учитываются в status/confirmation. +- Обновить Help/inventory, responsive status, preview debounce integration и named tests. Рекурсивный поиск, content search, regex/fuzzy и persistent history не входят в scope. + +## Capabilities + +### New Capabilities + +- `file-filtering`: incremental запрос, видимая проекция listing, match navigation, lifecycle при refresh/navigation и независимость панелей/selection. + +### Modified Capabilities + +- `terminal-ui`: новые команды и видимые состояния фильтра, responsive rendering и полный Help input inventory. + +## Impact + +- `PaneState` и чистая projection listing, input/reducer, status/render, Help, preview scheduler integration. +- Новые unit/headless/full-Buffer/PTY tests; существующие selection/clipboard, live refresh, Local/SSH и operation planning guards должны остаться зелёными. +- Новых dependencies, сетевых протоколов и файловых mutations не требуется. diff --git a/openspec/changes/add-file-search-and-filter/specs/file-filtering/spec.md b/openspec/changes/add-file-search-and-filter/specs/file-filtering/spec.md new file mode 100644 index 0000000..d730b3a --- /dev/null +++ b/openspec/changes/add-file-search-and-filter/specs/file-filtering/spec.md @@ -0,0 +1,103 @@ +# Spec Delta + +## Purpose + +Быстрое сужение и поиск внутри уже загруженного Local/SSH-каталога с сохранением стабильной идентичности выбора, панелей и файловых операций. + +## ADDED Requirements + +### Requirement: Incremental запрос и совпадения +Система SHALL фильтровать уже загруженные entries по документированному lowercase-based substring без нового filesystem I/O. Query SHALL применяться после hidden-file policy и одинаково относиться к файлам и каталогам. + +#### Scenario: Ввод сужает список +- **WHEN** пользователь открывает фильтр и вводит query +- **THEN** после каждого изменения видимы только совпадения, текущий выбор сохраняется если он совпадает, иначе выбирается первый видимый элемент + +#### Scenario: Применение и отмена draft +- **WHEN** пользователь нажимает Enter либо Esc во время редактирования +- **THEN** Enter применяет draft, а Esc восстанавливает прежние applied query и выбор по EntryId без побочных эффектов + +#### Scenario: Пустой query и отсутствие совпадений +- **WHEN** query пуст либо совпадений нет +- **THEN** пустой query показывает все разрешённые hidden-policy entries, а непустой query без совпадений показывает явное empty-match состояние без ложного выбора + +#### Scenario: Имена и регистр +- **WHEN** имена различаются регистром, содержат Unicode либо non-UTF-8 bytes +- **THEN** обе стороны проходят Unicode `to_lowercase`, non-UTF-8 использует lossy display representation, а исходные EntryId/имена не изменяются + +#### Scenario: Границы lowercase matching +- **WHEN** query содержит `SS` для имени с `ß` либо другой вариант sigma +- **THEN** отсутствие совпадения является документированным результатом lowercase-based matching, а не обещанием полного Unicode case folding + +### Requirement: Навигация по совпадениям +Система SHALL поддерживать `n`/`N` для циклического перехода к следующему/предыдущему совпадению применённого непустого фильтра. Обычная навигация SHALL сохранять существующие границы. + +#### Scenario: Следующее и предыдущее совпадение +- **WHEN** применён фильтр с совпадениями и пользователь нажимает `n` либо `N`, включая Repeat +- **THEN** выбор перемещается по видимым совпадениям с wrap на первом/последнем элементе и запускает существующий preview selection path + +#### Scenario: Нет активного запроса или совпадений +- **WHEN** query пуст, не применён либо не имеет совпадений +- **THEN** `n`/`N` не меняют location/entries и показывают понятное неблокирующее состояние без preview устаревшего элемента + +#### Scenario: Обычное движение внутри фильтра +- **WHEN** используются `j/k`, arrows, paging, first/last или multi-select advance +- **THEN** команды перемещаются только по видимой проекции с прежними clamp/selection semantics + +### Requirement: Lifecycle фильтра и панелей +Фильтр SHALL быть независимым состоянием панели. Same-location refresh и hidden-policy changes SHALL сохранять query, а успешная смена location/endpoint SHALL очищать его. + +#### Scenario: Background или ручной refresh +- **WHEN** тот же каталог обновлён при активном фильтре +- **THEN** query сохраняется, видимая проекция атомарно пересчитывается, выбор остаётся по EntryId либо переходит к допустимому совпадению без stale preview + +#### Scenario: Refresh во время редактирования +- **WHEN** background listing завершается при открытом draft +- **THEN** draft не заменяется applied query, rollback остаётся определённым по EntryId, а новые entries не создают неограниченную очередь запросов + +#### Scenario: Background refresh во время draft/debounce +- **WHEN** background listing сохраняет, меняет либо удаляет выбор при активном draft/debounce +- **THEN** same EntryId сохраняет существующий pending/background path, а changed/removed selection использует immediate current load либо invalidation без старого preview и без нового debounce поверх background response + +#### Scenario: Навигация в другой каталог +- **WHEN** переход либо SSH connect успешно открыл новое location +- **THEN** фильтр новой панели очищается; при ошибке перехода прежние location, query и выбор сохраняются + +#### Scenario: Accepted navigation во время draft +- **WHEN** accepted response подтверждает новый Location/SourceId либо новый SessionEpoch при открытом draft +- **THEN** applied query и editor этой панели удаляются, а Filter overlay закрывается только если он всё ещё активен; Quit/другой overlay не затирается + +#### Scenario: Reconnect к тому же home +- **WHEN** SSH reconnect успешно открыл тот же host/home с новым SessionEpoch +- **THEN** фильтр и draft очищаются как для новой session identity; failed reconnect сохраняет оба + +#### Scenario: Две панели и hidden toggle +- **WHEN** панели имеют разные фильтры либо пользователь меняет hidden policy +- **THEN** изменения затрагивают только активную панель, а проекция всегда учитывает оба условия без повторного listing + +### Requirement: Выделение и операции при фильтре +Фильтр SHALL сохранять SelectionSet по EntryId и MUST NOT выполнять mutations. Скрытые фильтром marked entries SHALL явно учитываться до source-операций. + +#### Scenario: Marked элемент скрыт и снова показан +- **WHEN** query скрывает marked EntryId, а затем очищается +- **THEN** маркер сохраняется на прежнем элементе без переноса на другое имя, а status показывает число скрытых именно query среди hidden-policy eligible entries + +#### Scenario: Combined dotfile policy и query +- **WHEN** marked dotfile исключён hidden-policy, но соответствует query +- **THEN** он не включается в hidden-by-query count; при необходимости policy-hidden source остаётся виден только в полном operation review + +#### Scenario: Select all и invert +- **WHEN** пользователь применяет Ctrl-a либо `I` при активном фильтре +- **THEN** команда изменяет только видимые EntryId, не удаляя существующие скрытые маркеры без явной команды очистки + +#### Scenario: Source-операция со скрытыми маркерами +- **WHEN** часть SelectionSet скрыта и пользователь начинает copy/move/lifecycle action +- **THEN** набор источников не подменяется только видимыми строками, а review/status явно сообщает полное число и скрытую часть до confirmation + +#### Scenario: Нет видимых источников +- **WHEN** фильтр не оставил видимых entries и пользователь вызывает действие над текущим списком +- **THEN** hovered/SelectionSet source-действие не создаёт plan/mutation; paste из ранее созданного clipboard сохраняет собственные guards + +#### Scenario: Preview и очистка фильтра +- **WHEN** выбор исчезает, появляется либо меняется из-за query +- **THEN** preview следует текущему EntryId через существующие generation/debounce guards и никогда не показывает содержимое скрытого прежнего выбора diff --git a/openspec/changes/add-file-search-and-filter/specs/terminal-ui/spec.md b/openspec/changes/add-file-search-and-filter/specs/terminal-ui/spec.md new file mode 100644 index 0000000..10cd5f0 --- /dev/null +++ b/openspec/changes/add-file-search-and-filter/specs/terminal-ui/spec.md @@ -0,0 +1,48 @@ +# Spec Delta + +## ADDED Requirements + +### Requirement: Ввод поиска и фильтра +Система SHALL открывать фильтр по `/`, принимать printable input буквально и предоставлять Backspace, Ctrl-u, Enter и Esc. Команды ввода MUST NOT просачиваться в workspace. + +#### Scenario: Редактирование query +- **WHEN** фильтр открыт и пользователь вводит символы, Backspace либо Ctrl-u +- **THEN** символы добавляются буквально, Backspace удаляет последний Unicode scalar, Ctrl-u очищает draft, а workspace aliases не выполняются + +#### Scenario: Подтверждение и отмена +- **WHEN** пользователь нажимает Enter либо Esc +- **THEN** Press-only Enter применяет draft, Press-only Esc откатывает draft, а Release игнорируется + +#### Scenario: Повторный ввод и очистка applied filter +- **WHEN** фильтр уже применён и пользователь снова нажимает `/` либо Esc вне overlays +- **THEN** `/` открывает текущий query для редактирования, а Esc очищает applied filter после предварительного выхода из visual mode, если он активен + +#### Scenario: Выход из приложения +- **WHEN** открыт draft и пользователь нажимает F10 +- **THEN** Press-only F10 использует существующий quit path после отмены draft; Stay не оставляет скрытый transient ввод или неприменённую проекцию + +### Requirement: Отображение состояния фильтра +Система SHALL показывать текущий query, число visible/total и отличимое empty-match состояние. Transient editor и controls SHALL оставаться доступными на поддерживаемых размерах без постоянной hints-строки. + +#### Scenario: Применённый фильтр +- **WHEN** query применён и список содержит совпадения +- **THEN** status содержит sanitized query и `visible/total`, где total — число entries после hidden-policy до query, а selection/markers остаются различимыми не только цветом + +#### Scenario: Нет совпадений +- **WHEN** непустой query не совпадает ни с одним элементом +- **THEN** панель показывает `NO MATCHES`, status сообщает `0/total`, а прежние entries и preview не выдаются за текущий выбор + +#### Scenario: Responsive editor +- **WHEN** фильтр редактируется на 40×8, 80×24, 120×40, в NO_COLOR, ASCII либо icons-off +- **THEN** query и Enter/Esc controls видимы без overlap, длинный Unicode query безопасно обрезается по display width, а обычная раскладка восстанавливается после ввода + +#### Scenario: Скрытые marked элементы +- **WHEN** SelectionSet содержит скрытые фильтром EntryId +- **THEN** status/review содержит текстовый count скрытой части независимо от theme/icon mode + +### Requirement: Справка по фильтру +Help SHALL включать `/`, `n`/`N`, редактирование и очистку фильтра с отдельным input context без внешних product references. + +#### Scenario: Полный inventory +- **WHEN** пользователь просматривает Navigation/General и Filter input context +- **THEN** все команды открытия, ввода, Apply/Cancel, match navigation, clear и F10 доступны с исходными aliases и не изменяют workspace при чтении Help diff --git a/openspec/changes/add-file-search-and-filter/tasks.md b/openspec/changes/add-file-search-and-filter/tasks.md new file mode 100644 index 0000000..e8b076f --- /dev/null +++ b/openspec/changes/add-file-search-and-filter/tasks.md @@ -0,0 +1,40 @@ +# Tasks + +## 1. Canonical listing и matching + +- [x] 1.1 Добавить ListingSnapshot/folded names и pure lowercase-based substring matcher; unit/property tests покрывают Unicode, `ß/SS`/sigma limits, пустой query, regex literals, non-UTF-8, deterministic order и отсутствие I/O. +- [x] 1.2 Реализовать rebuild_projection с режимами FirstMatch/Nearest/Baseline и сохранением `entries` compatibility; reducer tests проверяют current/removed/empty selection и отсутствие preview request при неизменном EntryId. +- [x] 1.3 Перевести successful listing и ToggleHidden на canonical snapshot с atomic background replacement; live-refresh tests с RecordingFs доказывают hidden+query projection без дополнительного listing и сохранение SelectionSet по полному EntryId set. +- [x] 1.4 Добавить synthetic large-listing regression с повторными keystrokes и обновить spec matrix ссылками на matcher/projection/refresh tests. + +## 2. Filter editor и команды + +- [x] 2.1 Ввести applied query, FilterEditor baseline/draft, Overlay::Filter и команды Open/Input/Backspace/Clear/Apply/Cancel; tests проверяют incremental FirstMatch, Enter commit, Esc rollback и отсутствие LoadListing/connect/mutation; при смене EntryId разрешён только существующий DebouncePreview. +- [x] 2.2 Добавить `/`, отдельный input context и Press/Repeat policy; table tests доказывают literal aliases (`j/q/?/n`), Unicode Backspace, Ctrl-u, Press-only Enter/Esc/F10 и игнорирование Release без утечки в workspace. +- [x] 2.3 Реализовать `n/N` wrap только для applied nonempty query, notices и обычный clamped movement; input/reducer tests покрывают Repeat, no-query/no-match, preview debounce и очистку Esc после visual-mode precedence. +- [x] 2.4 Закрыть lifecycle accepted/failed navigation во время draft, same-home new SessionEpoch, dual independence и F10→Quit Stay rollback; tests подтверждают reset query/editor по Location/SourceId/epoch, закрытие только активного Filter overlay и сохранение при ошибке. + +## 3. Responsive UI и Help + +- [x] 3.1 Добавить общую frame_layout_with_filter для renderer/page_size и transient query/controls; full-Buffer tests на 40×8/80×24/120×40 проверяют видимую entry row, отсутствие overlap и восстановление обычной geometry. +- [x] 3.2 Отрисовать sanitized query, visible/total после hidden-policy, NO MATCHES, eligible-only hidden-marked count и notices; tests покрывают combined dotfile+query, Unicode truncation, NO_COLOR, ASCII/icons-off и отсутствие постоянной hints row. +- [x] 3.3 Расширить HelpContext::Filter и inventory `/`, `n/N`, editing/Apply/Cancel/clear/F10; help inventory/reachability tests проходят все категории на 40×8 без внешних product references. +- [x] 3.4 Обновить README, guideline, docs/testing и design keymap фактическими keys/layout; documented input examples совпадают с table-driven tests. + +## 4. Selection, operations и сквозное поведение + +- [x] 4.1 Закрепить Ctrl-a/I/U при активном фильтре, hidden-marked count и восстановление маркеров после clear; selection tests доказывают отсутствие переноса EntryId и скрытого удаления маркеров. +- [x] 4.2 Защитить active_operation_sources при пустой проекции и сохранить полный immutable source set/review; operation tests доказывают no plan/mutation при NO MATCHES, явную скрытую часть и работоспособность clipboard paste. +- [x] 4.3 Добавить Local/fake-SSH headless flow applied/draft × refresh × selection, background same/changed/removed preview guards и NO MATCHES recovery; tests подтверждают нулевой listing I/O от matching, только DebouncePreview для пользовательской смены EntryId и не более одного current preview read после deadline. +- [x] 4.4 Добавить PTY incremental ввод/Apply/Cancel/n/N/clear/F10 terminal lifecycle и обновить spec matrix/acceptance фактическими named tests. + +## 5. Приёмка + +- [x] 5.1 Прогнать fmt, strict Clippy, полный tests/doc/PTY suite и отсутствие `.snap.new`; зафиксировано **680/0/4 в 83 suites**, representative 40×8/wide frames покрыты `filter_ui`. +- [x] 5.2 Получить независимый verify через `rcom-tui-design`: все findings исправлены, финальный verdict **0 findings**, включая epoch/reset, foreground/background projection и operation races. +- [ ] 5.3 Получить пользовательский visual review filter editor, NO MATCHES, hidden marked и n/N на Local панели перед archive. + +## Workflow follow-up + +- Синхронизировать новую capability `file-filtering` и ADDED requirements `terminal-ui`, выполнить archive и проверить archived result. +- Рекурсивный/content/regex/fuzzy search оформлять отдельными changes, не расширяя этот scope. diff --git a/src/app/filtering.rs b/src/app/filtering.rs new file mode 100644 index 0000000..dec03da --- /dev/null +++ b/src/app/filtering.rs @@ -0,0 +1,269 @@ +//! Pure current-listing filtering and draft editor transitions. + +use std::collections::BTreeSet; + +use super::{AppState, Effect, FilterEditor, Overlay, PaneId}; +use crate::domain::{EntryId, ListingSnapshot, fold_query}; + +#[derive(Clone, Copy)] +pub(crate) enum ProjectionFallback { + FirstMatch, + Nearest, + Baseline, +} + +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct FilterStats { + pub query: String, + pub visible: usize, + pub total: usize, + pub hidden_marked: usize, + pub notice: Option, +} + +impl AppState { + pub fn filter_query(&self, pane: PaneId) -> &str { + if let Some(editor) = &self.filter_editor + && editor.pane == pane + { + return &editor.draft; + } + &self.pane(pane).filter + } + + pub fn filter_stats(&self, pane_id: PaneId) -> FilterStats { + let pane = self.pane(pane_id); + let query = self.filter_query(pane_id).to_owned(); + let Some(listing) = &pane.listing else { + return FilterStats { + query, + visible: pane.entries.len(), + total: pane.entries.len(), + hidden_marked: 0, + notice: pane.filter_notice.clone(), + }; + }; + let projection = listing.project(pane.show_hidden, &fold_query(&query)); + let eligible: BTreeSet = projection + .eligible + .iter() + .map(|entry| pane.location.entry_id(&entry.name)) + .collect(); + let visible: BTreeSet = pane + .entries + .iter() + .map(|entry| pane.location.entry_id(&entry.name)) + .collect(); + let hidden_marked = if query.is_empty() { + 0 + } else { + pane.selection_set + .iter() + .filter(|id| eligible.contains(*id) && !visible.contains(*id)) + .count() + }; + FilterStats { + query, + visible: pane.entries.len(), + total: projection.eligible.len(), + hidden_marked, + notice: pane.filter_notice.clone(), + } + } + + pub(crate) fn open_filter(&mut self) -> Vec { + if self.overlay != Overlay::None { + return Vec::new(); + } + let pane_id = self.active; + let pane = self.pane_mut(pane_id); + if pane.listing.is_none() { + pane.listing = Some(ListingSnapshot::new(pane.entries.clone())); + } + let baseline_entry = pane + .selected_entry() + .map(|entry| pane.location.entry_id(&entry.name)); + let editor = FilterEditor { + pane: pane_id, + draft: pane.filter.clone(), + baseline_query: pane.filter.clone(), + baseline_entry, + baseline_index: pane.selection.index(), + }; + pane.filter_notice = None; + self.filter_editor = Some(editor); + self.set_overlay(Overlay::Filter); + Vec::new() + } + + pub(crate) fn edit_filter(&mut self, edit: impl FnOnce(&mut String)) -> Option { + if self.overlay != Overlay::Filter { + return None; + } + let editor = self.filter_editor.as_mut()?; + edit(&mut editor.draft); + let pane = editor.pane; + self.rebuild_projection(pane, ProjectionFallback::FirstMatch, None) + } + + pub(crate) fn apply_filter(&mut self) -> Vec { + if self.overlay != Overlay::Filter { + return Vec::new(); + } + let Some(editor) = self.filter_editor.take() else { + return Vec::new(); + }; + self.pane_mut(editor.pane).filter = editor.draft; + self.set_overlay(Overlay::None); + Vec::new() + } + + pub(crate) fn cancel_filter(&mut self) -> Option { + let editor = self.filter_editor.take()?; + let pane = editor.pane; + self.pane_mut(pane).filter = editor.baseline_query.clone(); + let effect = self.rebuild_projection(pane, ProjectionFallback::Baseline, Some(&editor)); + if self.overlay == Overlay::Filter { + self.set_overlay(Overlay::None); + } + effect + } + + pub(crate) fn clear_applied_filter(&mut self) -> Option { + let pane = self.active; + if self.pane(pane).filter.is_empty() { + return None; + } + self.pane_mut(pane).filter.clear(); + self.pane_mut(pane).filter_notice = None; + self.rebuild_projection(pane, ProjectionFallback::Nearest, None) + } + + pub(crate) fn move_match(&mut self, delta: isize) -> Option { + let pane_id = self.active; + let pane = self.pane_mut(pane_id); + if pane.filter.is_empty() { + pane.filter_notice = Some("No active filter".into()); + return None; + } + let len = pane.entries.len(); + if len == 0 { + pane.filter_notice = Some("No matches".into()); + return None; + } + let current = pane.selection.index().unwrap_or(0) as isize; + let next = (current + delta).rem_euclid(len as isize) as usize; + let changed = pane.selection.index() != Some(next); + pane.selection.set(Some(next), len); + pane.filter_notice = None; + if changed { + self.select_visual_path(pane_id); + self.debounce_preview(pane_id) + } else { + None + } + } + + pub(crate) fn rebuild_projection( + &mut self, + pane_id: PaneId, + fallback: ProjectionFallback, + baseline: Option<&FilterEditor>, + ) -> Option { + self.rebuild_projection_impl(pane_id, fallback, baseline, true) + } + + pub(crate) fn rebuild_listing_projection( + &mut self, + pane_id: PaneId, + previous_entry: Option, + previous_index: Option, + ) { + let baseline = FilterEditor { + pane: pane_id, + draft: String::new(), + baseline_query: String::new(), + baseline_entry: previous_entry, + baseline_index: previous_index, + }; + let _ = self.rebuild_projection_impl( + pane_id, + ProjectionFallback::Baseline, + Some(&baseline), + false, + ); + } + + fn rebuild_projection_impl( + &mut self, + pane_id: PaneId, + fallback: ProjectionFallback, + baseline: Option<&FilterEditor>, + allow_preview: bool, + ) -> Option { + let query = self.filter_query(pane_id).to_owned(); + let pane = self.pane_mut(pane_id); + if pane.listing.is_none() { + pane.listing = Some(ListingSnapshot::new(pane.entries.clone())); + } + let previous_entry = pane + .selected_entry() + .map(|entry| pane.location.entry_id(&entry.name)); + let previous_index = pane.selection.index(); + let projection = pane + .listing + .as_ref() + .expect("listing initialized") + .project(pane.show_hidden, &fold_query(&query)); + pane.entries = projection.visible; + let (preferred_entry, preferred_index) = match fallback { + ProjectionFallback::Baseline => baseline + .map_or((previous_entry.clone(), previous_index), |base| { + (base.baseline_entry.clone(), base.baseline_index) + }), + _ => (previous_entry.clone(), previous_index), + }; + let position = preferred_entry.as_ref().and_then(|id| { + pane.entries + .iter() + .position(|entry| &pane.location.entry_id(&entry.name) == id) + }); + let next = match position { + Some(index) => Some(index), + None if pane.entries.is_empty() => None, + None if matches!(fallback, ProjectionFallback::FirstMatch) => Some(0), + None => preferred_index + .map(|index| index.min(pane.entries.len() - 1)) + .or(Some(0)), + }; + pane.selection.set(next, pane.entries.len()); + pane.filter_notice = None; + let current_entry = pane + .selected_entry() + .map(|entry| pane.location.entry_id(&entry.name)); + if allow_preview && current_entry != previous_entry { + self.debounce_preview(pane_id) + } else { + None + } + } + + pub(crate) fn reset_filter_for_identity(&mut self, pane_id: PaneId, reset: bool) { + if !reset { + return; + } + let pane = self.pane_mut(pane_id); + pane.filter.clear(); + pane.filter_notice = None; + if self + .filter_editor + .as_ref() + .is_some_and(|editor| editor.pane == pane_id) + { + self.filter_editor = None; + if self.overlay == Overlay::Filter { + self.set_overlay(Overlay::None); + } + } + } +} diff --git a/src/app/help.rs b/src/app/help.rs index 5173ac7..f9f2792 100644 --- a/src/app/help.rs +++ b/src/app/help.rs @@ -71,6 +71,7 @@ pub enum HelpContext { Tasks, TaskDetails, Preview, + Filter, Help, DestinationPrompt, Confirmation, @@ -93,6 +94,7 @@ impl HelpContext { Self::Tasks => "Tasks", Self::TaskDetails => "Task Details", Self::Preview => "Preview", + Self::Filter => "Filter", Self::Help => "Help", Self::DestinationPrompt => "Destination", Self::Confirmation => "Confirmation", @@ -137,7 +139,7 @@ const fn entry( use HelpCategory::{Files, General, Navigation, Selection, Ssh, Tasks}; use HelpContext::{ Collision, Confirmation, DestinationPrompt, Editor, EntryConfirmation, EntryPrompt, - ErrorDetails, Global, Help, HostPicker, Preview, QuitConfirmation, TaskDetails, + ErrorDetails, Filter, Global, Help, HostPicker, Preview, QuitConfirmation, TaskDetails, Tasks as TaskList, ThemePicker, Undo, Workspace, }; @@ -146,6 +148,76 @@ use HelpContext::{ /// This is deliberately data, not a second input dispatcher. Tests independently enumerate input /// contexts and action IDs so a new handler cannot silently disappear from the reference. pub static HELP_INVENTORY: &[HelpEntry] = &[ + entry( + Navigation, + "filter-open", + "/", + Workspace, + "Filter/search the current directory", + ), + entry( + Navigation, + "filter-next-match", + "n", + Workspace, + "Next filter match with wrap", + ), + entry( + Navigation, + "filter-previous-match", + "N", + Workspace, + "Previous filter match with wrap", + ), + entry( + General, + "filter-clear-applied", + "Esc", + Workspace, + "Clear the applied filter when visual mode is off", + ), + entry( + General, + "filter-input", + "Printable", + Filter, + "Edit the filter literally", + ), + entry( + General, + "filter-backspace", + "Backspace", + Filter, + "Delete the last query character", + ), + entry( + General, + "filter-clear-draft", + "Ctrl-u", + Filter, + "Clear the draft query", + ), + entry( + General, + "filter-apply", + "Enter", + Filter, + "Apply the draft query", + ), + entry( + General, + "filter-cancel", + "Esc", + Filter, + "Cancel the draft and restore the previous view", + ), + entry( + General, + "filter-quit", + "F10", + Filter, + "Cancel the draft and quit", + ), entry( Navigation, "workspace-next-entry", diff --git a/src/app/mod.rs b/src/app/mod.rs index 84526bf..01e23a9 100644 --- a/src/app/mod.rs +++ b/src/app/mod.rs @@ -8,6 +8,7 @@ use std::collections::{BTreeMap, BTreeSet}; use std::ffi::OsString; pub mod actions; +pub mod filtering; pub mod help; pub mod operations; pub mod preview; @@ -99,6 +100,7 @@ pub enum Overlay { Help, HostPicker, Preview, + Filter, ThemePicker, Message, DestinationPrompt, @@ -144,6 +146,15 @@ impl ThemePickerState { } } +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct FilterEditor { + pub pane: PaneId, + pub draft: String, + pub baseline_query: String, + pub baseline_entry: Option, + pub baseline_index: Option, +} + #[derive(Clone, Debug, Default, Eq, PartialEq)] pub struct PreviewState { /// Location for which the current preview request or result was produced. @@ -187,6 +198,10 @@ pub struct PaneState { /// The directory currently being loaded, or the placeholder remote home during SSH connect. pub pending_target: Option, pub entries: Vec, + /// Successful canonical listing, independent of hidden/query projection. + pub listing: Option, + pub filter: String, + pub filter_notice: Option, /// Cursor position in `entries`; multi-selection is stored separately by stable entry id. pub selection: Selection, pub selection_set: SelectionSet, @@ -220,6 +235,9 @@ impl PaneState { location: location.clone(), pending_target: None, entries: Vec::new(), + listing: None, + filter: String::new(), + filter_notice: None, selection: Selection::default(), selection_set: SelectionSet::new(), visual_mode: false, @@ -291,6 +309,7 @@ pub struct AppState { pub images_enabled: bool, pub theme_picker: Option, pub overlay: Overlay, + pub filter_editor: Option, /// Category and normalized rendered-line offset for the current Help opening. pub help: HelpState, /// Logical first line of non-Help scrollable overlays. Rendering clamps it to the viewport. @@ -341,6 +360,7 @@ impl AppState { images_enabled: true, theme_picker: None, overlay: Overlay::None, + filter_editor: None, help: HelpState::default(), overlay_scroll: 0, should_quit: false, @@ -392,8 +412,13 @@ impl AppState { pub fn reduce(&mut self, command: Command) -> Vec { match command { Command::Quit => { + let effects = if self.overlay == Overlay::Filter { + self.cancel_filter().into_iter().collect() + } else { + Vec::new() + }; self.request_quit(); - Vec::new() + effects } Command::DecideQuit(decision) => self.decide_quit(decision), Command::TogglePaneMode => self.toggle_pane_mode(), @@ -553,10 +578,16 @@ impl AppState { Command::ToggleHidden => { let active = self.active; self.pane_mut(active).show_hidden = !self.pane(active).show_hidden; - let target = self.pane(active).location.clone(); - self.request_listing(active, target, None) - .into_iter() - .collect() + if self.pane(active).listing.is_some() { + self.rebuild_projection(active, filtering::ProjectionFallback::Nearest, None) + .into_iter() + .collect() + } else { + let target = self.pane(active).location.clone(); + self.request_listing(active, target, None) + .into_iter() + .collect() + } } Command::Refresh => { let active = self.active; @@ -665,6 +696,20 @@ impl AppState { let active = self.active; self.request_preview(active).into_iter().collect() } + Command::OpenFilter => self.open_filter(), + Command::FilterInput(character) => self + .edit_filter(|draft| draft.push(character)) + .into_iter() + .collect(), + Command::FilterBackspace => self + .edit_filter(|draft| { + draft.pop(); + }) + .into_iter() + .collect(), + Command::ClearFilterInput => self.edit_filter(String::clear).into_iter().collect(), + Command::ApplyFilter => self.apply_filter(), + Command::MoveMatch(delta) => self.move_match(delta).into_iter().collect(), Command::OpenMessage => { if self.active_pane().error.is_some() { self.set_overlay(Overlay::Message); @@ -682,9 +727,14 @@ impl AppState { } Command::CloseOverlay => match self.overlay { Overlay::None => { - self.exit_visual(self.active); - Vec::new() + if self.active_pane().visual_mode { + self.exit_visual(self.active); + Vec::new() + } else { + self.clear_applied_filter().into_iter().collect() + } } + Overlay::Filter => self.cancel_filter().into_iter().collect(), Overlay::DestinationPrompt | Overlay::ConfirmOperation | Overlay::Collision => { self.cancel_pending_operation(); Vec::new() @@ -907,6 +957,9 @@ impl AppState { fn active_operation_sources(&self) -> Vec { let pane = self.active_pane(); + if pane.entries.is_empty() { + return Vec::new(); + } if pane.selection_set.is_empty() { hovered_entry_id(pane).into_iter().collect() } else { @@ -1093,7 +1146,9 @@ impl AppState { } fn request_ssh_connect(&mut self, pane_id: PaneId, host: HostAlias) -> Option { - self.set_overlay(Overlay::None); + if self.overlay != Overlay::Filter { + self.set_overlay(Overlay::None); + } let pane = self.pane_mut(pane_id); cancel_cross_endpoint_pending(pane); pane.navigation_generation = next_generation(pane.navigation_generation); @@ -1143,6 +1198,27 @@ impl AppState { self.pane_mut(pane_id).background_refresh = false; match result { Ok(entries) => { + let filter_identity_changed = { + let pane = self.pane(pane_id); + let epoch_changed = match &target.source { + SourceId::Local => false, + SourceId::Ssh(host) => { + pane.confirmed_session.as_ref().is_some_and(|session| { + &session.host == host && session.epoch != session_epoch.unwrap_or(0) + }) + } + }; + pane.location != target || epoch_changed + }; + self.reset_filter_for_identity(pane_id, filter_identity_changed); + let projected_selection_before = { + let pane = self.pane(pane_id); + ( + pane.selected_entry() + .map(|entry| pane.location.entry_id(&entry.name)), + pane.selection.index(), + ) + }; { let pane = self.pane_mut(pane_id); let preferred_name = pane.pending_selection.take(); @@ -1165,7 +1241,9 @@ impl AppState { .iter() .map(|entry| target.entry_id(&entry.name)) .collect(); - let entries = prepare_entries(entries, pane.show_hidden); + let snapshot = crate::domain::ListingSnapshot::new(entries); + let entries = prepare_entries(snapshot.entries.clone(), pane.show_hidden); + pane.listing = Some(snapshot); let selection = restore_selection( &entries, previous_index, @@ -1206,6 +1284,21 @@ impl AppState { pane.error = None; } + let projected_selection = if !self.filter_query(pane_id).is_empty() { + projected_selection_before + } else { + let pane = self.pane(pane_id); + ( + pane.selected_entry() + .map(|entry| pane.location.entry_id(&entry.name)), + pane.selection.index(), + ) + }; + self.rebuild_listing_projection( + pane_id, + projected_selection.0, + projected_selection.1, + ); // A new successful listing also selects an entry, so persistent and overlay preview // can share the same generation-isolated request path. let preserve_selection_debounce = { @@ -1344,7 +1437,8 @@ impl AppState { } fn synchronize_ssh_epoch(&mut self, host: HostAlias, session_epoch: SessionEpoch) { - for pane in &mut self.panes { + let mut reset_filter = [false, false]; + for (index, pane) in self.panes.iter_mut().enumerate() { let confirmed_host = match &pane.location.source { SourceId::Ssh(confirmed) => Some(confirmed.clone()), SourceId::Local => None, @@ -1372,6 +1466,14 @@ impl AppState { continue; } + if confirmed_host.as_ref() == Some(&host) + && pane + .confirmed_session + .as_ref() + .is_some_and(|session| session.epoch != session_epoch) + { + reset_filter[index] = true; + } pane.session_host = Some(host.clone()); pane.session_epoch = Some(session_epoch); // The confirmed session changes only for the confirmed endpoint, even while a pending @@ -1396,6 +1498,14 @@ impl AppState { } } } + for (index, reset) in reset_filter.into_iter().enumerate() { + let pane = if index == 0 { + PaneId::Left + } else { + PaneId::Right + }; + self.reset_filter_for_identity(pane, reset); + } } fn finish_ssh_connect(&mut self, result: ConnectSshResult) -> Vec { @@ -1856,6 +1966,12 @@ pub enum Command { }, OpenHostPicker, OpenPreview, + OpenFilter, + FilterInput(char), + FilterBackspace, + ClearFilterInput, + ApplyFilter, + MoveMatch(isize), OpenMessage, ScrollOverlay(isize), CloseOverlay, diff --git a/src/domain/filter.rs b/src/domain/filter.rs new file mode 100644 index 0000000..2cbcac6 --- /dev/null +++ b/src/domain/filter.rs @@ -0,0 +1,62 @@ +use super::{Entry, prepare_entries}; + +/// A complete, canonically sorted listing with display names prepared for matching. +/// +/// `entries` always includes hidden entries. `folded_names` is parallel to `entries`; +/// both are rebuilt together when a new snapshot is created. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct ListingSnapshot { + pub entries: Vec, + pub folded_names: Vec, +} + +impl ListingSnapshot { + pub fn new(entries: Vec) -> Self { + let entries = prepare_entries(entries, true); + let folded_names = entries + .iter() + .map(|entry| entry.name.to_string_lossy().to_lowercase()) + .collect(); + Self { + entries, + folded_names, + } + } + + /// Applies the hidden-entry policy first, then the already-folded substring query. + pub fn project(&self, show_hidden: bool, folded_query: &str) -> FilterProjection { + let mut eligible = Vec::new(); + let mut visible = Vec::new(); + + for (entry, folded_name) in self.entries.iter().zip(&self.folded_names) { + if !show_hidden && entry.is_hidden() { + continue; + } + + eligible.push(entry.clone()); + if matches_folded(folded_name, folded_query) { + visible.push(entry.clone()); + } + } + + FilterProjection { eligible, visible } + } +} + +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct FilterProjection { + pub eligible: Vec, + pub visible: Vec, +} + +/// Lowercases a query for matching against [`ListingSnapshot::folded_names`]. +/// +/// This is deliberately lowercase-based matching, not full Unicode case folding. +pub fn fold_query(query: &str) -> String { + query.to_lowercase() +} + +/// Matches a literal substring without interpreting regular-expression syntax. +pub fn matches_folded(folded_name: &str, folded_query: &str) -> bool { + folded_name.contains(folded_query) +} diff --git a/src/domain/mod.rs b/src/domain/mod.rs index 33f1603..00d70a1 100644 --- a/src/domain/mod.rs +++ b/src/domain/mod.rs @@ -1,9 +1,11 @@ //! Typed locations, entries and navigation primitives. mod entry; +mod filter; mod location; mod selection; pub use entry::{Entry, EntryId, EntryKind, entry_name, prepare_entries}; +pub use filter::{FilterProjection, ListingSnapshot, fold_query, matches_folded}; pub use location::{HostAlias, Location, SourceId}; pub use selection::{Selection, SelectionSet, restore_selection}; diff --git a/src/input/mod.rs b/src/input/mod.rs index 2db8a95..b501087 100644 --- a/src/input/mod.rs +++ b/src/input/mod.rs @@ -328,6 +328,39 @@ impl InputState { } } + /// Literal incremental filter input; workspace aliases never execute in this context. + pub fn handle_filter_key(&mut self, key: KeyEvent) -> InputOutcome { + self.pending = None; + if key.kind == KeyEventKind::Release { + return InputOutcome::Ignored; + } + if is_press(key, KeyCode::F(10)) { + return InputOutcome::Command(Command::Quit); + } + if is_press(key, KeyCode::Esc) { + return InputOutcome::Command(Command::CloseOverlay); + } + if is_press(key, KeyCode::Enter) { + return InputOutcome::Command(Command::ApplyFilter); + } + if key.kind == KeyEventKind::Press + && key.modifiers.contains(KeyModifiers::CONTROL) + && key.code == KeyCode::Char('u') + { + return InputOutcome::Command(Command::ClearFilterInput); + } + if matches!(key.kind, KeyEventKind::Press | KeyEventKind::Repeat) { + match key.code { + KeyCode::Backspace => return InputOutcome::Command(Command::FilterBackspace), + KeyCode::Char(character) if is_plain(key) => { + return InputOutcome::Command(Command::FilterInput(character)); + } + _ => {} + } + } + InputOutcome::Ignored + } + /// Text capture for create/rename. Global aliases are never interpreted in this mode. pub fn handle_entry_prompt_key(&mut self, key: KeyEvent) -> InputOutcome { self.pending = None; @@ -574,6 +607,9 @@ fn map_command(key: KeyEvent, page_size: usize) -> Option { 'h' => Some(Command::Parent), 'l' => Some(Command::Enter), 'G' => Some(Command::SelectLast), + '/' => Some(Command::OpenFilter), + 'n' => Some(Command::MoveMatch(1)), + 'N' => Some(Command::MoveMatch(-1)), ' ' => Some(Command::ToggleSelect), 'v' => Some(Command::ToggleVisual), 'I' => Some(Command::InvertSelection), @@ -640,7 +676,12 @@ fn is_repeatable_navigation(key: KeyEvent) -> bool { if key.modifiers.contains(KeyModifiers::CONTROL) { return matches!(key.code, KeyCode::Char('b' | 'f' | 'u' | 'd')); } - if is_plain(key) && matches!(key.code, KeyCode::Char('h' | 'j' | 'k' | 'l' | 'G')) { + if is_plain(key) + && matches!( + key.code, + KeyCode::Char('h' | 'j' | 'k' | 'l' | 'G' | 'n' | 'N') + ) + { return true; } matches!( diff --git a/src/session.rs b/src/session.rs index c443410..ac7f0f6 100644 --- a/src/session.rs +++ b/src/session.rs @@ -411,6 +411,7 @@ impl Application { .input .handle_host_picker_key(key, &mut self.host_picker), Overlay::ThemePicker => self.input.handle_theme_picker_key(key, page_size), + Overlay::Filter => self.input.handle_filter_key(key), Overlay::Help => self.input.handle_help_key( key, help_viewport.unwrap_or(HelpViewport { diff --git a/src/tui.rs b/src/tui.rs index 023034d..7258e70 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -20,7 +20,7 @@ use crate::app::{AppState, Command, Overlay}; use crate::session::Application; use crate::ssh::HostPickerState; use crate::ui::help::help_view_model; -use crate::ui::layout::active_page_size; +use crate::ui::layout::active_page_size_with_filter; use crate::ui::terminal::{RcomTerminal, TerminalGuard}; /// Terminal ownership used only by the event loop. The production entry point historically passes @@ -130,7 +130,12 @@ pub async fn run_event_loop( let size = terminal.terminal().size()?; let state = application.state(); let area = Rect::new(0, 0, size.width, size.height); - let page_size = active_page_size(area, state.mode, state.active); + let page_size = active_page_size_with_filter( + area, + state.mode, + state.active, + state.overlay == crate::app::Overlay::Filter, + ); let help_viewport = (state.overlay == Overlay::Help) .then(|| help_view_model(area, &state.help).viewport()); application.handle_key_with_help_viewport(key, page_size, help_viewport); diff --git a/src/ui/layout.rs b/src/ui/layout.rs index db64290..8169ae1 100644 --- a/src/ui/layout.rs +++ b/src/ui/layout.rs @@ -29,24 +29,38 @@ pub struct FrameLayout { pub header: Option, pub workspace: Rect, pub status: Option, + pub filter_editor: Option, pub columns: Vec, } /// Computes all persistent UI regions. Preview overlays deliberately do not participate here. pub fn frame_layout(area: Rect, mode: PaneMode, active: PaneId) -> FrameLayout { + frame_layout_with_filter(area, mode, active, false) +} + +pub fn frame_layout_with_filter( + area: Rect, + mode: PaneMode, + active: PaneId, + editing_filter: bool, +) -> FrameLayout { if area.width < MIN_WIDTH || area.height < MIN_HEIGHT { return FrameLayout { too_small: true, header: None, workspace: area, status: None, + filter_editor: None, columns: Vec::new(), }; } let status_height = 1; let header_height = 1; - let workspace_height = area.height.saturating_sub(header_height + status_height); + let editor_height = if editing_filter { 2 } else { 0 }; + let workspace_height = area + .height + .saturating_sub(header_height + status_height + editor_height); let header = Some(Rect::new(area.x, area.y, area.width, header_height)); let workspace = Rect::new( area.x, @@ -54,10 +68,16 @@ pub fn frame_layout(area: Rect, mode: PaneMode, active: PaneId) -> FrameLayout { area.width, workspace_height, ); - let status = Some(Rect::new( + let filter_editor = editing_filter.then_some(Rect::new( area.x, workspace.y.saturating_add(workspace.height), area.width, + editor_height, + )); + let status = Some(Rect::new( + area.x, + workspace.y.saturating_add(workspace.height + editor_height), + area.width, status_height, )); let columns = columns(workspace, mode, active); @@ -66,6 +86,7 @@ pub fn frame_layout(area: Rect, mode: PaneMode, active: PaneId) -> FrameLayout { header, workspace, status, + filter_editor, columns, } } @@ -75,7 +96,16 @@ pub fn frame_layout(area: Rect, mode: PaneMode, active: PaneId) -> FrameLayout { /// This uses the same frame, pane border, and table-header geometry as the renderer. Tiny or /// invalid layouts still produce a useful minimum step for the input reducer. pub fn active_page_size(area: Rect, mode: PaneMode, active: PaneId) -> usize { - let layout = frame_layout(area, mode, active); + active_page_size_with_filter(area, mode, active, false) +} + +pub fn active_page_size_with_filter( + area: Rect, + mode: PaneMode, + active: PaneId, + editing_filter: bool, +) -> usize { + let layout = frame_layout_with_filter(area, mode, active, editing_filter); let rows = layout .columns .iter() diff --git a/src/ui/render.rs b/src/ui/render.rs index 188e6b5..9b42ddf 100644 --- a/src/ui/render.rs +++ b/src/ui/render.rs @@ -19,7 +19,7 @@ use crate::preview::{EntryPreview, Preview, PreviewKind, TRUNCATION_MARKER}; use crate::ssh::HostPickerState; use super::help::{HelpTabs, help_view_model}; -use super::layout::{ColumnRole, centered, frame_layout, pane_rows_area}; +use super::layout::{ColumnRole, centered, frame_layout_with_filter, pane_rows_area}; use super::text::{fit, sanitize, truncate_filename, truncate_middle, wrap}; use super::{IconMode, ResolvedIcon, Theme, ThemeId}; @@ -47,7 +47,8 @@ pub fn render_with_context( } frame.render_widget(Block::new().style(theme.base()), area); - let layout = frame_layout(area, app.mode, app.active); + let layout = + frame_layout_with_filter(area, app.mode, app.active, app.overlay == Overlay::Filter); if layout.too_small { render_too_small(frame, area, theme); return; @@ -63,6 +64,7 @@ pub fn render_with_context( frame, column.area, app.pane(id), + !app.filter_query(id).is_empty(), app.clipboard.as_ref(), id, id == app.active, @@ -83,12 +85,15 @@ pub fn render_with_context( } } } + if let Some(editor) = layout.filter_editor { + render_filter_editor(frame, editor, app, theme); + } if let Some(status) = layout.status { render_status(frame, status, app, theme); } match app.overlay { - Overlay::None => {} + Overlay::None | Overlay::Filter => {} Overlay::Help => render_help(frame, area, app, theme), Overlay::HostPicker => render_host_picker(frame, area, host_picker, theme), Overlay::Preview => render_preview_overlay( @@ -201,6 +206,7 @@ fn render_pane( frame: &mut Frame, area: Rect, pane: &PaneState, + filtering: bool, clipboard: Option<&Clipboard>, id: PaneId, active: bool, @@ -314,17 +320,24 @@ fn render_pane( theme, ); } else if pane.entries.is_empty() { - render_message( - frame, - inner, - "EMPTY DIRECTORY", - &[ - "No visible entries.".to_owned(), - [". Show hidden", "Ctrl-r Refresh"].join(theme.separator()), - ], - theme.muted(), - theme, - ); + let (heading, messages) = if filtering { + ( + "NO MATCHES", + vec![ + "No entries match the current filter.".to_owned(), + ["/ Edit filter", "Esc Close/Clear"].join(theme.separator()), + ], + ) + } else { + ( + "EMPTY DIRECTORY", + vec![ + "No visible entries.".to_owned(), + [". Show hidden", "Ctrl-r Refresh"].join(theme.separator()), + ], + ) + }; + render_message(frame, inner, heading, &messages, theme.muted(), theme); } else { render_entries(frame, area, inner, pane, clipboard, active, theme); } @@ -803,8 +816,38 @@ fn render_message( frame.render_widget(Paragraph::new(lines).style(theme.panel()), area); } +fn render_filter_editor(frame: &mut Frame, area: Rect, app: &AppState, theme: &Theme) { + let query = app + .filter_editor + .as_ref() + .map(|editor| editor.draft.as_str()) + .unwrap_or(""); + let input = format!( + "FILTER> {}", + crate::preview::sanitize_text(query.as_bytes()) + ); + frame.render_widget( + Paragraph::new(fit(&input, usize::from(area.width), theme.is_ascii())) + .style(theme.active()), + Rect::new(area.x, area.y, area.width, 1), + ); + if area.height > 1 { + frame.render_widget( + Paragraph::new(fit( + "Enter Apply | Esc Cancel | Ctrl-u Clear", + usize::from(area.width), + theme.is_ascii(), + )) + .alignment(Alignment::Center) + .style(theme.secondary()), + Rect::new(area.x, area.y + 1, area.width, 1), + ); + } +} + fn render_status(frame: &mut Frame, area: Rect, app: &AppState, theme: &Theme) { let pane = app.active_pane(); + let filter = app.filter_stats(app.active); let (message, style) = if let Some(error) = &pane.error { ( format!("ERROR {}{}", theme.separator(), error.user_message()), @@ -828,6 +871,36 @@ fn render_status(frame: &mut Frame, area: Rect, app: &AppState, theme: &Theme) { ), theme.active(), ) + } else if !filter.query.is_empty() { + let query = crate::preview::sanitize_text(filter.query.as_bytes()); + let marked = if filter.hidden_marked > 0 { + format!( + "{}Hidden marked {}", + theme.separator(), + filter.hidden_marked + ) + } else { + String::new() + }; + let counts = format!( + "{}{}/{}{}", + theme.separator(), + filter.visible, + filter.total, + marked + ); + let prefix = "FILTER "; + let query_width = usize::from(area.width) + .saturating_sub(UnicodeWidthStr::width(prefix)) + .saturating_sub(UnicodeWidthStr::width(counts.as_str())); + let query = if query_width == 0 { + String::new() + } else { + truncate_middle(&query, query_width, theme.is_ascii()) + }; + (format!("{prefix}{query}{counts}"), theme.secondary()) + } else if let Some(notice) = filter.notice { + (notice, theme.secondary()) } else { let selected = pane.selection.index().map_or(0, |index| index + 1); let hidden = if pane.show_hidden { "shown" } else { "hidden" }; diff --git a/tests/app_navigation.rs b/tests/app_navigation.rs index c4ec0c0..9114dce 100644 --- a/tests/app_navigation.rs +++ b/tests/app_navigation.rs @@ -206,8 +206,7 @@ async fn hidden_filter_applies_to_loaded_entries() { refresh(&fs, &mut app).await; assert_eq!(names(&app), ["visible"]); - let request = one_listing(app.reduce(Command::ToggleHidden)); - finish_listing(&fs, &mut app, request).await; + assert!(app.reduce(Command::ToggleHidden).is_empty()); assert_eq!(names(&app), [".secret", "visible"]); } diff --git a/tests/file_filter.rs b/tests/file_filter.rs new file mode 100644 index 0000000..952fbbe --- /dev/null +++ b/tests/file_filter.rs @@ -0,0 +1,144 @@ +use std::ffi::OsString; + +use rcom::domain::{Entry, EntryKind, ListingSnapshot, fold_query, matches_folded}; + +fn file(name: impl Into) -> Entry { + Entry::new(name, EntryKind::File) +} + +fn names(entries: &[Entry]) -> Vec { + entries + .iter() + .map(|entry| entry.name.to_string_lossy().into_owned()) + .collect() +} + +#[test] +fn snapshot_keeps_the_complete_canonical_order_and_parallel_folded_names() { + let snapshot = ListingSnapshot::new(vec![ + file("zeta"), + Entry::new("Beta", EntryKind::Directory), + file("ALPHA"), + file(".hidden"), + ]); + + assert_eq!( + names(&snapshot.entries), + ["Beta", ".hidden", "ALPHA", "zeta"] + ); + assert_eq!(snapshot.folded_names, ["beta", ".hidden", "alpha", "zeta"]); + assert_eq!(snapshot.entries.len(), snapshot.folded_names.len()); + assert_eq!(snapshot, snapshot.clone()); +} + +#[test] +fn projection_applies_hidden_policy_before_the_query() { + let snapshot = ListingSnapshot::new(vec![ + file("notes"), + file(".readme-secret"), + file("README.md"), + Entry::new("readme-dir", EntryKind::Directory), + file(".hidden"), + ]); + + let without_hidden = snapshot.project(false, &fold_query("README")); + assert_eq!( + names(&without_hidden.eligible), + ["readme-dir", "notes", "README.md"] + ); + assert_eq!(names(&without_hidden.visible), ["readme-dir", "README.md"]); + + let with_hidden = snapshot.project(true, &fold_query("readme")); + assert_eq!( + names(&with_hidden.visible), + ["readme-dir", ".readme-secret", "README.md"] + ); + + let no_matches = snapshot.project(false, &fold_query("absent")); + assert_eq!(no_matches.eligible, without_hidden.eligible); + assert!(no_matches.visible.is_empty()); +} + +#[test] +fn empty_query_makes_visible_equal_to_eligible() { + let snapshot = ListingSnapshot::new(vec![file("visible"), file(".hidden")]); + + for show_hidden in [false, true] { + let projection = snapshot.project(show_hidden, ""); + assert_eq!(projection.visible, projection.eligible); + } + assert!(matches_folded("anything", "")); +} + +#[test] +fn query_is_a_literal_substring_not_a_regular_expression() { + let snapshot = ListingSnapshot::new(vec![ + file("report[1].txt"), + file("report1.txt"), + file("literal.*.txt"), + ]); + + let character_class = snapshot.project(true, &fold_query("[1].")); + assert_eq!(names(&character_class.visible), ["report[1].txt"]); + + let repetition = snapshot.project(true, &fold_query(".*")); + assert_eq!(names(&repetition.visible), ["literal.*.txt"]); +} + +#[test] +fn unicode_lowercase_does_not_promise_full_case_folding() { + let snapshot = + ListingSnapshot::new(vec![file("Straße"), file("STRASSE"), file("Σ"), file("ς")]); + + let sharp_s = snapshot.project(true, &fold_query("SS")); + assert_eq!(names(&sharp_s.visible), ["STRASSE"]); + assert_eq!(fold_query("Straße"), "straße"); + + let capital_sigma = snapshot.project(true, &fold_query("Σ")); + assert_eq!(names(&capital_sigma.visible), ["Σ"]); + + let final_sigma = snapshot.project(true, &fold_query("ς")); + assert_eq!(names(&final_sigma.visible), ["ς"]); +} + +#[cfg(unix)] +#[test] +fn non_utf8_names_match_lossy_display_text_without_changing_the_entry() { + use std::os::unix::ffi::{OsStrExt, OsStringExt}; + + let raw = OsString::from_vec(vec![b'F', 0x80, b'O', b'.', b'T', b'X', b'T']); + let snapshot = ListingSnapshot::new(vec![file(raw.clone())]); + + assert_eq!(snapshot.folded_names, ["f\u{fffd}o.txt"]); + let projection = snapshot.project(true, &fold_query("F\u{fffd}O")); + assert_eq!(projection.visible.len(), 1); + assert_eq!( + snapshot.entries[0].name.as_os_str().as_bytes(), + raw.as_bytes() + ); + assert_eq!( + projection.visible[0].name.as_os_str().as_bytes(), + raw.as_bytes() + ); +} + +#[test] +fn twenty_thousand_entries_support_repeated_precomputed_matching() { + let entries = (0..20_000) + .map(|index| file(format!("Item-{index:05}-suffix"))) + .collect(); + let snapshot = ListingSnapshot::new(entries); + let folded_names = snapshot.folded_names.clone(); + let query = fold_query("ITEM-0199"); + let expected = (1_990..=1_999) + .map(|index| format!("Item-{index:05}-suffix")) + .collect::>(); + + for _ in 0..16 { + let projection = snapshot.project(true, &query); + assert_eq!(projection.eligible.len(), 20_000); + assert_eq!(names(&projection.visible), expected); + } + + assert_eq!(snapshot.folded_names, folded_names); +} diff --git a/tests/filter_input.rs b/tests/filter_input.rs new file mode 100644 index 0000000..ea870f8 --- /dev/null +++ b/tests/filter_input.rs @@ -0,0 +1,87 @@ +use crossterm::event::{KeyCode, KeyEvent, KeyEventKind, KeyEventState, KeyModifiers}; +use rcom::app::Command; +use rcom::input::{InputOutcome, InputState}; + +fn event(code: KeyCode, modifiers: KeyModifiers, kind: KeyEventKind) -> KeyEvent { + KeyEvent { + code, + modifiers, + kind, + state: KeyEventState::NONE, + } +} + +#[test] +fn filter_input_captures_aliases_and_press_repeat_policy() { + for kind in [KeyEventKind::Press, KeyEventKind::Repeat] { + for character in ['j', 'q', '?', 'n', '/'] { + assert_eq!( + InputState::new().handle_filter_key(event( + KeyCode::Char(character), + KeyModifiers::NONE, + kind + )), + InputOutcome::Command(Command::FilterInput(character)) + ); + } + assert_eq!( + InputState::new().handle_filter_key(event( + KeyCode::Backspace, + KeyModifiers::NONE, + kind + )), + InputOutcome::Command(Command::FilterBackspace) + ); + } + for (key, command) in [ + ( + event(KeyCode::Enter, KeyModifiers::NONE, KeyEventKind::Press), + Command::ApplyFilter, + ), + ( + event(KeyCode::Esc, KeyModifiers::NONE, KeyEventKind::Press), + Command::CloseOverlay, + ), + ( + event(KeyCode::F(10), KeyModifiers::NONE, KeyEventKind::Press), + Command::Quit, + ), + ( + event( + KeyCode::Char('u'), + KeyModifiers::CONTROL, + KeyEventKind::Press, + ), + Command::ClearFilterInput, + ), + ] { + assert_eq!( + InputState::new().handle_filter_key(key), + InputOutcome::Command(command) + ); + } + for code in [KeyCode::Enter, KeyCode::Esc, KeyCode::F(10)] { + assert_eq!( + InputState::new().handle_filter_key(event( + code, + KeyModifiers::NONE, + KeyEventKind::Release + )), + InputOutcome::Ignored + ); + } + assert_eq!( + InputState::new().handle_key( + event(KeyCode::Char('/'), KeyModifiers::NONE, KeyEventKind::Repeat), + 10 + ), + InputOutcome::Ignored + ); + assert_eq!( + InputState::new().handle_key( + event(KeyCode::Char('n'), KeyModifiers::NONE, KeyEventKind::Repeat), + 10 + ), + InputOutcome::Command(Command::MoveMatch(1)) + ); +} diff --git a/tests/filter_navigation.rs b/tests/filter_navigation.rs new file mode 100644 index 0000000..8883bf8 --- /dev/null +++ b/tests/filter_navigation.rs @@ -0,0 +1,481 @@ +use rcom::app::{AppState, Command, Effect, Overlay, PaneId}; +use rcom::domain::{Entry, EntryKind, Location}; +use rcom::fs::FsError; + +fn app_with_entries(names: &[&str]) -> AppState { + let mut app = AppState::new(Location::local("/work")); + let initial = app.reduce(Command::Refresh); + let [Effect::LoadListing(request)] = initial.as_slice() else { + panic!("initial listing") + }; + let entries = names + .iter() + .map(|name| Entry::new(*name, EntryKind::File)) + .collect(); + let effects = app.reduce(Command::ListingFinished( + request.clone().into_result(Ok(entries)), + )); + for effect in effects { + if let Effect::LoadPreview(request) = effect { + app.reduce(Command::PreviewFinished( + request.into_result(Ok(rcom::preview::preview_bytes(b"initial", false))), + )); + } + } + app +} + +fn names(app: &AppState) -> Vec { + app.active_pane() + .entries + .iter() + .map(|entry| entry.name.to_string_lossy().into_owned()) + .collect() +} + +#[test] +fn filter_apply_cancel_and_match_navigation_preserve_entry_identity() { + let mut app = app_with_entries(&["alpha", "alphabet", "beta", "gamma"]); + let original_id = app.active_pane().location.entry_id("alpha"); + app.reduce(Command::OpenFilter); + assert_eq!(app.overlay, Overlay::Filter); + let effects = app.reduce(Command::FilterInput('b')); + assert!(matches!(effects.as_slice(), [Effect::DebouncePreview(_)])); + assert_eq!(names(&app), ["alphabet", "beta"]); + assert_eq!(app.active_pane().selected_entry().unwrap().name, "alphabet"); + assert!(app.active_pane().filter.is_empty(), "draft is not applied"); + + app.reduce(Command::CloseOverlay); + assert_eq!(app.overlay, Overlay::None); + assert_eq!(names(&app), ["alpha", "alphabet", "beta", "gamma"]); + assert_eq!(app.active_pane().selected_entry().unwrap().name, "alpha"); + assert_eq!(app.active_pane().location.entry_id("alpha"), original_id); + + app.reduce(Command::OpenFilter); + for character in "alpha".chars() { + app.reduce(Command::FilterInput(character)); + } + app.reduce(Command::ApplyFilter); + assert_eq!(app.active_pane().filter, "alpha"); + assert_eq!(names(&app), ["alpha", "alphabet"]); + assert_eq!(app.active_pane().selection.index(), Some(0)); + app.reduce(Command::MoveMatch(1)); + assert_eq!(app.active_pane().selection.index(), Some(1)); + app.reduce(Command::MoveMatch(1)); + assert_eq!(app.active_pane().selection.index(), Some(0)); + app.reduce(Command::MoveMatch(-1)); + assert_eq!(app.active_pane().selection.index(), Some(1)); + app.reduce(Command::CloseOverlay); + assert_eq!(names(&app), ["alpha", "alphabet", "beta", "gamma"]); + assert_eq!(app.active_pane().selected_entry().unwrap().name, "alphabet"); +} + +#[test] +fn no_matches_blocks_source_actions_and_notices_do_not_mutate_listing() { + let mut app = app_with_entries(&["alpha", "beta"]); + app.reduce(Command::OpenFilter); + app.reduce(Command::FilterInput('z')); + assert!(app.active_pane().entries.is_empty()); + assert_eq!(app.active_pane().selection.index(), None); + app.reduce(Command::ApplyFilter); + let before = app.active_pane().clone(); + assert!(app.reduce(Command::Copy).is_empty()); + assert!(app.pending_operation.is_none()); + assert_eq!(app.active_pane().location, before.location); + app.reduce(Command::MoveMatch(1)); + assert_eq!( + app.active_pane().filter_notice.as_deref(), + Some("No matches") + ); +} + +#[test] +fn hidden_marked_sources_stay_complete_and_clipboard_paste_survives_empty_projection() { + let mut app = app_with_entries(&["alpha", "beta"]); + app.reduce(Command::SelectAll); + app.reduce(Command::Yank); + app.reduce(Command::OpenFilter); + for character in "alpha".chars() { + app.reduce(Command::FilterInput(character)); + } + app.reduce(Command::ApplyFilter); + app.reduce(Command::TogglePaneMode); + let effects = app.reduce(Command::Copy); + assert!(matches!(effects.as_slice(), [Effect::PlanOperation(_)])); + assert_eq!(app.pending_operation.as_ref().unwrap().sources.len(), 2); + assert_eq!(app.filter_stats(PaneId::Left).hidden_marked, 1); + app.reduce(Command::CloseOverlay); + + app.reduce(Command::OpenFilter); + app.reduce(Command::ClearFilterInput); + app.reduce(Command::FilterInput('z')); + app.reduce(Command::ApplyFilter); + assert!(app.active_pane().entries.is_empty()); + let paste = app.reduce(Command::Paste); + assert!(matches!(paste.as_slice(), [Effect::PlanOperation(_)])); +} + +#[test] +fn visual_escape_precedes_filter_clear_and_no_active_match_is_inert() { + let mut app = app_with_entries(&["alpha", "beta"]); + app.reduce(Command::MoveMatch(1)); + assert_eq!( + app.active_pane().filter_notice.as_deref(), + Some("No active filter") + ); + app.reduce(Command::ToggleVisual); + app.reduce(Command::OpenFilter); + app.reduce(Command::FilterInput('a')); + app.reduce(Command::ApplyFilter); + app.reduce(Command::CloseOverlay); + assert!(!app.active_pane().visual_mode); + assert_eq!(app.active_pane().filter, "a"); + app.reduce(Command::CloseOverlay); + assert!(app.active_pane().filter.is_empty()); +} + +#[test] +fn hidden_policy_and_query_have_separate_marked_counts() { + let mut app = app_with_entries(&[".secret", "alpha", "beta"]); + app.reduce(Command::OpenFilter); + app.reduce(Command::FilterInput('a')); + app.reduce(Command::ApplyFilter); + assert_eq!(names(&app), ["alpha", "beta"]); + app.reduce(Command::ClearSelection); + app.reduce(Command::ToggleSelect); + let beta = app.active_pane().location.entry_id("beta"); + app.active_pane_mut().selection_set.insert(beta); + let secret = app.active_pane().location.entry_id(".secret"); + app.active_pane_mut().selection_set.insert(secret); + app.reduce(Command::OpenFilter); + app.reduce(Command::ClearFilterInput); + for character in "alpha".chars() { + app.reduce(Command::FilterInput(character)); + } + app.reduce(Command::ApplyFilter); + let stats = app.filter_stats(PaneId::Left); + assert_eq!((stats.visible, stats.total), (1, 2)); + assert_eq!(stats.hidden_marked, 1); + app.reduce(Command::CloseOverlay); + assert!( + app.active_pane() + .selection_set + .contains(&app.active_pane().location.entry_id("beta")) + ); +} + +#[test] +fn failed_navigation_preserves_filter_and_accepted_navigation_resets_draft() { + let mut app = app_with_entries(&["alpha", "beta"]); + app.reduce(Command::OpenFilter); + for character in "alpha".chars() { + app.reduce(Command::FilterInput(character)); + } + app.reduce(Command::ApplyFilter); + let target = Location::local("/other"); + let failed_effects = app.reduce(Command::GoHome(target.clone())); + let [Effect::LoadListing(failed)] = failed_effects.as_slice() else { + panic!("navigation") + }; + app.reduce(Command::ListingFinished( + failed.clone().into_result(Err(FsError::NotFound)), + )); + assert_eq!(app.active_pane().filter, "alpha"); + assert_eq!(app.active_pane().location, Location::local("/work")); + + app.reduce(Command::OpenFilter); + app.reduce(Command::FilterInput('x')); + let succeeded_effects = app.reduce(Command::GoHome(target.clone())); + let [Effect::LoadListing(succeeded)] = succeeded_effects.as_slice() else { + panic!("navigation") + }; + app.reduce(Command::ListingFinished( + succeeded + .clone() + .into_result(Ok(vec![Entry::new("new", EntryKind::File)])), + )); + assert_eq!(app.active_pane().location, target); + assert!(app.active_pane().filter.is_empty()); + assert!(app.filter_editor.is_none()); + assert_eq!(app.overlay, Overlay::None); +} + +#[test] +fn superseded_navigation_followed_by_same_location_refresh_preserves_filter() { + let mut app = app_with_entries(&["alpha", "beta"]); + app.reduce(Command::OpenFilter); + app.reduce(Command::FilterInput('a')); + app.reduce(Command::ApplyFilter); + let _superseded = app.reduce(Command::GoHome(Location::local("/other"))); + let refresh = app.reduce(Command::Refresh); + let [Effect::LoadListing(refresh)] = refresh.as_slice() else { + panic!("same-location refresh") + }; + app.reduce(Command::ListingFinished(refresh.clone().into_result(Ok( + vec![ + Entry::new("alpha", EntryKind::File), + Entry::new("beta", EntryKind::File), + ], + )))); + assert_eq!(app.active_pane().location, Location::local("/work")); + assert_eq!(app.active_pane().filter, "a"); +} + +#[test] +fn f10_and_dual_transitions_do_not_leak_draft_or_merge_filters() { + let mut quit = app_with_entries(&["alpha", "beta"]); + quit.reduce(Command::OpenFilter); + quit.reduce(Command::FilterInput('b')); + quit.reduce(Command::Quit); + assert!(quit.should_quit); + assert!(quit.filter_editor.is_none()); + assert!(quit.active_pane().filter.is_empty()); + quit.should_quit = false; + quit.overlay = Overlay::Quit; + quit.reduce(Command::DecideQuit(rcom::app::QuitDecision::Stay)); + assert!(quit.filter_editor.is_none()); + assert_eq!(quit.overlay, Overlay::None); + + let mut dual = app_with_entries(&["alpha", "beta"]); + dual.reduce(Command::OpenFilter); + dual.reduce(Command::FilterInput('a')); + dual.reduce(Command::ApplyFilter); + dual.reduce(Command::TogglePaneMode); + dual.reduce(Command::OpenFilter); + dual.reduce(Command::ClearFilterInput); + dual.reduce(Command::FilterInput('b')); + dual.reduce(Command::ApplyFilter); + assert_eq!(dual.pane(PaneId::Left).filter, "b"); + assert_eq!(dual.pane(PaneId::Right).filter, "a"); +} + +#[test] +fn same_home_reconnect_resets_filter_only_after_accepted_new_epoch() { + let host = rcom::domain::HostAlias::new("edge"); + let home = Location::ssh(host.clone(), "/home/user"); + let mut app = AppState::new(home.clone()); + let effects = app.reduce(Command::ConnectSsh(host.clone())); + let [Effect::ConnectSsh(connect)] = effects.as_slice() else { + panic!("connect") + }; + let listing = app.reduce(Command::ConnectSshFinished(connect.clone().into_result( + Ok(rcom::app::SshConnection { + location: home.clone(), + session_epoch: 1, + }), + ))); + let [Effect::LoadListing(listing)] = listing.as_slice() else { + panic!("home listing") + }; + app.reduce(Command::ListingFinished(listing.clone().into_result(Ok( + vec![ + Entry::new("alpha", EntryKind::File), + Entry::new("beta", EntryKind::File), + ], + )))); + app.reduce(Command::OpenFilter); + for character in "alpha".chars() { + app.reduce(Command::FilterInput(character)); + } + app.reduce(Command::ApplyFilter); + app.reduce(Command::TogglePaneMode); + app.reduce(Command::OpenFilter); + app.reduce(Command::FilterInput('x')); + let reconnect = app.reduce(Command::ConnectSsh(host.clone())); + let [Effect::ConnectSsh(reconnect)] = reconnect.as_slice() else { + panic!("reconnect") + }; + app.reduce(Command::SynchronizeSshEpoch { + host: host.clone(), + session_epoch: 2, + }); + let listing = app.reduce(Command::ConnectSshFinished(reconnect.clone().into_result( + Ok(rcom::app::SshConnection { + location: home.clone(), + session_epoch: 2, + }), + ))); + let [Effect::LoadListing(listing)] = listing.as_slice() else { + panic!("new home listing") + }; + app.reduce(Command::ListingFinished( + listing + .clone() + .into_result(Ok(vec![Entry::new("alpha", EntryKind::File)])), + )); + assert!(app.active_pane().filter.is_empty()); + assert!(app.pane(PaneId::Right).filter.is_empty()); + assert!(app.filter_editor.is_none()); + assert_eq!(app.overlay, Overlay::None); + + app.reduce(Command::OpenFilter); + for character in "alpha".chars() { + app.reduce(Command::FilterInput(character)); + } + app.reduce(Command::ApplyFilter); + app.reduce(Command::OpenFilter); + app.reduce(Command::FilterInput('x')); + let failed = app.reduce(Command::ConnectSsh(host.clone())); + let [Effect::ConnectSsh(failed)] = failed.as_slice() else { + panic!("failed reconnect") + }; + app.reduce(Command::ConnectSshFinished( + failed.clone().into_result(Err(FsError::Disconnected)), + )); + let refresh = app.reduce(Command::Refresh); + let [Effect::LoadListing(refresh)] = refresh.as_slice() else { + panic!("same-location refresh") + }; + app.reduce(Command::ListingFinished( + refresh + .clone() + .into_result(Ok(vec![Entry::new("alpha", EntryKind::File)])), + )); + assert_eq!(app.active_pane().filter, "alpha"); + assert_eq!(app.filter_editor.as_ref().unwrap().draft, "alphax"); + app.reduce(Command::CloseOverlay); + let cached = app.reduce(Command::ConnectSsh(host.clone())); + let [Effect::ConnectSsh(cached)] = cached.as_slice() else { + panic!("cached reconnect") + }; + let listing = app.reduce(Command::ConnectSshFinished(cached.clone().into_result(Ok( + rcom::app::SshConnection { + location: home, + session_epoch: 2, + }, + )))); + let [Effect::LoadListing(listing)] = listing.as_slice() else { + panic!("cached home listing") + }; + app.reduce(Command::ListingFinished( + listing + .clone() + .into_result(Ok(vec![Entry::new("alpha", EntryKind::File)])), + )); + assert_eq!(app.active_pane().filter, "alpha"); +} + +#[test] +fn background_refresh_preserves_draft_or_immediately_reloads_changed_selection() { + let mut same = app_with_entries(&["alpha", "beta"]); + same.reduce(Command::OpenFilter); + same.reduce(Command::FilterInput('b')); + let effects = same.reduce(Command::RefreshPane(PaneId::Left)); + let [Effect::LoadListing(listing)] = effects.as_slice() else { + panic!("background listing") + }; + let result = same.reduce(Command::ListingFinished(listing.clone().into_result(Ok( + vec![ + Entry::new("alpha", EntryKind::File), + Entry::new("beta", EntryKind::File), + ], + )))); + assert!(result.is_empty()); + assert!(same.active_pane().preview.debouncing); + assert_eq!(same.filter_editor.as_ref().unwrap().draft, "b"); + + let mut changed = app_with_entries(&["alpha", "alphabet"]); + changed.reduce(Command::OpenFilter); + for character in "alpha".chars() { + changed.reduce(Command::FilterInput(character)); + } + changed.reduce(Command::ApplyFilter); + let effects = changed.reduce(Command::RefreshPane(PaneId::Left)); + let [Effect::LoadListing(listing)] = effects.as_slice() else { + panic!("background listing") + }; + let result = changed.reduce(Command::ListingFinished( + listing + .clone() + .into_result(Ok(vec![Entry::new("alphabet", EntryKind::File)])), + )); + assert!(matches!(result.as_slice(), [Effect::LoadPreview(_)])); + assert!(!changed.active_pane().preview.debouncing); + assert_eq!( + changed.active_pane().selected_entry().unwrap().name, + "alphabet" + ); + + let mut removed = app_with_entries(&["alpha"]); + removed.reduce(Command::OpenFilter); + removed.reduce(Command::FilterInput('a')); + removed.reduce(Command::ApplyFilter); + let effects = removed.reduce(Command::RefreshPane(PaneId::Left)); + let [Effect::LoadListing(listing)] = effects.as_slice() else { + panic!("background listing") + }; + let result = removed.reduce(Command::ListingFinished( + listing + .clone() + .into_result(Ok(vec![Entry::new("0", EntryKind::File)])), + )); + assert!(result.is_empty()); + assert!(removed.active_pane().entries.is_empty()); + assert_eq!(removed.active_pane().preview.target, None); +} + +#[test] +fn background_removed_match_uses_previous_projected_index_for_nearest_fallback() { + let mut app = app_with_entries(&["0", "a1", "a2", "a3"]); + app.reduce(Command::OpenFilter); + app.reduce(Command::FilterInput('a')); + app.reduce(Command::ApplyFilter); + app.reduce(Command::MoveMatch(1)); + assert_eq!(app.active_pane().selected_entry().unwrap().name, "a2"); + let effects = app.reduce(Command::RefreshPane(PaneId::Left)); + let [Effect::LoadListing(listing)] = effects.as_slice() else { + panic!("background listing") + }; + let result = app.reduce(Command::ListingFinished(listing.clone().into_result(Ok( + vec![ + Entry::new("0", EntryKind::File), + Entry::new("a1", EntryKind::File), + Entry::new("a3", EntryKind::File), + ], + )))); + assert_eq!(app.active_pane().selected_entry().unwrap().name, "a3"); + assert_eq!(app.active_pane().selection.index(), Some(1)); + assert!( + matches!(result.as_slice(), [Effect::LoadPreview(request)] if request.target == Location::local("/work/a3")) + ); +} + +#[test] +fn foreground_removed_match_uses_previous_projected_index_for_nearest_fallback() { + let mut app = app_with_entries(&["0", "a1", "a2", "a3"]); + app.reduce(Command::OpenFilter); + app.reduce(Command::FilterInput('a')); + app.reduce(Command::ApplyFilter); + app.reduce(Command::MoveMatch(1)); + let effects = app.reduce(Command::Refresh); + let [Effect::LoadListing(listing)] = effects.as_slice() else { + panic!("foreground refresh") + }; + let result = app.reduce(Command::ListingFinished(listing.clone().into_result(Ok( + vec![ + Entry::new("0", EntryKind::File), + Entry::new("a1", EntryKind::File), + Entry::new("a3", EntryKind::File), + ], + )))); + assert_eq!(app.active_pane().selected_entry().unwrap().name, "a3"); + assert!( + matches!(result.as_slice(), [Effect::LoadPreview(request)] if request.target == Location::local("/work/a3")) + ); +} + +#[test] +fn hidden_toggle_uses_canonical_snapshot_without_a_listing_effect() { + let mut app = app_with_entries(&["visible"]); + let hidden = Entry::new(".secret", EntryKind::File); + let initial = app.reduce(Command::Refresh); + let [Effect::LoadListing(request)] = initial.as_slice() else { + panic!("refresh") + }; + app.reduce(Command::ListingFinished(request.clone().into_result(Ok( + vec![hidden, Entry::new("visible", EntryKind::File)], + )))); + assert_eq!(names(&app), ["visible"]); + assert!(app.reduce(Command::ToggleHidden).is_empty()); + assert_eq!(names(&app), [".secret", "visible"]); +} diff --git a/tests/filter_runtime.rs b/tests/filter_runtime.rs new file mode 100644 index 0000000..240665f --- /dev/null +++ b/tests/filter_runtime.rs @@ -0,0 +1,62 @@ +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use rcom::app::Command; +use rcom::domain::{Entry, EntryKind, Location}; +use rcom::fs::BackendRegistry; +use rcom::session::Application; +use rcom::ssh::{ConnectionManager, DiscoveryResult, OpenSshConnector}; +use rcom::test_support::{MemoryFs, RecordingFs}; + +#[tokio::test] +async fn matching_has_zero_listing_io_and_only_one_current_preview_read_after_deadline() { + let fs = MemoryFs::new() + .with_file(Location::local("/alpha.txt"), "alpha") + .with_file(Location::local("/beta.txt"), "beta"); + let recording = Arc::new(RecordingFs::new(Arc::new(fs))); + let registry = BackendRegistry::new(recording.clone()); + let connections = ConnectionManager::new(Arc::new(OpenSshConnector::default()), registry); + let (mut app, mut results) = Application::new( + Location::local("/"), + connections, + DiscoveryResult::default(), + ); + app.state_mut_for_test().panes[0].entries = vec![ + Entry::new("alpha.txt", EntryKind::File), + Entry::new("beta.txt", EntryKind::File), + ]; + app.state_mut_for_test().panes[0].selection.set(Some(0), 2); + let start = Instant::now(); + app.dispatch_at(Command::OpenFilter, start); + app.dispatch_at(Command::FilterInput('b'), start + Duration::from_millis(1)); + assert!(recording.operations().is_empty()); + assert_eq!(app.pending_preview_count(), 1); + app.expire_pending_at(start + Duration::from_millis(41)); + let command = tokio::time::timeout(Duration::from_secs(1), results.recv()) + .await + .unwrap() + .unwrap(); + assert!(matches!(command, Command::PreviewFinished(_))); + assert_eq!(recording.operations().len(), 2); +} + +#[test] +fn local_and_ssh_locations_share_the_same_projection_contract() { + for location in [ + Location::local("/work"), + Location::ssh(rcom::domain::HostAlias::new("fake"), "/work"), + ] { + let mut app = rcom::app::AppState::new(location); + app.active_pane_mut().entries = vec![ + Entry::new("Alpha", EntryKind::File), + Entry::new("beta", EntryKind::File), + ]; + app.active_pane_mut().selection.set(Some(0), 2); + app.reduce(Command::OpenFilter); + app.reduce(Command::FilterInput('a')); + assert_eq!(app.active_pane().entries.len(), 2); + app.reduce(Command::FilterInput('l')); + assert_eq!(app.active_pane().entries.len(), 1); + assert_eq!(app.active_pane().selected_entry().unwrap().name, "Alpha"); + } +} diff --git a/tests/filter_ui.rs b/tests/filter_ui.rs new file mode 100644 index 0000000..375c1b8 --- /dev/null +++ b/tests/filter_ui.rs @@ -0,0 +1,107 @@ +use ratatui::{Terminal, backend::TestBackend, buffer::Buffer}; +use rcom::app::{AppState, Command, Overlay}; +use rcom::domain::{Entry, EntryKind, Location}; +use rcom::ui::{IconMode, Theme, render}; + +fn app() -> AppState { + let mut app = AppState::new(Location::local("/work")); + app.active_pane_mut().entries = ["alpha", "beta", "gamma"] + .into_iter() + .map(|name| Entry::new(name, EntryKind::File)) + .collect(); + app.active_pane_mut().selection.set(Some(0), 3); + app +} + +fn buffer(app: &AppState, width: u16, height: u16, theme: &Theme) -> Buffer { + let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap(); + terminal + .draw(|frame| render(frame, app, None, theme)) + .unwrap(); + terminal.backend().buffer().clone() +} + +fn text(buffer: &Buffer) -> String { + (0..buffer.area.height) + .map(|y| { + (0..buffer.area.width) + .map(|x| buffer.cell((x, y)).unwrap().symbol()) + .collect::() + }) + .collect::>() + .join("\n") +} + +#[test] +fn filter_editor_and_applied_status_fit_every_supported_layout() { + for (width, height) in [(40, 8), (80, 24), (120, 40)] { + let mut app = app(); + app.reduce(Command::OpenFilter); + for character in "alpha".chars() { + app.reduce(Command::FilterInput(character)); + } + let output = text(&buffer(&app, width, height, &Theme::default())); + assert!( + output.contains("FILTER> alpha"), + "{width}x{height}\n{output}" + ); + assert!(output.contains("Enter Apply"), "{output}"); + assert!(output.contains("Esc Cancel"), "{output}"); + assert!(output.contains("alpha"), "{output}"); + app.reduce(Command::ApplyFilter); + assert_eq!(app.overlay, Overlay::None); + let applied = text(&buffer(&app, width, height, &Theme::default())); + assert!(applied.contains("FILTER alpha"), "{applied}"); + assert!(applied.contains("1/3"), "{applied}"); + assert!(!applied.contains("Enter Apply"), "{applied}"); + } +} + +#[test] +fn no_matches_and_hidden_marked_are_textual_in_monochrome_and_icons_off() { + let mut app = app(); + app.reduce(Command::SelectAll); + app.reduce(Command::OpenFilter); + for _ in 0..30 { + app.reduce(Command::FilterInput('ж')); + } + app.reduce(Command::ApplyFilter); + for theme in [ + Theme::no_color(), + Theme::ascii().with_icon_mode(IconMode::None), + ] { + let output = text(&buffer(&app, 40, 8, &theme)); + assert!(output.contains("NO MATCHES"), "{output}"); + assert!(output.contains("0/3"), "{output}"); + assert!(output.contains("Hidden marked 3"), "{output}"); + } +} + +#[test] +fn cancel_restores_workspace_geometry_and_unicode_input_is_sanitized() { + let mut app = app(); + let normal = rcom::ui::layout::frame_layout( + ratatui::layout::Rect::new(0, 0, 40, 8), + app.mode, + app.active, + ); + app.reduce(Command::OpenFilter); + app.reduce(Command::FilterInput('\u{2028}')); + let editing = rcom::ui::layout::frame_layout_with_filter( + ratatui::layout::Rect::new(0, 0, 40, 8), + app.mode, + app.active, + true, + ); + assert_eq!(normal.workspace.height, editing.workspace.height + 2); + let output = text(&buffer(&app, 40, 8, &Theme::default())); + assert!(!output.contains('\u{2028}')); + app.reduce(Command::CloseOverlay); + let restored = rcom::ui::layout::frame_layout_with_filter( + ratatui::layout::Rect::new(0, 0, 40, 8), + app.mode, + app.active, + app.overlay == Overlay::Filter, + ); + assert_eq!(normal.workspace, restored.workspace); +} diff --git a/tests/help_inventory.rs b/tests/help_inventory.rs index 2e05ee3..c04751b 100644 --- a/tests/help_inventory.rs +++ b/tests/help_inventory.rs @@ -10,6 +10,10 @@ use rcom::input::{InputOutcome, InputState}; // This fixture intentionally does not derive data from the renderer or input dispatcher. Adding a // handler or changing its public aliases requires a conscious update of this independent contract. const WORKSPACE: &[(&str, &str)] = &[ + ("filter-open", "/"), + ("filter-next-match", "n"), + ("filter-previous-match", "N"), + ("filter-clear-applied", "Esc"), ("workspace-next-entry", "j / Down"), ("workspace-previous-entry", "k / Up"), ("workspace-parent", "h / Left"), @@ -86,6 +90,14 @@ const TASK_DETAILS: &[(&str, &str)] = &[ ("details-close", "m / Enter / Esc / q / t"), ]; const PREVIEW: &[(&str, &str)] = &[("preview-close", "F3 / Esc / q")]; +const FILTER: &[(&str, &str)] = &[ + ("filter-input", "Printable"), + ("filter-backspace", "Backspace"), + ("filter-clear-draft", "Ctrl-u"), + ("filter-apply", "Enter"), + ("filter-cancel", "Esc"), + ("filter-quit", "F10"), +]; const HELP: &[(&str, &str)] = &[ ("help-previous-category", "h / Left / Shift-Tab"), ("help-next-category", "l / Right / Tab"), @@ -160,6 +172,7 @@ fn independently_enumerated_input_contexts_match_every_inventory_action_and_alia (HelpContext::Tasks, TASKS), (HelpContext::TaskDetails, TASK_DETAILS), (HelpContext::Preview, PREVIEW), + (HelpContext::Filter, FILTER), (HelpContext::Help, HELP), (HelpContext::DestinationPrompt, DESTINATION), (HelpContext::Confirmation, CONFIRMATION), @@ -199,6 +212,7 @@ fn independently_enumerated_input_contexts_match_every_inventory_action_and_alia + TASKS.len() + TASK_DETAILS.len() + PREVIEW.len() + + FILTER.len() + HELP.len() + DESTINATION.len() + CONFIRMATION.len() @@ -229,6 +243,22 @@ fn context_specific_bindings_execute_only_their_documented_handler() { InputState::new().handle_entry_confirmation_key(press(KeyCode::Enter)), InputOutcome::Command(Command::ConfirmEntryAction) ); + assert_eq!( + InputState::new().handle_key(press(KeyCode::Char('/')), 10), + InputOutcome::Command(Command::OpenFilter) + ); + assert_eq!( + InputState::new().handle_key(press(KeyCode::Char('n')), 10), + InputOutcome::Command(Command::MoveMatch(1)) + ); + assert_eq!( + InputState::new().handle_key(shifted('N'), 10), + InputOutcome::Command(Command::MoveMatch(-1)) + ); + assert_eq!( + InputState::new().handle_filter_key(press(KeyCode::Enter)), + InputOutcome::Command(Command::ApplyFilter) + ); for (key, choice, apply_to_all) in [ (press(KeyCode::Char('s')), CollisionChoice::Skip, false), (shifted('S'), CollisionChoice::Skip, true), diff --git a/tests/pty_smoke.rs b/tests/pty_smoke.rs index 0d6a4f8..35c30d1 100644 --- a/tests/pty_smoke.rs +++ b/tests/pty_smoke.rs @@ -113,6 +113,49 @@ fn help_close_reopen_aliases_preserve_terminal_lifecycle() { assert_contains(output.as_bytes(), b"\x1b[?25h"); } +#[test] +fn filter_input_apply_match_clear_and_f10_restore_terminal() { + let fixture = TempDir::new().unwrap(); + for name in ["alpha.txt", "alphabet.txt", "beta.txt"] { + fs::write(fixture.path().join(name), format!("contents-{name}")).unwrap(); + } + let mut session = spawn_app(fixture.path()); + session.get_process_mut().set_window_size(120, 30).unwrap(); + session.expect("contents-alpha.txt").unwrap(); + session.send("/").unwrap(); + session.expect("FILTER>").unwrap(); + session.send("alpha").unwrap(); + session.expect("Enter Apply").unwrap(); + session.send("\r").unwrap(); + std::thread::sleep(std::time::Duration::from_millis(80)); + session.send("n").unwrap(); + session.expect("contents-alphabet.txt").unwrap(); + session.send("\x1b").unwrap(); + std::thread::sleep(std::time::Duration::from_millis(100)); + session.send("\x1b[21~").unwrap(); + let output = session.expect(Eof).unwrap(); + let status = session.get_process_mut().wait().unwrap(); + assert!(matches!(status, WaitStatus::Exited(_, 0))); + assert_contains(output.as_bytes(), b"\x1b[?1049l"); + assert_contains(output.as_bytes(), b"\x1b[?25h"); +} + +#[test] +fn filter_no_matches_cancel_and_quit_restore_workspace() { + let fixture = TempDir::new().unwrap(); + fs::write(fixture.path().join("alpha.txt"), "contents-alpha").unwrap(); + let mut session = spawn_app(fixture.path()); + session.get_process_mut().set_window_size(120, 30).unwrap(); + session.expect("contents-alpha").unwrap(); + session.send("/").unwrap(); + session.expect("FILTER>").unwrap(); + session.send("z").unwrap(); + std::thread::sleep(std::time::Duration::from_millis(100)); + session.send("\x1b").unwrap(); + std::thread::sleep(std::time::Duration::from_millis(100)); + let _ = quit_and_expect_restore(&mut session, 0); +} + #[test] fn image_halfblocks_render_in_pty_without_calling_substitute_tmux() { use std::io::Cursor; diff --git a/tests/selection_clipboard.rs b/tests/selection_clipboard.rs index e591f31..0b3ebe2 100644 --- a/tests/selection_clipboard.rs +++ b/tests/selection_clipboard.rs @@ -203,11 +203,11 @@ fn refresh_retains_existing_ids_across_sorting_hidden_filtering_and_removal() { .contains(&location.entry_id("new")) ); - let hidden = one_listing(app.reduce(Command::ToggleHidden)); - finish_listing( - &mut app, - hidden, - vec![file("z"), file("new"), file(".hidden"), file("a")], + let hidden_effects = app.reduce(Command::ToggleHidden); + assert!( + hidden_effects + .iter() + .all(|effect| matches!(effect, Effect::DebouncePreview(_))) ); assert_eq!( app.active_pane() diff --git a/tests/snapshots/ui_overlays__snapshot_help_120x40.snap b/tests/snapshots/ui_overlays__snapshot_help_120x40.snap index b746648..02697a0 100644 --- a/tests/snapshots/ui_overlays__snapshot_help_120x40.snap +++ b/tests/snapshots/ui_overlays__snapshot_help_120x40.snap @@ -9,6 +9,9 @@ expression: "draw(&app, None, 120, 40)" │▸ 📖 REA╭HELP──────────────────────────────────────────────────────────────────────────────────────────────╮---------│ │ │[Navigation] Selection Files Tasks SSH General │ │ │ │ │ │ +│ │/ Workspace: Filter/search the current directory │ │ +│ │n Workspace: Next filter match with wrap │ │ +│ │N Workspace: Previous filter match with wrap │ │ │ │j / Down Workspace: Next entry │ │ │ │k / Up Workspace: Previous entry │ │ │ │h / Left Workspace: Parent directory │ │ @@ -33,10 +36,7 @@ expression: "draw(&app, None, 120, 40)" │ │ │ │ │ │ │ │ │ │ │ │ -│ │ │ │ -│ │ │ │ -│ │ │ │ -│ │1-11/11 | h/l/Tab Category | j/k/PgUp/PgDn Scroll | Esc/q/?/F1 Close │ │ +│ │1-14/14 | h/l/Tab Category | j/k/PgUp/PgDn Scroll | Esc/q/?/F1 Close │ │ │ ╰──────────────────────────────────────────────────────────────────────────────────────────────────╯ │ │ ││ │ │ ││ │ diff --git a/tests/ui_accessibility.rs b/tests/ui_accessibility.rs index 6039d1b..b261ae3 100644 --- a/tests/ui_accessibility.rs +++ b/tests/ui_accessibility.rs @@ -93,7 +93,7 @@ fn intermediate_help_footer_uses_measured_compact_controls_without_truncation() let mut app = sample_app(); app.reduce(Command::ToggleHelp); let model = help_view_model(Rect::new(0, 0, 62, 24), &app.help); - for expected in ["1-11/11", "h/l", "j/k/Pg", "Esc/q/?/F1"] { + for expected in ["1-16/16", "h/l", "j/k/Pg", "Esc/q/?/F1"] { assert!( model.footer_text.contains(expected), "{}", diff --git a/tests/workspace_panes.rs b/tests/workspace_panes.rs index 9fab55f..9311c84 100644 --- a/tests/workspace_panes.rs +++ b/tests/workspace_panes.rs @@ -195,8 +195,12 @@ async fn hidden_mode_is_independent_and_survives_navigation() { finish_from_memory(&fs, &mut app, initial).await; app.reduce(Command::TogglePaneMode); - let show_hidden = one_listing(app.reduce(Command::ToggleHidden)); - finish_from_memory(&fs, &mut app, show_hidden).await; + let show_hidden = app.reduce(Command::ToggleHidden); + assert!( + show_hidden + .iter() + .all(|effect| matches!(effect, Effect::DebouncePreview(_))) + ); assert!(app.pane(PaneId::Left).show_hidden); assert!(!app.pane(PaneId::Right).show_hidden); assert_eq!(names(&app, PaneId::Left), ["child", ".secret", "visible"]);