From 36e8173b5a5d2c03baf9f2450911080c36620a04 Mon Sep 17 00:00:00 2001 From: Jean-Pierre Martineau Date: Sat, 11 Jul 2026 15:17:33 -0400 Subject: [PATCH] Map: arrows-only movement, find-as-you-type node filter MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Panning is the arrow keys (Shift for fine), zoom is PgUp/PgDn alone, and reset moves to Home — freeing every letter and +/- so typing can drive a live name filter instead: matches keep bright white labels and always win the label contest, everything else dims to bare context glyphs, Enter frames the matches, Backspace edits, and Esc peels the filter before the map. The footer swaps to the query while a find is active, the title counts matches, and the location picker follows the same movement keys with find disabled (typing there has no job). Hints fit 72 columns. Co-Authored-By: Claude Fable 5 --- meshterm/ui/map_render.py | 53 ++++++++++--- meshterm/ui/map_screen.py | 148 ++++++++++++++++++++++++------------ tests/test_config_editor.py | 15 ++-- tests/test_map.py | 74 ++++++++++++++---- 4 files changed, 212 insertions(+), 78 deletions(-) diff --git a/meshterm/ui/map_render.py b/meshterm/ui/map_render.py index cee3dca..99a1615 100644 --- a/meshterm/ui/map_render.py +++ b/meshterm/ui/map_render.py @@ -137,6 +137,7 @@ def render_map( markers: list[MapMarker], *, max_labels: int = 80, + find: str = "", ) -> list[str]: """Render a full map frame to truecolour ANSI lines. @@ -145,6 +146,9 @@ def render_map( tiles: Decoded layers keyed by ``(z, x, y)``; ``None`` values are pending/absent. markers: Mesh nodes to overlay. max_labels: Cap on basemap labels placed, to keep the map readable. + find: A live node-name filter: markers whose label contains it + (case-insensitively) draw with bright white labels while the rest dim to + unlabelled context. Empty draws every node normally. Returns: One ANSI string per row, ready for the TUI frame or the console. @@ -157,7 +161,7 @@ def render_map( _draw_tile(frame, layers, z, x, y) # Nodes reserve their cells first so basemap labels route around them. - _draw_nodes(canvas, viewport, markers) + _draw_nodes(canvas, viewport, markers, find=find) # Then place basemap labels by importance, honouring the zoom gate and collisions. placed = 0 @@ -336,7 +340,21 @@ def _pile_color(color: RGB, count: int, *, cap: int = _PILE_FULL) -> RGB: ) -def _draw_nodes(canvas: MapCanvas, viewport: Viewport, markers: list[MapMarker]) -> None: +#: How far a node outside an active find filter dims (glyph colour multiplier). +_FIND_DIM = 0.35 + +#: Label colour for find-filter matches: full white, the brightest thing on the map. +_FIND_MATCH_LABEL: RGB = (255, 255, 255) + + +def _dimmed(color: RGB, factor: float) -> RGB: + """``color`` scaled toward black by ``factor``, clamped to byte range.""" + return tuple(max(0, min(255, round(c * factor))) for c in color) # type: ignore[return-value] + + +def _draw_nodes( + canvas: MapCanvas, viewport: Viewport, markers: list[MapMarker], *, find: str = "" +) -> None: """Overlay mesh nodes: every glyph, then labels by importance until they collide. Glyphs are drawn lowest-priority first so self/repeaters land on top of leaf nodes. @@ -345,23 +363,38 @@ def _draw_nodes(canvas: MapCanvas, viewport: Viewport, markers: list[MapMarker]) Labels are then placed highest-priority first — self, then repeaters, then leaf nodes — each only if it fits without overlapping. So on a crowded map the important labels win the available space and the rest show as a bare marker (no overlap). + + With a ``find`` filter active only the matching nodes keep labels — drawn in bright + white so they pop — while everything else dims to near-background context and match + labels never lose the collision contest to non-matches. """ - placed: list[tuple[MapMarker, int, int]] = [] + needle = find.casefold() + placed: list[tuple[MapMarker, int, int, bool]] = [] for marker in markers: x, y = viewport.lonlat_to_dot(marker.lat, marker.lon) ix, iy = int(round(x)), int(round(y)) if not (0 <= ix < viewport.dot_w and 0 <= iy < viewport.dot_h): continue - placed.append((marker, ix, iy)) + matched = not needle or needle in marker.label.casefold() + placed.append((marker, ix, iy, matched)) # A cell is (dot_x >> 1, dot_y >> 2); count how many nodes land on each. - pile = Counter((ix >> 1, iy >> 2) for _, ix, iy in placed) + pile = Counter((ix >> 1, iy >> 2) for _, ix, iy, _m in placed) - for marker, ix, iy in sorted(placed, key=lambda p: p[0]._rank()): + # Matches draw after (over) dimmed non-matches whatever their rank, so the node + # being searched for is never buried under a brighter neighbour. + for marker, ix, iy, matched in sorted(placed, key=lambda p: (p[3], p[0]._rank())): glyph, color = _marker_style(marker) - count = pile[(ix >> 1, iy >> 2)] - canvas.marker(ix, iy, glyph, _pile_color(parse_hex(color), count)) + rgb = parse_hex(color) + if not matched: + rgb = _dimmed(rgb, _FIND_DIM) + else: + rgb = _pile_color(rgb, pile[(ix >> 1, iy >> 2)]) + canvas.marker(ix, iy, glyph, rgb) - for marker, ix, iy in sorted(placed, key=lambda p: -p[0]._rank()): + # A filtered-out node is context: bare dim glyph, no label. + labelled = (p for p in placed if p[3]) + for marker, ix, iy, _matched in sorted(labelled, key=lambda p: -p[0]._rank()): _, color = _marker_style(marker) - canvas.marker_label(ix, iy, marker.label, parse_hex(color)) + label_color = _FIND_MATCH_LABEL if needle else parse_hex(color) + canvas.marker_label(ix, iy, marker.label, label_color) diff --git a/meshterm/ui/map_screen.py b/meshterm/ui/map_screen.py index e68fa09..b6a2046 100644 --- a/meshterm/ui/map_screen.py +++ b/meshterm/ui/map_screen.py @@ -5,13 +5,16 @@ Viewport` over the mesh's nodes, fetches the vector tiles covering it in the bac the UI never blocks on the network), and redraws via :func:`~meshterm.ui.map_render. render_map`. Keys: -* ``w`` / ``a`` / ``s`` / ``d`` (or the arrow keys) pan north / west / south / east, -* holding **Shift** (Shift+arrows, or the uppercase ``W`` / ``A`` / ``S`` / ``D``) pans by a - single character cell for fine positioning, -* ``=`` / ``+`` zoom in, ``-`` / ``_`` zoom out, -* ``r`` recenters and refits to the dense core of the nodes (the same default view the map - opens on), -* ``Esc`` / ``q`` leaves the map. +* the **arrow keys** pan; holding **Shift** pans by a single character cell for fine + positioning, +* ``PgUp`` / ``PgDn`` zoom in / out, +* ``Home`` recenters and refits to the dense core of the nodes (the same default view the + map opens on), +* **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 + 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 blank grid — the map still works, it just has no streets. @@ -43,9 +46,6 @@ _PAN_DIRS: dict[str, tuple[int, int]] = { "right": (1, 0), } -#: Which pan direction each letter key drives (w/a/s/d ≈ north/west/south/east). -_PAN_KEYS: dict[str, str] = {"w": "up", "a": "left", "s": "down", "d": "right"} - #: How far past the tile source's max zoom the display may go (lower tiles are magnified). _OVERZOOM = 2 @@ -59,6 +59,11 @@ class MapScreen(Screen): floating = False + #: Whether printable keys feed the find-as-you-type node filter. The location + #: picker turns this off: there, typing has no job and a silent filter would + #: mysteriously dim the context markers. + find_enabled = True + def __init__( self, session, # noqa: ANN001 - TuiSession, imported lazily to avoid a cycle @@ -96,6 +101,10 @@ class MapScreen(Screen): # The view last handed to ``on_view_change``; seeded with the restored view so # reopening unchanged doesn't rewrite it. self._last_saved = saved_view + #: The live find-as-you-type node filter ("" = off). Every printable key lands + #: here — the map binds no letters to actions — and rendering highlights the + #: matching markers while dimming the rest. + self._filter = "" self._viewport: Optional[Viewport] = None self._size: tuple[int, int] = (0, 0) # (dot_w, dot_h) the viewport is built for # Ask the session to scrub the panel's right edge on the next paint (see @@ -110,10 +119,15 @@ class MapScreen(Screen): @property def footer_hint(self) -> str: # type: ignore[override] - """Key hints plus a live tile-loading indicator.""" - base = ( - "wasd/↑↓←→ pan (⇧ fine) · +/-/PgUp/PgDn zoom · r reset · Esc back" - ) + """Key hints — or the live find query — plus a tile-loading indicator. + + While a find filter is active the hints give way to the query itself with its + editing keys, so the typed text is always visible somewhere fixed. + """ + if self._filter: + base = f"find: {self._filter}▏ · Enter frame · Bksp erase · Esc clear" + else: + base = "↑↓←→ pan · ⇧ fine · PgUp/PgDn zoom · Home reset · type to find · Esc" if self._pending: return f"{base} · [muted]loading {len(self._pending)} tiles…[/muted]" if not self._source.available: @@ -153,7 +167,7 @@ class MapScreen(Screen): self.title = self._title(self._viewport) self._persist() tiles = {t: self._tiles.get(t) for t in self._viewport.tiles(self._max_tile_zoom)} - return render_map(self._viewport, tiles, self._markers) + return render_map(self._viewport, tiles, self._markers, find=self._filter) def _initial_viewport(self, dot_w: int, dot_h: int) -> Viewport: """Restore the saved view (clamped to sane bounds) or frame the nodes' dense core. @@ -184,8 +198,15 @@ class MapScreen(Screen): self._last_saved = view self._on_view_change(vp) + def _matches(self) -> list[MapMarker]: + """The markers the live find filter currently matches (all of them when off).""" + if not self._filter: + return self._markers + needle = self._filter.casefold() + return [m for m in self._markers if needle in m.label.casefold()] + def _title(self, vp: Viewport) -> str: - """A compact status title: zoom, node count, and scale (metres per dot).""" + """A compact status title: zoom, node count (find matches), and ground scale.""" # Ground metres per braille dot at the view centre, for a rough sense of scale. m_per_dot = ( 2 * math.pi * EARTH_RADIUS_KM * 1000 @@ -194,7 +215,11 @@ class MapScreen(Screen): ) scale = f"{m_per_dot * vp.dot_w:.0f} m across" if m_per_dot * vp.dot_w < 1000 else \ f"{m_per_dot * vp.dot_w / 1000:.1f} km across" - return f"Map · z{vp.zoom} · {len(self._markers)} nodes · {scale}" + if self._filter: + nodes = f"{len(self._matches())} of {len(self._markers)} match" + else: + nodes = f"{len(self._markers)} nodes" + return f"Map · z{vp.zoom} · {nodes} · {scale}" # --- tiles --------------------------------------------------------------- @@ -224,11 +249,19 @@ class MapScreen(Screen): # --- input --------------------------------------------------------------- def handle(self, action: str, data: str = "") -> None: - """Pan, zoom, reset, or exit in response to a normalized key action.""" + """Pan, zoom, reset, edit the find filter, or exit. + + Every printable key feeds the find filter — nothing pans or zooms by letter, so + typing a node name can never fling the view around. Esc peels one layer: an + active filter first, the map itself only once the filter is clear. + """ vp = self._viewport if action == "escape": - self.resolve(None) - return + if self._filter: + self._filter = "" + else: + self.resolve(None) + return if vp is None: return if action in _PAN_DIRS: @@ -239,12 +272,47 @@ class MapScreen(Screen): self._viewport = vp.zoomed(1, max_zoom=self._max_tile_zoom + _OVERZOOM) elif action == "pagedown": self._viewport = vp.zoomed(-1) - elif action == "text": - self._handle_key(data, vp) + elif action in ("home", "ctrl_home"): + self._reset_view(vp) + elif action == "text" and self.find_enabled: + self._filter += data + elif action == "space" and self._filter: + 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() + def _reset_view(self, vp: Viewport) -> None: + """Refit the view to the nodes' dense core (the map's opening frame).""" + self._viewport = Viewport.fit( + [(m.lat, m.lon) for m in self._markers], + vp.dot_w, + vp.dot_h, + max_zoom=self._max_tile_zoom, + fraction=self._view_fraction, + ) + + def _frame_matches(self, vp: Viewport) -> None: + """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), and no matches at all leaves the view alone. + """ + matches = self._matches() + if not matches: + return + self._viewport = Viewport.fit( + [(m.lat, m.lon) for m in matches], + vp.dot_w, + vp.dot_h, + max_zoom=self._max_tile_zoom, + fraction=1.0, + ) + def _pan(self, vp: Viewport, direction: str, *, fine: bool) -> None: """Pan by one coarse step, or — when ``fine`` — a single character cell. @@ -257,29 +325,6 @@ class MapScreen(Screen): else: self._viewport = vp.panned(dx * _PAN_STEP, dy * _PAN_STEP) - def _handle_key(self, key: str, vp: Viewport) -> None: - """Handle a printable-key action (pan/zoom/reset/quit). - - An uppercase pan letter (Shift held) pans by a single cell for fine positioning. - """ - low = key.lower() - if low in _PAN_KEYS: - self._pan(vp, _PAN_KEYS[low], fine=key.isupper()) - elif low in ("=", "+"): - self._viewport = vp.zoomed(1, max_zoom=self._max_tile_zoom + _OVERZOOM) - elif low in ("-", "_"): - self._viewport = vp.zoomed(-1) - elif low == "r": - self._viewport = Viewport.fit( - [(m.lat, m.lon) for m in self._markers], - vp.dot_w, - vp.dot_h, - max_zoom=self._max_tile_zoom, - fraction=self._view_fraction, - ) - elif low == "q": - self.resolve(None) - class LocationPickScreen(MapScreen): """The map, repurposed as a coordinate picker: pan the crosshair, Enter to choose. @@ -287,13 +332,16 @@ class LocationPickScreen(MapScreen): Used by the config editor to set the node's advertised location by *pointing at the map* instead of typing degrees. It is a :class:`MapScreen` with three changes: a crosshair marker rides the view centre (labelled with the live coordinates, so the - user always sees exactly what they're about to pick), Enter resolves with the centre's - ``(lat, lon)`` instead of doing nothing, and ``r`` recentres on the *initial* location + user always sees exactly what they're about to pick), Enter resolves with the + centre's ``(lat, lon)`` instead of framing find matches (find is off here — see + :attr:`MapScreen.find_enabled`), and ``Home`` recentres on the *initial* location rather than refitting the node cloud. The surrounding mesh nodes are still drawn, so placing yourself relative to a known repeater is easy. Esc cancels (resolves CANCEL, surfaced as ``None`` by the caller). """ + find_enabled = False + def __init__( self, session, # noqa: ANN001 - TuiSession, imported lazily to avoid a cycle @@ -324,7 +372,7 @@ class LocationPickScreen(MapScreen): @property def footer_hint(self) -> str: # type: ignore[override] """Key hints for picking, plus the live tile-loading indicator.""" - base = "wasd/↑↓←→ pan (⇧ fine) · +/- zoom · Enter set location · Esc cancel" + base = "↑↓←→ pan · ⇧ fine · PgUp/PgDn zoom · Enter set location · Esc cancel" if self._pending: return f"{base} · [muted]loading {len(self._pending)} tiles…[/muted]" if not self._source.available: @@ -370,13 +418,13 @@ class LocationPickScreen(MapScreen): return f"set location · {vp.center_lat:.5f}, {vp.center_lon:.5f} · z{vp.zoom} · {scale}" def handle(self, action: str, data: str = "") -> None: - """Commit the centre on Enter; ``r`` returns to the initial spot; else the map keys.""" + """Commit the centre on Enter; ``Home`` returns to the initial spot; else map keys.""" if action == "enter": vp = self._viewport if vp is not None: self.resolve((vp.center_lat, vp.center_lon)) return - if action == "text" and data.lower() == "r" and self._viewport is not None: + if action in ("home", "ctrl_home") and self._viewport is not None: # Reset returns to the *starting* view — the initial location when one was # given, else the node frame — rather than refitting a cloud that now includes # nowhere in particular. With neither, fall back to the world view. diff --git a/tests/test_config_editor.py b/tests/test_config_editor.py index a1fe907..459a9bc 100644 --- a/tests/test_config_editor.py +++ b/tests/test_config_editor.py @@ -190,19 +190,24 @@ def test_location_picker_opens_on_the_initial_spot_and_commits_the_centre() -> N def test_location_picker_moves_the_crosshair_and_resets_to_initial() -> None: - """Panning moves the committed point; ``r`` returns to the starting location.""" + """Panning moves the committed point; ``Home`` returns to the starting location.""" screen = _picker(initial=(45.5, -73.6)) screen.render_body(80) - screen.handle("text", "d") # pan east - screen.handle("text", "s") # pan south + screen.handle("right") # pan east + screen.handle("down") # pan south screen.handle("enter") lat, lon = screen.future.value assert lon > -73.6 and lat < 45.5 - screen.handle("text", "r") # back to the initial spot + screen.handle("home") # back to the initial spot assert screen._viewport.center_lat == pytest.approx(45.5) assert screen._viewport.center_lon == pytest.approx(-73.6) + # Typing does nothing here — the picker has no find filter to feed. + view = screen._viewport + screen.handle("text", "d") + assert screen._viewport is view and screen._filter == "" + def test_location_picker_draws_a_live_crosshair_without_keeping_it() -> None: """The centre crosshair (with live coordinates) renders each frame but is transient.""" @@ -221,7 +226,7 @@ def test_location_picker_without_nodes_or_initial_shows_the_world() -> None: screen = _picker() screen.render_body(80) assert screen._viewport.zoom == 2 - screen.handle("text", "r") # reset with nothing to fit stays on the world view + screen.handle("home") # reset with nothing to fit stays on the world view assert screen._viewport.zoom == 2 screen.handle("escape") assert screen.future.value is None diff --git a/tests/test_map.py b/tests/test_map.py index 450ac77..adc111e 100644 --- a/tests/test_map.py +++ b/tests/test_map.py @@ -444,29 +444,35 @@ def test_map_screen_renders_pans_zooms_and_resets() -> None: assert len(lines) == 24 # fills the body height reported by the session start = screen._viewport - screen.handle("text", "d") # pan east → longitude increases + screen.handle("right") # pan east → longitude increases assert screen._viewport.center_lon > start.center_lon - screen.handle("text", "w") # pan north → latitude increases + screen.handle("up") # pan north → latitude increases assert screen._viewport.center_lat > start.center_lat z = screen._viewport.zoom - screen.handle("text", "=") + screen.handle("pageup") assert screen._viewport.zoom == z + 1 - screen.handle("text", "-") + screen.handle("pagedown") assert screen._viewport.zoom == z - screen.handle("text", "r") # reset refits to the nodes + screen.handle("home") # reset refits to the nodes refit = Viewport.fit([(m.lat, m.lon) for m in markers], start.dot_w, start.dot_h, max_zoom=14) assert screen._viewport.zoom == refit.zoom assert screen._viewport.center_lat == pytest.approx(refit.center_lat) + # Letters never pan or zoom — they feed the find filter instead. + view = screen._viewport + screen.handle("text", "d") + assert screen._viewport is view and screen._filter == "d" + screen.handle("backspace") + # Offline source: nodes still render and both markers are present. assert "▲" in _plain(screen.render_body(80)) and "●" in _plain(screen.render_body(80)) assert "offline" in screen.footer_hint def test_map_screen_shift_pans_by_a_single_cell() -> None: - """Holding Shift (Shift+arrow, or uppercase WASD) pans finely, by one character cell.""" + """Holding Shift with an arrow pans finely, by one character cell.""" from meshterm.core.geo import lonlat_to_world, world_to_lonlat from meshterm.ui.map_render import MapMarker from meshterm.ui.map_screen import MapScreen @@ -490,10 +496,52 @@ def test_map_screen_shift_pans_by_a_single_cell() -> None: _, expected_lon = world_to_lonlat(cx + 2, cy, start.zoom) assert screen._viewport.center_lon == pytest.approx(expected_lon) - # Uppercase WASD is the same fine step via the text path. - screen._viewport = start - screen.handle("text", "D") - assert screen._viewport.center_lon == pytest.approx(start.center_lon + fine) + +def test_map_screen_find_filters_frames_and_clears() -> None: + """Typing builds the find query; Enter frames matches; Esc peels filter then map.""" + import asyncio + + from meshterm.ui.map_render import MapMarker + from meshterm.ui.map_screen import MapScreen + + markers = [ + MapMarker("YUL-Cartierville", 45.53, -73.71, is_repeater=True), + MapMarker("Alice", 45.40, -73.50), + MapMarker("Yagi-North", 45.60, -73.65), + ] + screen = MapScreen(_StubSession(80, 24), markers, _StubSource(), 14) + screen.render_body(80) + + for ch in "yu": + screen.handle("text", ch) + assert screen._filter == "yu" + assert [m.label for m in screen._matches()] == ["YUL-Cartierville"] + screen.render_body(80) + assert "1 of 3 match" in screen.title + assert "find: yu" in screen.footer_hint + + # Only the match keeps a label; the others dim to bare context glyphs. + body = _plain(screen.render_body(80)) + 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") + assert screen._viewport.center_lat == pytest.approx(45.53, abs=0.05) + assert screen._viewport.center_lon == pytest.approx(-73.71, abs=0.05) + + # Backspace edits; Esc clears the filter first and only then dismisses. + screen.handle("backspace") + assert screen._filter == "y" + + async def drive() -> object: + screen.future = asyncio.get_running_loop().create_future() + screen.handle("escape") + assert screen._filter == "" and not screen.future.done() + screen.handle("escape") + return await screen.future + + assert asyncio.run(drive()) is None def test_map_screen_restores_and_persists_view() -> None: @@ -518,11 +566,11 @@ def test_map_screen_restores_and_persists_view() -> None: assert screen._viewport.center_lon == pytest.approx(-71.20) assert saved == [] # reopening unchanged doesn't rewrite the stored view - screen.handle("text", "d") # pan east persists the moved view + screen.handle("right") # pan east persists the moved view assert saved and saved[-1][2] == 12 # zoom unchanged assert saved[-1][1] > -71.20 # centre moved east - screen.handle("text", "=") # zooming in persists too + screen.handle("pageup") # zooming in persists too assert saved[-1][2] == 13 @@ -534,7 +582,7 @@ def test_map_screen_scrubs_right_edge_after_move() -> None: markers = [MapMarker("A", 45.5, -73.6)] braille = MapScreen(_StubSession(80, 24), markers, _StubSource(), 14) braille.render_body(80) - braille.handle("text", "d") # a move flags the edge for a scrub + braille.handle("right") # a move flags the edge for a scrub assert braille.consume_edge_scrub() == 2 # right padding + border columns assert braille.consume_edge_scrub() == 0 # consumed — not repeated without another move