From b40caf68919e061917ad916b73d6cf274993625e Mon Sep 17 00:00:00 2001 From: Jean-Pierre Martineau Date: Sat, 18 Jul 2026 19:41:26 -0400 Subject: [PATCH] Nodes screen: the Time Machine picker's node list, now shared The picker's lane layout - NAME/HEARD/PKTS/HASH under a sort-aware header, own node pinned, Ctrl+arrow sorting, type-to-filter, a content-sized name lane flexing the hash lane - moves to a shared ui/nodelist.py (NodeRow + NodeListScreen). The Time Machine picker becomes a thin subclass over stored history; the Nodes screen is rebuilt as the same list over the device's contacts, replacing its plain-arrow-sorted table (its ring gains the hash column). Enter is deliberately inert on the Nodes screen for now - per-node actions come later. The one-shot CLI keeps the static table. Co-Authored-By: Claude Fable 5 --- meshterm/tools/nodes.py | 10 +- meshterm/ui/nodelist.py | 406 ++++++++++++++++++++++++++++++ meshterm/ui/nodes_screen.py | 181 +++++-------- meshterm/ui/timemachine_screen.py | 401 ++++------------------------- tests/test_device_config.py | 86 ++++--- tests/test_timemachine.py | 58 +++-- 6 files changed, 601 insertions(+), 541 deletions(-) create mode 100644 meshterm/ui/nodelist.py diff --git a/meshterm/tools/nodes.py b/meshterm/tools/nodes.py index 22228bb..a9b3333 100644 --- a/meshterm/tools/nodes.py +++ b/meshterm/tools/nodes.py @@ -56,15 +56,19 @@ class NodesTool(Tool): self_name = str(info.get("name") or "this node") self_key = str(info.get("public_key") or "") - sort = NodesSort.from_name(str(params.get("sort") or "name")) + sort_name = str(params.get("sort") or "name") - # In the menu, hand the list to the interactive screen so the arrows re-sort it live; - # on the scripted CLI, render the table once in the requested order. + # In the menu, hand the list to the interactive screen so the Ctrl+arrows re-sort it + # live — its ring spans the shared node list's four columns (hash included); on the + # scripted CLI, render the static table once in the requested order. if isinstance(ctx.ui, TuiUi): + from ..ui.nodelist import SORT_COLUMNS, SORT_OPENS_ASCENDING from ..ui.nodes_screen import open_nodes + sort = NodesSort.from_name(sort_name, SORT_COLUMNS, SORT_OPENS_ASCENDING) await open_nodes(ctx, self_name, self_key, contacts, prefix_bytes, counts, sort) else: + sort = NodesSort.from_name(sort_name) ctx.ui.show(nodes_table(self_name, self_key, contacts, prefix_bytes, counts, sort)) return ToolResult(summary={"contacts": len(contacts)}) diff --git a/meshterm/ui/nodelist.py b/meshterm/ui/nodelist.py new file mode 100644 index 0000000..c6fe5cc --- /dev/null +++ b/meshterm/ui/nodelist.py @@ -0,0 +1,406 @@ +"""The shared node list: one sortable, filterable lane layout for every screenful of nodes. + +Extracted from the Time Machine's subject picker so the app has exactly one way to draw "a +full-screen list of nodes": aligned ``NAME · HEARD · PKTS · HASH`` lanes under a sort-aware +column header, our own node pinned first, the sort riding the Ctrl+arrows (plain arrows keep +the highlight, letters keep type-to-filter), and the name lane sized to its content so the +columns anchor left while the hash lane soaks up the rest of the terminal. The Time Machine +picker and the Nodes screen both build on :class:`NodeListScreen`; each hands its rows over +as :class:`NodeRow` values — however it learned them (stored history, the device's contact +table) — so the two lists render, sort, and steer identically without sharing a data source. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from datetime import datetime +from typing import Optional + +from rich.cells import cell_len +from rich.text import Text + +from .map_render import _SELF +from .menus import fit_cells +from .tui.select import Choice, SelectScreen, Separator +from .widgets import ( + _DEFAULT_GLYPH, + _NODE_GLYPHS, + _age_seconds, + _format_age, + _recency_style, + highlighted_hash, + NodesSort, +) + +#: The narrowest the name lane shrinks to (a very narrow terminal), so the header's ``NAME`` +#: label and its sort triangle always have somewhere to sit. +_NAME_MIN = 6 + +#: The hash lane's floor in cells — four leading bytes plus an ellipsis, still a recognisable +#: prefix on a very narrow terminal. The lane otherwise flexes to fill whatever width the +#: (content-sized) name lane leaves, so a longer key — our own 64-hex node key, or a full key +#: resolved from a contact — shows as many whole bytes as fit, ellipsized past that (see +#: :func:`~meshterm.ui.widgets.highlighted_hash`). +_HASH_MIN = 8 + +#: Everything in a row *besides* the name and hash lanes, in cells: the select pointer (2), +#: the type glyph and its space (2), then the two gapped fixed lanes — heard (2 gap + 5) and +#: packets (2 gap + 5) — and the 3-cell gap before the hash. The name lane is content-sized +#: and the hash lane takes the rest (see :meth:`NodeListScreen._lane_widths`). +_LEAD = 2 + 2 + (2 + 5) + (2 + 5) + 3 + +#: The muted ``(you)`` tag on the own-node lane (see :func:`_lane`), its width folded into +#: the name lane's content sizing so the tag never truncates. +_YOU_TAG = " (you)" + +#: The sort ring and each column's natural opening direction — name A→Z, most-recently-heard +#: first, most packets first, and ``hash`` on the node's key (ascending = ``0`` → ``f``). +#: Callers build their :class:`~meshterm.ui.widgets.NodesSort` over these so the Ctrl+arrows +#: walk the same four columns on every node list. +SORT_COLUMNS: tuple[str, ...] = ("name", "heard", "packets", "hash") +SORT_OPENS_ASCENDING: dict[str, bool] = { + "name": True, "heard": True, "packets": False, "hash": True, +} + +#: The cyan the active sort column and its triangle are lit in, matching the static Nodes +#: table's header (see :func:`~meshterm.ui.widgets._sort_header`) so sort cues read +#: identically everywhere. +_SORT_ACTIVE = "bold #22d3ee" + +#: The default footer: navigation, the Ctrl+arrow sort, filtering, then Esc last. +_HINT = "↑↓ move · ^←→↑↓ sort · type filter · Enter open · Esc back" + + +@dataclass +class NodeRow: + """One node's lane data, however the caller learned it. + + Attributes: + value: What the row's :class:`~meshterm.ui.tui.select.Choice` resolves with — + also the identity a re-sort uses to keep the highlight on its node, so it + should be unique across the list. + name: The display name; ``None`` renders the heat-coloured ``unknown`` (an + own-node row falls back to a bare ``you`` instead). + key: The hex the hash lane shows — as full a key as the caller could resolve; + empty renders a muted ``?``. + node_type: The node's type for the leading glyph (``None`` = the plain-node + ``●``; ignored on the own-node row, which always leads with the yellow ``★``). + last_seen: When the node was last heard (aware UTC) — colours the name by recency + heat and fills the heard lane; ``None`` reads ``never`` and the cold style. + count: The packet tally; ``None`` renders a faint ``—`` (never overheard). + you: Whether this is our own node: the ``★`` marker, the pure-white ``you`` name + style with a muted ``(you)`` tag, faint ``—`` heard/packet lanes (we never + overhear ourselves), pinned above the sorted block whatever the sort. + """ + + value: object + name: Optional[str] + key: str = "" + node_type: Optional[int] = None + last_seen: Optional[datetime] = None + count: Optional[int] = None + you: bool = False + + +def _header(name_w: int, sort: NodesSort) -> Text: + """Column labels over the node lanes (see :func:`_lane`). + + The lanes read ``NAME · HEARD · PKTS · HASH``, matching the row builder. The four + leading spaces cover the select screen's pointer column (2 cells) plus the one-cell + type glyph and its gap, so each label lands over its lane. + + All four columns are sortable, so any one can be the active sort. The active column's + label *and* its direction triangle (``▲`` ascending, ``▼`` descending) are lit cyan + together — the same cue the static Nodes table's + :func:`~meshterm.ui.widgets._sort_header` lights — and the triangle is drawn *into the + two-cell reserve that already follows every label*, so switching the sort never widens + a lane and shifts the rest of the row. Returned as a :class:`~rich.text.Text` (not a + plain string) so just the active column carries the colour while the rest stays muted. + """ + + def column(header: Text, label: str, key: str, *, pad_to: int = 0) -> None: + """Append one column: its label plus a two-cell mark reserve, lit when it's the sort.""" + if key == sort.column: + cell = f"{label} " + ("▲" if sort.ascending else "▼") + header.append(cell, style=_SORT_ACTIVE) + else: + cell = f"{label} " + header.append(cell, style="muted") + if pad_to: # left-justify the flexing name lane; the pad stays muted + header.append(" " * max(0, pad_to - cell_len(cell)), style="muted") + + header = Text(" ", style="muted") # pointer (2) + the row's type glyph and gap (2) + column(header, "NAME", "name", pad_to=name_w) + header.append(" ", style="muted") # gap to the HEARD lane + column(header, "HEARD", "heard") + column(header, f"{'PKTS':>5}", "packets") + # HASH sits one cell further out than the other lanes so a packets-sort triangle — + # packets being the lane just before it — never abuts the hash label. + header.append(" ", style="muted") + column(header, "HASH", "hash") + return header + + +def _you_lane(row: NodeRow, name_w: int, prefix_bytes: int, hash_w: int) -> Text: + """Our own node's lane — laid out exactly like :func:`_lane`'s regular rows. + + Drawn like the map and the static table draw us: the ``★`` self marker (yellow), the + name in the pure-white ``you`` style with a muted ``(you)`` tag, and our key hash lit + at the routing width, filling the flexing hash lane — our 64-hex key is longer than + any lane, so it shows as many digits as fit and ellipsizes. The heard and packet lanes + read a faint ``—``: we never overhear ourselves, so there is no reception age or count + to show. With no reachable device to name us, the name falls back to a bare ``you`` + and the hash to ``?``. + """ + text = Text(no_wrap=True, overflow="ellipsis") + text.append(_SELF[0], style=_SELF[1]) + text.append(" ") + # The name lane, exactly name_w cells: the name (white) with a snug muted "(you)" tag — + # padded out to fill the lane — or, when the name alone would crowd out the tag, the + # name fit to the lane with the tag dropped. The lane is sized to hold the tag (see + # NodeListScreen._widest_name), so the drop is a very-long-name guard. + used = cell_len(row.name) + cell_len(_YOU_TAG) if row.name else 0 + if row.name and used <= name_w: + text.append(row.name, style="you") + text.append(_YOU_TAG, style="muted") + text.append(" " * (name_w - used)) + else: + text.append(fit_cells(row.name or "you", name_w), style="you") + text.append(" ") + text.append(f"{'—':>5}", style="faint") # heard: we don't hear ourselves + text.append(" ") + text.append(f"{'—':>5}", style="faint") # packets: nothing to count + text.append(" ") # the wider gap the header's HASH lane keeps (see _header) + if row.key: + text.append_text(highlighted_hash(row.key, prefix_bytes, width=hash_w)) + else: + text.append("?", style="muted") + return text + + +def _lane(row: NodeRow, name_w: int, prefix_bytes: int, hash_w: int) -> Text: + """One node as fixed, colour-coded lanes under :func:`_header`'s columns. + + The type glyph leads (the app's shared marker palette), so the mark reads ``▲`` for a + repeater, ``■`` for a room, ``◉`` for a sensor, ``●`` for a plain node. The name is + coloured by recency heat, ``unknown`` included, so a freshly heard mystery node still + reads hot, and takes the flexing name lane (``name_w`` cells). Last-heard age and + packet count follow, right-aligned under their headers — a node never overheard reads + a faint ``—`` in the packets lane; the hash closes the row in the shared hash widget, + its path-hash prefix lit at the device's routing width, or a muted ``?`` when no key + is known at all. An own-node row (:attr:`NodeRow.you`) takes its own drawing — + see :func:`_you_lane`. + + Args: + row: The node's lane data. + name_w: The name lane's width in cells (content-sized across the whole list). + prefix_bytes: Path-hash width in bytes to light in the hash. + hash_w: The flexing hash lane's width in cells (a short key pads out to it; see + :func:`~meshterm.ui.widgets.highlighted_hash`). + """ + if row.you: + return _you_lane(row, name_w, prefix_bytes, hash_w) + glyph, glyph_style = _NODE_GLYPHS.get(row.node_type, _DEFAULT_GLYPH) + secs = _age_seconds(row.last_seen) + text = Text(no_wrap=True, overflow="ellipsis") + text.append(glyph, style=glyph_style) + text.append(" ") + text.append(fit_cells(row.name or "unknown", name_w), style=_recency_style(secs)) + text.append(" ") + text.append(f"{_format_age(secs):>5}", style="muted") + text.append(" ") + if row.count is None: + text.append(f"{'—':>5}", style="faint") + else: + text.append(f"{min(row.count, 99999):>5}", style="muted") + text.append(" ") # the wider gap the header's HASH lane keeps (see _header) + if row.key: + text.append_text(highlighted_hash(row.key, prefix_bytes, width=hash_w)) + else: + text.append("?", style="muted") + return text + + +def _ordered(rows: list[NodeRow], sort: NodesSort) -> list[NodeRow]: + """Order the sortable rows by the active sort (own-node rows are pinned elsewhere). + + The four columns' natural metrics: name A→Z, ``heard`` by age so ascending is + most-recently-heard first (a never-heard row gathers at the old end), ``packets`` by + count, ``hash`` by the displayed key (ascending = ``0`` → ``f``). A name-ascending + pre-sort is the stable tiebreak, so two nodes sharing a metric keep an A→Z order + under both directions rather than flipping with the primary key. + """ + + def key_name(row: NodeRow) -> str: + return (row.name or "unknown").casefold() + + def metric(row: NodeRow): # noqa: ANN202 - homogeneous per sort + if sort.column == "name": + return key_name(row) + if sort.column == "packets": + return row.count or 0 + if sort.column == "hash": + return row.key + secs = _age_seconds(row.last_seen) # "heard": ascending = freshest first + return secs if secs is not None else float("inf") + + ordered = sorted(rows, key=key_name) + ordered.sort(key=metric, reverse=not sort.ascending) + return ordered + + +class NodeListScreen(SelectScreen): + """A full-screen, sortable, filterable node list in the shared lane layout. + + The rows run in aligned lanes — name (coloured by recency heat), last-heard age, + packet count, and key hash — own-node rows first, then the rest in the active sort + order. The lanes anchor to the left: the name lane is sized to its widest name (not + the terminal), so the columns stay put as the window widens and the freed width flows + to the hash lane, which shows each key as fully as it fits (see :meth:`_lane_widths`). + It is a full-screen list, not a floating popup. + + The sort rides the Ctrl+arrows, leaving the plain arrows for the highlight and the + letters for type-to-filter: **Ctrl+←/→** pick the column (name → heard → packets → + hash, each adopting its natural direction) and **Ctrl+↑/↓** force ascending/ + descending. Every change re-sorts the node block in place — the lead rows and headers + stay pinned, the highlight rides its node, and any active filter holds — the same + :class:`~meshterm.ui.widgets.NodesSort` model and cyan triangle cue the static Nodes + table uses, only its keys moved off the plain arrows that a filterable list already + spends. + """ + + floating = False + + def __init__( + self, + title: str, + *, + rows: list[NodeRow], + prefix_bytes: int, + sort: NodesSort, + prompt: str = "", + lead: Optional[list] = None, + footer_hint: str = _HINT, + ) -> None: + """Build the list over already-resolved rows. + + Args: + title: Short heading shown in the border. + rows: Every node's lane data; :attr:`NodeRow.you` rows are pinned first (in + the order given), the rest re-sorted here per ``sort``. + prefix_bytes: Path-hash width in bytes to light in each hash. + sort: The sort state, mutated in place by the Ctrl+arrows — pass the same + instance across re-opens so the chosen order persists. Its ring should + span :data:`SORT_COLUMNS` for the hash column to be reachable. + prompt: An optional instruction shown above the list. + lead: Rows (choices/separators) drawn above the column header — the Time + Machine's whole-mesh row and its section heading; ``None`` for none. + footer_hint: Footer key hint; the default advertises the full grammar. + """ + self._node_rows = rows + self._prefix_bytes = prefix_bytes + self._sort = sort + self._lead = list(lead) if lead else [] + # Provisional until the first render learns the true width (see render_body). + self._name_w = _NAME_MIN + self._hash_w = _HASH_MIN + super().__init__( + title, + self._compose_items(), + prompt=prompt, + footer_hint=footer_hint, + wrap=False, + ) + + def _compose_items(self) -> list: + """The lead rows, the sort-aware column header, then the node lanes. + + Own-node rows lead the lanes and stay first whatever the sort: only the block + below them reorders (see :func:`_ordered`).""" + items: list = list(self._lead) + items.append(Separator(_header(self._name_w, self._sort))) + pinned = [row for row in self._node_rows if row.you] + rest = [row for row in self._node_rows if not row.you] + for row in (*pinned, *_ordered(rest, self._sort)): + items.append( + Choice( + _lane(row, self._name_w, self._prefix_bytes, self._hash_w), + row.value, + ) + ) + return items + + def _rebuild(self) -> None: + """Recompose the rows for the current sort/width, keeping the highlight on its node.""" + current = self._current_choice() + keep = current.value if current is not None else None + self._items = self._compose_items() + self._reselect(keep) + + def _reselect(self, value: object) -> None: + """Move the highlight back onto the choice with ``value`` (else clamp it in range).""" + choices = self._choices() + for i, choice in enumerate(choices): + if choice.value == value: + self._index = i + return + self._index = max(0, min(self._index, len(choices) - 1)) if choices else 0 + + def _widest_name(self) -> int: + """The widest rendered name in cells across every lane the list draws. + + The name lane is sized to its content, not the terminal, so the columns anchor to + the left instead of drifting apart as the window widens. The measure spans the + regular rows (``unknown`` for the nameless, as the row renders them) and any + own-node row's name plus its ``(you)`` tag, so the tag always fits. + """ + widths = [cell_len("unknown")] + for row in self._node_rows: + if row.you: + widths.append( + cell_len(row.name) + cell_len(_YOU_TAG) if row.name else cell_len("you") + ) + else: + widths.append(cell_len(row.name or "unknown")) + return max(widths) + + def _lane_widths(self, width: int) -> tuple[int, int]: + """The name and hash lane widths for a terminal ``width`` cells wide. + + The name lane is content-sized (see :meth:`_widest_name`) so it stays put as the + window grows; it only yields when a very long name would starve the hash lane past + its :data:`_HASH_MIN` floor. The hash lane then takes all the width the fixed + lanes and the name lane leave, so keys show as fully as they fit — a heard id's 12 + hex digits with room to spare, a 64-hex key ellipsized to the lane. + """ + 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 render_body(self, width: int) -> list[str]: + """Size the name lane to content and flex the hash 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 + self._rebuild() + return super().render_body(width) + + def handle(self, action: str, data: str = "") -> None: + """Steer the sort with the Ctrl+arrows; everything else is the base list's.""" + if action == "ctrl_left": + self._sort.move(-1) + self._rebuild() + elif action == "ctrl_right": + self._sort.move(1) + self._rebuild() + elif action == "ctrl_up": + if not self._sort.ascending: + self._sort.ascending = True + self._rebuild() + elif action == "ctrl_down": + if self._sort.ascending: + self._sort.ascending = False + self._rebuild() + else: + super().handle(action, data) diff --git a/meshterm/ui/nodes_screen.py b/meshterm/ui/nodes_screen.py index 888a699..0c6fb36 100644 --- a/meshterm/ui/nodes_screen.py +++ b/meshterm/ui/nodes_screen.py @@ -1,41 +1,42 @@ -"""The interactive nodes list: the node table with arrow-key sorting. +"""The interactive Nodes screen: the device's contacts in the shared sortable node list. -This wraps :func:`~meshterm.ui.widgets.nodes_table` in a full-screen TUI layer whose sort the -user steers with the arrows — left/right pick the column, up/down set ascending/descending — -so the table re-renders in place. The rows scroll in a window inside the fixed screen: the -title, column header, and bottom legend hold still, faint ``↑/↓ n more`` markers bracket the -window, and PgUp/PgDn slide it. The one-shot CLI (``meshterm nodes --sort …``) renders the -same table statically; only the menu gets the live sorting. +The Time Machine picker's presentation pointed at the companion's contact table: the same +aligned ``NAME · HEARD · PKTS · HASH`` lanes, our own node pinned first, the same Ctrl+arrow +sort (now including the hash column) and type-to-filter — one node list app-wide, whatever +the data source (see :mod:`~meshterm.ui.nodelist`). Enter is deliberately inert for now: the +highlight is a cursor, not yet a selection — a per-node action will land on it later. The +one-shot CLI (``meshterm nodes --sort …``) still renders the static +:func:`~meshterm.ui.widgets.nodes_table`; only the menu gets the live list. """ from __future__ import annotations -import re from typing import TYPE_CHECKING -from .tui.render import render_lines, render_to_ansi -from .tui.screen import ListWindow, Screen -from .widgets import NodesSort, _nodes_legend, nodes_table +from .nodelist import NodeListScreen, NodeRow +from .widgets import NodesSort, _contact_pkts if TYPE_CHECKING: from ..context import AppContext from ..core.models import Contact -#: Strips SGR colour codes so the header-rule line can be recognized by its bare glyphs. -_ANSI_RE = re.compile(r"\x1b\[[0-9;]*m") +#: A stable identity for the own-node row (its lane data has no key to stand on when no +#: device answered), so a re-sort can keep the highlight on it. +YOU = ("you",) + +#: The Nodes list's footer: the shared list's grammar minus the Enter atom — pressing it +#: does nothing yet, so the hint doesn't advertise it. +_HINT = "↑↓ move · ^←→↑↓ sort · type filter · Esc back" -class NodesScreen(Screen): - """A full-screen, keyboard-sortable list of this node and its known contacts.""" - - floating = False - footer_hint = "←→ column · ↑ asc ↓ desc · PgUp/PgDn scroll · Esc back" +class NodesScreen(NodeListScreen): + """A full-screen, Ctrl+arrow-sortable list of this node and its known contacts.""" def __init__( self, self_name: str, self_key: str, - contacts: list[Contact], + contacts: "list[Contact]", prefix_bytes: int, counts: dict[str, int], sort: NodesSort, @@ -44,126 +45,56 @@ class NodesScreen(Screen): Args: self_name: This node's advertised name. - self_key: This node's full public key (hex). + self_key: This node's full public key (hex); blank renders a muted ``?``. contacts: Known contacts to list under our own node. prefix_bytes: Path-hash width in bytes to highlight in every key. - counts: Overheard-packet counts keyed by lowercased 12-hex node id. - sort: The initial sort; mutated in place as the user presses the arrows. + counts: Overheard-packet counts keyed by lowercased 12-hex node id; a contact + with no entry shows a faint ``—``. + sort: The initial sort; mutated in place by the Ctrl+arrows. Its ring should + span :data:`~meshterm.ui.nodelist.SORT_COLUMNS` so the hash sort is + reachable. """ - super().__init__() - self.title = "Nodes" - self._self_name = self_name - self._self_key = self_key - self._contacts = contacts - self._prefix_bytes = prefix_bytes - self._counts = counts - self._sort = sort - #: The row window inside the fixed screen (title, header, and legend pinned). - self._rows_window = ListWindow() - #: Whether the last render actually windowed the rows — degenerate renders - #: (no header rule found, or a viewport too short) fall back to whole-body - #: scrolling, and the page keys follow suit. - self._windowed = False - - def render_body(self, width: int) -> list[str]: - """Render the table at the current sort, windowing its rows in place. - - The title, column header, and rule pin above the window; the glyph legend - pins beneath it; only the node rows scroll between them. A render whose - header rule can't be found (degenerate narrow width) or whose viewport - leaves the window no room falls back to the plain whole-body scroll. - """ - table = nodes_table( - self._self_name, - self._self_key, - self._contacts, - self._prefix_bytes, - self._counts, - self._sort, + rows = [NodeRow(value=YOU, name=self_name, key=self_key, you=True)] + for c in contacts: + rows.append( + NodeRow( + value=c.public_key or c.name, + name=c.name, + key=c.public_key, + node_type=c.node_type, + last_seen=c.last_seen, + count=_contact_pkts(c, counts), + ) + ) + super().__init__( + f"Nodes · {len(contacts)} known", + rows=rows, + prefix_bytes=prefix_bytes, + sort=sort, + footer_hint=_HINT, ) - lines = render_lines(table, width) - rule = self._rule_index(lines) - legend_h = len(render_lines(_nodes_legend(), width)) + 1 # + its blank spacer - win = self._scroll_viewport - (rule + 1) - legend_h if rule is not None else 0 - self._windowed = rule is not None and win >= 3 - if not self._windowed: - self._scroll_total = max(1, len(lines)) - return lines - - head, rows, tail = ( - lines[: rule + 1], lines[rule + 1 : len(lines) - legend_h], - lines[len(lines) - legend_h :], - ) - top, count = self._rows_window.fit(len(rows), win) - out = list(head) - if top > 0: - out.append(render_to_ansi(ListWindow.marker(top, "above"), width)) - out.extend(rows[top : top + count]) - below = len(rows) - top - count - if below > 0: - out.append(render_to_ansi(ListWindow.marker(below, "below"), width)) - out.extend(tail) - self._scroll_total = max(1, len(out)) - return out - - @staticmethod - def _rule_index(lines: list[str]) -> "int | None": - """Locate the rule the table draws under its column labels. - - The table renders a full-width run of ``─`` there (box.SIMPLE_HEAD); the - first such line marks where the pinned head ends and the rows begin. - ``None`` if no rule is found (e.g. a degenerate narrow render). - """ - for idx in range(1, len(lines)): - bare = _ANSI_RE.sub("", lines[idx]).strip() - if bare and set(bare) == {"─"}: - return idx - return None def handle(self, action: str, data: str = "") -> None: - """Re-sort with the arrows, slide the row window with the page keys, or dismiss.""" - if action == "left": - self._sort.move(-1) - elif action == "right": - self._sort.move(1) - elif action == "up": - self._sort.ascending = True - elif action == "down": - self._sort.ascending = False - elif action == "pageup": - if self._windowed: - self._rows_window.top -= self._rows_window.page - else: - self.scroll_pages(-1) - elif action in ("pagedown", "space"): - if self._windowed: - self._rows_window.top += self._rows_window.page - else: - self.scroll_pages(1) - elif action in ("home", "ctrl_home"): - if self._windowed: - self._rows_window.top = 0 - else: - self.scroll_to_top() - elif action in ("end", "ctrl_end"): - if self._windowed: - self._rows_window.to_end() - else: - self.scroll_to_bottom() - elif action in ("escape", "enter"): - self.resolve(None) + """Swallow Enter; every other key is the shared list's. + + The highlight is only a cursor until per-node actions land, so committing it + must neither act nor dismiss the screen — only Esc leaves. + """ + if action == "enter": + return + super().handle(action, data) async def open_nodes( - ctx: AppContext, + ctx: "AppContext", self_name: str, self_key: str, - contacts: list[Contact], + contacts: "list[Contact]", prefix_bytes: int, counts: dict[str, int], sort: NodesSort, ) -> None: - """Open the interactive, arrow-sortable nodes list and run until dismissed. + """Open the interactive, sortable nodes list and run until dismissed with Esc. Args: ctx: Shared application context (must be in the interactive menu). @@ -172,7 +103,7 @@ async def open_nodes( contacts: Known contacts to list under our own node. prefix_bytes: Path-hash width in bytes to highlight in every key. counts: Overheard-packet counts keyed by lowercased 12-hex node id. - sort: The initial sort (column + direction). + sort: The initial sort (column + direction) over the shared list's ring. Raises: RuntimeError: If called outside the interactive menu (no full-screen session). diff --git a/meshterm/ui/timemachine_screen.py b/meshterm/ui/timemachine_screen.py index ed069d1..52e9d07 100644 --- a/meshterm/ui/timemachine_screen.py +++ b/meshterm/ui/timemachine_screen.py @@ -26,23 +26,19 @@ from datetime import date, datetime, timedelta from statistics import median from typing import TYPE_CHECKING, Callable, Optional -from rich.cells import cell_len from rich.console import Group, RenderableType from rich.text import Text from ..core.models import utcnow from .braillechart import _TICK_GAP, GAP, axis_chart, chart_span, timeline_rows -from .map_render import _SELF from .menus import fit_cells, section_heading +from .nodelist import SORT_COLUMNS, SORT_OPENS_ASCENDING, NodeListScreen, NodeRow from .theme import snr_style from .tui.render import render_lines from .tui.screen import CANCEL, Screen -from .tui.select import Choice, Separator, SelectScreen +from .tui.select import Choice, Separator from .widgets import ( - _DEFAULT_GLYPH, - _NODE_GLYPHS, _age_seconds, - _format_age, _recency_style, format_ago, highlighted_hash, @@ -958,7 +954,7 @@ def _mesh_sections( #: Widest the mesh page's arrivals name lane grows (longer names ellipsize so the lanes #: stay put). The picker sizes its own name lane to content instead (see -#: :meth:`TimeMachinePickerScreen._lane_widths`). +#: :meth:`~meshterm.ui.nodelist.NodeListScreen._lane_widths`). _PICK_NAME_MAX = 18 #: The mesh page's arrivals hash lane in cells. Heard-node ids are the observations' 12-hex @@ -966,44 +962,6 @@ _PICK_NAME_MAX = 18 #: as the arrival row's hash column the padding falls before the FIRST HEARD lane. _PICK_HASH_W = 16 -#: The narrowest the picker's name lane shrinks to (a very narrow terminal), so the header's -#: ``NAME`` label and its sort triangle always have somewhere to sit. -_PICK_NAME_MIN = 6 - -#: The picker hash lane's floor in cells — four leading bytes plus an ellipsis, still a -#: recognisable prefix on a very narrow terminal. The lane otherwise flexes to fill whatever -#: width the (content-sized) name lane leaves, so a longer key — our own 64-hex node key, or -#: a heard node's full key resolved from a contact — shows as many whole bytes as fit, -#: ellipsized past that (see :func:`~meshterm.ui.widgets.highlighted_hash`). -_PICK_HASH_MIN = 8 - -#: Everything in a picker row *besides* the name and hash lanes, in cells: the select pointer -#: (2), the type glyph and its space (2), then the two gapped fixed lanes — heard (2 gap + 5) -#: and packets (2 gap + 5) — and the 3-cell gap before the hash. The name lane is content- -#: sized and the hash lane takes the rest (see :meth:`TimeMachinePickerScreen._lane_widths`). -_PICK_LEAD = 2 + 2 + (2 + 5) + (2 + 5) + 3 - -#: The muted ``(you)`` tag on the own-node lane (see :func:`_self_picker_row`), its width -#: folded into the name lane's content sizing so the tag never truncates. -_YOU_TAG = " (you)" - -#: The picker's sort ring and each column's natural opening direction — the Nodes list's -#: three (see :data:`~meshterm.ui.widgets._SORT_COLUMNS`) plus a fourth, ``hash``, sorting on -#: the node's key id (ascending = ``0`` → ``f``). Passed to :class:`NodesSort` so the ring -#: the Ctrl+arrows walk includes the hash without touching the Nodes list's own three. -_PICKER_SORT_COLUMNS: tuple[str, ...] = ("name", "heard", "packets", "hash") -_PICKER_SORT_OPENS_ASCENDING: dict[str, bool] = { - "name": True, "heard": True, "packets": False, "hash": True, -} - -#: The cyan the active sort column and its triangle are lit in, matching the Nodes table's -#: header (see :func:`~meshterm.ui.widgets._sort_header`) so the two lists' sort cues read -#: identically. -_PICK_SORT_ACTIVE = "bold #22d3ee" - -#: The picker's footer: navigation, the Ctrl+arrow sort, filtering, then Esc last. -_PICKER_HINT = "↑↓ move · ^←→↑↓ sort · type filter · Enter open · Esc back" - def _known_name(resolve: "NodeResolver", node: Optional[str], name: Optional[str]) -> Optional[str]: """The best display name for a heard node, or ``None`` when truly unknown. @@ -1022,169 +980,6 @@ def _known_name(resolve: "NodeResolver", node: Optional[str], name: Optional[str return None -def _picker_header(name_w: int, sort: NodesSort) -> Text: - """Column labels over the node picker's lanes (see :func:`_picker_row`). - - The lanes read ``NAME · HEARD · PKTS · HASH``, matching the row builder. The four - leading spaces cover the select screen's pointer column (2 cells) plus the one-cell - type glyph and its gap, so each label lands over its lane. - - All four columns are sortable, so any one can be the active sort. The active column's - label *and* its direction triangle (``▲`` ascending, ``▼`` descending) are lit cyan - together — the same cue the Nodes table's :func:`~meshterm.ui.widgets._sort_header` - lights — and the triangle is drawn *into the two-cell reserve that already follows - every label*, so switching the sort never widens a lane and shifts the rest of the row. - Returned as a :class:`~rich.text.Text` (not a plain string) so just the active column - carries the colour while the rest stays muted. - """ - - def column(header: Text, label: str, key: str, *, pad_to: int = 0) -> None: - """Append one column: its label plus a two-cell mark reserve, lit when it's the sort.""" - if key == sort.column: - cell = f"{label} " + ("▲" if sort.ascending else "▼") - header.append(cell, style=_PICK_SORT_ACTIVE) - else: - cell = f"{label} " - header.append(cell, style="muted") - if pad_to: # left-justify the flexing name lane; the pad stays muted - header.append(" " * max(0, pad_to - cell_len(cell)), style="muted") - - header = Text(" ", style="muted") # pointer (2) + the row's type glyph and gap (2) - column(header, "NAME", "name", pad_to=name_w) - header.append(" ", style="muted") # gap to the HEARD lane - column(header, "HEARD", "heard") - column(header, f"{'PKTS':>5}", "packets") - # HASH sits one cell further out than the other lanes so a packets-sort triangle — - # packets being the lane just before it — never abuts the hash label. - header.append(" ", style="muted") - column(header, "HASH", "hash") - return header - - -def _self_picker_row( - self_name: Optional[str], self_key: Optional[str], name_w: int, prefix_bytes: int, - hash_w: int, -) -> Text: - """Our own node as the picker's first node lane — the Nodes list's self row. - - Laid out exactly like :func:`_picker_row` so it sits *inside* the node list rather than - above it, and drawn like the Nodes screen's own-node row: the ``★`` self marker (yellow), - the name in the pure-white ``you`` style with a muted ``(you)`` tag, and our key hash lit - at the routing width, filling the flexing hash lane (``hash_w`` cells) — our 64-hex key - is longer than any lane, so it shows as many digits as fit and ellipsizes. The heard and - packet lanes read a faint ``—`` — we never overhear ourselves, so there is no reception - age or count to show (the page itself is built from what we *sent*). With no reachable - device to name us, the name falls back to a bare ``you`` and the hash to ``?``. - """ - row = Text(no_wrap=True, overflow="ellipsis") - row.append(_SELF[0], style=_SELF[1]) - row.append(" ") - # The name lane, exactly name_w cells: the name (white) with a snug muted "(you)" tag — - # padded out to fill the lane, matching the Nodes screen's own-node row — or, when the - # name alone would crowd out the tag, the name fit to the lane with the tag dropped. The - # lane is sized to hold the tag (see _widest_name), so the drop is a very-long-name guard. - used = cell_len(self_name) + cell_len(_YOU_TAG) if self_name else 0 - if self_name and used <= name_w: - row.append(self_name, style="you") - row.append(_YOU_TAG, style="muted") - row.append(" " * (name_w - used)) - else: - row.append(fit_cells(self_name or "you", name_w), style="you") - row.append(" ") - row.append(f"{'—':>5}", style="faint") # heard: we don't hear ourselves - row.append(" ") - row.append(f"{'—':>5}", style="faint") # packets: nothing to count - row.append(" ") # the wider gap the header's HASH lane keeps (see _picker_header) - if self_key: - row.append_text(highlighted_hash(self_key, prefix_bytes, width=hash_w)) - else: - row.append("?", style="muted") - return row - - -def _picker_row( - node: "HeardNode", - name: Optional[str], - name_w: int, - prefix_bytes: int, - hash_w: int, - node_type: Optional[int] = None, - *, - key: Optional[str] = None, -) -> Text: - """One heard node as fixed, colour-coded picker lanes. - - The type glyph leads (the app's shared marker palette), so the mark reads ``▲`` for a - repeater, ``■`` for a room, ``◉`` for a sensor, ``●`` for a plain node. The name — - stored, or filled in by the contact resolver (see :func:`_known_name`) — is coloured by - recency heat, ``unknown`` included, so a freshly heard mystery node still reads hot, and - takes the flexing name lane (``name_w`` cells). Last-heard age and packet count follow, - right-aligned under their headers; the hash closes the row in the shared hash widget, its - path-hash prefix lit at the device's routing width, exactly as the Nodes list draws keys. - - Args: - node: The heard node whose stats fill the lanes. - name: Its resolved display name (``None`` renders the heat-coloured ``unknown``). - name_w: The name lane's width in cells (content-sized across the whole list). - prefix_bytes: Path-hash width in bytes to light in the hash. - hash_w: The flexing hash lane's width in cells (a heard id's 12 hex digits pad out - to it; see :func:`~meshterm.ui.widgets.highlighted_hash`). - node_type: The node's type when known from a source other than its stored - observations (the device's contacts, say) — used for the glyph only when the - stored :attr:`~meshterm.core.models.HeardNode.node_type` is absent, so a node - heard only via non-advert packets still shows its true kind (see - :func:`~meshterm.services.trace_runner.make_node_type_resolver`). - key: The hex to render in the hash lane — the node's full public key when we have - one (captured with the observation, or resolved from the device's contacts), so - more than the stored 12-hex prefix shows; ``None`` falls back to the stored prefix. - """ - kind = node.node_type if node.node_type is not None else node_type - glyph, glyph_style = _NODE_GLYPHS.get(kind, _DEFAULT_GLYPH) - secs = _age_seconds(node.last_seen) - row = Text(no_wrap=True, overflow="ellipsis") - row.append(glyph, style=glyph_style) - row.append(" ") - row.append(fit_cells(name or "unknown", name_w), style=_recency_style(secs)) - row.append(" ") - row.append(f"{_format_age(secs):>5}", style="muted") - row.append(" ") - row.append(f"{min(node.count, 99999):>5}", style="muted") - row.append(" ") # the wider gap the header's HASH lane keeps (see _picker_header) - row.append_text(highlighted_hash(key or node.node or "", prefix_bytes, width=hash_w)) - return row - - -def _ordered_heard( - listed: list[tuple["HeardNode", Optional[str]]], sort: NodesSort -) -> list[tuple["HeardNode", Optional[str]]]: - """Order the picker's ``(node, resolved name)`` pairs by the active sort. - - The heard-node counterpart of the Nodes list's :func:`~meshterm.ui.widgets._ordered_contacts`, - over the picker's four columns and their natural directions: name A→Z, ``heard`` by age so - ascending is most-recently-heard first, ``packets`` by count, ``hash`` by the node's key id - (ascending = ``0`` → ``f``). A name-ascending pre-sort is the stable tiebreak, so two nodes - sharing a metric keep an A→Z order under both directions rather than flipping with the - primary key. - """ - - def key_name(item: tuple["HeardNode", Optional[str]]) -> str: - return (item[1] or "unknown").casefold() - - def metric(item: tuple["HeardNode", Optional[str]]): # noqa: ANN202 - homogeneous per sort - node, _name = item - if sort.column == "name": - return key_name(item) - if sort.column == "packets": - return node.count - if sort.column == "hash": - return node.node or "" - return _age_seconds(node.last_seen) # "heard": ascending = freshest first - - ordered = sorted(listed, key=key_name) - ordered.sort(key=metric, reverse=not sort.ascending) - return ordered - - async def _routing_prefix_bytes(ctx: "AppContext") -> int: """The device's path-hash width in bytes, or 0 when unknowable. @@ -1254,29 +1049,16 @@ async def _self_identity(ctx: "AppContext") -> tuple[Optional[str], Optional[str return (str(name) if name else None), (str(key) if key else None) -class TimeMachinePickerScreen(SelectScreen): - """The Time Machine's subject picker: a full-screen, sortable, filterable node list. +class TimeMachinePickerScreen(NodeListScreen): + """The Time Machine's subject picker: the shared node list under the whole-mesh row. - The whole-mesh overview leads; under it the node list runs in aligned lanes — name - (coloured by recency heat), last-heard age, packet count, and key hash — our own node - first (the Nodes screen's own-node-first order), then every node ever heard. The lanes - anchor to the left: the name lane is sized to its widest name (not the terminal), so the - columns stay put as the window widens and the freed width flows to the hash lane, which - shows each key as fully as it fits — a heard node's full key when a contact holds it, - ellipsized on a byte boundary past that (see :meth:`_lane_widths`). It is a full-screen - list, not a floating popup. - - The sort rides the Ctrl+arrows, leaving the plain arrows for the highlight and the - letters for type-to-filter: **Ctrl+←/→** pick the column (name → heard → packets → hash, - each adopting its natural direction) and **Ctrl+↑/↓** force ascending/descending. Every - change re-sorts the node block in place — the whole-mesh row and headers stay pinned, - the highlight rides its node, and any active filter holds — the same :class:`NodesSort` - model and cyan triangle cue the Nodes list uses (over a fourth, hash, column here), only - its keys moved off the plain arrows that a filterable list already spends. + The whole-mesh overview leads; under it runs the app's shared sortable node list + (see :class:`~meshterm.ui.nodelist.NodeListScreen` for the lanes, the Ctrl+arrow + sort, and type-to-filter) — our own node first, then every node ever heard. A heard + node's hash lane shows its fullest known key: the one captured with an observation + (shows offline), else the device's contact list, else the stored 12-hex prefix. """ - floating = False - def __init__( self, *, @@ -1293,16 +1075,16 @@ class TimeMachinePickerScreen(SelectScreen): Args: listed: Every heard node with a resolved display name (``None`` = unknown), - in the repository's most-recently-heard order; re-sorted here per ``sort``. + in the repository's most-recently-heard order; re-sorted per ``sort``. prefix_bytes: Path-hash width in bytes to light in each hash. sort: The sort state, mutated in place by the Ctrl+arrows — pass the same instance across re-opens so the chosen order persists. Its ring should span - :data:`_PICKER_SORT_COLUMNS` for the hash column to be reachable. + :data:`~meshterm.ui.nodelist.SORT_COLUMNS` for the hash column to be + reachable. prompt: The instruction shown above the list. self_name: Our own node's advertised name, for the own-node lane that always - leads the node list (see :func:`_self_picker_row`); ``None`` (no reachable - device) falls back to a bare ``you``. The row is always present — the - own-node page reads stored history. + leads the node list; ``None`` (no reachable device) falls back to a bare + ``you``. The row is always present — the own-node page reads stored history. self_key: Our own node's full public key, lit as the own-node lane's hash; ``None`` renders a muted ``?``. type_of: Resolves a node's type from the device's contacts, filling the leading @@ -1314,132 +1096,35 @@ class TimeMachinePickerScreen(SelectScreen): the stored digits (see :func:`_contact_resolvers`); the default returns the prefix unchanged, leaving the stored 12 hex to stand. """ - self._listed = listed - self._prefix_bytes = prefix_bytes - self._sort = sort - self._self_name = self_name - self._self_key = self_key - self._type_of = type_of - self._resolve_key = resolve_key - # Provisional until the first render learns the true width (see render_body). - self._name_w = _PICK_NAME_MIN - self._hash_w = _PICK_HASH_MIN - super().__init__( - "Time machine", - self._compose_items(), - prompt=prompt, - footer_hint=_PICKER_HINT, - wrap=False, - ) - - def _compose_items(self) -> list: - """The whole-mesh row, the heading and sort-aware column header, then the node choices - — our own node first, the heard nodes after it in the active sort order. - - Our node leads the ``── Nodes ──`` list and stays first whatever the sort: only the - heard-node block below it reorders. It reads as an ordinary node lane (see - :func:`_self_picker_row`), matching the Nodes screen's own-node-first table.""" - items: list = [ - Choice("🌐 The whole mesh — days, arrivals, the ledger", MESH), - Separator(" "), - section_heading("Nodes"), - Separator(_picker_header(self._name_w, self._sort)), - Choice( - _self_picker_row( - self._self_name, self._self_key, self._name_w, - self._prefix_bytes, self._hash_w, - ), - SELF, - ), - ] - for node, name in _ordered_heard(self._listed, self._sort): - node_type = node.node_type if node.node_type is not None else self._type_of(node.node) - # The full key, most-durable source first: the one captured with the observation - # (shows offline), else the device's live contact list, else the stored prefix. - key = node.public_key or self._resolve_key(node.node) or node.node - items.append( - Choice( - _picker_row( - node, name, self._name_w, self._prefix_bytes, self._hash_w, - node_type, key=key, + rows = [NodeRow(value=SELF, name=self_name, key=self_key or "", you=True)] + for node, name in listed: + rows.append( + NodeRow( + value=(node.node, name or node.node), + name=name, + # The full key, most-durable source first: the one captured with the + # observation (shows offline), else the device's live contact list, + # else the stored prefix. + key=node.public_key or resolve_key(node.node) or node.node or "", + node_type=( + node.node_type if node.node_type is not None else type_of(node.node) ), - (node.node, name or node.node), + last_seen=node.last_seen, + count=node.count, ) ) - return items - - def _rebuild(self) -> None: - """Recompose the rows for the current sort/width, keeping the highlight on its node.""" - current = self._current_choice() - keep = current.value if current is not None else None - self._items = self._compose_items() - self._reselect(keep) - - def _reselect(self, value: object) -> None: - """Move the highlight back onto the choice with ``value`` (else clamp it in range).""" - choices = self._choices() - for i, choice in enumerate(choices): - if choice.value == value: - self._index = i - return - self._index = max(0, min(self._index, len(choices) - 1)) if choices else 0 - - def _widest_name(self) -> int: - """The widest rendered name in cells across every lane the list draws. - - The name lane is sized to its content, not the terminal, so the columns anchor to - the left instead of drifting apart as the window widens. The measure spans the heard - nodes (``unknown`` for the nameless, as the row renders them), plus our own row's - name and its ``(you)`` tag so the tag always fits. - """ - widths = [cell_len("unknown")] - if self._self_name: - widths.append(cell_len(self._self_name) + cell_len(_YOU_TAG)) - else: - widths.append(cell_len("you")) - widths.extend(cell_len(name or "unknown") for _node, name in self._listed) - return max(widths) - - def _lane_widths(self, width: int) -> tuple[int, int]: - """The name and hash lane widths for a terminal ``width`` cells wide. - - The name lane is content-sized (see :meth:`_widest_name`) so it stays put as the - window grows; it only yields when a very long name would starve the hash lane past - its :data:`_PICK_HASH_MIN` floor. The hash lane then takes all the width the fixed - lanes and the name lane leave, so keys show as fully as they fit — a heard id's 12 - hex digits with room to spare, our own 64-hex key ellipsized to the lane. - """ - name_cap = max(_PICK_NAME_MIN, width - _PICK_LEAD - _PICK_HASH_MIN) - name_w = max(_PICK_NAME_MIN, min(self._widest_name(), name_cap)) - hash_w = max(_PICK_HASH_MIN, width - _PICK_LEAD - name_w) - return name_w, hash_w - - def render_body(self, width: int) -> list[str]: - """Size the name lane to content and flex the hash 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 - self._rebuild() - return super().render_body(width) - - def handle(self, action: str, data: str = "") -> None: - """Steer the sort with the Ctrl+arrows; everything else is the base list's.""" - if action == "ctrl_left": - self._sort.move(-1) - self._rebuild() - elif action == "ctrl_right": - self._sort.move(1) - self._rebuild() - elif action == "ctrl_up": - if not self._sort.ascending: - self._sort.ascending = True - self._rebuild() - elif action == "ctrl_down": - if self._sort.ascending: - self._sort.ascending = False - self._rebuild() - else: - super().handle(action, data) + super().__init__( + "Time machine", + rows=rows, + prefix_bytes=prefix_bytes, + sort=sort, + prompt=prompt, + lead=[ + Choice("🌐 The whole mesh — days, arrivals, the ledger", MESH), + Separator(" "), + section_heading("Nodes"), + ], + ) async def open_timemachine(ctx: "AppContext") -> None: @@ -1461,8 +1146,8 @@ async def open_timemachine(ctx: "AppContext") -> None: self_name, self_key = await _self_identity(ctx) # One sort for the whole visit, so the order the user picks survives leaving a subject # page and coming back. Opens most-recently-heard first, as the list always has; its ring - # spans the picker's four columns so the Ctrl+arrows can reach the hash sort. - sort = NodesSort.from_name("heard", _PICKER_SORT_COLUMNS, _PICKER_SORT_OPENS_ASCENDING) + # spans the shared list's four columns so the Ctrl+arrows can reach the hash sort. + sort = NodesSort.from_name("heard", SORT_COLUMNS, SORT_OPENS_ASCENDING) while True: heard = ctx.repo.heard_nodes() diff --git a/tests/test_device_config.py b/tests/test_device_config.py index 61e9006..01a8f41 100644 --- a/tests/test_device_config.py +++ b/tests/test_device_config.py @@ -200,51 +200,79 @@ def test_nodes_table_breaks_metric_ties_by_name_ascending() -> None: assert order(ascending=False) == ["Bob", "Alice", "Charlie"] -def test_nodes_screen_arrows_steer_the_sort() -> None: - """Left/right walk the sort column (wrapping); up/down set ascending/descending.""" - from meshterm.ui.nodes_screen import NodesScreen +def _nodes_sort(name: str = "name"): + """The interactive Nodes screen's sort: the shared node list's four-column ring.""" + from meshterm.ui.nodelist import SORT_COLUMNS, SORT_OPENS_ASCENDING from meshterm.ui.widgets import NodesSort - screen = NodesScreen("Us", "aabbcc" + "00" * 29, [], 3, {}, NodesSort()) + return NodesSort.from_name(name, SORT_COLUMNS, SORT_OPENS_ASCENDING) + + +def test_nodes_screen_ctrl_arrows_steer_the_sort() -> None: + """Ctrl+←/→ walk the shared four-column ring (wrapping); Ctrl+↑/↓ force the direction — + the Time Machine picker's keys, now the Nodes screen's too.""" + from meshterm.ui.nodes_screen import NodesScreen + + screen = NodesScreen("Us", "aabbcc" + "00" * 29, [], 3, {}, _nodes_sort()) assert (screen._sort.column, screen._sort.ascending) == ("name", True) - screen.handle("right") # name -> heard, opening in its natural (ascending) direction + screen.handle("ctrl_right") # name -> heard, opening in its natural (ascending) direction assert (screen._sort.column, screen._sort.ascending) == ("heard", True) - screen.handle("right") # heard -> packets, which opens descending + screen.handle("ctrl_right") # heard -> packets, which opens descending assert (screen._sort.column, screen._sort.ascending) == ("packets", False) - screen.handle("up") # force ascending + screen.handle("ctrl_up") # force ascending assert screen._sort.ascending is True - screen.handle("down") # force descending + screen.handle("ctrl_down") # force descending assert screen._sort.ascending is False - screen.handle("right") # packets -> wraps back to name + screen.handle("ctrl_right") # packets -> hash, the ring's fourth column + assert (screen._sort.column, screen._sort.ascending) == ("hash", True) + screen.handle("ctrl_right") # hash -> wraps back to name assert screen._sort.column == "name" - screen.handle("left") # name -> wraps to packets - assert screen._sort.column == "packets" + screen.handle("ctrl_left") # name -> wraps to hash + assert screen._sort.column == "hash" -def test_nodes_screen_windows_rows_between_pinned_header_and_legend() -> None: - """The rows scroll in place: header and legend hold still, hidden rows counted.""" +def test_nodes_screen_lists_contacts_in_the_shared_lanes() -> None: + """Contacts render in the shared NAME/HEARD/PKTS/HASH lanes, our node pinned first; + plain arrows only move the highlight, and Enter is inert (selection comes later).""" import re - from meshterm.core.models import Contact - from meshterm.ui.nodes_screen import NodesScreen - from meshterm.ui.widgets import NodesSort + from meshterm.core.models import Contact, utcnow + from meshterm.ui.nodes_screen import YOU, NodesScreen + from meshterm.ui.tui.screen import CANCEL - contacts = [Contact(name=f"n{i:02}", public_key="ab" * 16) for i in range(30)] - screen = NodesScreen("Us", "aabbcc" + "00" * 29, contacts, 3, {}, NodesSort()) - screen.note_viewport(18) # the frame records this before every real paint - lines = screen.render_body(70) - plain = [re.sub(r"\x1b\[[0-9;]*m", "", line) for line in lines] - body = "\n".join(plain) + contacts = [ + Contact(name="Alice", public_key="aa" * 32, last_seen=utcnow()), + Contact(name="Bob", public_key="bb" * 32), + ] + counts = {"aa" * 6: 7} # Alice was overheard; Bob never + screen = NodesScreen("Us", "cc" * 32, contacts, 1, counts, _nodes_sort()) + body = "\n".join(re.sub(r"\x1b\[[0-9;]*m", "", ln) for ln in screen.render_body(72)) - assert len(lines) <= 18 # header + window + legend fit the frame exactly - assert "NAME" in body and "you" in body # the pinned header and legend survive - assert "↓" in body and "more" in body # hidden rows are counted below - assert "n29" not in body # ...because the tail really is out of the window + # The shared column header (recorded sticky, so it pins once scrolled past)... + assert "NAME" in body and "HEARD" in body and "PKTS" in body and "HASH" in body + assert screen._sticky_headers + # ...our own node leading the lanes, then the contacts with their tallies. + choices = screen._choices() + assert choices[0].value == YOU + assert "(you)" in choices[0].label.plain + assert "Alice" in body and "Bob" in body + assert f"{7:>5}" in body # Alice's overheard packets, right-aligned in its lane + assert "never" in body # Bob has no last_seen - screen.handle("end") # slide the window to the tail - body = "\n".join(re.sub(r"\x1b\[[0-9;]*m", "", ln) for ln in screen.render_body(70)) - assert "n29" in body and "↑" in body # tail visible, hidden rows counted above + # Plain arrows move the highlight without touching the sort. + before = (screen._sort.column, screen._sort.ascending) + screen.handle("down") + assert (screen._sort.column, screen._sort.ascending) == before + assert screen._current_choice().value != YOU + + # Enter does nothing yet; Esc still leaves. + resolved: list = [] + screen.resolve = lambda value: resolved.append(value) # type: ignore[method-assign] + screen.handle("enter") + assert resolved == [] + screen.handle("escape") + assert resolved == [CANCEL] def test_non_strict_enum_accepts_unlisted_value() -> None: diff --git a/tests/test_timemachine.py b/tests/test_timemachine.py index e48764a..22cf8e1 100644 --- a/tests/test_timemachine.py +++ b/tests/test_timemachine.py @@ -554,14 +554,20 @@ def test_mesh_page_rhythm_left_edge_aligns_with_the_day_charts(tmp_path: Path) - def test_picker_row_lanes_align_under_the_header() -> None: """Picker rows lane up under the header; unknown nodes read as heat-coloured names.""" from meshterm.core.models import HeardNode - from meshterm.ui.timemachine_screen import _picker_header, _picker_row + from meshterm.ui.nodelist import NodeRow, _header, _lane from meshterm.ui.widgets import NodesSort node = HeardNode( node="3d" * 6, name=None, count=42, median_snr=None, best_snr=None, last_rssi=None, last_seen=utcnow(), ) - row = _picker_row(node, node.name, 10, 2, 16) + row = _lane( + NodeRow( + value=node.node, name=node.name, key=node.node or "", + last_seen=node.last_seen, count=node.count, + ), + 10, 2, 16, + ) plain = row.plain assert "unknown" in plain and "3d" * 6 in plain and "42" in plain # A just-heard mystery node reads hot (white), not placeholder-grey. @@ -574,7 +580,7 @@ def test_picker_row_lanes_align_under_the_header() -> None: ) # Header labels land over their lanes (+2 covers the select pointer column); the lanes # now read NAME · HEARD · PKTS · HASH, with the hash closing the row. - header = _picker_header(10, NodesSort.from_name("heard")).plain + header = _header(10, NodesSort.from_name("heard")).plain assert header.index("NAME") == plain.index("unknown") + 2 assert header.index("HASH") == plain.index("3d" * 6) + 2 assert header.index("HEARD") < header.index("PKTS") < header.index("HASH") @@ -582,28 +588,28 @@ def test_picker_row_lanes_align_under_the_header() -> None: def test_picker_header_marks_the_active_sort_column() -> None: """The sort column carries a direction triangle; toggling flips ▲/▼, and only it.""" - from meshterm.ui.timemachine_screen import _picker_header + from meshterm.ui.nodelist import _header from meshterm.ui.widgets import NodesSort - heard_desc = _picker_header(12, NodesSort("heard", ascending=False)).plain + heard_desc = _header(12, NodesSort("heard", ascending=False)).plain assert "HEARD ▼" in heard_desc and "▲" not in heard_desc # Ascending flips the same column's glyph without touching the others. - assert "HEARD ▲" in _picker_header(12, NodesSort("heard", ascending=True)).plain + assert "HEARD ▲" in _header(12, NodesSort("heard", ascending=True)).plain # A different active column moves the mark; packets opens descending. - packets = _picker_header(12, NodesSort.from_name("packets")).plain + packets = _header(12, NodesSort.from_name("packets")).plain assert "PKTS ▼" in packets and "HEARD" in packets and "HEARD ▼" not in packets # The hash column is sortable now too, so it carries the mark when it's active. - hash_sorted = _picker_header(12, NodesSort("hash", ascending=True)).plain + hash_sorted = _header(12, NodesSort("hash", ascending=True)).plain assert "HASH ▲" in hash_sorted and "PKTS ▲" not in hash_sorted def test_picker_header_highlights_only_the_active_sort_column() -> None: """The active column's label and its triangle are lit cyan; the other lanes stay muted.""" - from meshterm.ui.timemachine_screen import _PICK_SORT_ACTIVE, _picker_header + from meshterm.ui.nodelist import _SORT_ACTIVE, _header from meshterm.ui.widgets import NodesSort - header = _picker_header(12, NodesSort.from_name("packets")) - lit = [header.plain[s.start:s.end] for s in header.spans if s.style == _PICK_SORT_ACTIVE] + header = _header(12, NodesSort.from_name("packets")) + lit = [header.plain[s.start:s.end] for s in header.spans if s.style == _SORT_ACTIVE] # Exactly the active PKTS lane (label + triangle) carries the highlight. assert any("PKTS" in seg and "▼" in seg for seg in lit) assert not any(any(other in seg for other in ("NAME", "HEARD", "HASH")) for seg in lit) @@ -611,16 +617,11 @@ def test_picker_header_highlights_only_the_active_sort_column() -> None: def _picker(listed, *, prefix_bytes=0, sort=None, type_of=None, resolve_key=None, width=80): """Build a rendered picker over ``listed`` and return it (rows sized to ``width``).""" - from meshterm.ui.timemachine_screen import ( - _PICKER_SORT_COLUMNS, - _PICKER_SORT_OPENS_ASCENDING, - TimeMachinePickerScreen, - ) + from meshterm.ui.nodelist import SORT_COLUMNS, SORT_OPENS_ASCENDING + from meshterm.ui.timemachine_screen import TimeMachinePickerScreen from meshterm.ui.widgets import NodesSort - default_sort = NodesSort.from_name( - "heard", _PICKER_SORT_COLUMNS, _PICKER_SORT_OPENS_ASCENDING - ) + default_sort = NodesSort.from_name("heard", SORT_COLUMNS, SORT_OPENS_ASCENDING) screen = TimeMachinePickerScreen( listed=listed, prefix_bytes=prefix_bytes, @@ -764,17 +765,17 @@ def test_picker_resort_keeps_the_highlight_on_its_node_and_the_filter() -> None: def test_picker_name_lane_is_content_sized_and_hash_lane_flexes() -> None: """Columns anchor left: the name lane hugs its content and stays put as the window widens, and the freed width flows to the hash lane so more of each key shows.""" - from meshterm.ui.timemachine_screen import _PICK_LEAD + from meshterm.ui.nodelist import _LEAD screen = _picker(_heard_nodes(), width=72) # The widest name here is the "unknown" fallback (7 cells); the lane sizes to it. name_w, hash_w = screen._name_w, screen._hash_w assert name_w == len("unknown") - assert hash_w == 72 - _PICK_LEAD - name_w + assert hash_w == 72 - _LEAD - name_w # Widen the terminal: the name lane does not move, the hash lane takes the extra width. screen.render_body(120) assert screen._name_w == name_w - assert screen._hash_w == 120 - _PICK_LEAD - name_w + assert screen._hash_w == 120 - _LEAD - name_w assert screen._hash_w > hash_w @@ -914,17 +915,22 @@ def test_self_sections_render_the_page_and_empty_window(tmp_path: Path) -> None: def test_self_row_leads_the_node_list_as_a_lane() -> None: """The own-node lane shows our name + (you), faint — for heard/pkts, and our key hash.""" - from meshterm.ui.timemachine_screen import _self_picker_row + from meshterm.ui.nodelist import NodeRow, _lane + from meshterm.ui.timemachine_screen import SELF - named = _self_picker_row( - "YUL-Johputer", "3d" * 32, name_w=30, prefix_bytes=1, hash_w=30 + named = _lane( + NodeRow(value=SELF, name="YUL-Johputer", key="3d" * 32, you=True), + name_w=30, prefix_bytes=1, hash_w=30, ).plain assert named.startswith("★") assert "YUL-Johputer" in named and "(you)" in named assert "—" in named # heard and packets have nothing to show for us assert "3d3d" in named # our key hash, its routing prefix lit # No reachable device: a bare "you" name and a "?" hash, no "(you)" tag. - anon = _self_picker_row(None, None, name_w=30, prefix_bytes=0, hash_w=30).plain + anon = _lane( + NodeRow(value=SELF, name=None, key="", you=True), + name_w=30, prefix_bytes=0, hash_w=30, + ).plain assert "you" in anon and "(you)" not in anon assert anon.rstrip().endswith("?")