diff --git a/meshterm/ui/courier_screen.py b/meshterm/ui/courier_screen.py index ebabd95..9d991d0 100644 --- a/meshterm/ui/courier_screen.py +++ b/meshterm/ui/courier_screen.py @@ -25,13 +25,13 @@ import re from datetime import datetime, timedelta, timezone from typing import TYPE_CHECKING, Any +from rich.cells import cell_len from rich.text import Text from ..core.courier_store import DELIVERED, QUEUED, QueuedMessage from ..core.models import Contact, is_direct_messageable, utcnow from .contactlist import SORT_COLUMNS, SORT_OPENS_ASCENDING, ContactListScreen, ContactRow -from .menus import command_label, marked_label, run_steps, section_heading -from .theme import glyph +from .menus import icon_lane, marked_label, run_steps, section_heading from .tui import CANCEL, DM_BYTE_LIMIT, Choice, SelectScreen, Separator from .watchtower_screen import contact_watch_key from .widgets import ContactsSort, _age_seconds, _contact_pkts, format_ago @@ -43,6 +43,18 @@ if TYPE_CHECKING: _QUEUE = ("queue",) _CLEAR = ("clear",) +#: The status marks an outbox entry leads with: waiting, delivered, gave up. They are the +#: row's outcome rather than decoration, so unlike a command row's icon they are drawn on +#: every platform — and measured raw, since the PicoCalc's render fold pads a folded mark +#: back out to the width the emoji measured. +_ENTRY_MARKS = ("⏳", "✓", "✗") + +#: The widest entry mark in cells: the part of the outbox's icon column no platform drops. +_MARK_LANE = max(cell_len(mark) for mark in _ENTRY_MARKS) + +#: The outbox's decorative command icons — queue a message, clear the finished history. +_COMMAND_ICONS = ("📨", "🗑") + #: Seconds between the open outbox's refresh ticks (shape check + repaint). _REFRESH_S = 1.0 @@ -229,28 +241,55 @@ def _menu_items(ctx: AppContext, entries: list[QueuedMessage]) -> list: waiting = [m for m in entries if m.status == QUEUED] done = [m for m in entries if m.status != QUEUED] + # One icon column for the whole list, across both sections. The terminal draws ⏳ and + # 📨 in two cells but ✓ ✗ 🗑 in one, so rows written ``mark + " "`` started a finished + # entry's recipient a column left of a waiting one's, and *Clear finished* a column left + # of *Queue a message…*. The entry marks always keep their share of the column; the + # command icons go where the platform draws no icon lane, and marked_label leaves those + # two labels bare rather than padded out to a mark that isn't there. + lane = max(icon_lane(_COMMAND_ICONS), _MARK_LANE) + items: list = [section_heading("Outbox")] if not waiting: items.append(Separator(" empty — queued messages wait here for their moment")) for message in waiting: - items.append(Choice(lambda m=message: _waiting_row(ctx, m), ("msg", message.ident))) + items.append(Choice(lambda m=message: _waiting_row(ctx, m, lane), ("msg", message.ident))) items.append(Separator(" ")) # space the action off the outbox rows above it - items.append(Choice(f"{glyph('📨')} Queue a message…", _QUEUE)) + items.append(Choice(marked_label("📨", "Queue a message…", "", lane=lane), _QUEUE)) if done: items.append(Separator(" ")) items.append(section_heading("Finished")) for message in done[:15]: - items.append(Choice(lambda m=message: _done_row(m), ("msg", message.ident))) - items.append(Choice(f"{glyph('🗑')} Clear finished", _CLEAR)) + items.append(Choice(lambda m=message: _done_row(m, lane), ("msg", message.ident))) + items.append(Choice(marked_label("🗑", "Clear finished", "", lane=lane), _CLEAR)) return items -def _waiting_row(ctx: AppContext, message: QueuedMessage) -> Text: +def _entry_mark(mark: str, style: str, lane: int) -> Text: + """An entry's status mark, tinted and padded out to the outbox's icon column. + + The entry-row twin of :func:`~meshterm.ui.menus.icon_mark`, which cannot serve here: + that one drops its icon where the platform draws no icon lane, and an entry's mark is + its outcome (waiting, delivered, gave up), which every platform must still show. + + Args: + mark: One of :data:`_ENTRY_MARKS`. + style: The theme style the mark is drawn in. + lane: The list's icon column in cells (see :func:`_menu_items`). + + Returns: + The mark followed by enough spaces to start the words in the column after it. + """ + text = Text(mark, style=style) + text.append(" " * (lane - cell_len(mark) + 1)) + return text + + +def _waiting_row(ctx: AppContext, message: QueuedMessage, lane: int = _MARK_LANE) -> Text: """One waiting entry: recipient, body, and what it is waiting for.""" - row = Text() - row.append("⏳ ", style="warn") + row = _entry_mark("⏳", "warn", lane) row.append(message.node_name) row.append(f" “{_shorten(message.text)}”", style="muted") row.append(" · ", style="muted") @@ -273,13 +312,12 @@ def _waiting_row(ctx: AppContext, message: QueuedMessage) -> Text: return row -def _done_row(message: QueuedMessage) -> Text: +def _done_row(message: QueuedMessage, lane: int = _MARK_LANE) -> Text: """One finished entry: outcome marker, recipient, body, and when it settled.""" - row = Text() if message.status == DELIVERED: - row.append("✓ ", style="ok") + row = _entry_mark("✓", "ok", lane) else: - row.append("✗ ", style="err") + row = _entry_mark("✗", "err", lane) row.append(message.node_name, style="muted") row.append(f" “{_shorten(message.text)}”", style="muted") when = message.finished or message.created @@ -513,9 +551,13 @@ async def _entry_actions(ctx: AppContext, ident: int) -> None: ) await session.message_dialog(body, title=message.node_name) return + # One measured column for both rows: 📤 draws two cells and ✗ one, and the Cancel row + # measuring only its own mark started its words a column left of Send now's. Where the + # platform draws no icon lane both go bare, Cancel's err tint moving onto its words. + lane = icon_lane(("📤", "✗")) items = [ - Choice(command_label("📤 Send now — one forced attempt"), "send"), - Choice(marked_label("✗", "Cancel this message", "err"), "cancel"), + Choice(marked_label("📤", "Send now — one forced attempt", "", lane=lane), "send"), + Choice(marked_label("✗", "Cancel this message", "err", lane=lane), "cancel"), ] picked = await session.select( f"{message.node_name} — “{_shorten(message.text, 28)}”", diff --git a/meshterm/ui/device_picker.py b/meshterm/ui/device_picker.py index 029306c..863fc64 100644 --- a/meshterm/ui/device_picker.py +++ b/meshterm/ui/device_picker.py @@ -45,7 +45,7 @@ from ..core.discovery import ( ) from ..platforms import get_platform from .logo import load_logo -from .menus import Lane, column_header, fit_cells +from .menus import Lane, align_icons, column_header, fit_cells from .tui import Choice, DeleteRequest, KeyRequest, Separator if TYPE_CHECKING: @@ -849,12 +849,14 @@ def _action_rows() -> list: A network (TCP) companion doesn't advertise and isn't attached, so it can't be scanned for — the "add a network device" row opens a host:port prompt to name one. The Quit row - mirrors the main menu. The leading spaces line both up under the device-name column. + mirrors the main menu. The leading spaces line both up under the device-name column, and + the icons share one measured column (:func:`~meshterm.ui.menus.align_icons`): ``🌐`` and + ``🚪`` happen to be the same width today, and the words stay aligned if one changes. Where + the platform draws no icon lane the icons go, padding and all, like every command row's. """ - add_row = Text() - add_row.append(f" {_TCP_ICON} Add a network device…") + add_label, quit_label = align_icons([f"{_TCP_ICON} Add a network device…", "🚪 Quit"]) return [ Separator(" "), - Choice(title=add_row, value=_ADD_TCP), - Choice(title=" 🚪 Quit", value=_QUIT), + Choice(title=Text.assemble(" ", add_label), value=_ADD_TCP), + Choice(title=Text.assemble(" ", quit_label), value=_QUIT), ] diff --git a/meshterm/ui/menu.py b/meshterm/ui/menu.py index 3cc8fa1..3f3f2b3 100644 --- a/meshterm/ui/menu.py +++ b/meshterm/ui/menu.py @@ -31,7 +31,6 @@ from .braillechart import activity_peak, activity_sparkline from .menus import ( SEP_COMPACT, SEP_ROOMY, - command_label, icon_lane, icon_mark, section_heading, @@ -468,7 +467,37 @@ async def _unpair_on_exit(ctx: AppContext) -> None: await MeshCoreDevice.unpair_ble(address) -def _menu_labels(tools: Sequence[Any]) -> list[Text]: +#: The mark the menu's closing Quit row leads with. Named rather than written inline in the +#: row because the menu's icon column has to *measure* it: it is one of the icons the list +#: can show, the same as any tool's. +_QUIT_ICON = "🚪" + +#: The value the Quit row resolves with — Esc's ``CANCEL`` and this both open the quit +#: confirm (see :func:`_menu_round`). +_QUIT_VALUE = "__quit__" + + +def _menu_lane(tools: Sequence[Any]) -> int: + """The main menu's icon column in cells: every tool's mark *and* the Quit row's. + + The Quit row shares the list with the tool rows, so it has to share their column too. + It used to write ``🚪 Quit`` as a plain string outside the measurement. That only lined + up because ``🚪`` happened to be as wide as the widest tool icon. A one-cell quit mark + would have started *Quit* a column early. A three-cell tool icon (a ZWJ cluster, say) + would have left it a column behind. Measuring the column over both makes the alignment + hold by construction instead of by luck. + + Args: + tools: The menu's visible tools. + + Returns: + The column width from :func:`~meshterm.ui.menus.icon_lane` — ``0`` where the + platform draws no icon lane. + """ + return icon_lane([*(tool.icon for tool in tools), _QUIT_ICON]) + + +def _menu_labels(tools: Sequence[Any], *, lane: int | None = None) -> list[Text]: """Every visible tool's menu label — the icon, its column, and the title after it. The menu's icons are **not all one width**: ``⚙`` draws a single cell where ``📡`` @@ -482,20 +511,70 @@ def _menu_labels(tools: Sequence[Any]) -> list[Text]: Args: tools: The menu's visible tools, in the order they are drawn. + lane: The icon column's width, when the caller has already measured it for the + whole list (see :func:`_menu_items`). ``None`` measures it here, over the same + icons — the tools' marks and the Quit row's — so either way the answer is the + one :func:`_menu_lane` gives. Returns: One label per tool, in that same order — fresh :class:`~rich.text.Text` the caller is free to append its description to. """ - lane = icon_lane([tool.icon for tool in tools]) + width = _menu_lane(tools) if lane is None else lane labels: list[Text] = [] for tool in tools: - label = icon_mark(tool.icon, "", lane) + label = icon_mark(tool.icon, "", width) label.append(tool.title or tool.name) labels.append(label) return labels +def _menu_items(tools: Sequence[Any]) -> list: + """The main menu's rows: the tools under their section headings, then Quit. + + Separated from :func:`_menu_loop` so the list can be built and checked without a + session. It is a pure function of the tools, which is also why the loop builds it + once and keeps it for the whole session. + + The rows have two columns, the tool's name and then its muted description, and no + header line. They are commands rather than table data, so the alignment is enough. + The Quit row is marked from the **same measured icon column** as the tool rows (see + :func:`_menu_lane`), so its word starts in the same cell as every title above it. + The platform decides the column's width. Where the platform draws no icon lane, + :func:`~meshterm.ui.menus.icon_mark` returns nothing, separator included, and the + row is the bare word *Quit*, flush with titles that are flush themselves. + + Args: + tools: The menu's visible tools, in the order they are drawn (already sorted by + category, so each heading opens its section exactly once). + + Returns: + The :class:`~meshterm.ui.tui.Choice` and :class:`~meshterm.ui.tui.Separator` + rows, ready for the menu's :class:`~meshterm.ui.tui.SelectScreen`. + """ + lane = _menu_lane(tools) + labels = _menu_labels(tools, lane=lane) + name_w = max((label.cell_len for label in labels), default=0) + items: list = [] + current_category: str | None = None + for tool, row in zip(tools, labels, strict=True): + if tool.category != current_category: + current_category = tool.category + items.append(section_heading(current_category)) + row.append(" " * (name_w - row.cell_len + 2)) + row.append(tool.help, style="muted") + # The tool's name is the row's identity and always fits; only the description + # runs long, so ←→ slide it alone under a pinned name (Choice.hscroll_from). + items.append(Choice(title=row, value=tool.name, hscroll_from=name_w + 2)) + items.append(Separator(" ")) + # Quit carries no description, so it takes no part in name_w; only its mark joins + # the tools' column. + quit_label = icon_mark(_QUIT_ICON, "", lane) + quit_label.append("Quit") + items.append(Choice(title=quit_label, value=_QUIT_VALUE)) + return items + + async def _menu_loop(ctx: AppContext, session: TuiSession) -> None: """Show the tool menu and run selections until the user quits. @@ -515,24 +594,8 @@ async def _menu_loop(ctx: AppContext, session: TuiSession) -> None: ctx: The shared application context. session: The running TUI session. """ - # Two aligned columns — tool name, then its muted description — with no header - # line: these are commands, not tabular data, so the alignment alone carries it. tools = [tool for tool in all_tools() if tool.menu_visible] - labels = _menu_labels(tools) - name_w = max((label.cell_len for label in labels), default=0) - items: list = [] - current_category: str | None = None - for tool, row in zip(tools, labels, strict=True): - if tool.category != current_category: - current_category = tool.category - items.append(section_heading(current_category)) - row.append(" " * (name_w - row.cell_len + 2)) - row.append(tool.help, style="muted") - # The tool's name is the row's identity and always fits; only the description - # runs long, so ←→ slide it alone under a pinned name (Choice.hscroll_from). - items.append(Choice(title=row, value=tool.name, hscroll_from=name_w + 2)) - items.append(Separator(" ")) - items.append(Choice(title=command_label("🚪 Quit"), value="__quit__")) + items = _menu_items(tools) # Drive the menu list ourselves (rather than via session.select) so it stays on the # stack while the quit dialog floats over it: the confirm is drawn as a centered box @@ -608,7 +671,7 @@ async def _menu_round( # Both picking "quit" and pressing Esc ask to leave; confirm on a dialog floating # over the (still-pushed) menu so a stray key doesn't drop the user out. Cancel # (Esc) sits left of Quit (Enter); Quit starts highlighted so Enter commits it. - if selection in (None, "__quit__"): + if selection in (None, _QUIT_VALUE): # Offer to drop the OS pairing on the way out, but only when there is a live # Bluetooth bond to drop — never on serial, an open (PIN-less) companion, or a # platform we can't unpair. The extra button sits between Cancel and Quit and is diff --git a/meshterm/ui/menus.py b/meshterm/ui/menus.py index 03746c0..7e9951c 100644 --- a/meshterm/ui/menus.py +++ b/meshterm/ui/menus.py @@ -11,7 +11,10 @@ construction: an err-tinted ``✗ Back — discard staged changes``, and *nothing at all* when clean. * :func:`menu_rows` — label + muted description :class:`Choice` rows in two aligned lanes, padded in display cells so double-width emoji can't skew the description - column (the Device actions presentation). + column (the Device actions presentation), its icons lined up by :func:`align_icons`. +* :func:`align_icons` — THE icon column for labels that carry their icon inside the string: + a one-cell ``⌨`` and a two-cell ``📡`` start their words in the same cell. A list that + builds its :class:`Choice` rows by hand runs its labels through it. * :func:`lane_row` — one SETTING / VALUE / DESCRIPTION row for the editor-style lists. * :func:`column_header` / :class:`Lane` — the header line over a lane-aligned list, which abbreviates its labels to fit a narrow terminal instead of wrapping or losing one, and @@ -180,13 +183,74 @@ def command_label(label: LabelT) -> LabelT: if get_platform().menu_icons: return label plain = label.plain if isinstance(label, Text) else label - head, sep, rest = plain.partition(" ") - if not sep or not head or head[0].isalnum() or not rest.strip(): + head = _icon_head(plain) + if not head: return label # Take the gap with the icon: a row that padded a one-cell mark out to the width of # its two-cell siblings ("↕ Reorder channels") must not leave the padding behind. - cut = len(plain) - len(rest.lstrip(" ")) - return label[cut:] + return label[_words_start(plain, head) :] + + +def _icon_head(plain: str) -> int: + """How many characters of ``plain`` are its leading icon — ``0`` when it has none. + + The one definition of "this label leads with an icon", shared by :func:`command_label` + (which drops the head) and :func:`align_icons` (which pads it): everything before the + first space, when that head starts with a non-alphanumeric character and words follow. + """ + head, sep, rest = plain.partition(" ") + if not sep or not head or head[0].isalnum() or not rest.strip(): + return 0 + return len(head) + + +def _words_start(plain: str, head: int) -> int: + """The character index where the words after an ``head``-long icon begin.""" + return len(plain) - len(plain[head:].lstrip(" ")) + + +def align_icons(labels: Iterable[LabelT]) -> list[LabelT]: + """``labels`` with every leading icon padded out so the words all start in one cell. + + THE icon column for a list whose icons ride *inside* its label strings. The terminal + draws ``↻ ⌨ 🗑 ✎ ⚙`` in one cell and ``📡 💾 🔐`` in two, so rows written ``icon + " "`` + start their words a column apart — the fault that kept reappearing screen by screen + (the node page, the main menu, the repeater admin) until the column was measured here, + once, for every list. :func:`menu_rows` runs its labels through it, so a screen built on + that never has to think about it; a list that builds its :class:`Choice` rows by hand + passes its labels through this instead. + + Each label first passes :func:`command_label`, so where the platform draws no icon lane + the icons are already gone and nothing is padded. A label with no icon head is returned + as it came, and so is a lone icon row's spacing when every head is the same width. + Re-aligning a list that was already aligned (by :func:`marked_label` with a ``lane``, or + by an earlier pass) changes nothing: the existing gap is replaced, never added to. + + Args: + labels: The list's labels in order, icons included — plain strings or styled + :class:`~rich.text.Text` (whose spans and base style survive, the base style + carried as a span). + + Returns: + The labels, a padded :class:`~rich.text.Text` for every one that leads with an + icon and the original object for every one that doesn't. + """ + stripped = [command_label(label) for label in labels] + plains = [label.plain if isinstance(label, Text) else label for label in stripped] + heads = [_icon_head(plain) for plain in plains] + lane = max( + (cell_len(plain[:head]) for plain, head in zip(plains, heads, strict=True) if head), + default=0, + ) + aligned: list[LabelT] = [] + for label, plain, head in zip(stripped, plains, heads, strict=True): + if not head: + aligned.append(label) + continue + text = label if isinstance(label, Text) else Text(label) + pad = " " * (lane - cell_len(plain[:head]) + 1) + aligned.append(Text.assemble(text[:head], pad, text[_words_start(plain, head) :])) + return aligned def exit_rows(staged: int, *, apply_value: Any, back_value: Any) -> list: @@ -233,11 +297,14 @@ def menu_rows(rows: Iterable[tuple[str | Text, str, Any]]) -> list: description column starting two cells past the widest label, padding computed in display cells so a double-width emoji can't skew it. - Each label passes through :func:`command_label` first, so a platform that draws no - icon lane loses it *before* the lane is measured — the description column moves left - with the labels rather than going ragged behind them. Each row also pins that column - as its :attr:`~meshterm.ui.tui.select.Choice.hscroll_from`, so on an ``hscroll`` list - ←→ slide the description under a label that stays put. + The labels pass through :func:`align_icons` first, which is two guarantees at once: a + platform that draws no icon lane loses the icons *before* the lane is measured (so the + description column moves left with the labels rather than going ragged behind them), + and where icons are drawn, a one-cell ``⌨`` and a two-cell ``📡`` start their words in + the same cell — no caller has to measure an icon column for a list built here. Each row + also pins the description column as its + :attr:`~meshterm.ui.tui.select.Choice.hscroll_from`, so on an ``hscroll`` list ←→ slide + the description under a label that stays put. Args: rows: ``(label, description, value)`` triples. A :class:`Text` label keeps its @@ -246,11 +313,11 @@ def menu_rows(rows: Iterable[tuple[str | Text, str, Any]]) -> list: Returns: One :class:`Choice` per row, lanes aligned across them all. """ + rows = list(rows) + labels = align_icons(label for label, _, _ in rows) prepared = [ (Text(label) if isinstance(label, str) else label.copy(), help_text, value) - for label, help_text, value in ( - (command_label(label), help_text, value) for label, help_text, value in rows - ) + for label, (_, help_text, value) in zip(labels, rows, strict=True) ] width = max((cell_len(label.plain) for label, _, _ in prepared), default=0) items: list = [] diff --git a/meshterm/ui/records_screen.py b/meshterm/ui/records_screen.py index 7b81467..a9ddce6 100644 --- a/meshterm/ui/records_screen.py +++ b/meshterm/ui/records_screen.py @@ -48,7 +48,7 @@ from ..persistence.repository import DiscoveredPath from ..services import trace_runner from ..services.records import CATEGORIES, CATEGORY_BY_ID, Category, _local_xy from .mapcanvas import RGB, MapCanvas -from .menus import fit_cells, marked_label, section_heading +from .menus import fit_cells, icon_lane, marked_label, section_heading from .pathgraph import PathLayer, render_path_graph from .pathline import path_line from .theme import glyph, name_style, snr_style @@ -505,15 +505,21 @@ class RecordDialog(Screen): lines.append("") self._cursor = None + # One measured icon column for both action rows: 🗑 is one cell where 👣 is two, so + # each mark measured on its own started "Delete record…" a column left of "Trace this + # path". Empty where the platform draws no icons, and the labels take the cells back. + lane = icon_lane(("👣", "🗑")) for i, key in enumerate(self._actions): selected = i == self._index row = Text("❯ " if selected else " ", style="cursor" if selected else "") if key == "trace": row.append_text( - marked_label("👣", "Trace this path — reopen in Trace path", "accent") + marked_label( + "👣", "Trace this path — reopen in Trace path", "accent", lane=lane + ) ) else: - row.append_text(marked_label("🗑", "Delete record…", "err")) + row.append_text(marked_label("🗑", "Delete record…", "err", lane=lane)) if selected: row.style = "cursor" self._cursor = len(lines) diff --git a/meshterm/ui/watchtower_screen.py b/meshterm/ui/watchtower_screen.py index e899506..60984fc 100644 --- a/meshterm/ui/watchtower_screen.py +++ b/meshterm/ui/watchtower_screen.py @@ -18,12 +18,13 @@ from __future__ import annotations from collections.abc import Callable from typing import TYPE_CHECKING, Any +from rich.cells import cell_len from rich.text import Text from ..core.models import Contact from ..core.watch_store import OFF, SILENCE_CHOICES_H, Alert, WatchedNode from ..services.trace_runner import make_name_key_resolver -from .menus import command_label, marked_label, section_heading +from .menus import icon_lane, icon_mark, marked_label, section_heading from .theme import name_style from .tui import Choice, Separator from .widgets import _DEFAULT_GLYPH, _NODE_GLYPHS, _age_seconds, _format_age @@ -195,12 +196,19 @@ def _menu_items( hscroll_from=lanes.cell_len, ) ) + # One measured icon column for every action row on this screen, across its headings: the + # terminal draws ✓ and 🗑 in one cell and ⭐ and 🔔 in two, so the bulk actions used to + # start their words a column left of Watch a node… and the new-node toggle below them. + # Declared whole rather than from the rows present, so the column holds still as the + # conditional rows come and go; empty where the platform draws no icons. + lane = icon_lane(("✓", "🗑", "⭐", "🔔")) unacked = sum(1 for a in alerts if not a.acked) acked = len(alerts) - unacked if unacked: - items.append(Choice(marked_label("✓", f"Acknowledge all ({unacked})", "ok"), _ACK_ALL)) + ack_all = marked_label("✓", f"Acknowledge all ({unacked})", "ok", lane=lane) + items.append(Choice(ack_all, _ACK_ALL)) if acked: - items.append(Choice(marked_label("🗑", "Clear acknowledged", "err"), _CLEAR)) + items.append(Choice(marked_label("🗑", "Clear acknowledged", "err", lane=lane), _CLEAR)) items.append(Separator(" ")) items.append(section_heading("Watched nodes")) @@ -208,20 +216,14 @@ def _menu_items( items.append(Separator(" none starred yet — silence and SNR rules need one")) for key in sorted(watched, key=lambda k: watched[k].name.casefold()): items.append(Choice(_watched_row(watched[key], type_of), ("node", key))) - items.append(Choice(command_label("⭐ Watch a node…"), _WATCH)) + items.append(Choice(marked_label("⭐", "Watch a node…", "", lane=lane), _WATCH)) items.append(Separator(" ")) state = "[ok]on[/ok]" if new_node_alerts else "[muted]off[/muted]" - items.append( - Choice( - command_label( - Text.from_markup( - f"🔔 New-node alerts: {state} [muted]— announce first-ever appearances[/muted]" - ) - ), - _TOGGLE_NEW, - ) + toggle = Text.from_markup( + f"New-node alerts: {state} [muted]— announce first-ever appearances[/muted]" ) + items.append(Choice(Text.assemble(icon_mark("🔔", "", lane), toggle), _TOGGLE_NEW)) return items @@ -349,19 +351,9 @@ async def _node_rules(ctx: AppContext, key: str) -> None: entry = store.watched().get(key) if entry is None: return - silence = "off" if entry.silence_hours == OFF else f"after {entry.silence_hours} h" - items = [ - Choice(command_label(f"🕒 Silence alarm {silence}"), "silence"), - Choice( - command_label("📶 SNR watch " + ("on" if entry.snr_watch else "off")), - "snr", - ), - Separator(" "), - Choice(marked_label("✗", "Stop watching this node", "err"), "unwatch"), - ] picked = await session.select( f"Rules — {entry.name}", - items, + _rule_items(entry), filterable=False, footer_hint="↑↓ move · Enter change · Esc back", ) @@ -376,6 +368,47 @@ async def _node_rules(ctx: AppContext, key: str) -> None: return +#: Cells between the widest rule name and its value in the rule popover. +_RULE_VALUE_GAP = 6 + + +def _rule_items(entry: WatchedNode) -> list: + """One watched node's rule popover rows: its two rules with their values, then Stop. + + The terminal draws ``🕒`` and ``📶`` in two cells and ``✗`` in one, so the rows share one + measured icon column — the Stop row used to start its words a column left of the rules + above it. The value lane is measured too, in cells from the rule names, rather than + padded by hand with spaces: it then sits in one column whatever the icon column comes + to, including nothing at all where the platform draws no icons. + + Args: + entry: The watched node whose rules the rows show. + + Returns: + The popover's rows, ``"silence"``/``"snr"``/``"unwatch"`` as their values. + """ + lane = icon_lane(("🕒", "📶", "✗")) + silence = "off" if entry.silence_hours == OFF else f"after {entry.silence_hours} h" + snr = "on" if entry.snr_watch else "off" + rules = (("🕒", "Silence alarm", silence, "silence"), ("📶", "SNR watch", snr, "snr")) + name_w = max(cell_len(name) for _, name, _, _ in rules) + items: list = [ + Choice( + Text.assemble( + icon_mark(icon, "", lane), + name, + " " * (name_w - cell_len(name) + _RULE_VALUE_GAP), + value, + ), + choice, + ) + for icon, name, value, choice in rules + ] + items.append(Separator(" ")) + items.append(Choice(marked_label("✗", "Stop watching this node", "err", lane=lane), "unwatch")) + return items + + async def _pick_silence(ctx: AppContext, key: str, entry: WatchedNode) -> None: """Float the silence-threshold picker for one watched node.""" session = ctx.ui.session diff --git a/tests/test_courier.py b/tests/test_courier.py index 5bce91b..bd11051 100644 --- a/tests/test_courier.py +++ b/tests/test_courier.py @@ -7,11 +7,14 @@ The service is driven synchronously (eligibility) and through stubbed chat sends from __future__ import annotations import logging +import re from datetime import timedelta from pathlib import Path from types import SimpleNamespace import pytest +from rich.cells import cell_len +from rich.text import Text from meshterm.core import exitcodes from meshterm.core.courier_store import DONE_CAP, QUEUED, CourierStore @@ -21,6 +24,7 @@ from meshterm.services.courier import FRESH_S, MAX_ATTEMPTS, CourierService from meshterm.ui.courier_screen import ( CANCEL_SCHEDULE, WHEN_HEARD, + _entry_actions, _pick_schedule, parse_clock, ) @@ -442,7 +446,7 @@ def test_outbox_refresh_moves_a_delivered_entry_without_a_keypress(tmp_path: Pat ctx.courier_store.mark_delivered(entry.ident) screen.refresh() after = _outbox_plain(screen) - assert "Finished" in after and "✓ Hub" in after and "⏳" not in after + assert "Finished" in after and re.search(r"✓ +Hub", after) and "⏳" not in after def test_outbox_refresh_keeps_the_highlight_on_its_entry(tmp_path: Path) -> None: @@ -487,6 +491,94 @@ def test_outbox_rows_recompute_live_state_per_repaint(tmp_path: Path) -> None: assert "try 1" in _outbox_plain(screen) +def _title_plain(choice) -> str: + """A row's label as plain text, resolving a live (callable) title the way a paint does.""" + title = choice.title() if callable(choice.title) else choice.title + return title.plain if isinstance(title, Text) else title + + +def _outbox_titles(tmp_path: Path) -> list[str]: + """Every row of an outbox holding one waiting, one delivered and one given-up entry.""" + from meshterm.ui.courier_screen import CourierOutboxScreen + + ctx = _outbox_ctx(tmp_path) + ctx.courier_store.queue(NODE, "Waiting", "hold this") + landed = ctx.courier_store.queue(NODE, "Landed", "got it") + ctx.courier_store.mark_delivered(landed.ident) + lost = ctx.courier_store.queue(NODE, "Lost", "never") + ctx.courier_store.mark_gave_up(lost.ident) + return [_title_plain(choice) for choice in CourierOutboxScreen(ctx)._choices()] + + +async def _entry_action_titles(tmp_path: Path) -> list[str]: + """The labels a waiting entry's action menu offers (the menu is dismissed unanswered).""" + offered: list = [] + + class _Session: + async def select(self, title, items, **kwargs): + offered.extend(items) + return None + + store = CourierStore(tmp_path / "courier.json") + entry = store.queue(NODE, "Hub", "hello") + ctx = SimpleNamespace(ui=SimpleNamespace(session=_Session()), courier_store=store) + await _entry_actions(ctx, entry.ident) + return [_title_plain(choice) for choice in offered] + + +def _word_starts(rows: list[str], leads: dict[str, str]) -> set[int]: + """The display cell each row's first word starts in, checking the mark it leads with.""" + starts = set() + for word, mark in leads.items(): + row = next(row for row in rows if word in row) + assert row.startswith(mark), f"{word!r} lost its mark: {row!r}" + starts.add(cell_len(row[: row.index(word)])) + return starts + + +async def test_courier_rows_start_every_label_in_the_same_cell(tmp_path: Path) -> None: + """Both of the courier's lists share one icon column, whatever each mark's width. + + The outbox mixes two-cell marks (⏳ a waiting entry, 📨 the queue row) with one-cell ones + (✓ ✗ a finished entry, 🗑 the clear row), and wrote each as ``mark + " "`` — so a finished + recipient sat a column left of a waiting one and *Clear finished* a column left of + *Queue a message…*. An entry's actions did the same with 📤 over ✗. Cells, not + characters, are the measure: that is what the terminal lines up. + """ + outbox = {"Waiting": "⏳", "Queue": "📨", "Landed": "✓", "Lost": "✗", "Clear": "🗑"} + actions = {"Send": "📤", "Cancel": "✗"} + assert {cell_len(mark) for mark in outbox.values()} == {1, 2}, "a mixed list, or no proof" + assert {cell_len(mark) for mark in actions.values()} == {1, 2} + + assert len(_word_starts(_outbox_titles(tmp_path), outbox)) == 1 + assert len(_word_starts(await _entry_action_titles(tmp_path), actions)) == 1 + + +async def test_courier_command_rows_go_bare_where_the_platform_draws_no_icons( + tmp_path: Path, +) -> None: + """No icon lane: the command icons go with no padding left, and the entry marks stay. + + An entry's ✓/✗/⏳ is its outcome, not decoration, so the PicoCalc keeps it — and keeps + those rows aligned with one another — while the queue, clear, send and cancel rows lose + their icons exactly as every other command row does there. + """ + from meshterm.platforms import PICOCALC, REGULAR, set_platform + + set_platform(PICOCALC) + try: + rows = _outbox_titles(tmp_path / "outbox") + assert "Queue a message…" in rows and "Clear finished" in rows + marks = {"Waiting": "⏳", "Landed": "✓", "Lost": "✗"} + assert len(_word_starts(rows, marks)) == 1 + assert await _entry_action_titles(tmp_path / "actions") == [ + "Send now — one forced attempt", + "Cancel this message", + ] + finally: + set_platform(REGULAR) + + # --- the recipient picker ---------------------------------------------------------------- diff --git a/tests/test_icon_alignment.py b/tests/test_icon_alignment.py new file mode 100644 index 0000000..2854cf0 --- /dev/null +++ b/tests/test_icon_alignment.py @@ -0,0 +1,271 @@ +"""The icon-column guard: in any one list, every icon-led row starts its words in one cell. + +The terminal draws some of the app's icons in one cell (``🗑 ✎ ⚙ ▶ ★ ↻ ↕ ⇄ ⌨ # ✓ ✗ ⚠``) +and most emoji in two, so a row written ``icon + " " + label`` starts its words a column +left of its two-cell siblings. The fault is invisible in review — the source reads the same +either way — and it kept coming back screen by screen (the node page's ``🗑 Remove +contact…`` under ``⏳ Time machine``, the main menu, the repeater admin) until the column +was measured once in :mod:`meshterm.ui.menus`: :func:`~meshterm.ui.menus.align_icons` (which +:func:`~meshterm.ui.menus.menu_rows` applies for you), or +:func:`~meshterm.ui.menus.icon_lane` with :func:`~meshterm.ui.menus.icon_mark` / +:func:`~meshterm.ui.menus.marked_label`. This file is what keeps a new list from skipping +them. + +**Coverage comes from the gallery, not from a list kept here.** :mod:`tests.test_gallery` +already builds every screen the menu can open, through its real builders, on both +platforms; this sweep imports that inventory (``_ENTRIES`` × ``_COMBOS``) so a screen added +there is guarded here with no edit. Two readings, because the gallery's screens hold their +rows two ways: + +* A :class:`~meshterm.ui.tui.select.SelectScreen` holds :class:`~meshterm.ui.tui.select.Choice` + items, so its rows are read as *data*: every choice's natural title, filter or viewport + notwithstanding, including the rows scrolled below the fold. +* A screen that draws its own action rows (the node page, Trace, the TX sweep, a trophy + card) has no items to read, so its body is rendered — under a viewport tall enough that + nothing is clipped — and the list is found by its ``❯`` cursor: the contiguous run of + pointer-column lines (``❯ `` or two spaces, then content) around it, blank lines included. + +"Leads with an icon" is :func:`meshterm.ui.menus._icon_head` — the one definition the +aligner and the icon-dropping :func:`~meshterm.ui.menus.command_label` share — and a row's +words start where :func:`meshterm.ui.menus._words_start` says, measured in display cells +with :func:`rich.cells.cell_len`, never characters. + +Glyphs that are *data* rather than decoration — a node's ``● ▲ ■ ◉ ○ ★``, a channel's +``# 🌐 🔒`` — get no exemption. They sit in the same column as the command icons around +them (the chat picker pads ``●`` out to ``🌐`` so every conversation name lines up), and a +data lane that went ragged is the same fault the reader sees. The one allowance is structural +and small: in a Choice list, a **blank** :class:`~meshterm.ui.tui.select.Separator` starts a +new group. That blank line is how :func:`~meshterm.ui.menus.exit_rows` sets its ``✓ Apply`` +/ ``✗ Back — discard`` pair apart, and how a table sets its command tail apart (the Contacts +list's rows under its maintenance rows, the Courier queue row under its outbox) — the space +says "a different list", and each side is still held to its own column. A section heading +(``── Label ──``) does not break a group: sections of one list read as one column. +""" + +from __future__ import annotations + +from collections.abc import Iterable +from dataclasses import dataclass + +import pytest +from rich.cells import cell_len +from rich.text import Text + +from meshterm.platforms import REGULAR, Platform, set_platform +from meshterm.ui.menus import _icon_head, _words_start, align_icons, exit_rows, menu_rows +from meshterm.ui.tui import Choice, Screen, SelectScreen, Separator +from tests.conftest import plain as _plain +from tests.test_gallery import _COMBOS, _ENTRIES, _Entry + +#: The pointer column every list draws before its rows: the cursor row's ``❯ ``, or two +#: spaces for the rest (see :class:`~meshterm.ui.tui.select.SelectScreen`). One cell of +#: glyph and one of space, so two cells wherever it appears. +_CURSOR = "❯ " +_GUTTER = " " + +#: A viewport taller than any gallery screen's content, so a hand-drawn list pushed below +#: the fold is still in the rendered body the sweep reads. +_TALL_VIEWPORT = 400 + + +@dataclass(frozen=True) +class _IconRow: + """One icon-led row of a list: its label as the reader sees it, and where its words start. + + Attributes: + label: The row's plain text, pointer column removed. + start: The display cell (0-based, from the label's first cell) its words begin in. + """ + + label: str + start: int + + +def _icon_row(label: str) -> _IconRow | None: + """``label`` measured as an icon row, or ``None`` when it does not lead with an icon.""" + head = _icon_head(label) + if not head: + return None + return _IconRow(label, cell_len(label[: _words_start(label, head)])) + + +def _choice_groups(items: Iterable) -> list[list[_IconRow]]: + """A Choice list's icon rows, grouped — a blank separator line starts a new group. + + See the module docstring for why the blank line (and only the blank line) separates + two lists: it is the seam :func:`~meshterm.ui.menus.exit_rows` draws above its pair. + """ + groups: list[list[_IconRow]] = [[]] + for item in items: + if isinstance(item, Separator): + title = item.title(_TALL_VIEWPORT) if callable(item.title) else item.title + text = title.plain if isinstance(title, Text) else title + if not text.strip(): + groups.append([]) + continue + if not isinstance(item, Choice): + continue + label = item.label + row = _icon_row(label.plain if isinstance(label, Text) else label) + if row is not None: + groups[-1].append(row) + return [group for group in groups if group] + + +def _in_pointer_column(line: str) -> bool: + """Whether a rendered line belongs to a hand-drawn list: blank, or a pointer + content.""" + if not line.strip(): + return True + return line.startswith((_CURSOR, _GUTTER)) and line[2:3] not in ("", " ") + + +def _rendered_groups(lines: list[str]) -> list[list[_IconRow]]: + """The icon rows of every hand-drawn list in a rendered body, one group per list. + + A list is anchored by its ``❯`` row and runs, both ways, over every contiguous line in + the pointer column. Blank lines stay inside it: a screen that spaces its actions into + clusters (Trace's compose/explore, width/samples, run) still measures one icon column + for all of them, and the reader reads them as one. + """ + groups: list[list[_IconRow]] = [] + for anchor, line in enumerate(lines): + if not line.startswith(_CURSOR): + continue + first = anchor + while first > 0 and _in_pointer_column(lines[first - 1]): + first -= 1 + last = anchor + while last + 1 < len(lines) and _in_pointer_column(lines[last + 1]): + last += 1 + rows = [_icon_row(row[2:]) for row in lines[first : last + 1] if row.strip()] + groups.append([row for row in rows if row is not None]) + return [group for group in groups if group] + + +def _screen_groups(screen: Screen, cols: int) -> list[list[_IconRow]]: + """Every list on ``screen``, read as items where it has them and as rendering where not.""" + if isinstance(screen, SelectScreen): + return _choice_groups(screen._items) + screen.note_viewport(_TALL_VIEWPORT) + return _rendered_groups(_plain(screen.render_body(cols)).splitlines()) + + +def _misalignments(where: str, groups: list[list[_IconRow]]) -> list[str]: + """One failure sentence per group whose icon rows start their words in different cells.""" + problems = [] + for number, group in enumerate(groups, start=1): + if len({row.start for row in group}) < 2: + continue + rows = "\n".join(f" cell {row.start:>2}: {row.label.rstrip()!r}" for row in group) + problems.append( + f"{where}, list {number} of {len(groups)}: icon rows start their words in " + f"different cells —\n{rows}\n" + " Pad the marks to one column: build the labels through menus.align_icons " + "(menu_rows does it for you), or icon_lane + icon_mark / marked_label(lane=...)." + ) + return problems + + +def _cases(): + for entry in _ENTRIES: + for platform, cols, rows in _COMBOS: + yield pytest.param( + entry, platform, cols, rows, id=f"{entry.name}-{platform.name}-{cols}x{rows}" + ) + + +@pytest.mark.parametrize("entry,platform,cols,rows", list(_cases())) +def test_icon_rows_share_one_column( + entry: _Entry, platform: Platform, cols: int, rows: int +) -> None: + """Within one list, every icon-led row starts its words in the same display cell. + + Swept over the whole gallery on both platforms. The PicoCalc drops a command row's icon + lane outright, but its data glyphs (a node's type, a channel's openness) stay and fold to + one-cell stand-ins, so the rule still has something to hold there. + """ + set_platform(platform) + screen = entry.factory(cols, rows) + where = f"{entry.name} on {platform.name} {cols}x{rows}" + problems = _misalignments(where, _screen_groups(screen, cols)) + assert not problems, "\n\n".join(problems) + + +@pytest.mark.parametrize("platform", sorted({p for p, _, _ in _COMBOS}, key=lambda p: p.name)) +def test_the_sweep_measures_something_on_every_platform(platform: Platform) -> None: + """The guard is not vacuous: each platform compares real lists, on each reading it can. + + A gallery refactor that hid a screen's items, or a render change that moved the ``❯`` + pointer, would otherwise leave every case above passing because it found nothing to + measure. On the desktop both readings must reach a list of two or more icon rows; on the + PicoCalc the hand-drawn action lists carry no icons at all (the lane is dropped), so only + the Choice reading — node-type and channel glyphs, the exit pair — is required there. + """ + set_platform(platform) + cols, rows = next((c, r) for p, c, r in _COMBOS if p is platform) + measured = {"items": 0, "rendered": 0} + for entry in _ENTRIES: + screen = entry.factory(cols, rows) + reading = "items" if isinstance(screen, SelectScreen) else "rendered" + measured[reading] += sum(len(g) > 1 for g in _screen_groups(screen, cols)) + assert measured["items"] > 0, f"no Choice list with 2+ icon rows on {platform.name}" + if platform is REGULAR: + assert measured["rendered"] > 0, "no hand-drawn list with 2+ icon rows on regular" + + +def test_guard_catches_a_hand_written_icon_prefix() -> None: + """A list written ``icon + " " + label`` fails, naming both rows and both start cells. + + ``🗑`` is one cell and ``💾`` two: the exact pair that put the node page's delete row out + of line under its archive row. If this stops failing, the guard has stopped guarding. + """ + screen = SelectScreen("Node", [Choice("💾 Archive contact", 1), Choice("🗑 Delete contact…", 2)]) + problems = _misalignments("node page", _screen_groups(screen, 72)) + assert len(problems) == 1 + assert "cell 3: '💾 Archive contact'" in problems[0] + assert "cell 2: '🗑 Delete contact…'" in problems[0] + + aligned = SelectScreen( + "Node", + [ + Choice(label, n) + for n, label in enumerate(align_icons(["💾 Archive contact", "🗑 Delete contact…"])) + ], + ) + assert not _misalignments("node page", _screen_groups(aligned, 72)) + + +def test_guard_catches_a_hand_drawn_list_through_its_rendering() -> None: + """A screen with no items is read off its rendered body, the pointer column removed. + + The cursor row and its gutter siblings are one list across a blank line, and the text + above (a card, not in the pointer column) is not part of it. + """ + lines = [ + "route ★ → 3d63 → ★", + "", + " ✎ Compose path", + " ⚡ Explore paths", + "", + "❯ ▶ Trace — one transmission", + "", + "Per-hop medians", + " ↓ 2 more", + ] + groups = _rendered_groups(lines) + assert [[row.start for row in group] for group in groups] == [[2, 3, 2]] + assert _misalignments("trace", groups) + + +def test_exit_pair_is_its_own_group() -> None: + """The staged-changes pair after its blank line is measured apart from the rows above it. + + ``✓``/``✗`` are one-cell status marks on a commit row, never padded to a list's emoji + column (see :func:`~meshterm.ui.menus.exit_rows`); the blank separator is the seam. The + pair is still held to its own column, and so are the rows above it. + """ + items = menu_rows([("📡 Send advert", "Flood it", 1), ("⌨ Command line", "Raw CLI", 2)]) + items += exit_rows(2, apply_value="apply", back_value="back") + groups = _choice_groups(items) + assert [[row.start for row in group] for group in groups] == [[3, 3], [2, 2]] + assert not _misalignments("editor", groups) diff --git a/tests/test_live_screens.py b/tests/test_live_screens.py index 323fac3..e429207 100644 --- a/tests/test_live_screens.py +++ b/tests/test_live_screens.py @@ -462,6 +462,58 @@ async def test_trace_screen_action_labels_share_one_column() -> None: assert len(columns) == 1, columns +def _words_start(row: str) -> int: + """The display cell an action row's words begin in — past its pointer and its mark. + + Measured in *cells* over the text before the first letter or digit, never as a + character index: ``⚡`` is one character drawn in two cells, so a character count + would call a misaligned row aligned (and ``#``, the sample-count mark, is no letter). + """ + return cell_len(row[: next(i for i, ch in enumerate(row) if ch.isalnum())]) + + +@pytest.mark.parametrize("platform_name", ["regular", "picocalc"]) +def test_every_action_row_starts_its_words_in_one_cell_in_both_modes(platform_name: str) -> None: + """Every action the screen can draw, in either mode, lit or not, shares one word column. + + The rendered test above reads target mode only, and only the rows it names — so the + path walk's ``⇄ Reverse path`` row, which exists nowhere else, was never measured. This + asks the screen for its own action list instead, which also pins the other half of the + contract: the one column holds *across* modes. ``_ACTION_ICONS`` declares ``⚡`` even in + path mode, where no row draws it, so toggling a walk into a target (or back) never nudges + the labels sideways under the reader. + + The column is measured from the marks the rows actually draw, and every one of those + must be in ``_ACTION_ICONS`` — a new action with a mark the tuple doesn't know about is + how a two-cell icon lands in a one-cell column. On the PicoCalc the lane is dropped + whole, so every word starts straight after the pointer. + """ + from meshterm.platforms import PICOCALC, REGULAR, set_platform + from meshterm.ui.trace_screen import _ACTION_ICONS + + platform = {"regular": REGULAR, "picocalc": PICOCALC}[platform_name] + set_platform(platform) + starts: set[int] = set() + marks: set[str] = set() + for mode in ("target", "path"): + screen, _ = _trace_screen(mode=mode) + for key in screen._actions: + for selected in (False, True): + row = screen._action_text(key, selected).plain + starts.add(_words_start(row)) + if platform is REGULAR: # the mark sits between the pointer and its gap + marks.add(row[2:].split(" ", 1)[0]) + pointer = cell_len("❯ ") + if platform is REGULAR: + # Declared-ness first: an undeclared wide mark eats its own gap ("⚡Explore"), and + # that is the diagnosis to read — not the width premise it would also break. + assert marks == set(_ACTION_ICONS), "every drawn mark is declared, and nothing else" + assert {cell_len(mark) for mark in marks} == {1, 2}, "a list of one width proves nothing" + assert starts == {pointer + 2 + 1}, starts # the widest mark, then its space + else: + assert starts == {pointer}, starts # no icon lane, no padding left behind + + async def test_trace_screen_action_cursor_commits_the_selected_row() -> None: """↑↓ move over the action rows; Enter commits the one under the cursor. diff --git a/tests/test_menu_quit_row.py b/tests/test_menu_quit_row.py new file mode 100644 index 0000000..160adb0 --- /dev/null +++ b/tests/test_menu_quit_row.py @@ -0,0 +1,124 @@ +"""The main menu's Quit row shares the tool rows' icon column (JP, 2026-09-11). + +The menu closes on a ``🚪 Quit`` row below its tool rows, and for as long as it has existed +that row sat *outside* the measured icon column the tools are drawn through: a literal +string whose word happened to start in the right cell because ``🚪`` happened to be as wide +as the widest tool icon. These tests pin the alignment itself rather than today's icons, so +a narrower quit mark or a wider tool mark cannot quietly reopen it, and they pin the +PicoCalc case — no icon lane, so the bare word and not a stray indent. +""" + +from __future__ import annotations + +from collections.abc import Iterator +from types import SimpleNamespace + +import pytest +from rich.cells import cell_len + +from meshterm.platforms import PICOCALC, REGULAR, set_platform +from meshterm.tools import all_tools, load_all_tools +from meshterm.ui import menu +from meshterm.ui.tui import Choice + +#: A mark the terminal draws in one cell — the width a quit or tool icon must not be +#: allowed to mis-align by. +_NARROW = "⚙" + +#: A mark the terminal draws in two. +_WIDE = "📡" + + +@pytest.fixture +def tools() -> list: + """The real menu-visible tools, in drawing order — the registry the menu is built from.""" + load_all_tools() + return [tool for tool in all_tools() if tool.menu_visible] + + +@pytest.fixture +def picocalc() -> Iterator[None]: + """Run a test on the PicoCalc platform, restoring the regular one afterwards.""" + set_platform(PICOCALC) + try: + yield + finally: + set_platform(REGULAR) + + +def _fake_tool(name: str, icon: str) -> SimpleNamespace: + """A stand-in tool carrying only what the menu reads, with an icon of our choosing.""" + return SimpleNamespace( + name=name, title=name.capitalize(), icon=icon, category="Test", help="does a thing" + ) + + +def _word_starts(items: list, tools: list) -> dict[str, int]: + """The cell each row's words start in, keyed by row value — the tools' titles and Quit. + + Measured from the rendered title rather than from the lane, so it checks what the + reader sees: everything before the title (the mark and its padding) in display cells. + """ + words = {tool.name: tool.title or tool.name for tool in tools} + words[menu._QUIT_VALUE] = "Quit" + starts: dict[str, int] = {} + for item in items: + if not isinstance(item, Choice): + continue + plain = item.title.plain + starts[item.value] = cell_len(plain[: plain.index(words[item.value])]) + return starts + + +def test_the_quit_row_starts_its_word_in_the_tool_titles_cell(tools: list) -> None: + """On the real menu, *Quit* lines up under every tool title above it.""" + items = menu._menu_items(tools) + starts = _word_starts(items, tools) + + assert menu._QUIT_VALUE in starts, "the menu lost its Quit row" + assert set(starts) == {tool.name for tool in tools} | {menu._QUIT_VALUE} + assert len(set(starts.values())) == 1, f"a row starts a column off: {starts}" + # The row closes the list, behind its blank separator, with its wording intact. + assert items[-1].value == menu._QUIT_VALUE + assert items[-1].title.plain == f"{menu._QUIT_ICON} Quit" + + +def test_a_narrower_quit_mark_still_lines_up(tools: list, monkeypatch: pytest.MonkeyPatch) -> None: + """A one-cell quit icon pads out to the tools' two-cell column instead of starting early. + + This is the case the old literal ``🚪 Quit`` would have got wrong: its word followed + the mark by exactly one space, whatever the mark's width. + """ + assert cell_len(_NARROW) == 1, "the substitute must actually be narrower" + monkeypatch.setattr(menu, "_QUIT_ICON", _NARROW) + + starts = _word_starts(menu._menu_items(tools), tools) + + assert len(set(starts.values())) == 1, f"a row starts a column off: {starts}" + + +def test_the_quit_mark_is_measured_into_the_column(monkeypatch: pytest.MonkeyPatch) -> None: + """When Quit's mark is the widest in the list, the tool titles move over to meet it. + + Every tool here leads with a one-cell mark and Quit with a two-cell one. A column + measured over the tools alone would be one cell wide: the titles would start in cell 2 + and Quit's mark, with no room left for its separator, would run into its word + (``📡Quit``). The menu's column counts Quit's icon too, so every word starts in cell 3. + """ + fakes = [_fake_tool("alpha", _NARROW), _fake_tool("beta", _NARROW)] + monkeypatch.setattr(menu, "_QUIT_ICON", _WIDE) + + starts = _word_starts(menu._menu_items(fakes), fakes) + + assert set(starts.values()) == {cell_len(_WIDE) + 1} + + +@pytest.mark.usefixtures("picocalc") +def test_no_icon_lane_leaves_the_bare_word_flush_with_the_titles(tools: list) -> None: + """No icon lane on the PicoCalc: the row is just *Quit*, with no padding left behind.""" + items = menu._menu_items(tools) + starts = _word_starts(items, tools) + + assert items[-1].value == menu._QUIT_VALUE + assert items[-1].title.plain == "Quit" + assert set(starts.values()) == {0} diff --git a/tests/test_menus.py b/tests/test_menus.py index 75a1971..4bcd662 100644 --- a/tests/test_menus.py +++ b/tests/test_menus.py @@ -12,6 +12,7 @@ from rich.text import Text from meshterm.ui.menus import ( Lane, + align_icons, changes_phrase, column_header, exit_rows, @@ -241,6 +242,75 @@ def test_marked_label_lines_up_a_mixed_list_when_told_its_lane() -> None: ) +def _plain(label) -> str: + return label.plain if isinstance(label, Text) else label + + +def test_align_icons_starts_every_word_in_the_same_cell() -> None: + """A one-cell and a two-cell icon inside label strings pad out to one column. + + The fault this closes kept reappearing a screen at a time (the node page, the main + menu, the repeater admin's ``↻``/``⌨`` rows), because each list had to remember to + measure its own icon column. Iconless labels pass through as the object they were. + """ + plain_row = "Reorder" + labels = align_icons( + [f"{_NARROW} Purge contacts…", Text.assemble((_WIDE, "ok"), " View archived"), plain_row] + ) + assert [_plain(label) for label in labels] == [ + f"{_NARROW} Purge contacts…", + f"{_WIDE} View archived", + "Reorder", + ] + assert labels[2] is plain_row + styled = labels[1] + assert any( + span.style == "ok" and styled.plain[span.start : span.end] == _WIDE for span in styled.spans + ), "the icon's own tint survives the padding" + + +def test_align_icons_keeps_a_base_style_and_never_adds_to_an_existing_gap() -> None: + """A whole-row tint survives as a span; aligning an aligned list changes nothing.""" + danger = Text(f"{_NARROW} Factory reset…", style="err") + once = align_icons([danger, f"{_WIDE} Sync clock…"]) + words = once[0].plain.index("Factory") + assert any(span.style == "err" and span.start <= words < span.end for span in once[0].spans) + twice = align_icons(once) + assert [_plain(label) for label in twice] == [_plain(label) for label in once] + padded_by_hand = marked_label(_NARROW, "Delete", "", lane=icon_lane((_NARROW, _WIDE))) + assert _plain(align_icons([padded_by_hand, f"{_WIDE} Keep"])[0]) == padded_by_hand.plain + + +def test_menu_rows_line_up_mixed_icon_widths_without_being_told() -> None: + """A list built through menu_rows gets the icon column for free — no lane to pass.""" + from rich.cells import cell_len + + rows = menu_rows( + [ + (f"{_NARROW} Read settings", "one", 1), + (f"{_WIDE} Send advert…", "two", 2), + (Text(f"{_NARROW} Factory reset…", style="err"), "three", 3), + ] + ) + starts = { + cell_len(row.title.plain[: row.title.plain.index(word)]) + for row, word in zip(rows, ("Read", "Send", "Factory"), strict=True) + } + assert starts == {3} + + +def test_align_icons_pads_nothing_where_the_platform_draws_no_icons() -> None: + """No icon lane: the icons go, and no padding is left standing in their place.""" + from meshterm.platforms import PICOCALC, REGULAR, set_platform + + set_platform(PICOCALC) + try: + labels = align_icons([f"{_NARROW} Purge contacts…", f"{_WIDE} View archived"]) + assert [_plain(label) for label in labels] == ["Purge contacts…", "View archived"] + finally: + set_platform(REGULAR) + + def test_the_main_menu_starts_every_title_in_the_same_cell() -> None: """The app's front door obeys its own icon-column rule (JP, 2026-09-06). diff --git a/tests/test_records_screen.py b/tests/test_records_screen.py index 6981d16..28658f1 100644 --- a/tests/test_records_screen.py +++ b/tests/test_records_screen.py @@ -211,6 +211,35 @@ def test_record_dialog_down_moves_to_delete() -> None: assert dialog._actions[dialog._index] == "delete" +def test_record_dialog_actions_start_both_labels_in_the_same_cell() -> None: + """*Trace this path* and *Delete record…* share one icon column, on both platforms. + + ``👣`` is two cells and ``🗑`` one, so each mark measured on its own left the delete + row's words a column left of the trace row's. Measured in cells, not characters, since + it is the cell the words land in that the eye compares. Where the platform draws no icon + lane the marks go, and so must their padding: both labels open right after the pointer. + """ + from meshterm.platforms import PICOCALC, set_platform + + def starts() -> set[int]: + lines = _plain(_dialog(_record()).render_body(60)).splitlines() + rows = [ + line[: line.index(word)] + for word in ("Trace this path", "Delete record…") + for line in lines + if word in line + ] + assert len(rows) == 2, lines + return {cell_len(head) for head in rows} + + regular = starts() + assert len(regular) == 1 # one column for both words… + assert regular == {2 + 2 + 1} # …after the pointer, the two-cell lane, and its space + + set_platform(PICOCALC) + assert starts() == {2} # no lane, no leftover padding: the words follow the pointer + + def test_record_dialog_names_the_far_point() -> None: """The reached node's name rides beside the far-point distance.""" body = _plain(_dialog(_record(), far_label="Far").render_body(60)) diff --git a/tests/test_repeater_admin.py b/tests/test_repeater_admin.py index 039908e..17b240d 100644 --- a/tests/test_repeater_admin.py +++ b/tests/test_repeater_admin.py @@ -677,3 +677,27 @@ def test_admin_menu_header_abbreviates_rather_than_wrapping() -> None: assert full.endswith("DESCRIPTION") narrow = header.text(cell_len(full) - 2) assert narrow.endswith("DESC") and "\n" not in narrow + + +def test_admin_actions_start_every_label_in_the_same_cell() -> None: + """``↻`` and ``⌨`` are one cell among two-cell siblings; the icon column absorbs it. + + The Actions rows used to write ``icon + " "``, which started *Read settings* and + *Command line…* a column left of *Send advert…* below them. + """ + from rich.cells import cell_len + + from meshterm.ui.tui import Choice + + _title, items = repeater_admin._menu_items(NODE, {}, {}) + labels = ("Read settings", "Command line…", "Send advert…", "Sync clock…", "Reboot node…") + starts = {} + for item in items: + if not isinstance(item, Choice) or not hasattr(item.title, "plain"): + continue + plain = item.title.plain + for label in labels: + if label in plain: + starts[label] = cell_len(plain[: plain.index(label)]) + assert set(starts) == set(labels) + assert len(set(starts.values())) == 1, f"a label starts a column early: {starts}" diff --git a/tests/test_tui.py b/tests/test_tui.py index f867ecc..3aab58d 100644 --- a/tests/test_tui.py +++ b/tests/test_tui.py @@ -3102,6 +3102,34 @@ def test_the_splash_says_so_when_it_is_empty_only_because_of_hiding() -> None: assert not any("hidden" in line for line in rows) +def test_the_splash_action_rows_share_one_icon_column() -> None: + """Add-a-network-device and Quit start their words in one cell, measured, on both platforms. + + They used to be literal ``" 🌐 Add…"`` / ``" 🚪 Quit"`` strings that lined up only because + the two emoji happen to be the same width, and that kept their icons on the PicoCalc, where + every other command row drops its icon lane. + """ + from rich.cells import cell_len + + from meshterm.platforms import PICOCALC, REGULAR, set_platform + from meshterm.ui.device_picker import _ADD_TCP, _QUIT, _action_rows + from meshterm.ui.tui import Choice + + def starts() -> dict: + rows = {it.value: it.title.plain for it in _action_rows() if isinstance(it, Choice)} + words = {_ADD_TCP: "Add a network device…", _QUIT: "Quit"} + return { + value: cell_len(rows[value][: rows[value].index(word)]) for value, word in words.items() + } + + assert len(set(starts().values())) == 1 + set_platform(PICOCALC) + try: + assert set(starts().values()) == {2}, "the icons go, and no padding stays behind" + finally: + set_platform(REGULAR) + + def test_hiding_a_device_leaves_the_highlight_where_the_row_was() -> None: """The next device down, or the one above at the end — so a run of adapters clears in a run.""" from meshterm.core.discovery import serial_device diff --git a/tests/test_watchtower.py b/tests/test_watchtower.py index 71fe854..502645c 100644 --- a/tests/test_watchtower.py +++ b/tests/test_watchtower.py @@ -313,3 +313,78 @@ def test_alert_rows_pin_their_lanes_and_scroll_only_the_message() -> None: assert row.label.plain.startswith(lanes.plain) assert lanes.plain.endswith(" — ") # the lead-in stays with the head it introduces assert row.label.plain[row.hscroll_from :] == alert.message # …and the run is the message + + +def _word_starts(items: list, words: dict) -> dict: + """The display cell each row's first word starts in, by row value. + + Cells, not characters: a two-cell ``⭐`` and a one-cell ``✓`` are both one character, so + counting characters is exactly what hid a label starting a column early. + """ + from rich.cells import cell_len + + from meshterm.ui.tui import Choice + + starts = {} + for item in items: + if isinstance(item, Choice) and item.value in words: + plain = item.label.plain + starts[item.value] = cell_len(plain[: plain.index(words[item.value])]) + assert starts.keys() == words.keys(), "every row the test names is on the screen" + return starts + + +def test_watchtower_actions_start_every_label_in_the_same_cell() -> None: + """The action rows share one icon column, across the list's section headings. + + ``✓`` and ``🗑`` draw one cell and ``⭐`` and ``🔔`` two, so the bulk actions started + their words a column left of *Watch a node…* and the new-node toggle. On the PicoCalc + the icons go and must take their padding with them. + """ + from rich.cells import cell_len + + from meshterm.core.watch_store import Alert + from meshterm.platforms import PICOCALC, REGULAR, set_platform + from meshterm.ui.watchtower_screen import _ACK_ALL, _CLEAR, _TOGGLE_NEW, _WATCH, _menu_items + + assert {cell_len("✓"), cell_len("⭐")} == {1, 2}, "a list of one icon width proves nothing" + alerts = [ + Alert(ident=1, when=utcnow(), kind="silence", label="Roof", message="quiet"), + Alert(ident=2, when=utcnow(), kind="snr", label="Roof", message="sag", acked=True), + ] + words = { + _ACK_ALL: "Acknowledge", + _CLEAR: "Clear", + _WATCH: "Watch", + _TOGGLE_NEW: "New-node", + } + assert set(_word_starts(_menu_items(alerts, {}, True), words).values()) == {3} + try: + set_platform(PICOCALC) + assert set(_word_starts(_menu_items(alerts, {}, True), words).values()) == {0} + finally: + set_platform(REGULAR) + + +def test_node_rules_start_every_label_and_value_in_the_same_cell() -> None: + """The rule popover's words share one column, and its values another, on both platforms. + + ``🕒`` and ``📶`` draw two cells and ``✗`` one, so *Stop watching this node* started a + column early. The values used to be lined up with hand-typed spaces, so they are pinned + here too: whatever the icon column measures, the values stay in one column. + """ + from meshterm.core.watch_store import WatchedNode + from meshterm.platforms import PICOCALC, REGULAR, set_platform + from meshterm.ui.watchtower_screen import _rule_items + + entry = WatchedNode(key="a1" * 6, name="Roof", silence_hours=12, snr_watch=True) + words = {"silence": "Silence", "snr": "SNR", "unwatch": "Stop"} + values = {"silence": "after 12 h", "snr": "on"} + try: + for platform, start in ((REGULAR, 3), (PICOCALC, 0)): + set_platform(platform) + items = _rule_items(entry) + assert set(_word_starts(items, words).values()) == {start} + assert len(set(_word_starts(items, values).values())) == 1 + finally: + set_platform(REGULAR)