contacts --sort takes place and hash; the Archived list gets the PLACE column
The CLI sorts on the same ring as the Contacts screen (name, heard, packets, place, hash). The ring moved to ui/widgets.py so the CLI loads no TUI code, and ordered_contacts sorts by place (no place last) and by key. The Archived list reads NAME · ARCHIVED · PLACE · KEY, sorts by place, cuts no value and pans with ←→, like the Contacts list. The place fill and its live refresh moved from ContactsScreen into ContactListScreen, so any list that declares the PLACE lane gets them from places=. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
2df3dd2c39
commit
d08513aa69
10 files changed
+299
-113
No files matched your search
+3
-3
@@ -563,7 +563,7 @@ $ meshterm contacts --sort bogus
|
||||
Usage: meshterm contacts [OPTIONS]
|
||||
Try 'meshterm contacts --help' for help.
|
||||
|
||||
Error: Invalid value: --sort must be one of: name, heard, packets (got 'bogus')
|
||||
Error: Invalid value: --sort must be one of: name, heard, packets, place, hash (got 'bogus')
|
||||
```
|
||||
|
||||
**A confirmation that you did not give** is in the same class, because nothing has
|
||||
@@ -624,7 +624,7 @@ $ meshterm contacts --sort bogus --json
|
||||
Usage: meshterm contacts [OPTIONS]
|
||||
Try 'meshterm contacts --help' for help.
|
||||
|
||||
Error: Invalid value: --sort must be one of: name, heard, packets (got 'bogus')
|
||||
Error: Invalid value: --sort must be one of: name, heard, packets, place, hash (got 'bogus')
|
||||
$ echo $?
|
||||
2
|
||||
```
|
||||
@@ -894,7 +894,7 @@ The contacts that your device knows.
|
||||
|
||||
| Option | What it does |
|
||||
| --- | --- |
|
||||
| `-s`, `--sort ORDER` | `heard` (default), `name`, or `packets`. |
|
||||
| `-s`, `--sort ORDER` | `heard` (default), `name`, `packets`, `place`, or `hash` (the key). |
|
||||
|
||||
```console
|
||||
$ meshterm contacts --sort name
|
||||
|
||||
+47
-20
@@ -46,7 +46,12 @@ class ContactsTool(Tool):
|
||||
A :class:`ToolResult` with a summary of the number of known contacts.
|
||||
"""
|
||||
from ..ui.surface import TuiUi
|
||||
from ..ui.widgets import ContactsSort, ordered_contacts
|
||||
from ..ui.widgets import (
|
||||
CONTACTS_SORT_COLUMNS,
|
||||
CONTACTS_SORT_OPENS_ASCENDING,
|
||||
ContactsSort,
|
||||
ordered_contacts,
|
||||
)
|
||||
|
||||
# Read through the session cache. On a busy node, the contacts table is a slow
|
||||
# round trip. If MeshTerm reads it again (and the self info) at each visit to the
|
||||
@@ -76,29 +81,34 @@ class ContactsTool(Tool):
|
||||
# A list from A to Z does not. Then the Ctrl+arrows sort the list again (and
|
||||
# ``--sort`` sets the order of the CLI).
|
||||
sort_name = str(params.get("sort") or "heard")
|
||||
# The two faces use the same ring: the five columns of the Contacts list (also the
|
||||
# place and the hash).
|
||||
sort = ContactsSort.from_name(
|
||||
sort_name, CONTACTS_SORT_COLUMNS, CONTACTS_SORT_OPENS_ASCENDING
|
||||
)
|
||||
|
||||
# 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 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.
|
||||
# it again while it is open. On the scripted CLI, print the plain listing one time,
|
||||
# in the requested order.
|
||||
if isinstance(ctx.ui, TuiUi):
|
||||
from ..ui.contactlist import CONTACTS_SORT_COLUMNS, CONTACTS_SORT_OPENS_ASCENDING
|
||||
from ..ui.contacts_screen import open_contacts
|
||||
|
||||
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)})
|
||||
|
||||
sort = ContactsSort.from_name(sort_name)
|
||||
# The CLI reads the stored places only. It never starts the job that finds them.
|
||||
places = getattr(ctx, "places", None)
|
||||
place_of = _place_lookup(places.get) if places is not None else None
|
||||
listing = _listing(
|
||||
ordered_contacts(contacts, counts, sort),
|
||||
ordered_contacts(
|
||||
contacts,
|
||||
counts,
|
||||
sort,
|
||||
(lambda c: _place_label(place_of(c))) if place_of else None,
|
||||
),
|
||||
counts,
|
||||
prefix_bytes,
|
||||
places.get if places is not None else None,
|
||||
place_of,
|
||||
)
|
||||
return ToolResult(
|
||||
summary={"contacts": len(contacts)},
|
||||
@@ -113,29 +123,46 @@ class ContactsTool(Tool):
|
||||
app: The Typer application.
|
||||
"""
|
||||
from ..cli import run_tool_command
|
||||
from ..ui.widgets import ContactsSort
|
||||
from ..ui.widgets import CONTACTS_SORT_COLUMNS, ContactsSort
|
||||
|
||||
@app.command(name=self.name, help=self.help)
|
||||
def _contacts(
|
||||
sort: str = typer.Option(
|
||||
"heard", "--sort", "-s", help="Order contacts by: heard, name, packets"
|
||||
"heard",
|
||||
"--sort",
|
||||
"-s",
|
||||
help="Order contacts by: heard, name, packets, place, hash",
|
||||
),
|
||||
) -> None:
|
||||
# For an unknown name, `ContactsSort.from_name` uses the first column. This is
|
||||
# on purpose, so that a saved preference from an older build cannot block the
|
||||
# list of the menu. On the command line, the same silence hides a typing error:
|
||||
# the caller asked for one order and got another, and nothing said so.
|
||||
if sort not in ContactsSort.names():
|
||||
choices = ", ".join(ContactsSort.names())
|
||||
if sort not in ContactsSort.names(CONTACTS_SORT_COLUMNS):
|
||||
choices = ", ".join(ContactsSort.names(CONTACTS_SORT_COLUMNS))
|
||||
raise typer.BadParameter(f"--sort must be one of: {choices} (got {sort!r})")
|
||||
run_tool_command(self, {"sort": sort})
|
||||
|
||||
|
||||
def _place_lookup(get: Callable[[str], Place | None]) -> Callable[[Contact], Place | None]:
|
||||
"""Give the stored place of a contact, from a lookup by key (or key prefix)."""
|
||||
|
||||
def place_of(contact: Contact) -> Place | None:
|
||||
return get((contact.public_key or contact.key_prefix).lower())
|
||||
|
||||
return place_of
|
||||
|
||||
|
||||
def _place_label(place: Place | None) -> str | None:
|
||||
"""The full label of a place (``Villeray, Montréal``), or ``None`` for no place."""
|
||||
return (place.label or None) if place else None
|
||||
|
||||
|
||||
def _listing(
|
||||
contacts: list[Contact],
|
||||
counts: dict[str, int],
|
||||
prefix_bytes: int,
|
||||
place_of: Callable[[str], Place | None] | None = None,
|
||||
place_of: Callable[[Contact], Place | None] | None = None,
|
||||
) -> Listing:
|
||||
"""The contact list, stated one time for the two faces.
|
||||
|
||||
@@ -155,8 +182,8 @@ def _listing(
|
||||
prefix_bytes: The path hash width of the device. Because of it, ``HASH`` is the
|
||||
token by which a forced path addresses this node, not a random part of the
|
||||
key.
|
||||
place_of: Gives the stored place of a key, or ``None``. ``PLACE`` is the label of
|
||||
that place, and it is ``null`` in the document when there is none.
|
||||
place_of: Gives the stored place of a contact, or ``None``. ``PLACE`` is the label
|
||||
of that place, and it is ``null`` in the document when there is none.
|
||||
|
||||
Returns:
|
||||
The listing.
|
||||
@@ -168,7 +195,7 @@ def _listing(
|
||||
rows = []
|
||||
for contact in contacts:
|
||||
key = (contact.public_key or "").lower()
|
||||
place = place_of(key or contact.key_prefix) if place_of else None
|
||||
place = place_of(contact) if place_of else None
|
||||
rows.append(
|
||||
{
|
||||
"node": fields.NodeRef(
|
||||
@@ -176,7 +203,7 @@ def _listing(
|
||||
key=key or None,
|
||||
hash=(key or contact.key_prefix.lower())[: prefix_bytes * 2] or None,
|
||||
type=NODE_TYPE_LABELS.get(contact.node_type),
|
||||
place=(place.label or None) if place else None,
|
||||
place=_place_label(place),
|
||||
),
|
||||
"heard_at": contact.last_seen,
|
||||
"packets": contact_packets(contact, counts),
|
||||
|
||||
@@ -4,9 +4,11 @@
|
||||
An archive sweep (refer to :mod:`~meshterm.ui.sweep_screen`) removes a contact from the
|
||||
*device*, which is the scarce resource, and keeps the contact here in full. This screen is
|
||||
where those contacts are. It has the same sortable and filterable lane layout as the
|
||||
Contacts list, with its own lane set (``NAME · ARCHIVED · KEY``,
|
||||
Contacts list, with its own lane set (``NAME · ARCHIVED · PLACE · KEY``,
|
||||
:data:`~meshterm.ui.contactlist.ARCHIVED_LANES`) and its own sort ring over exactly those
|
||||
three columns.
|
||||
four columns. The rest is the same as on the Contacts list: the ``PLACE`` lane comes from
|
||||
the place service and fills in while the list is open, the filter matches a place, and no
|
||||
value is cut. A row that is wider than the terminal pans with ←→.
|
||||
|
||||
The ``ARCHIVED`` lane is drawn in the same way as ``HEARD`` on the main list: a relative
|
||||
age in the recency heat colours. It answers the same type of question about a different
|
||||
@@ -41,6 +43,7 @@ from .widgets import ContactsSort
|
||||
if TYPE_CHECKING:
|
||||
from ..context import AppContext
|
||||
from ..core.contact_store import RememberedContact
|
||||
from ..services.places import PlaceService
|
||||
|
||||
#: The footer of the list: navigation, the sort, the filter, then Esc last. The hint has
|
||||
#: ``Enter open`` because a row pushes the detail page of the node. The Contacts list uses
|
||||
@@ -91,7 +94,13 @@ def archived_rows(archived: list[RememberedContact]) -> list[ContactRow]:
|
||||
class ArchivedScreen(ContactListScreen):
|
||||
"""A full-screen, sortable list of the contacts that a sweep took off this device."""
|
||||
|
||||
def __init__(self, rows: list[ContactRow], prefix_bytes: int, sort: ContactsSort) -> None:
|
||||
def __init__(
|
||||
self,
|
||||
rows: list[ContactRow],
|
||||
prefix_bytes: int,
|
||||
sort: ContactsSort,
|
||||
places: PlaceService | None = None,
|
||||
) -> None:
|
||||
"""Build the list over rows that MeshTerm already resolved.
|
||||
|
||||
Args:
|
||||
@@ -99,6 +108,8 @@ class ArchivedScreen(ContactListScreen):
|
||||
prefix_bytes: The path hash width in bytes to highlight in each key.
|
||||
sort: The sort. The Ctrl+arrows change it in place. Its ring should span
|
||||
:data:`~meshterm.ui.contactlist.ARCHIVED_SORT_COLUMNS`.
|
||||
places: The places of the nodes, for the ``PLACE`` lane and for the filter. With
|
||||
``None``, the lane shows a faint ``—`` in each row.
|
||||
"""
|
||||
super().__init__(
|
||||
f"Archived contacts · {len(rows)} kept",
|
||||
@@ -108,6 +119,8 @@ class ArchivedScreen(ContactListScreen):
|
||||
prompt=("Off the device, kept here with their history. Open one to restore it."),
|
||||
footer_hint=_HINT,
|
||||
lanes=ARCHIVED_LANES,
|
||||
pan=True,
|
||||
places=places,
|
||||
)
|
||||
|
||||
|
||||
@@ -150,7 +163,7 @@ async def open_archived(ctx: AppContext, self_key: str, prefix_bytes: int) -> bo
|
||||
# note that MeshTerm shows when the user goes back.
|
||||
ctx.ui.note("[muted]no archived contacts[/muted]")
|
||||
return changed
|
||||
screen = ArchivedScreen(rows, prefix_bytes, sort)
|
||||
screen = ArchivedScreen(rows, prefix_bytes, sort, getattr(ctx, "places", None))
|
||||
rebuild = False
|
||||
async with session.stay(screen) as visit:
|
||||
while True:
|
||||
|
||||
+71
-31
@@ -19,7 +19,7 @@ starts with the name and ends with the key. These two lanes are what a contact *
|
||||
flexible widths are built around them. Each list declares the middle lanes that it wants as
|
||||
a tuple of :class:`ContactLane` (:data:`DEFAULT_LANES` for ``NAME · HEARD · PKTS · KEY``,
|
||||
:data:`TRACE_LANES` for the extra ``TRACED`` of the Trace picker, :data:`ARCHIVED_LANES` for
|
||||
the single ``ARCHIVED`` of the Archived list).
|
||||
the ``ARCHIVED`` and ``PLACE`` of the Archived list).
|
||||
|
||||
A lane has its own sort ring id, header label, width, and the way to read its value from a
|
||||
row. Thus to add a lane is a declaration, not a branch: the header, the row builder, the
|
||||
@@ -27,12 +27,18 @@ sort metric, and the calculation of the lane widths all read the same tuple. The
|
||||
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.
|
||||
**A list can show every value in full.** The Contacts list and the Archived list pass
|
||||
``pan=True``. Their 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.
|
||||
|
||||
**A list with the** ``PLACE`` **lane reads its places from the place service.** The caller
|
||||
gives the service (``places``), and the list fills the place of each row from the key of
|
||||
the row. The service counts its changes. When a place arrives while the list is open, the
|
||||
next paint fills the rows again, and the highlight, the sort, the filter, and the pan stay.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -41,7 +47,7 @@ import dataclasses
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from rich.cells import cell_len
|
||||
from rich.text import Text
|
||||
@@ -60,6 +66,9 @@ from .widgets import (
|
||||
highlighted_hash,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - typing only
|
||||
from ..services.places import PlaceService
|
||||
|
||||
#: The minimum width of the name lane (on a very narrow terminal), so that the ``NAME``
|
||||
#: label of the header and its sort triangle always have space.
|
||||
_NAME_MIN = 6
|
||||
@@ -127,7 +136,7 @@ PKTS_LANE = ContactLane("packets", "PKTS", 5, "count", kind="count")
|
||||
#: How long ago the node was last traced: the extra lane of the Trace-target picker.
|
||||
TRACED_LANE = ContactLane("traced", "TRACED", 6, "last_traced")
|
||||
|
||||
#: How long ago the contact was archived and removed from the device: the only lane of the
|
||||
#: How long ago the contact was archived and removed from the device: the first lane of the
|
||||
#: Archived list. It is drawn exactly as ``HEARD`` is, with the recency heat. It is the same
|
||||
#: question (how long ago did this occur) about a different event. A visual language of its
|
||||
#: own is a second grammar that the user must learn, with no benefit.
|
||||
@@ -147,10 +156,11 @@ 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)
|
||||
|
||||
#: The middle lanes of the Archived list: ``NAME · ARCHIVED · KEY``. There is no ``HEARD``
|
||||
#: and no ``PKTS``. An archived contact is not on the device, so this screen is not about
|
||||
#: what the contact still transmits. It is about when the contact left.
|
||||
ARCHIVED_LANES: tuple[ContactLane, ...] = (ARCHIVED_LANE,)
|
||||
#: The middle lanes of the Archived list: ``NAME · ARCHIVED · PLACE · KEY``. There is no
|
||||
#: ``HEARD`` and no ``PKTS``. An archived contact is not on the device, so this screen is not
|
||||
#: about what the contact still transmits. It is about when the contact left, and where it
|
||||
#: is. The ``PLACE`` lane is the same as on the Contacts screen, immediately before the key.
|
||||
ARCHIVED_LANES: tuple[ContactLane, ...] = (ARCHIVED_LANE, PLACE_LANE)
|
||||
|
||||
|
||||
def _row_marks(row: ContactRow) -> str:
|
||||
@@ -197,19 +207,6 @@ 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
|
||||
@@ -231,14 +228,17 @@ TRACE_SORT_OPENS_ASCENDING: dict[str, bool] = {
|
||||
"hash": True,
|
||||
}
|
||||
|
||||
#: The sort ring of the Archived list: ``NAME · ARCHIVED · KEY``, the same as
|
||||
#: The sort ring of the Archived list: ``NAME · ARCHIVED · PLACE · KEY``, the same as
|
||||
#: :data:`ARCHIVED_LANES`. ``archived`` opens *ascending* on the age of the lane, so the
|
||||
#: most recently archived contacts come first. This screen answers the question "what did
|
||||
#: that sweep just take?", and the answer must be at the top of the screen.
|
||||
ARCHIVED_SORT_COLUMNS: tuple[str, ...] = ("name", "archived", "hash")
|
||||
#: that sweep just take?", and the answer must be at the top of the screen. ``place`` sorts
|
||||
#: as on the Contacts screen (refer to
|
||||
#: :data:`~meshterm.ui.widgets.CONTACTS_SORT_OPENS_ASCENDING`).
|
||||
ARCHIVED_SORT_COLUMNS: tuple[str, ...] = ("name", "archived", "place", "hash")
|
||||
ARCHIVED_SORT_OPENS_ASCENDING: dict[str, bool] = {
|
||||
"name": True,
|
||||
"archived": True,
|
||||
"place": True,
|
||||
"hash": True,
|
||||
}
|
||||
|
||||
@@ -607,6 +607,12 @@ class ContactListScreen(SelectScreen):
|
||||
|
||||
floating = False
|
||||
|
||||
#: 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. Only a list that pans has the atom.
|
||||
spare_hint_atoms = ("←→ scroll",)
|
||||
|
||||
@property
|
||||
def picocalc_lyra_lane(self):
|
||||
"""The F-key lane of the select list, with the full sort added on F3/F8.
|
||||
@@ -652,6 +658,7 @@ class ContactListScreen(SelectScreen):
|
||||
lanes: tuple[ContactLane, ...] = DEFAULT_LANES,
|
||||
key_hint: Callable[[Any], str] | None = None,
|
||||
pan: bool = False,
|
||||
places: PlaceService | None = None,
|
||||
) -> None:
|
||||
"""Build the list over rows that are already resolved.
|
||||
|
||||
@@ -687,7 +694,14 @@ class ContactListScreen(SelectScreen):
|
||||
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.
|
||||
places: The places of the nodes, for a list whose ``lanes`` have the ``PLACE``
|
||||
lane. The list fills the place of each row from its key, and fills them
|
||||
again when the service counts a change (refer to :meth:`render_body`).
|
||||
With ``None``, each row keeps the place that the caller gave it.
|
||||
"""
|
||||
self._places = places if PLACE_LANE in lanes else None
|
||||
self._place_rev = self._places.revision if self._places is not None else 0
|
||||
rows = self._with_places(rows)
|
||||
self._contact_rows = rows
|
||||
self._prefix_bytes = prefix_bytes
|
||||
self._sort = sort
|
||||
@@ -780,9 +794,26 @@ class ContactListScreen(SelectScreen):
|
||||
Args:
|
||||
rows: The lane data of each contact, as :meth:`__init__` accepts it.
|
||||
"""
|
||||
self._contact_rows = rows
|
||||
self._contact_rows = self._with_places(rows)
|
||||
self._rebuild()
|
||||
|
||||
def _with_places(self, rows: list[ContactRow]) -> list[ContactRow]:
|
||||
"""The rows with the place of each node from the place service, if the list has one.
|
||||
|
||||
The key of the row finds the place. A row without a full key uses the key prefix of
|
||||
its contact. A node with no known place gets ``None``, and its lane shows a faint
|
||||
``—``.
|
||||
"""
|
||||
if self._places is None:
|
||||
return rows
|
||||
filled = []
|
||||
for row in rows:
|
||||
key = row.key or getattr(row.value, "key_prefix", None)
|
||||
place = self._places.get(key) if key else None
|
||||
label = (place.label or None) if place is not None else None
|
||||
filled.append(dataclasses.replace(row, place=label))
|
||||
return filled
|
||||
|
||||
def _rebuild(self) -> None:
|
||||
"""Rebuild the rows for the current sort and width, with the highlight on its contact."""
|
||||
current = self._current_choice()
|
||||
@@ -861,7 +892,16 @@ class ContactListScreen(SelectScreen):
|
||||
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."""
|
||||
"""Size the name lane to its content and adjust the key lane, then render 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 list reads again only after a change. The
|
||||
highlight, the sort, the filter, and the pan stay (refer to :meth:`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)
|
||||
name_w, hash_w = self._lane_widths(width)
|
||||
anchor = self._pinned_head(name_w, width)
|
||||
if (name_w, hash_w, anchor) != (self._name_w, self._hash_w, self._anchor):
|
||||
|
||||
@@ -88,12 +88,6 @@ 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.
|
||||
@@ -160,12 +154,11 @@ class ContactsScreen(ContactListScreen):
|
||||
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`).
|
||||
``None``, the lane shows a faint ``—`` in each row. The list draws the
|
||||
rows again when a place changes (refer to
|
||||
:meth:`~meshterm.ui.contactlist.ContactListScreen.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
|
||||
@@ -214,21 +207,14 @@ class ContactsScreen(ContactListScreen):
|
||||
key_hint=lambda value: "^L map" if self._marker_of(value) is not None else "",
|
||||
lanes=CONTACTS_LANES,
|
||||
pan=True,
|
||||
places=places,
|
||||
)
|
||||
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,
|
||||
place=self._place_of(self._self_key),
|
||||
)
|
||||
]
|
||||
rows = [ContactRow(value=YOU, name=self._self_name, key=self._self_key, you=True)]
|
||||
for c in self._contacts:
|
||||
rows.append(
|
||||
ContactRow(
|
||||
@@ -240,33 +226,12 @@ 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:
|
||||
|
||||
+41
-2
@@ -1381,6 +1381,22 @@ def contact_packets(contact: Contact, counts: dict[str, int]) -> int | None:
|
||||
_SORT_COLUMNS: tuple[str, ...] = ("name", "heard", "packets")
|
||||
_SORT_OPENS_ASCENDING: dict[str, bool] = {"name": True, "heard": True, "packets": False}
|
||||
|
||||
#: The sort ring of the Contacts list, on the screen and on the CLI (``contacts --sort``).
|
||||
#: It adds a ``place`` column between ``packets`` and ``hash``, the same order as the lanes
|
||||
#: of the screen. ``place`` 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. ``hash`` sorts on the key of the contact (ascending = ``0`` → ``f``).
|
||||
#: The ring is here and not in :mod:`~meshterm.ui.contactlist`, so that the CLI can read it
|
||||
#: and not load the TUI.
|
||||
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,
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class ContactsSort:
|
||||
@@ -1438,7 +1454,10 @@ class ContactsSort:
|
||||
|
||||
|
||||
def ordered_contacts(
|
||||
contacts: list[Contact], counts: dict[str, int], sort: ContactsSort
|
||||
contacts: list[Contact],
|
||||
counts: dict[str, int],
|
||||
sort: ContactsSort,
|
||||
place_of: Callable[[Contact], str | None] | None = None,
|
||||
) -> list[Contact]:
|
||||
"""The contacts, sorted as ``sort`` says (our node is pinned separately, above these).
|
||||
|
||||
@@ -1446,7 +1465,16 @@ def ordered_contacts(
|
||||
always breaks by the case-folded name, *ascending*. Thus two contacts with the same
|
||||
metric (for example the same ``heard`` age) keep a stable A→Z order, and the order does
|
||||
not flip with the primary direction. The rows that were never heard or never overheard
|
||||
have an extreme metric, so they gather at the ascending end.
|
||||
have an extreme metric, so they gather at the ascending end. A contact with no place
|
||||
does the same in a sort by ``place``.
|
||||
|
||||
Args:
|
||||
contacts: The contacts to sort.
|
||||
counts: The counts of overheard packets, keyed by node id.
|
||||
sort: The column and the direction.
|
||||
place_of: Gives the place label of a contact (``Villeray, Montréal``), or ``None``.
|
||||
Without it, no contact has a place, and a sort by ``place`` keeps the A→Z order
|
||||
of the names.
|
||||
"""
|
||||
if sort.column == "heard":
|
||||
# Use one clock snapshot for the whole sort. If each row calls utcnow(), two
|
||||
@@ -1462,6 +1490,17 @@ def ordered_contacts(
|
||||
|
||||
def metric(c: Contact) -> float:
|
||||
return contact_packets(c, counts) or 0
|
||||
elif sort.column == "place":
|
||||
|
||||
def metric(c: Contact) -> object:
|
||||
# A blank place sorts after each text (its first key is larger), the same as
|
||||
# the place lane of the Contacts screen.
|
||||
label = place_of(c) if place_of is not None else None
|
||||
return (0, label.casefold()) if label else (1, "")
|
||||
elif sort.column == "hash":
|
||||
|
||||
def metric(c: Contact) -> object:
|
||||
return (c.public_key or c.key_prefix).lower()
|
||||
else:
|
||||
|
||||
def metric(c: Contact) -> object:
|
||||
|
||||
@@ -342,6 +342,13 @@ def test_a_global_option_taking_a_value_moves_with_its_value(run) -> None: # no
|
||||
assert run("contacts", "--sort", "name", "--json").exit_code == exitcodes.OK
|
||||
|
||||
|
||||
@pytest.mark.parametrize("order", ["place", "hash"])
|
||||
def test_contacts_sorts_by_each_column_of_the_screen(run, order) -> None: # noqa: ANN001
|
||||
"""``--sort`` accepts each sort column of the Contacts screen, the place and the hash too."""
|
||||
result = run("contacts", "--sort", order, "--json")
|
||||
assert result.exit_code == exitcodes.OK, result.output
|
||||
|
||||
|
||||
def test_lifting_a_global_never_steals_a_subcommands_own_help(run) -> None: # noqa: ANN001
|
||||
"""``contacts --help`` must stay the help of ``contacts``, not the help of the app.
|
||||
|
||||
|
||||
@@ -14,15 +14,13 @@ 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 (
|
||||
from meshterm.ui.contactlist import PLACE_LANE, ContactListScreen, ContactRow
|
||||
from meshterm.ui.contacts_screen import ContactsScreen
|
||||
from meshterm.ui.widgets import (
|
||||
CONTACTS_SORT_COLUMNS,
|
||||
CONTACTS_SORT_OPENS_ASCENDING,
|
||||
PLACE_LANE,
|
||||
ContactListScreen,
|
||||
ContactRow,
|
||||
ContactsSort,
|
||||
)
|
||||
from meshterm.ui.contacts_screen import ContactsScreen
|
||||
from meshterm.ui.widgets import ContactsSort
|
||||
|
||||
_ANSI = re.compile(r"\x1b\[[0-9;]*m")
|
||||
|
||||
@@ -215,6 +213,71 @@ def test_lists_without_the_lane_are_unchanged() -> None:
|
||||
assert "Villeray" not in _row(screen, 100, "Alice")
|
||||
|
||||
|
||||
# -- part 1b: the Archived list ------------------------------------------------------
|
||||
|
||||
|
||||
def _archived(places: _Places | None = None, sort: str = "name") -> ContactListScreen:
|
||||
"""The Archived list over Alice, Bob, and Carl, with the place service of the test."""
|
||||
from meshterm.core.contact_store import RememberedContact
|
||||
from meshterm.ui.archived_screen import ArchivedScreen, archived_rows
|
||||
from meshterm.ui.contactlist import ARCHIVED_SORT_COLUMNS, ARCHIVED_SORT_OPENS_ASCENDING
|
||||
|
||||
remembered = [
|
||||
RememberedContact(public_key=_ALICE, name="Alice", archived_at=1_700_000_000),
|
||||
RememberedContact(public_key=_BOB, name="Bob", archived_at=1_700_000_000),
|
||||
RememberedContact(public_key=_CARL, name="Carl", archived_at=1_700_000_000),
|
||||
]
|
||||
order = ContactsSort.from_name(sort, ARCHIVED_SORT_COLUMNS, ARCHIVED_SORT_OPENS_ASCENDING)
|
||||
return ArchivedScreen(archived_rows(remembered), 1, order, places or _places())
|
||||
|
||||
|
||||
def _archived_names(screen: ContactListScreen) -> list[str]:
|
||||
"""The names in the order that the Archived list draws them."""
|
||||
drawn = _lines(screen, 200)
|
||||
order = ["Alice", "Bob", "Carl"]
|
||||
return sorted(order, key=lambda n: next(i for i, line in enumerate(drawn) if n in line))
|
||||
|
||||
|
||||
def test_archived_list_has_the_place_column_before_the_key() -> None:
|
||||
"""The Archived list reads NAME, ARCHIVED, PLACE, KEY, and shows each full label."""
|
||||
screen = _archived()
|
||||
header = next(line for line in _lines(screen, 200) if "NAME" in line)
|
||||
labels = [header.index(label) for label in ("NAME", "ARCHIVED", "PLACE", "KEY")]
|
||||
assert labels == sorted(labels)
|
||||
alice = _row(screen, 200, "Alice")
|
||||
assert "Villeray, Montréal" in alice
|
||||
assert alice.index("Villeray") < alice.index("aaaa")
|
||||
|
||||
|
||||
def test_archived_list_sorts_by_place() -> None:
|
||||
"""Ctrl+→ reaches the place column. Places run A to Z, and a node with none runs last."""
|
||||
screen = _archived(sort="archived")
|
||||
screen.handle("ctrl_right")
|
||||
assert screen._sort.column == "place" # noqa: SLF001
|
||||
assert _archived_names(screen) == ["Bob", "Alice", "Carl"]
|
||||
screen.handle("ctrl_down")
|
||||
assert _archived_names(screen) == ["Carl", "Alice", "Bob"]
|
||||
|
||||
|
||||
def test_archived_list_fills_a_found_place_and_filters_by_place() -> None:
|
||||
"""A place that arrives while the list is open draws, and the filter matches it."""
|
||||
places = _places()
|
||||
screen = _archived(places)
|
||||
places.found[_CARL[:12]] = Place("Verdun", "Montréal", SOURCE_TILES)
|
||||
places.revision += 1
|
||||
assert "Verdun, Montréal" in _row(screen, 200, "Carl")
|
||||
_type(screen, "verdun")
|
||||
shown = "\n".join(_lines(screen, 200))
|
||||
assert "Carl" in shown
|
||||
assert "Alice" not in shown and "Bob" not in shown
|
||||
|
||||
|
||||
def test_archived_list_cuts_no_value() -> None:
|
||||
"""The Archived list pans as the Contacts list does, so a narrow terminal cuts no key."""
|
||||
screen = _archived()
|
||||
assert all(choice.pans for choice in screen._choices()) # noqa: SLF001
|
||||
|
||||
|
||||
# -- part 2: the filter ---------------------------------------------------------------
|
||||
|
||||
|
||||
@@ -247,14 +310,45 @@ def test_filter_matches_the_coarse_part_of_the_place() -> None:
|
||||
# -- part 3: the CLI and the machine object -------------------------------------------
|
||||
|
||||
|
||||
def _cli_contacts(place_of): # noqa: ANN001, ANN202 - a lookup function or None
|
||||
from meshterm.tools.contacts import _listing
|
||||
def _cli_contacts(get): # noqa: ANN001, ANN202 - a lookup by key, or None
|
||||
from meshterm.tools.contacts import _listing, _place_lookup
|
||||
|
||||
contacts = [
|
||||
Contact(name="Alice", public_key=_ALICE, key_prefix=_ALICE[:12]),
|
||||
Contact(name="Carl", public_key=_CARL, key_prefix=_CARL[:12]),
|
||||
]
|
||||
return _listing(contacts, {}, 1, place_of)
|
||||
return _listing(contacts, {}, 1, _place_lookup(get) if get else None)
|
||||
|
||||
|
||||
def _cli_order(sort: str, ascending: bool | None = None) -> list[str]:
|
||||
"""The names in the order that the CLI lists them for ``sort``."""
|
||||
from meshterm.tools.contacts import _place_label, _place_lookup
|
||||
from meshterm.ui.widgets import ordered_contacts
|
||||
|
||||
contacts = [
|
||||
Contact(name="Alice", public_key=_ALICE, key_prefix=_ALICE[:12]),
|
||||
Contact(name="Bob", public_key=_BOB, key_prefix=_BOB[:12]),
|
||||
Contact(name="Carl", public_key=_CARL, key_prefix=_CARL[:12]),
|
||||
]
|
||||
order = _sort(sort)
|
||||
if ascending is not None:
|
||||
order.ascending = ascending
|
||||
place_of = _place_lookup(_places().get)
|
||||
ordered = ordered_contacts(contacts, {}, order, lambda c: _place_label(place_of(c)))
|
||||
return [c.name for c in ordered]
|
||||
|
||||
|
||||
def test_cli_sorts_by_place() -> None:
|
||||
"""``--sort place`` runs A to Z on the label, and a contact with no place runs last."""
|
||||
assert _cli_order("place") == ["Bob", "Alice", "Carl"]
|
||||
# Descending turns the order over, and the contact with no place comes first.
|
||||
assert _cli_order("place", ascending=False) == ["Carl", "Alice", "Bob"]
|
||||
|
||||
|
||||
def test_cli_sorts_by_hash() -> None:
|
||||
"""``--sort hash`` runs on the key, from ``0`` to ``f``."""
|
||||
assert _cli_order("hash") == ["Alice", "Bob", "Carl"]
|
||||
assert _cli_order("hash", ascending=False) == ["Carl", "Bob", "Alice"]
|
||||
|
||||
|
||||
def _render(face, listing): # noqa: ANN001, ANN202 - the renderer class
|
||||
|
||||
@@ -250,9 +250,9 @@ async def test_contacts_tool_opens_sorted_by_heard(monkeypatch: pytest.MonkeyPat
|
||||
captured: dict = {}
|
||||
real_order = widgets.ordered_contacts
|
||||
|
||||
def fake_order(contacts, counts, sort): # noqa: ANN001, ANN202
|
||||
def fake_order(contacts, counts, sort, place_of=None): # noqa: ANN001, ANN202
|
||||
captured["sort"] = sort
|
||||
return real_order(contacts, counts, sort)
|
||||
return real_order(contacts, counts, sort, place_of)
|
||||
|
||||
monkeypatch.setattr(widgets, "ordered_contacts", fake_order)
|
||||
|
||||
|
||||
@@ -1946,8 +1946,9 @@ _PREEXISTING_REGULAR_OVERFLOW: set[str] = set()
|
||||
#: decision. ``courier_outbox``: JP, 2026-10-22, "bring the filter back, tough luck if it
|
||||
#: 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"}
|
||||
#: go when the footer is full (``ContactListScreen.spare_hint_atoms``). ``archived``: the
|
||||
#: same list and the same hint (JP, 2026-11-03: "same behavior as contacts list").
|
||||
_SHEDS_ITS_HINT: set[str] = {"courier_outbox", "contacts", "archived"}
|
||||
|
||||
|
||||
#: The specimens by name, for a test that needs one entry and not the whole sweep.
|
||||
|
||||
Reference in new issue
Block a user