diff --git a/meshterm/ui/chat.py b/meshterm/ui/chat.py index ca33e2b..9c0bcf4 100644 --- a/meshterm/ui/chat.py +++ b/meshterm/ui/chat.py @@ -98,11 +98,28 @@ class ChatScreen(Screen): channel message is never acknowledged, so there is no such thing to retry there — and merely dim in a direct chat with nothing outstanding. *Paths* needs a picked message to have paths of, and both nav slots need a transcript to walk. + + F1/F2 carry the **day** jump, the transcript's own section step (its dividers are + days) — the same claim a grouped select list makes with ``Sect ↑``/``Sect ↓``, on + the same keys, dispatching the same ``ctrl_pageup``/``ctrl_pagedown``. Naming it + for what the sections *are* here is the lane's rule that a chip names an action. + A left-hand pair rises toward F1, so ``Day ↑`` (back through the transcript) sits + outside ``Day ↓``, matching both the pager on the right and the list it echoes. + Lit only with more than one day to step between: a conversation held in an + afternoon has sections the way a one-section list does — none. """ from .tui.fkeys import FPair, default_lane lane = list(default_lane(nav=bool(self._messages))) live = bool(self._messages) + # Messages are chronological, so two days exist exactly when the ends disagree — + # O(1), where walking the dividers would re-date the whole transcript every paint. + days = live and ( + self._messages[0].created_at.astimezone().date() + != self._messages[-1].created_at.astimezone().date() + ) + lane[0] = FPair("Day ↑", "ctrl_pageup", enabled=days) + lane[1] = FPair("Day ↓", "ctrl_pagedown", enabled=days) lane[3] = FPair("Page ↓", "pagedown", "Latest", "ctrl_end", enabled=live, opp_enabled=live) lane[4] = FPair("Page ↑", "pageup", "Oldest", "ctrl_home", enabled=live, opp_enabled=live) retry = ("Retry", "retry") if not self._is_channel else ("", "") diff --git a/meshterm/ui/map_screen.py b/meshterm/ui/map_screen.py index d2e5577..c10d7e7 100644 --- a/meshterm/ui/map_screen.py +++ b/meshterm/ui/map_screen.py @@ -17,9 +17,10 @@ render_map`. Keys: * ``^U`` (for *you*) recenters on **your own node**, keeping the zoom you chose and clearing any find (the lane's ``You`` chip; its Shift half also zooms in close), * **typing finds nodes**: every letter key feeds a live name filter — matching nodes keep - bright labels while the rest dim to context, ``Enter`` frames the matches, ``Backspace`` - edits, and ``Esc`` clears the filter (a second ``Esc`` leaves the map). This is why no - plain letters are bound to actions here, + bright labels while the rest dim to context, ``Backspace`` edits, ``^Enter`` frames the + matches (keeping the query), and ``Enter`` or ``Esc`` drops the query where it is + without moving the view (a second ``Esc`` leaves the map). This is why no plain letters + are bound to actions here, * ``Esc`` leaves the map. With no network (and no cached tiles) the basemap is simply absent and nodes are plotted on a @@ -86,8 +87,8 @@ _TILE_CACHE_SCREENS = 2 #: history for a pan away and back to be instant. _MIN_TILE_CACHE = 8 -#: The zoom an Enter-to-frame homes in at when the matches set no extent of their own — a -#: single node (or several at one spot) has nothing to frame, so Enter zooms to this +#: The zoom a frame homes in at when the matches set no extent of their own — a +#: single node (or several at one spot) has nothing to frame, so ^Enter zooms to this #: street-level closeness rather than the fit's neutral default. Capped at the tile #: source's max so it never over-zooms onto blank tiles. _FIND_ZOOM = 16 @@ -124,8 +125,8 @@ class MapScreen(Screen): sits **You +**: the same jump home, but zoomed in close — the ``+`` borrowed from the zoom rocker's vocabulary, so the pair reads as "you / you, closer". Behind Frame sits **Clear**: the find axis's other end, dropping the query the way Frame - commits it — lit exactly while there is a query to drop, which Esc also does but - no chip could otherwise teach. + commits it — lit exactly while there is a query to drop. Enter and Esc both do + that on a keyboard; the chip is how the pair teaches it where there is no hint line. The zoom pair keeps the lane's handedness (see :data:`~meshterm.ui.tui.fkeys.DEFAULT_LANE`): out on the left, in on the right, so @@ -232,7 +233,7 @@ class MapScreen(Screen): finally brought the line inside the budget. """ if self._filter: - return f"find: {self._filter}▏ · Enter frame · ⌫ erase · Esc clear" + return f"find: {self._filter}▏ · ^Enter frame · ⌫ erase · Enter/Esc clear" return "↑↓←→ pan · PgUp/PgDn zoom · Home/^U region/you · type to find · Esc back" def consume_edge_scrub(self) -> int: @@ -521,10 +522,17 @@ class MapScreen(Screen): Three actions reframe the view, and each has both a key and an F-key chip: ``home`` the whole region, ``locate`` (^U, for *you*) our own node — ``locate_zoom`` - the Shift-bank variant that also homes in — and ``frame`` the find matches, - which is what Enter already does while a query is being typed, kept as a - separate action so the lane can name it on a platform that draws no hint line. - ``clear_find`` drops the query without leaving (Esc's first peel, as a chip). + the Shift-bank variant that also homes in — and ``frame`` (^Enter) the find + matches. ``clear_find`` drops the query without moving the view, which is also + what plain **Enter** does. + + Enter and ^Enter are the find's two ways out, and they split along whether the + *view* moves (JP, 2026-08-09). Typing a query dims everything that doesn't match, + and the common finish is "yes, that one — now let me look around it": the query + has done its job and only the dimming is in the way, so Enter drops the query and + leaves the view exactly where the reader put it. ^Enter is the other finish — + *take* me to them — and it keeps the query, because a frame is a place to arrive + and framing tighter from there is one more press, not a re-type. """ vp = self._viewport if action == "escape": @@ -563,9 +571,9 @@ class MapScreen(Screen): self._locate(vp) elif action == "locate_zoom": self._locate(vp, zoom_in=True) - elif action == "clear_find": + elif action in ("clear_find", "enter"): self._filter = "" - elif action == "frame" and self._filter: + elif action in ("frame", "ctrl_enter") and self._filter: self._frame_matches(vp) elif action == "text" and self.find_enabled: if not data.isspace() or self._filter: # never begin the filter with a space @@ -574,8 +582,6 @@ class MapScreen(Screen): self._filter += " " # node names carry spaces; only meaningful mid-query elif action == "backspace": self._filter = self._filter[:-1] - elif action == "enter" and self._filter: - self._frame_matches(vp) # Any handled key may have redrawn the body, so clean the right edge next paint. self._needs_scrub = True self._persist() @@ -616,7 +622,7 @@ class MapScreen(Screen): ) def _frame_matches(self, vp: Viewport) -> None: - """Refit the view around the find filter's matches (Enter on an active find). + """Refit the view around the find filter's matches (^Enter on an active find). All matches are framed (``fraction=1.0`` — the user asked for exactly these nodes, so no dense-core trimming). A single match — or several at one spot — has diff --git a/meshterm/ui/tui/session.py b/meshterm/ui/tui/session.py index a2b2991..f3841b9 100644 --- a/meshterm/ui/tui/session.py +++ b/meshterm/ui/tui/session.py @@ -92,6 +92,14 @@ _KEY_ACTIONS: dict[Any, str] = { Keys.ControlUp: "ctrl_up", Keys.ControlDown: "ctrl_down", Keys.Enter: "enter", + # Ctrl+Enter, as far as a terminal can spell it. There is no such keycode: Enter *is* + # ^M, so a console that doesn't do modifyOtherKeys has nothing left to modify and + # sends plain CR. What most do send is LF — prompt_toolkit's ``ControlJ`` — which is + # otherwise unbound here (an unprintable char, dropped by ``_typed``), so claiming it + # costs nothing and wins on the terminals that offer it. The right-Ctrl rescue below + # covers the rest through _CTRL_CHORDS, and on a console that spells neither, the + # F-lane chip is the affordance (which is the platform where that is already true). + Keys.ControlJ: "ctrl_enter", Keys.Escape: "escape", Keys.Backspace: "backspace", Keys.Delete: "delete", @@ -111,8 +119,10 @@ _KEY_ACTIONS: dict[Any, str] = { }, } -#: The plain navigation actions that have a Ctrl-chord sibling, for the right-Ctrl rescue -#: in :meth:`TuiSession._dispatch` (see :func:`_right_ctrl_down`). +#: The plain actions that have a Ctrl-chord sibling, for the right-Ctrl rescue in +#: :meth:`TuiSession._dispatch` (see :func:`_right_ctrl_down`). Navigation keys, plus +#: ``enter`` — the one key a terminal cannot reliably spell chorded (see ``Keys.ControlJ`` +#: above), so the rescue is not a fallback there but the surer of the two paths. _CTRL_CHORDS: dict[str, str] = { "up": "ctrl_up", "down": "ctrl_down", @@ -122,6 +132,7 @@ _CTRL_CHORDS: dict[str, str] = { "end": "ctrl_end", "pageup": "ctrl_pageup", "pagedown": "ctrl_pagedown", + "enter": "ctrl_enter", } diff --git a/meshterm/ui/walk_screen.py b/meshterm/ui/walk_screen.py index ea94b23..bf153c9 100644 --- a/meshterm/ui/walk_screen.py +++ b/meshterm/ui/walk_screen.py @@ -38,13 +38,15 @@ across the top grows (a :mod:`~meshterm.ui.pathline` path line — powerline chi terminal draws them, ``you › YUL-Cartierville › …`` where it doesn't, each name in its node's own hue), and **⌫ steps back** along it. Walking to a node already on the trail truncates the stack to its first appearance — the loop you walked to get back there is -dropped rather than recorded — and when the trail outgrows the line it neither wraps nor -scrolls: its *head* goes behind a leading ``⋯`` and the rest snaps flush right, so the -focus and the steps just taken stay in view. **Home** refocuses our own node. **Typing finds** — a -global filter over every node in -the graph, islands included; Enter teleports the focus to the highlighted match (the -trail restarts there, since the walk didn't cross the gap). Esc peels find first, the -screen second. +dropped rather than recorded. The trail never wraps: at rest its *head* goes behind a +leading ``⋯`` and the rest snaps flush right, so the focus and the steps just taken stay +in view, and **←→ scroll it** a hop at a time to read back over a long walk (a trailing +``⋯`` then marks the focus as the part out of view). **^U** refocuses our own node. +**Typing finds** — a global filter over every node in the graph, islands included — and +narrows the canvas's fan to matching neighbours as it goes, the focus and the came-from +node holding through it; Enter teleports the focus to the highlighted match (the trail +restarts there, since the walk didn't cross the gap). Esc peels find first, the screen +second. """ from __future__ import annotations @@ -133,6 +135,13 @@ _FAN_SLOT_DOTS = 12 #: never collide with a canonical id (those are hex). _MORE = "\x00more" +#: The breadcrumb trail's own hop joiner (``›``, not the app-wide ``→``) and the mark it +#: shows on whichever side holds walk that is out of view (see :meth:`WalkScreen._trail_text`). +#: The mark is the one :mod:`~meshterm.ui.pathline` elides with, so a head the widget hid +#: and a tail the scroll hid read as the same thing. +_TRAIL_SEP = " › " +_ELISION = "⋯" + #: How many find matches the list shows at most (the filter narrows it fast). _MAX_MATCHES = 10 @@ -258,8 +267,17 @@ class WalkScreen(Screen): self._self_label = self_label self._prefix_bytes = prefix_bytes #: The walked trail of canonical ids; the focus is its last entry. Walking - #: appends, ⌫ pops, Home resets to us, a find teleport restarts it. + #: appends, ⌫ pops, ^U resets to us, a find teleport restarts it. self._trail: list[str] = [topo.self_id] + #: Hops the breadcrumb line is scrolled off its *tail* end (see + #: :meth:`_trail_text`). 0 is the resting state — the focus flush right — and + #: every change to the trail returns it there. + self._trail_scroll = 0 + #: ``((width, trail) → the furthest that can scroll)``, settled at render (see + #: :meth:`_trail_max_scroll`) so a keypress can clamp itself without a width. + self._trail_fit: Optional[tuple[tuple, int]] = None + #: The width the trail last rendered at, for that same clamp. + self._trail_width = 0 #: Index of the highlighted row in the current list (neighbours or matches). self._index = 0 #: The live find-as-you-type filter ("" = off; matches every node known). @@ -342,16 +360,25 @@ class WalkScreen(Screen): self._hops_out_memo = depths return depths - def _matches(self) -> list[str]: - """Nodes the find filter matches: nearest first, then by display name.""" + def _is_match(self, node: str) -> bool: + """Whether the live find query matches this node (by display name or by id). + + The one predicate behind both things the query narrows: the list of teleport + candidates (:meth:`_matches`, over the whole graph) and the canvas's fan + (:meth:`_canvas_lines`, over the focus's own neighbours). No filter matches + everything, so a caller need not check for one first. + """ needle = self._filter.strip().casefold() if not needle: + return True + return needle in self._label(node).casefold() or needle in node.casefold() + + def _matches(self) -> list[str]: + """Nodes the find filter matches: nearest first, then by display name.""" + if not self._filter.strip(): return [] depths = self._hops_out() - candidates = [ - node for node in self._all_nodes() - if needle in self._label(node).casefold() or needle in node.casefold() - ] + candidates = [node for node in self._all_nodes() if self._is_match(node)] candidates.sort(key=lambda n: (depths.get(n, 999), self._label(n).casefold())) return candidates[:_MAX_MATCHES] @@ -365,10 +392,27 @@ class WalkScreen(Screen): @property def footer_hint(self) -> str: # type: ignore[override] - """Walking keys — or the live find query while one is being typed.""" + """Walking keys — or the live find query while one is being typed. + + Every atom fits the 72-cell budget only because two of them take turns. ``←→ + trail`` appears exactly while the breadcrumb has more walk than width (an inert + key is never advertised — the hint line's own long-standing rule, and the F-lane's + after it), and it takes the place of ``type to find``: a walk deep enough to + overflow the trail is one where the scroll is the unknown key, while typing + announces itself the instant a letter lands, replacing this whole line with the + query. The find is self-teaching; the scroll had no way to be. + """ if self._filter: return f"find: {self._filter}▏ · ↑↓ move · Enter focus · ⌫ erase · Esc clear" - return "↑↓ move · Enter focus · ⌫ back · ^U you · type to find · Esc back" + scrolls = self._trail_width > 0 and bool(self._trail_max_scroll(self._trail_width)) + atoms = ["↑↓ move"] + if scrolls: + atoms.append("←→ trail") + atoms += ["Enter focus", "⌫ back", "^U you"] + if not scrolls: + atoms.append("type to find") + atoms.append("Esc back") + return " · ".join(atoms) def handle(self, action: str, data: str = "") -> None: """Move the highlight, walk, back up, find, or dismiss. @@ -404,16 +448,28 @@ class WalkScreen(Screen): elif len(self._trail) > 1: self._trail.pop() self._index = 0 + self._trail_scroll = 0 elif action in ("home", "ctrl_home") and rows: self._index = 0 elif action in ("end", "ctrl_end") and rows: self._index = len(rows) - 1 + elif action == "left": + # The breadcrumb scrolls, the list doesn't — it is the one line here with more + # content than width. Clamped against the width the last paint settled, so + # holding ← parks at the head instead of banking presses to undo (0 until the + # trail actually overflows, which makes the key inert on a short walk). + self._trail_scroll = min( + self._trail_scroll + 1, self._trail_max_scroll(self._trail_width) + ) + elif action == "right": + self._trail_scroll = max(0, self._trail_scroll - 1) elif action == "locate": # ^U (and F3): abandon the walk rather than move within it — the trail goes # back to just us and any find narrowing the list is dropped with it. self._trail = [self._topo.self_id] self._filter = "" self._index = 0 + self._trail_scroll = 0 elif action == "text": if not data.isspace() or self._filter: # never begin the filter with a space self._filter += data @@ -442,6 +498,7 @@ class WalkScreen(Screen): else: self._trail.append(target) self._index = 0 + self._trail_scroll = 0 # the new focus is the news; put it back in view # --- smear scrub (same fallback-glyph problem as the map) --------------------- @@ -536,7 +593,7 @@ class WalkScreen(Screen): ] def _trail_text(self, width: int) -> Text: - """The breadcrumb trail as a path line: one line, tail-anchored, never wrapped. + """The breadcrumb trail as a path line: one line, ← → scrollable, never wrapped. The walk *is* a path — us, then every node stepped through, ending on the focus — so it renders through :class:`~meshterm.ui.pathline.PathLine` like every other hop @@ -546,23 +603,63 @@ class WalkScreen(Screen): reserved for keyed identities), so the trail and the rows below it agree on who is who. - The line neither wraps nor scrolls. When the walk outgrows the width the fit eats - into its *head* (:data:`~meshterm.ui.pathline.ELIDE_HEAD`) rather than a route's - usual tail: the oldest steps disappear behind a leading ``⋯`` and what survives - snaps flush against the **right** edge, so the focus and the steps that just led - to it are the ones always in view. A long walk therefore reads as a line that - grows rightward until it meets the margin and then starts shedding its oldest - steps, rather than one that pushes the focus off the end. + The line never wraps. At rest, a walk that outgrows the width eats into its + *head* (:data:`~meshterm.ui.pathline.ELIDE_HEAD`) rather than a route's usual + tail: the oldest steps go behind a leading ``⋯`` and what survives snaps flush + against the **right** edge, so the focus and the steps that just led to it are + what a glance lands on. + + ← and → then **scroll it** (JP, 2026-08-09), a hop at a time, off the tail end: + the elided head is a real part of the walk and a long one had no way to be read + at all. A scrolled line grows its own trailing ``⋯`` — the focus is now the part + out of view — so the mark on each side always means the same thing, more walk + that way. Scrolling stops where the head comes into view rather than running the + line off the edge, and any change to the trail itself resets it: a walk, a step + back, a teleport and ^U all end with the focus in view, which is where the next + move is read from. """ - line = PathLine([self._trail_hop(node) for node in self._trail], separator=" › ") - full = line.text() - if full.cell_len <= width: - return full - fitted = line.ellipsized(width, elide=ELIDE_HEAD) + hops = [self._trail_hop(node) for node in self._trail] + self._trail_width = width + limit = self._trail_max_scroll(width) + self._trail_scroll = max(0, min(self._trail_scroll, limit)) + if not limit and not self._trail_scroll: + full = PathLine(hops, separator=_TRAIL_SEP).text() + if full.cell_len <= width: + return full + kept = hops[: len(hops) - self._trail_scroll] + if self._trail_scroll: + kept.append(PathHop(_ELISION, dim=True)) # the focus is off to the right + fitted = PathLine(kept, separator=_TRAIL_SEP).ellipsized(width, elide=ELIDE_HEAD) snapped = Text(" " * max(0, width - fitted.cell_len)) # snap the tail to the edge snapped.append_text(fitted) return snapped + def _trail_max_scroll(self, width: int) -> int: + """How far ← may scroll the trail: the step that first brings its head into view. + + Scrolling past that only shortens a line that already shows every hop it has, so + the walk stops there — the same claim the F-lane makes when it dims a key that + would do nothing. ``0`` for a trail that fits, which is what makes ← inert on a + short walk without the handler needing to know the width. + + Memoized on ``(width, trail)``: it costs a rendering per candidate step and the + answer only moves when the walk or the terminal does. + """ + key = (width, tuple(self._trail)) + if self._trail_fit is not None and self._trail_fit[0] == key: + return self._trail_fit[1] + hops = [self._trail_hop(node) for node in self._trail] + limit = 0 + if PathLine(hops, separator=_TRAIL_SEP).text().cell_len > width: + mark = PathHop(_ELISION, dim=True) + for dropped in range(1, len(hops)): + limit = dropped + head = PathLine(hops[: len(hops) - dropped] + [mark], separator=_TRAIL_SEP) + if head.text().cell_len <= width: + break + self._trail_fit = (key, limit) + return limit + def _trail_hop(self, node: str) -> PathHop: """One walked step as a path hop: its display name in its own identity colour.""" style = self._list_name_style(node) @@ -643,6 +740,11 @@ class WalkScreen(Screen): is shown by its *label* going white and by the lit route, so the icons stay colourful throughout. + While a find query is being typed the fan is narrowed to the neighbours it matches + — the east is *the ways onward*, which is what the query is asking about — and the + focus and the came-from node stay put through it: those two are the walk so far, + not candidates, so the picture keeps its bearings while the choices thin out. + Only as many neighbours as the area can carry get their own marker (see :meth:`_fan_capacity`); the weaker rest collapse into one ``…`` marker at the fan's foot. Highlighting a collapsed row from the list lights that marker white and swaps @@ -660,7 +762,11 @@ class WalkScreen(Screen): pairs = self._links_of(self._focus) by_other = dict(pairs) back = self._came_from if self._came_from in by_other else None - fan = [other for other, _link in pairs if other != back] + # A find narrows the fan too (JP, 2026-08-09) — the *east* of the picture, which is + # the part the query is about: which of the ways onward from here am I looking for? + # The focus and the node we came from are the walk itself, not candidates, so they + # hold whatever is typed; the graph keeps its shape while the query thins the choices. + fan = [other for other, _link in pairs if other != back and self._is_match(other)] capacity = self._fan_capacity(canvas_h) if len(fan) > capacity + 1: # collapsing exactly one node would save nothing shown, hidden = fan[:capacity], fan[capacity:] diff --git a/tests/test_chat.py b/tests/test_chat.py index 784ce83..ca5d4c6 100644 --- a/tests/test_chat.py +++ b/tests/test_chat.py @@ -1853,3 +1853,36 @@ async def test_channel_slot_change_drops_the_cached_channel_list(repo: Repositor assert await chat.channel_id_for(0) == "slot:0" assert ctx.devstate.invalidations == 2 await device.disconnect() + + +def test_chat_fkey_lane_steps_by_day_on_the_free_left_pair() -> None: + """The transcript's sections are days, so F1/F2 name the section step ``Day``. + + Same keys and same actions as a grouped select list's ``Sect ↑``/``Sect ↓`` — the lane + names what the sections *are* here — and lit only with more than one day to step + between, the way a one-section list has no section jump. + """ + from datetime import timedelta + + from meshterm.core.models import utcnow + + now = utcnow() + one_day = [ChatMessage(text="hi", peer="d4e5f6a7", created_at=now)] + single = _screen(_StubSession(), send=None, messages=one_day) + assert [pair.label for pair in single.fkey_lane[:2]] == ["Day ↑", "Day ↓"] + assert [pair.action for pair in single.fkey_lane[:2]] == ["ctrl_pageup", "ctrl_pagedown"] + assert not any(pair.enabled for pair in single.fkey_lane[:2]) # one day: nowhere to step + + spread = _screen( + _StubSession(), send=None, + messages=[ + ChatMessage(text="then", peer="d4e5f6a7", created_at=now - timedelta(days=2)), + ChatMessage(text="now", peer="d4e5f6a7", created_at=now), + ], + ) + assert all(pair.enabled for pair in spread.fkey_lane[:2]) + # A left-hand pair rises toward F1, so stepping *back* through the transcript is the + # outer key — the same handedness as the pager's on the right. + assert fkeys.action_for(spread.fkey_lane, 1) == "ctrl_pageup" + spread.handle(fkeys.action_for(spread.fkey_lane, 1)) + assert spread._selected == 0 # jumped to the first message of the older day diff --git a/tests/test_map.py b/tests/test_map.py index d877cf7..321188c 100644 --- a/tests/test_map.py +++ b/tests/test_map.py @@ -1397,7 +1397,7 @@ def test_map_frame_chip_lights_only_with_matches_to_frame() -> None: def test_map_screen_find_filters_frames_and_clears() -> None: - """Typing builds the find query; Enter frames matches; Esc peels filter then map.""" + """Typing builds the query; ^Enter frames matches; Enter/Esc drop it; Esc then leaves.""" import asyncio from meshterm.ui.map_render import MapMarker @@ -1424,12 +1424,22 @@ def test_map_screen_find_filters_frames_and_clears() -> None: assert "YUL-Cartierville" in body assert "Alice" not in body and "Yagi-North" not in body - # Enter frames the matches: the view centres on YUL. - screen.handle("enter") + # ^Enter frames the matches: the view centres on YUL, and the query survives it. + screen.handle("ctrl_enter") assert screen._viewport.center_lat == pytest.approx(45.53, abs=0.05) assert screen._viewport.center_lon == pytest.approx(-73.71, abs=0.05) + assert screen._filter == "yu" + + # Plain Enter is the other way out: the query goes, the view stays exactly where the + # frame left it. + centre = (screen._viewport.center_lat, screen._viewport.center_lon) + screen.handle("enter") + assert screen._filter == "" + assert (screen._viewport.center_lat, screen._viewport.center_lon) == centre # Backspace edits; Esc clears the filter first and only then dismisses. + for ch in "yu": + screen.handle("text", ch) screen.handle("backspace") assert screen._filter == "y" @@ -1443,8 +1453,8 @@ def test_map_screen_find_filters_frames_and_clears() -> None: assert asyncio.run(drive()) is None -def test_map_screen_enter_zooms_in_on_a_single_match() -> None: - """Enter on a lone filtered node homes in close on it, not the fit's neutral default.""" +def test_map_screen_frame_zooms_in_on_a_single_match() -> None: + """^Enter on a lone filtered node homes in close on it, not the fit's neutral default.""" from meshterm.ui.map_render import MapMarker from meshterm.ui.map_screen import _FIND_ZOOM, MapScreen @@ -1457,7 +1467,7 @@ def test_map_screen_enter_zooms_in_on_a_single_match() -> None: for ch in "yul": screen.handle("text", ch) assert [m.label for m in screen._matches()] == ["YUL-Cartierville"] - screen.handle("enter") + screen.handle("ctrl_enter") assert screen._viewport.center_lat == pytest.approx(45.53, abs=0.01) assert screen._viewport.center_lon == pytest.approx(-73.71, abs=0.01) assert screen._viewport.zoom == _FIND_ZOOM # zoomed in, not the fit's default 14 diff --git a/tests/test_tui.py b/tests/test_tui.py index 2910c88..366d069 100644 --- a/tests/test_tui.py +++ b/tests/test_tui.py @@ -1920,10 +1920,12 @@ def test_dispatch_promotes_nav_actions_while_right_ctrl_is_held(monkeypatch) -> monkeypatch.setattr(session_mod, "_right_ctrl_down", lambda: True) session._dispatch("left") session._dispatch("home") - session._dispatch("enter") # no ctrl sibling: untouched even while held + # Enter has a sibling too — it is the one key a terminal can't spell chorded itself. + session._dispatch("enter") + session._dispatch("escape") # no ctrl sibling: untouched even while held monkeypatch.setattr(session_mod, "_right_ctrl_down", lambda: False) session._dispatch("left") - assert seen == ["ctrl_left", "ctrl_home", "enter", "left"] + assert seen == ["ctrl_left", "ctrl_home", "ctrl_enter", "escape", "left"] def test_dispatch_promotes_letter_chords_while_right_ctrl_is_held(monkeypatch) -> None: diff --git a/tests/test_walk.py b/tests/test_walk.py index 254eae4..b9f1eed 100644 --- a/tests/test_walk.py +++ b/tests/test_walk.py @@ -11,6 +11,7 @@ from datetime import timedelta from meshterm.core.models import Contact, utcnow from meshterm.services.topology import MeshTopology +from meshterm.ui.tui.render import render_to_ansi from meshterm.ui.walk_screen import WalkScreen US = "aa" * 6 @@ -573,3 +574,131 @@ def test_walk_esc_peels_find_then_dismisses() -> None: return await screen.future assert asyncio.run(drive()) is None + + +def _chain(length: int) -> MeshTopology: + """us — hop-01 — hop-02 — … , every name long enough to overflow a narrow trail.""" + contacts = [ + Contact(name=f"Repeater-{i:02d}", public_key=f"{i:02x}" * 32) for i in range(1, length + 1) + ] + topo = MeshTopology(US, contacts=contacts) + when = utcnow() + previous = topo.self_id + for contact in contacts: + node = topo.canonical(contact.public_key) + topo.add_walk([previous, node], snrs=[4.0], when=when, source="trace") + previous = node + return topo + + +def _walked_chain(length: int, *, width: int = 46): + """A screen walked to the end of a `length`-hop chain, rendered at `width`.""" + topo = _chain(length) + contacts = {topo.canonical(f"{i:02x}" * 32): Contact( + name=f"Repeater-{i:02d}", public_key=f"{i:02x}" * 32 + ) for i in range(1, length + 1)} + screen = WalkScreen( + session=_FakeSession(), topo=topo, contacts=contacts, self_label="Homestead" + ) + screen.note_viewport(24) + for _ in range(length): + screen.render_body(width) + rows = screen._rows() + # Always step *onward*, never back through the node we came from. + screen._index = next( + i for i, node in enumerate(rows) if node not in screen._trail + ) + screen.handle("enter") + screen.render_body(width) + return screen, width + + +def test_walk_trail_scrolls_a_hop_at_a_time_off_its_tail() -> None: + """← reads back over a long walk; → returns; the focus is what the marks are about.""" + screen, width = _walked_chain(8) + trail = _plain([render_to_ansi(screen._trail_text(width), width, no_wrap=True)]) + + # At rest the walk is flush right: the focus shows, the head is behind a leading ⋯. + assert "Repeater-08" in trail and "Homestead" not in trail + assert trail.lstrip().startswith("⋯") + assert screen._trail_scroll == 0 + + screen.handle("left") + scrolled = _plain([render_to_ansi(screen._trail_text(width), width, no_wrap=True)]) + assert screen._trail_scroll == 1 + # One hop of walk moved out of view on the right, and says so with the same mark. + assert "Repeater-08" not in scrolled and "Repeater-07" in scrolled + assert scrolled.rstrip().endswith("⋯") + + screen.handle("right") + assert screen._trail_scroll == 0 + assert _plain([render_to_ansi(screen._trail_text(width), width, no_wrap=True)]) == trail + + +def test_walk_trail_scroll_stops_at_the_head_and_resets_with_the_trail() -> None: + """← parks where the walk's start comes into view; any change to the trail rewinds it.""" + screen, width = _walked_chain(8) + limit = screen._trail_max_scroll(width) + assert limit > 0 + + for _ in range(limit + 5): # holding ← banks nothing to undo + screen.handle("left") + assert screen._trail_scroll == limit + head = _plain([render_to_ansi(screen._trail_text(width), width, no_wrap=True)]) + assert "Homestead" in head # scrolled far enough to read where the walk set out from + + screen.handle("backspace") # stepping back is a change to the trail + assert screen._trail_scroll == 0 + screen.render_body(width) + screen.handle("left") + screen.handle("locate") # and so is going home + assert screen._trail_scroll == 0 + + +def test_walk_trail_scroll_is_inert_on_a_walk_that_fits() -> None: + """A trail with nothing hidden has nothing to scroll — and the hint doesn't offer it.""" + screen = _screen(_topo()) + screen.render_body(80) + assert screen._trail_max_scroll(80) == 0 + assert "←→ trail" not in screen.footer_hint + assert "type to find" in screen.footer_hint + + screen.handle("left") + assert screen._trail_scroll == 0 + + walked, width = _walked_chain(8) + assert "←→ trail" in walked.footer_hint # advertised exactly where it does something + assert len(walked.footer_hint) <= 72 + + +def test_walk_find_narrows_the_canvas_fan_but_not_the_walk() -> None: + """Typing thins the ways onward; the focus and the node walked from hold their place.""" + bob = Contact(name="Bob-Tower", public_key="c7" * 32) + topo = MeshTopology(US, contacts=[YUL, ALICE, bob]) + yul, alice = topo.canonical(YUL.public_key), topo.canonical(ALICE.public_key) + bob_id = topo.canonical(bob.public_key) + when = utcnow() + topo.add_walk([topo.self_id, yul], snrs=[6.0], when=when, source="trace") + topo.add_walk([yul, alice], snrs=[-2.0], when=when, source="packet") + topo.add_walk([yul, bob_id], snrs=[1.0], when=when, source="packet") + + screen = WalkScreen( + session=_FakeSession(), topo=topo, + contacts={yul: YUL, alice: ALICE, bob_id: bob}, + self_label="Homestead", + ) + screen.note_viewport(24) + screen.render_body(80) + screen._index = screen._rows().index(yul) + screen.handle("enter") # focus YUL, came from us + + canvas = _plain(screen._canvas_lines(80, 12, None)) + assert "Alice" in canvas and "Bob-Tower" in canvas # the whole fan, unfiltered + + for ch in "ali": + screen.handle("text", ch) + canvas = _plain(screen._canvas_lines(80, 12, None)) + assert "Alice" in canvas # the way onward the query is about + assert "Bob-Tower" not in canvas # and the one it isn't + # The walk itself is not a candidate: both ends of it hold through any query. + assert "YUL-Cartierville" in canvas and "Homestead" in canvas