diff --git a/meshterm/tools/contacts.py b/meshterm/tools/contacts.py index cdda614..9a54c8f 100644 --- a/meshterm/tools/contacts.py +++ b/meshterm/tools/contacts.py @@ -76,14 +76,16 @@ class ContactsTool(Tool): sort_name = str(params.get("sort") or "heard") # In the menu, give the list to the interactive screen, so that the Ctrl+arrows sort - # it again while it is open. Their ring goes through the four columns of the shared - # contact list (also the hash). On the scripted CLI, print the plain listing one + # it again while it is open. Their ring goes through the five columns of the Contacts + # list (also the place and the hash). On the scripted CLI, print the plain listing one # time, in the requested order. if isinstance(ctx.ui, TuiUi): - from ..ui.contactlist import SORT_COLUMNS, SORT_OPENS_ASCENDING + from ..ui.contactlist import CONTACTS_SORT_COLUMNS, CONTACTS_SORT_OPENS_ASCENDING from ..ui.contacts_screen import open_contacts - sort = ContactsSort.from_name(sort_name, SORT_COLUMNS, SORT_OPENS_ASCENDING) + sort = ContactsSort.from_name( + sort_name, CONTACTS_SORT_COLUMNS, CONTACTS_SORT_OPENS_ASCENDING + ) await open_contacts(ctx, self_name, self_key, contacts, prefix_bytes, counts, sort) return ToolResult(summary={"contacts": len(contacts)}) diff --git a/meshterm/ui/contactlist.py b/meshterm/ui/contactlist.py index c53ff58..6f06bb3 100644 --- a/meshterm/ui/contactlist.py +++ b/meshterm/ui/contactlist.py @@ -26,10 +26,18 @@ row. Thus to add a lane is a declaration, not a branch: the header, the row buil sort metric, and the calculation of the lane widths all read the same tuple. The tuple replaces a ``show_traced`` flag. That flag had already caused three of those four places to say "and if it's the trace picker…". + +**A list can show every value in full.** The Contacts list passes ``pan=True``. Its lanes then +have the width of their content: the longest name, the longest place, and the full key. No +value is cut to fit the terminal. A row that is wider than the terminal pans: ←→ slide the +column header and all the rows by one shared shift, with the mark column and the name held +still (refer to :attr:`~meshterm.ui.tui.select.Choice.pans`). The other lists can be floating +dialogs (the Trace picker), so they keep the lanes that fit the terminal. """ from __future__ import annotations +import dataclasses from collections.abc import Callable from dataclasses import dataclass from datetime import datetime @@ -97,8 +105,10 @@ class ContactLane: width: The field width of the lane in cells. The values align to the right in it. field: The :class:`ContactRow` attribute that holds the value of the lane. kind: ``"age"`` for a datetime drawn as a relative age in the colour of the - recency heat, or ``"count"`` for an integer count drawn muted (a faint ``—`` - when ``None``). + recency heat, ``"count"`` for an integer count drawn muted (a faint ``—`` + when ``None``), or ``"text"`` for a string drawn on the left (a faint ``—`` + when ``None``). A ``text`` lane has no fixed width: the list sizes it to its + widest value (refer to :func:`_sized`), and :attr:`width` is the minimum. """ column: str @@ -123,9 +133,17 @@ TRACED_LANE = ContactLane("traced", "TRACED", 6, "last_traced") #: own is a second grammar that the user must learn, with no benefit. ARCHIVED_LANE = ContactLane("archived", "ARCHIVED", 8, "archived_at") +#: The place of the node: the named area nearest its location (refer to +#: :class:`~meshterm.core.places.Place`). It is text, so the list sizes it to its widest value. +#: It is the last lane, so it is immediately before the key. +PLACE_LANE = ContactLane("place", "PLACE", 5, "place", kind="text") + #: The middle lanes of the usual contact list: ``NAME · HEARD · PKTS · KEY``. DEFAULT_LANES: tuple[ContactLane, ...] = (HEARD_LANE, PKTS_LANE) +#: The middle lanes of the Contacts screen: ``NAME · HEARD · PKTS · PLACE · KEY``. +CONTACTS_LANES: tuple[ContactLane, ...] = (HEARD_LANE, PKTS_LANE, PLACE_LANE) + #: The middle lanes of the Trace-target picker, which puts ``TRACED`` before the usual two. TRACE_LANES: tuple[ContactLane, ...] = (TRACED_LANE, HEARD_LANE, PKTS_LANE) @@ -179,6 +197,19 @@ SORT_OPENS_ASCENDING: dict[str, bool] = { "hash": True, } +#: The sort ring of the Contacts screen. It adds a ``place`` column between ``packets`` and +#: ``hash``, the same order as the lanes. It opens *ascending* (A→Z). A node with no place +#: collects at the end when ascending, and at the start when descending, like a node that +#: was never heard in an age column (refer to :func:`_ordered`). +CONTACTS_SORT_COLUMNS: tuple[str, ...] = ("name", "heard", "packets", "place", "hash") +CONTACTS_SORT_OPENS_ASCENDING: dict[str, bool] = { + "name": True, + "heard": True, + "packets": False, + "place": True, + "hash": True, +} + #: The wider sort ring of the Trace-target picker. It adds a ``traced`` column (how long ago #: the node was last traced) between name and heard. It opens on that column *ascending*, #: which is the natural first direction of each age lane. The metric is an **age**, so @@ -248,6 +279,9 @@ class ContactRow: last_traced: When this node was last traced (aware UTC). It fills the ``TRACED`` lane (:data:`TRACE_LANES`), in the colour of the recency heat. ``None`` shows ``never``. Lists that do not declare the lane ignore it. + place: The place of the node, as its full label (``Villeray, Montréal``). It fills + the ``PLACE`` lane (:data:`PLACE_LANE`). ``None`` or blank renders a faint ``—``. + Lists that do not declare the lane ignore it. archived_at: When this contact was archived and removed from the device (aware UTC). It fills the ``ARCHIVED`` lane (:data:`ARCHIVED_LANES`). Lists without that lane ignore it. @@ -270,6 +304,7 @@ class ContactRow: count: int | None = None last_traced: datetime | None = None archived_at: datetime | None = None + place: str | None = None locked: bool = False managed: bool = False you: bool = False @@ -324,12 +359,39 @@ def _header( for lane in lanes: # A label aligned to the right, above a value aligned to the right. Thus the header # of a narrow field is where its digits will be (``PKTS`` above a 5-cell count), not - # to the left of them. - column(header, f"{lane.label:>{lane.width}}", lane.column, lane.width) + # to the left of them. A text lane is the other way: on the left, as its values are. + if lane.kind == "text": + column(header, _pad_cells(lane.label, lane.width), lane.column, lane.width) + else: + column(header, f"{lane.label:>{lane.width}}", lane.column, lane.width) column(header, "KEY", "hash", 3, last=True) return header +def _pad_cells(text: str, width: int) -> str: + """Return ``text`` padded on the right with spaces to ``width`` cells (a wide glyph is two).""" + return text + " " * max(0, width - cell_len(text)) + + +def _sized(lanes: tuple[ContactLane, ...], rows: list[ContactRow]) -> tuple[ContactLane, ...]: + """Return ``lanes`` with each ``text`` lane as wide as its widest value. + + A text lane cannot have a fixed width, because no width fits every place name. The list + measures its rows, so that no value is cut. A lane is never narrower than its label. The + other lanes are the same objects. + """ + sized = [] + for lane in lanes: + if lane.kind == "text": + widest = max( + (cell_len(str(getattr(row, lane.field, None) or "")) for row in rows), + default=0, + ) + lane = dataclasses.replace(lane, width=max(lane.width, cell_len(lane.label), widest)) + sized.append(lane) + return tuple(sized) + + def _lane_cell(row: ContactRow, lane: ContactLane) -> Text: """The value of one row in one lane: aligned to the right, with the style of its kind. @@ -337,9 +399,14 @@ def _lane_cell(row: ContactRow, lane: ContactLane) -> Text: colour of the recency heat. Thus a new value is bright and an old value is grey, the same for each event that the lane measures. A ``count`` lane draws the count muted, or a faint ``—`` where there is nothing to count. It clamps the count, so that a very - large count cannot make the column wider. + large count cannot make the column wider. A ``text`` lane draws its string on the left, + padded to the lane, or a faint ``—`` where there is none. """ value = getattr(row, lane.field, None) + if lane.kind == "text": + if not value: + return Text(_pad_cells("—", lane.width), style="faint") + return Text(_pad_cells(str(value), lane.width)) if lane.kind == "count": if value is None: return Text(f"{'—':>{lane.width}}", style="faint") @@ -364,7 +431,8 @@ def _you_lane( longer than any lane, so it shows as many digits as fit, and then an ellipsis. **Each middle lane shows a faint ``—``**, whatever lanes the list declares. MeshTerm never hears, traces, or archives our node, so no middle lane has a value to show, and - each lane says so in the same way. + each lane says so in the same way. The one exception is a ``text`` lane (the place), which + shows its value when the row has one. """ text = Text(" " * lock_w, no_wrap=True, overflow="ellipsis") # our node is never locked text.append(SELF_MARK[0], style=SELF_MARK[1]) @@ -383,7 +451,11 @@ def _you_lane( text.append(fit_cells(row.name or "you", name_w), style="you") for lane in lanes: text.append(_GAP_S) - text.append(f"{'—':>{lane.width}}", style="faint") + if lane.kind == "text": + # The place of our node is a fact about where it is, and MeshTerm can know it. + text.append_text(_lane_cell(row, lane)) + else: + text.append(f"{'—':>{lane.width}}", style="faint") text.append(_GAP_S) # the same gap as before KEY in the header (refer to _header) if row.key: text.append_text(highlighted_hash(row.key, prefix_bytes, width=hash_w)) @@ -487,6 +559,10 @@ def _ordered( # stays. return 0 value = getattr(row, lane.field, None) + if lane.kind == "text": + # A blank value sorts after each text (its first key is larger), like the nodes + # that were never heard in an age column. + return (0, str(value).casefold()) if value else (1, "") if lane.kind == "count": return value or 0 secs = age_seconds(value) @@ -524,6 +600,9 @@ class ContactListScreen(SelectScreen): This is the same :class:`~meshterm.ui.widgets.ContactsSort` model and white column cue that the static Contacts table uses. Only the keyboard keys are different, because a list with a filter already uses the plain arrow keys. + + With ``pan=True`` the list cuts no value (refer to the module docstring). Its rows and + its column header are one table that ←→ pan, with the marks and the name held still. """ floating = False @@ -572,6 +651,7 @@ class ContactListScreen(SelectScreen): footer_hint: str = _HINT, lanes: tuple[ContactLane, ...] = DEFAULT_LANES, key_hint: Callable[[Any], str] | None = None, + pan: bool = False, ) -> None: """Build the list over rows that are already resolved. @@ -603,17 +683,30 @@ class ContactListScreen(SelectScreen): key_hint: The hint atoms for the shortcut keys that act on the highlighted row (refer to :class:`~meshterm.ui.tui.select.SelectScreen`). ``None`` for a list with no such keys. + pan: Whether the list shows each value in full. The lanes then have the width + of their content, and ←→ pan the table when it is wider than the terminal + (refer to the module docstring). It is off for a list that can float as a + dialog, because the width of a dialog comes from the width of its rows. """ self._contact_rows = rows self._prefix_bytes = prefix_bytes self._sort = sort - self._lanes = tuple(lanes) + self._declared_lanes = tuple(lanes) + self._lanes = _sized(self._declared_lanes, rows) + self._pan_table = pan + #: The cells of the mark column, the type glyph, and the name: the head that stays + #: still while the table pans. The first paint finds the real value (refer to + #: :meth:`_pinned_head`). + self._anchor = 0 self._lead = list(lead) if lead else [] self._tail = list(tail) if tail else [] # Temporary values until the first render finds the true width (refer to # render_body). self._name_w = _NAME_MIN self._hash_w = _HASH_MIN + if pan: + # A list that cuts nothing knows its lanes before the first paint. + self._name_w, self._hash_w = self._lane_widths(0) super().__init__( title, self._compose_items(), @@ -631,12 +724,21 @@ class ContactListScreen(SelectScreen): whatever the sort. """ items: list = list(self._lead) + # The text lanes are as wide as the widest value that the rows have now. A change of + # the rows (a place that was found) can make a lane wider. + self._lanes = _sized(self._declared_lanes, self._contact_rows) # The lane names come before the contacts as their landmark, so they stay pinned at # the top while the list scrolls. Thus the user can still read the columns of a row - # far down in the sort. + # far down in the sort. In a list that pans, the header pans with the rows, and it + # holds the same head still. lock_w = _lock_lane_width(self._contact_rows) items.append( - Separator(_header(self._name_w, self._sort, self._lanes, lock_w), heading=True) + Separator( + _header(self._name_w, self._sort, self._lanes, lock_w), + heading=True, + pans=self._pan_table, + hscroll_from=self._anchor, + ) ) pinned = [row for row in self._contact_rows if row.you] rest = [row for row in self._contact_rows if not row.you] @@ -652,6 +754,8 @@ class ContactListScreen(SelectScreen): lock_w, ), row.value, + pans=self._pan_table, + hscroll_from=self._anchor, ) ) items.extend(self._tail) @@ -726,22 +830,42 @@ class ContactListScreen(SelectScreen): Each declared lane adds its width and gap to the fixed lead. Thus a list without two of the lanes (the Archived list) gives both widths back to the key. + + A list that pans cuts nothing. Its name lane is the widest name, and its key lane is + the longest key, whatever the width of the terminal. """ + if self._pan_table: + keys = (len(row.key.lower().removeprefix("0x")) for row in self._contact_rows) + return self._widest_name(), max(_HASH_MIN, *keys, 0) lead = ( _LEAD + _lock_lane_width(self._contact_rows) - + sum(_GAP + lane.width for lane in self._lanes) + + sum(_GAP + lane.width for lane in _sized(self._declared_lanes, self._contact_rows)) ) name_cap = max(_NAME_MIN, width - lead - _HASH_MIN) name_w = max(_NAME_MIN, min(self._widest_name(), name_cap)) hash_w = max(_HASH_MIN, width - lead - name_w) return name_w, hash_w + def _pinned_head(self, name_w: int, width: int) -> int: + """The cells of a row that stay still while the table pans, for a terminal ``width`` wide. + + The head is the mark column, the type glyph with its space, and the name. They tell + the user which contact a row is, so they must not slide away. But a very long name + could leave no room for the lanes that slide. The head is never more than half of + the row area. The rest of such a name slides with the lanes, and no cell is lost. + """ + if not self._pan_table: + return 0 + head = _lock_lane_width(self._contact_rows) + 2 + name_w + return min(head, max(0, (width - 2) // 2)) + def render_body(self, width: int) -> list[str]: """Size the name lane to its content and adjust the key lane, then render the list.""" name_w, hash_w = self._lane_widths(width) - if (name_w, hash_w) != (self._name_w, self._hash_w): - self._name_w, self._hash_w = name_w, hash_w + anchor = self._pinned_head(name_w, width) + if (name_w, hash_w, anchor) != (self._name_w, self._hash_w, self._anchor): + self._name_w, self._hash_w, self._anchor = name_w, hash_w, anchor self._rebuild() return super().render_body(width) diff --git a/meshterm/ui/contacts_screen.py b/meshterm/ui/contacts_screen.py index c63fd6f..be86a77 100644 --- a/meshterm/ui/contacts_screen.py +++ b/meshterm/ui/contacts_screen.py @@ -2,11 +2,13 @@ """The interactive Contacts screen: the contacts of the device in the shared sortable list. This screen shows the contact table of the companion with the presentation of the Time -Machine picker. It has the same aligned ``NAME · HEARD · PKTS · KEY`` lanes, with our node -pinned first. It has the same Ctrl+arrow sort (now with the key column) and the same -type-to-filter. Thus the whole app has one contact list, for each source of data (refer to -:mod:`~meshterm.ui.contactlist`). Enter opens the full-screen Node detail page of the -highlighted node (:mod:`~meshterm.ui.node_detail_screen`). That page shows the identity of +Machine picker. It has the same aligned ``NAME · HEARD · PKTS · PLACE · KEY`` lanes, with our +node pinned first. It has the same Ctrl+arrow sort (now with the place and key columns) and +the same type-to-filter. The filter also matches the place of a node. The list cuts no value: +a row that is wider than the terminal pans with ←→. Thus the whole app has one contact list, +for each source of data (refer to :mod:`~meshterm.ui.contactlist`). Enter opens the +full-screen Node detail page of the highlighted node +(:mod:`~meshterm.ui.node_detail_screen`). That page shows the identity of the node, a preview of its location, the routes that MeshTerm observed to it, and the ways to go further (trace, map, Time Machine). When the user backs out of that page, the list is as it was. ^L opens the map on the highlighted node, when it has a location. ^K locks the @@ -44,7 +46,7 @@ from __future__ import annotations from typing import TYPE_CHECKING from .archived_screen import open_archived -from .contactlist import ContactListScreen, ContactRow +from .contactlist import CONTACTS_LANES, ContactListScreen, ContactRow from .menus import icon_lane, marked_label, splice_if_room from .sweep_screen import archive_contacts from .tui import Choice, KeyRequest, Separator @@ -54,6 +56,7 @@ from .widgets import ContactsSort, contact_packets if TYPE_CHECKING: from ..context import AppContext from ..core.models import Contact + from ..services.places import PlaceService from .map_render import MapMarker from .map_screen import Locator @@ -85,6 +88,12 @@ class ContactsScreen(ContactListScreen): lock. The shared list handles the sort, the filter, and the navigation. """ + #: The hint sheds this atom first when it is too wide (refer to + #: :func:`~meshterm.ui.tui.frame.fit_hint`). The ``Left`` and ``Right`` keys are the + #: first thing that a user tries on a row that runs past the edge, and the other atoms + #: name keys that nothing else shows. + spare_hint_atoms = ("←→ scroll",) + @property def picocalc_lyra_lane(self): """The lane of the contact list, with ``Map`` (^L) and ``Lock`` (^K) on the Shift bank. @@ -120,6 +129,7 @@ class ContactsScreen(ContactListScreen): locator: Locator | None = None, can_lock: bool = False, managed: frozenset[str] = frozenset(), + places: PlaceService | None = None, ) -> None: """Create the contacts screen over contact data that MeshTerm already got. @@ -149,8 +159,13 @@ class ContactsScreen(ContactListScreen): managed: The full keys (lowercase hex) of the managed nodes: the contacts whose admin password MeshTerm stores. Each of those rows has the ``🔑`` in its mark column (refer to :data:`~meshterm.ui.marks.MANAGED_ICON`). + places: The places of the nodes, for the ``PLACE`` lane and for the filter. With + ``None``, the lane shows a faint ``—`` in each row. The screen draws the + rows again when a place changes (refer to :meth:`render_body`). """ self._self_name, self._self_key = self_name, self_key + self._places = places + self._place_rev = places.revision if places is not None else 0 self._locator = locator self._can_lock = can_lock self._locked = locked @@ -197,13 +212,23 @@ class ContactsScreen(ContactListScreen): sort=sort, tail=tail, key_hint=lambda value: "^L map" if self._marker_of(value) is not None else "", + lanes=CONTACTS_LANES, + pan=True, ) if archived: self.short_title = f"Contacts · {known} + {archived}" def _contact_rows_for(self, locked: frozenset[str]) -> list[ContactRow]: """Our node, then each contact. ``locked`` shows which contacts are locked.""" - rows = [ContactRow(value=YOU, name=self._self_name, key=self._self_key, you=True)] + rows = [ + ContactRow( + value=YOU, + name=self._self_name, + key=self._self_key, + you=True, + place=self._place_of(self._self_key), + ) + ] for c in self._contacts: rows.append( ContactRow( @@ -215,12 +240,33 @@ class ContactsScreen(ContactListScreen): node_type=c.node_type, last_seen=c.last_seen, count=contact_packets(c, self._counts), + place=self._place_of(c.public_key or c.key_prefix), locked=(c.public_key or "").lower().removeprefix("0x") in locked, managed=(c.public_key or "").lower().removeprefix("0x") in self._managed, ) ) return rows + def _place_of(self, key: str | None) -> str | None: + """The full label of the place of a node, or ``None`` when MeshTerm knows none.""" + if self._places is None or not key: + return None + place = self._places.get(key) + return (place.label or None) if place is not None else None + + def render_body(self, width: int) -> list[str]: + """Draw the list. First read the places again if the finder or the user changed one. + + The finder works in the background, and a place can arrive while this screen is open. + The service counts its changes, so the screen reads again only after a change. The + highlight, the sort, the filter, and the pan stay (refer to + :meth:`~meshterm.ui.contactlist.ContactListScreen.update_rows`). + """ + if self._places is not None and self._places.revision != self._place_rev: + self._place_rev = self._places.revision + self.update_rows(self._contact_rows_for(self._locked)) + return super().render_body(width) + def _marker_of(self, value: object) -> MapMarker | None: """The marker of the node of a row value, or ``None`` (a tail row, or no location).""" if self._locator is None: @@ -367,6 +413,7 @@ async def open_contacts( locator=locator, can_lock=_can_lock(ctx, self_key), managed=managed_keys(ctx, contacts), + places=getattr(ctx, "places", None), ) screen = build() diff --git a/meshterm/ui/tui/select.py b/meshterm/ui/tui/select.py index 20af3b6..0134cfc 100644 --- a/meshterm/ui/tui/select.py +++ b/meshterm/ui/tui/select.py @@ -271,6 +271,11 @@ class Separator: row: its first two cells are the pointer column, which does not move while the rest slides. :func:`~meshterm.ui.menus.column_header` already indents it in this way. + hscroll_from: The cells after the pointer column that stay still while the header + pans (only for a header that pans). A table whose rows pin a head block + (:attr:`Choice.hscroll_from`) gives its header the same count. Thus the labels + of the pinned lanes stay over their cells. With ``0``, the default, only the + pointer column stays. """ title: str | Text | Callable[[int], str | Text] @@ -279,6 +284,7 @@ class Separator: heading: bool = False spaced: bool = False pans: bool = False + hscroll_from: int = 0 def text(self, width: int) -> str | Text: """The content of the row at ``width`` cells. This method resolves a width-aware title.""" @@ -878,7 +884,7 @@ class SelectScreen(Screen): # Its fullest form, slid with the rows, with its pointer column held # still. It is one line, however wide, because its labels must stay above # their lanes. - slid = self._scroll_window(content, _POINTER, width) + slid = self._scroll_window(content, _POINTER + item.hscroll_from, width) drawn = [render_to_ansi(slid, width, no_wrap=True)] if item.pinned: self._pinned_header = (len(lines), drawn[0]) @@ -1021,7 +1027,7 @@ class SelectScreen(Screen): continue if isinstance(item, Separator): cells = cell_len(_plain(item.text(_UNBOUNDED))) - limit = max(limit, tail(cells, _POINTER, width)) + limit = max(limit, tail(cells, _POINTER + item.hscroll_from, width)) else: cells = cell_len(_plain(item.scroll_text(avail))) limit = max(limit, tail(cells, item.hscroll_from, avail)) diff --git a/tests/test_contact_places.py b/tests/test_contact_places.py new file mode 100644 index 0000000..2bb29b6 --- /dev/null +++ b/tests/test_contact_places.py @@ -0,0 +1,244 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Tests for the place of a node on the Contacts list, the CLI, and the map filter. + +The place is the named area nearest the location of a node (refer to +:mod:`meshterm.core.places`). These tests use a small stand-in for the place service, so +that no database and no network are necessary. +""" + +from __future__ import annotations + +import re + +from rich.cells import cell_len + +from meshterm.core.models import Contact +from meshterm.core.places import SOURCE_TILES, Place +from meshterm.ui.contactlist import ( + CONTACTS_SORT_COLUMNS, + CONTACTS_SORT_OPENS_ASCENDING, + PLACE_LANE, + ContactListScreen, + ContactRow, +) +from meshterm.ui.contacts_screen import ContactsScreen +from meshterm.ui.widgets import ContactsSort + +_ANSI = re.compile(r"\x1b\[[0-9;]*m") + +_ALICE = "aa" * 32 +_BOB = "bb" * 32 +_CARL = "dd" * 32 +_US = "cc" * 32 + + +class _Places: + """A stand-in for :class:`~meshterm.services.places.PlaceService`: ``get`` and ``revision``.""" + + def __init__(self, found: dict[str, Place]) -> None: + self.found = found + self.revision = 0 + + def get(self, node: str | None) -> Place | None: + return self.found.get((node or "")[:12]) + + +def _places() -> _Places: + return _Places( + { + _ALICE[:12]: Place("Villeray", "Montréal", SOURCE_TILES), + _BOB[:12]: Place("Mont Royal", None, SOURCE_TILES, peak=True), + } + ) + + +def _sort(name: str = "name") -> ContactsSort: + return ContactsSort.from_name(name, CONTACTS_SORT_COLUMNS, CONTACTS_SORT_OPENS_ASCENDING) + + +def _screen(places: _Places | None = None, sort: str = "name") -> ContactsScreen: + contacts = [ + Contact(name="Alice", public_key=_ALICE), + Contact(name="Bob", public_key=_BOB), + Contact(name="Carl", public_key=_CARL), + ] + return ContactsScreen( + "Homestead", _US, contacts, 1, {}, _sort(sort), places=places if places else _places() + ) + + +def _lines(screen: ContactListScreen, width: int) -> list[str]: + return [_ANSI.sub("", line) for line in screen.render_body(width)] + + +def _row(screen: ContactListScreen, width: int, name: str) -> str: + return next(line for line in _lines(screen, width) if name in line) + + +def _names(screen: ContactListScreen, width: int = 200) -> list[str]: + """The contact names in the order that the list draws them (our node first).""" + drawn = _lines(screen, width) + order = ["Homestead", "Alice", "Bob", "Carl"] + return sorted(order, key=lambda n: next(i for i, line in enumerate(drawn) if n in line)) + + +# -- part 1: the PLACE column --------------------------------------------------------- + + +def test_place_column_is_immediately_before_the_key() -> None: + """The header reads NAME, HEARD, PKTS, PLACE, KEY in that order.""" + header = _lines(_screen(), 200)[0] + labels = [header.index(label) for label in ("NAME", "HEARD", "PKTS", "PLACE", "KEY")] + assert labels == sorted(labels) + assert "PLACE" in header and header.rstrip().endswith("KEY") + + +def test_place_shows_the_full_label_and_a_dash_when_unknown() -> None: + """A known place is its label. An unknown place is the faint dash of the other lanes.""" + screen = _screen() + alice = _row(screen, 200, "Alice") + carl = _row(screen, 200, "Carl") + assert "Villeray, Montréal" in alice + assert "Mont Royal" in _row(screen, 200, "Bob") + # The place is before the key on the row, and a node with no place has the dash there. + assert alice.index("Villeray") < alice.index("aaaa") + assert carl.index("—", carl.index("Carl") + 4) < carl.index("dddd") + assert "Villeray" not in carl + + +def test_place_column_cuts_no_value() -> None: + """The label of a row keeps its full place and its full key, however narrow the terminal.""" + screen = _screen() + label = "".join( + _ANSI.sub("", str(getattr(c, "label", ""))) + for c in screen._choices() # noqa: SLF001 + ) + assert "Villeray, Montréal" in label + assert _ALICE in label + assert _US in label + + +def test_pan_keeps_header_and_rows_aligned() -> None: + """After the table pans, the PLACE label is still over the places of the rows.""" + screen = _screen() + width = 53 + for _ in range(3): + lines = _lines(screen, width) + header = lines[0] + alice = next(line for line in lines if "Alice" in line) + if "PLACE" in header and "Villeray" in alice: + assert header.index("PLACE") == alice.index("Villeray") + break + screen.handle("right") + else: # pragma: no cover - the place must come into view + raise AssertionError("the PLACE lane never came into view") + + +def test_pan_holds_the_name_still() -> None: + """The mark, the glyph, and the name stay while the lanes slide.""" + screen = _screen() + before = _row(screen, 53, "Alice")[:12] + screen.handle("right") + screen.handle("right") + assert _row(screen, 53, "Alice")[:12] == before + + +def test_unselected_rows_are_cut_only_at_the_screen_edge() -> None: + """A narrow terminal shows a cut mark at the edge. The row itself is not shortened.""" + screen = _screen() + narrow = _row(screen, 40, "Alice") + assert cell_len(narrow) <= 40 + wide = _row(screen, 200, "Alice") + assert "Villeray, Montréal" in wide and _ALICE in wide + + +def test_scroll_atom_is_in_the_hint_only_while_the_row_overflows() -> None: + """The footer names ←→ exactly when the highlighted row runs past the edge.""" + screen = _screen() + screen.render_body(40) + assert "←→ scroll" in screen.footer_hint + screen.render_body(400) + assert "←→ scroll" not in screen.footer_hint + + +def test_our_node_shows_its_place() -> None: + """The row of our node shows its place when MeshTerm knows it, and a dash if not.""" + places = _places() + assert "—" in _row(_screen(places), 200, "Homestead").split("(you)")[1] + places.found[_US[:12]] = Place("Rosemont", "Montréal", SOURCE_TILES) + assert "Rosemont, Montréal" in _row(_screen(places), 200, "Homestead") + + +def test_place_is_sortable() -> None: + """The sort ring has a place column. Places run A to Z, and a node with none runs last.""" + screen = _screen(sort="place") + assert [PLACE_LANE.column] == [c for c in CONTACTS_SORT_COLUMNS if c == "place"] + # Mont Royal (Bob), then Villeray (Alice), then no place (Carl). Our node stays first. + assert _names(screen) == ["Homestead", "Bob", "Alice", "Carl"] + screen.handle("ctrl_down") + assert _names(screen) == ["Homestead", "Carl", "Alice", "Bob"] + + +def test_ctrl_arrows_reach_the_place_column() -> None: + """Ctrl+→ goes name, heard, packets, place, hash.""" + screen = _screen() + seen = [] + for _ in range(4): + screen.handle("ctrl_right") + seen.append(screen._sort.column) # noqa: SLF001 + assert seen == ["heard", "packets", "place", "hash"] + + +def test_a_found_place_draws_without_a_new_screen() -> None: + """When the service counts a change, the list reads the places again and keeps the highlight.""" + places = _places() + screen = _screen(places) + screen.handle("down") + screen.handle("down") + current = screen._current_choice().value # noqa: SLF001 + assert "Verdun" not in "\n".join(_lines(screen, 200)) + places.found[_CARL[:12]] = Place("Verdun", "Montréal", SOURCE_TILES) + places.revision += 1 + assert "Verdun, Montréal" in _row(screen, 200, "Carl") + assert screen._current_choice().value == current # noqa: SLF001 + + +def test_lists_without_the_lane_are_unchanged() -> None: + """A list that does not declare the lane draws no PLACE column.""" + screen = ContactListScreen( + "Pick", + rows=[ContactRow(value=1, name="Alice", key=_ALICE, place="Villeray, Montréal")], + prefix_bytes=1, + sort=ContactsSort.from_name("name"), + ) + assert "PLACE" not in _lines(screen, 100)[0] + assert "Villeray" not in _row(screen, 100, "Alice") + + +# -- part 2: the filter --------------------------------------------------------------- + + +def _type(screen: ContactListScreen, text: str) -> None: + for char in text: + screen.handle("text", char) + + +def test_filter_matches_the_place() -> None: + """Typed text narrows the list by the place of a node, in any case.""" + screen = _screen() + _type(screen, "villeray") + shown = "\n".join(_lines(screen, 200)) + assert "Alice" in shown + assert "Bob" not in shown and "Carl" not in shown + + +def test_filter_matches_the_coarse_part_of_the_place() -> None: + """The city part of a place matches too, and a name still matches as before.""" + screen = _screen() + _type(screen, "montr") + shown = "\n".join(_lines(screen, 200)) + assert "Alice" in shown and "Bob" not in shown + screen.handle("escape") + _type(screen, "bob") + shown = "\n".join(_lines(screen, 200)) + assert "Bob" in shown and "Alice" not in shown diff --git a/tests/test_gallery.py b/tests/test_gallery.py index 7a158e5..22d0121 100644 --- a/tests/test_gallery.py +++ b/tests/test_gallery.py @@ -219,6 +219,19 @@ def _dashboard_scoped(cols: int, rows: int) -> Screen: return screen +class _GalleryPlaces: + """A stand-in for the place service: Alice is in a named area, and the rest are not.""" + + revision = 0 + + def get(self, node): # noqa: ANN001, ANN202 - the shape of PlaceService.get + from meshterm.core.places import SOURCE_TILES, Place + + return ( + Place("Villeray", "Montréal", SOURCE_TILES) if (node or "").startswith("aaaa") else None + ) + + def _contacts(cols: int, rows: int) -> Screen: sort = ContactsSort.from_name("name", SORT_COLUMNS, SORT_OPENS_ASCENDING) contacts = [ @@ -242,6 +255,8 @@ def _contacts(cols: int, rows: int) -> Screen: # The locked contact is also a managed node: the mark column then holds the # padlock and the key, its widest form, on each platform. managed=frozenset({"aa" * 32}), + # A place with an accent and a coarse part, the widest form of the PLACE lane. + places=_GalleryPlaces(), ) screen.handle("down") return screen @@ -1929,8 +1944,10 @@ _PREEXISTING_REGULAR_OVERFLOW: set[str] = set() #: The hint line removes atoms to fit (``frame.fitted_footer``), so the test measures the #: hint that the footer draws, and checks that it keeps its way out. Each entry names its #: decision. ``courier_outbox``: JP, 2026-10-22, "bring the filter back, tough luck if it -#: doesn't fit in the footer". -_SHEDS_ITS_HINT: set[str] = {"courier_outbox"} +#: doesn't fit in the footer". ``contacts``: the list cuts no value, so its hint gains +#: ``←→ scroll`` while the highlighted row runs past the edge, and the atom is the first to +#: go when the footer is full (``ContactsScreen.spare_hint_atoms``). +_SHEDS_ITS_HINT: set[str] = {"courier_outbox", "contacts"} #: The specimens by name, for a test that needs one entry and not the whole sweep.