diff --git a/meshterm/ui/nodes_screen.py b/meshterm/ui/nodes_screen.py index fe53481..c40e0b5 100644 --- a/meshterm/ui/nodes_screen.py +++ b/meshterm/ui/nodes_screen.py @@ -8,6 +8,7 @@ same table statically; only the menu gets the live sorting. from __future__ import annotations +import re from typing import TYPE_CHECKING from .tui.render import render_lines @@ -18,6 +19,9 @@ 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") + class NodesScreen(Screen): """A full-screen, keyboard-sortable list of this node and its known contacts.""" @@ -54,7 +58,7 @@ class NodesScreen(Screen): self._sort = sort def render_body(self, width: int) -> list[str]: - """Render the table+legend at the current sort and remember its line count.""" + """Render the table+legend at the current sort, pinning the column header on scroll.""" table = nodes_table( self._self_name, self._self_key, @@ -65,8 +69,26 @@ class NodesScreen(Screen): ) lines = render_lines(table, width) self._scroll_total = max(1, len(lines)) + # Pin the ``Name / Heard / Pkts / Key`` labels so they stay in view once the rows scroll + # past — the base Screen.sticky_header re-draws the recorded line as the top row. The + # header sits directly above the rule the table draws under it (box.SIMPLE_HEAD). + self._sticky_headers = self._column_header(lines) return lines + @staticmethod + def _column_header(lines: list[str]) -> list[tuple[int, str]]: + """Locate the column-header row (the line just above the table's header rule). + + The table renders a full-width rule of ``─`` under its column labels; the first such + line marks the header, so the row above it carries the labels. Returns a single-entry + sticky-header list, or empty 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 - 1, lines[idx - 1])] + return [] + def handle(self, action: str, data: str = "") -> None: """Re-sort with the arrows, scroll with PageUp/PageDown/Home/End, or dismiss.""" if action == "left": diff --git a/meshterm/ui/theme.py b/meshterm/ui/theme.py index 6b58b48..51e7399 100644 --- a/meshterm/ui/theme.py +++ b/meshterm/ui/theme.py @@ -24,6 +24,9 @@ MESH_THEME = Theme( "warn": "bold #fbbf24", "err": "bold #f87171", "muted": "#94a3b8", + # A step darker than ``muted`` for placeholder dashes (a node's missing packet count / + # age) that should recede below the real, muted values around them. + "faint": "#64748b", "snr.good": "bold #4ade80", "snr.ok": "bold #fbbf24", "snr.bad": "bold #f87171", diff --git a/meshterm/ui/widgets.py b/meshterm/ui/widgets.py index 6aeb17d..61e2624 100644 --- a/meshterm/ui/widgets.py +++ b/meshterm/ui/widgets.py @@ -570,9 +570,11 @@ def _ordered_contacts( ) -> list[Contact]: """Contacts sorted per ``sort`` (our own node is pinned separately, above these). - Sorts ascending by the active column's metric with a case-folded name tiebreak, then - reverses for a descending sort. Never-heard / never-overheard rows carry an extreme - metric so they gather at the ascending end. + The active column's metric drives the order (reversed for a descending sort); ties always + break by case-folded name *ascending*, so two nodes sharing a metric (e.g. the same + ``heard`` age) keep a stable A→Z order instead of flipping with the primary direction. + Never-heard / never-overheard rows carry an extreme metric so they gather at the ascending + end. """ if sort.column == "heard": def metric(c: Contact) -> float: @@ -585,9 +587,10 @@ def _ordered_contacts( def metric(c: Contact) -> object: return c.name.casefold() - ordered = sorted(contacts, key=lambda c: (metric(c), c.name.casefold())) - if not sort.ascending: - ordered.reverse() + # Name-ascending first, then a stable sort by the primary metric: equal-metric rows retain + # their A→Z order under both directions (reversing the whole list would flip the tiebreak). + ordered = sorted(contacts, key=lambda c: c.name.casefold()) + ordered.sort(key=metric, reverse=not sort.ascending) return ordered @@ -604,20 +607,16 @@ def _sort_header(label: str, column: str, sort: NodesSort) -> str: return f"[bold #22d3ee]{label} {triangle}[/]" -def _nodes_legend(contacts: list[Contact]) -> Text: - """A one-line glyph legend covering the node types actually present (plus us).""" - present = {c.node_type for c in contacts} - if any(t not in _NODE_GLYPHS for t in present): - present.add(NODE_TYPE_CHAT) # unknown/None types render as a plain node +def _nodes_legend() -> Text: + """A one-line glyph legend covering every node type (plus us), whatever's listed.""" legend = Text(" ") # a small indent to sit under the table body legend.append(_SELF[0], style=_SELF[1]) legend.append(" you", style="muted") for node_type in (NODE_TYPE_REPEATER, NODE_TYPE_CHAT, NODE_TYPE_ROOM, NODE_TYPE_SENSOR): - if node_type in present: - glyph, color = _NODE_GLYPHS[node_type] - legend.append(" ") - legend.append(glyph, style=color) - legend.append(f" {NODE_TYPE_LABELS[node_type]}", style="muted") + glyph, color = _NODE_GLYPHS[node_type] + legend.append(" ") + legend.append(glyph, style=color) + legend.append(f" {NODE_TYPE_LABELS[node_type]}", style="muted") return legend @@ -681,8 +680,8 @@ def nodes_table( table.add_row( Text(_SELF[0], style=_SELF[1]), Text.assemble((self_name, "accent"), (" (you)", "muted")), - Text("—", style="muted"), - Text("—", style="muted"), + Text("—", style="faint"), + Text("—", style="faint"), highlighted_hash(self_key, prefix_bytes) if self_key else unknown, ) table.add_section() @@ -694,10 +693,10 @@ def nodes_table( Text(glyph, style=glyph_style), Text(c.name, style=_recency_style(secs)), Text(_format_age(secs), style="muted"), - Text(str(pkts), style="brand") if pkts else Text("—", style="muted"), + Text(str(pkts), style="muted") if pkts else Text("—", style="faint"), highlighted_hash(c.public_key, prefix_bytes) if c.public_key else unknown, ) - return Group(table, Text(""), _nodes_legend(contacts)) + return Group(table, Text(""), _nodes_legend()) def tx_opt_table(result: TxOptResult) -> Table: diff --git a/tests/test_device_config.py b/tests/test_device_config.py index 39c4554..4797983 100644 --- a/tests/test_device_config.py +++ b/tests/test_device_config.py @@ -158,6 +158,30 @@ def test_nodes_table_sorts_by_heard_and_packets() -> None: assert names(NodesSort(column="heard", ascending=False))[1:] == ["Alice", "Bob"] +def test_nodes_table_breaks_metric_ties_by_name_ascending() -> None: + """Two nodes with the same metric keep an A→Z order in both sort directions (no flip).""" + from datetime import timedelta + + from meshterm.core.models import Contact, utcnow + from meshterm.ui.widgets import NodesSort, _ordered_contacts + + same = utcnow() - timedelta(minutes=5) + contacts = [ + Contact(name="Charlie", public_key="aa" * 16, last_seen=same), + Contact(name="Alice", public_key="bb" * 16, last_seen=same), + Contact(name="Bob", public_key="cc" * 16, last_seen=utcnow() - timedelta(hours=3)), + ] + + def order(ascending: bool) -> list[str]: + sort = NodesSort(column="heard", ascending=ascending) + return [c.name for c in _ordered_contacts(contacts, {}, sort)] + + # Freshest first: the two 5-min nodes lead, ordered Alice→Charlie, then Bob (3h). + assert order(ascending=True) == ["Alice", "Charlie", "Bob"] + # Oldest first: Bob leads, but the tie still breaks Alice→Charlie — not Charlie→Alice. + 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 @@ -180,6 +204,28 @@ def test_nodes_screen_arrows_steer_the_sort() -> None: assert screen._sort.column == "packets" +def test_nodes_screen_pins_column_header_when_scrolled() -> None: + """The Name/Heard/Pkts/Key labels stick to the top row once the rows scroll past them.""" + import re + + from meshterm.core.models import Contact + from meshterm.ui.nodes_screen import NodesScreen + from meshterm.ui.widgets import NodesSort + + contacts = [Contact(name=f"n{i}", public_key="ab" * 16) for i in range(12)] + screen = NodesScreen("Us", "aabbcc" + "00" * 29, contacts, 3, {}, NodesSort()) + screen.render_body(70) + + # Exactly one sticky header — the column-label row — recorded above the table's rule. + (idx, header), = screen._sticky_headers + labels = re.sub(r"\x1b\[[0-9;]*m", "", header) + assert "Name" in labels and "Heard" in labels and "Key" in labels + + # Not pinned while the header is still on screen; pinned once scrolled below it. + assert screen.sticky_header(idx) is None + assert screen.sticky_header(idx + 5) == header + + def test_non_strict_enum_accepts_unlisted_value() -> None: """multi_acks/adv_loc_policy list common values but still accept other ints.""" spec = get_spec("multi_acks")