From 0a413033663bdd7fb0b329f061f01341b71f66f7 Mon Sep 17 00:00:00 2001 From: Jean-Pierre Martineau Date: Wed, 29 Jul 2026 04:13:14 -0400 Subject: [PATCH] Lists: what stays overhead is the section you are in MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two things a grouped list has to keep in view while it scrolls, and neither one was staying: the lane names that read every row, and the heading that says which group a row belongs to. The lanes come first. A column header means the same thing in every section, so it is not a section landmark at all — it pins for the *whole* list, above any heading, once it scrolls off (`Separator(pinned=True)`). It is drawn outside the body slice, so it stays exactly one row: too wide for the terminal it ellipsizes rather than wrapping and stealing a second reserved row from the content. And it can now size itself — a Separator title may be a callable taking the render width — so `column_header`/`Lane` lay each label over its own lane and hand back the shorter form (DESCRIPTION → DESC) only for the lanes that actually overrun, from the right, where the trailing lane is the only one with a cell to give. `lane_header` is that header for `lane_row`'s lanes, shared by the two editors so they head identical lanes identically. The headings were the other half, and they were pinning the wrong row. Every non-pinned separator was a candidate, and the rule takes the last one at or above the scroll — so what pinned was whatever muted line sat lowest under the heading. In the Trophy case that meant a discipline's *description* stuck to the top and the heading itself never did; at the foot of any list, the blank spacer above Back pinned a blank row. So heading-ness is explicit now (`Separator.heading`, conferred by `section_heading`, which is why every hand-rolled `── … ──` in the app — the main menu's categories, the chat picker's Channels/Direct, Trace path's candidate and ranked lists — now goes through it, and why three lanes headers that genuinely *are* their block's only landmark say so). A landmark is also no longer one line but a block: a heading plus the separators written immediately under it, before the section's first row. Prose written there is the section's preamble — the Trophy case's "what this discipline scores" — and it belongs overhead with the heading rather than scrolling away from the rows it explains. The block hands its rows over one at a time as they leave, so the heading pins while its description is still the top content row and the two pin together once both are gone: what is overhead always continues seamlessly into the body. It never takes more than half the viewport, giving rows up from the end, so the row that says *which* section this is is the last one dropped. The frame settles the scroll against however many rows come back rather than assuming one, and re-asks after sliding the window at the bottom — a heading among the dropped lines would otherwise vanish instead of pinning. Co-Authored-By: Claude Opus 5 (1M context) --- CLAUDE.md | 5 + meshterm/tools/chat.py | 41 ++++--- meshterm/ui/channels.py | 4 +- meshterm/ui/chat.py | 10 +- meshterm/ui/config_editor.py | 12 ++- meshterm/ui/contactlist.py | 6 +- meshterm/ui/device_picker.py | 6 +- meshterm/ui/menu.py | 3 +- meshterm/ui/menus.py | 100 ++++++++++++++++- meshterm/ui/repeater_admin.py | 16 ++- meshterm/ui/trace_screen.py | 8 +- meshterm/ui/tui/frame.py | 72 +++++++++---- meshterm/ui/tui/screen.py | 87 ++++++++++----- meshterm/ui/tui/select.py | 82 ++++++++++++-- tests/test_chat.py | 63 +++++++++-- tests/test_config_editor.py | 18 ++++ tests/test_menus.py | 51 +++++++++ tests/test_repeater_admin.py | 37 +++++++ tests/test_tui.py | 197 +++++++++++++++++++++++++++++++--- 19 files changed, 700 insertions(+), 118 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 6aac4f3..1eca907 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -60,6 +60,11 @@ Relative ages: `format_ago` for prose ("now", "5m ago", "never" — never "now a Editors with staged changes show `✓ Apply n staged changes` over `✗ Back — discard staged changes`. - Grouped-list section headings use `section_heading("Label")` → `── Label ──` accent. + That is also what makes a heading *sticky* (it pins to the top row while its section + scrolls, and the ^PgUp/^PgDn jumps step by it), so build them through it — a hand-rolled + `Separator` is no landmark. Prose written *directly under* a heading (a description of + what the section holds) is its preamble and pins with it, in order, as each row scrolls + off; prose after the section's first row labels nothing and never pins. - Label + description command rows go through `menu_rows` (two cell-aligned lanes, description muted). Editor rows (setting/value/description) go through `lane_row`. - A row that opens further prompts ends with `…`; a row that acts immediately doesn't. diff --git a/meshterm/tools/chat.py b/meshterm/tools/chat.py index c67bb06..f2bb72f 100644 --- a/meshterm/tools/chat.py +++ b/meshterm/tools/chat.py @@ -38,7 +38,7 @@ from ..core.models import ( ) from ..services.trace_runner import NameKeyResolver, make_name_key_resolver from ..ui.chat import _MENTION, _split_channel_sender -from ..ui.menus import fit_cells +from ..ui.menus import Lane, column_header, fit_cells, section_heading from ..ui.theme import name_style from ..ui.tui import Choice, DeleteRequest, Separator from ..ui.widgets import _NODE_GLYPHS, channel_glyph @@ -148,9 +148,12 @@ class ChatTool(Tool): # colour rule); a name no contact or stored advert carries stays muted. key_of = make_name_key_resolver(contacts, ctx.repo.node_names()) + # The lane names pin for the whole picker (they mean the same in both groups), + # so scrolling into Direct keeps them overhead with that group's heading under + # them, instead of the header vanishing one row in — see Screen.sticky_rows. items: list = [ - Separator(_picker_header()), - Separator("── 📡 Channels ──", style="accent"), + Separator(_picker_header, pinned=True), + section_heading("📡 Channels"), ] for conversation in channels: items.append( @@ -160,7 +163,7 @@ class ChatTool(Tool): ) ) - items.append(Separator("── 👤 Direct ──", style="accent")) + items.append(section_heading("👤 Direct")) if companions: # List contacts by recency — those with messages first, newest exchange at # the top — then the never-contacted ones alphabetically (see _recency_key). @@ -623,20 +626,28 @@ _AGE_WIDTH = 3 _PREVIEW_WIDTH = 40 -def _picker_header() -> str: +def _picker_header(width: int) -> str: """Column headers over the picker's fixed lanes (see :func:`_title` for the layout). - Leading spaces cover the select screen's pointer column (2 cells, drawn on choice rows - but not separators) plus the marker lane (3 cells), so each header lands exactly over - its column. UNREAD borrows its lane's trailing gap — the badge lane itself is one cell - too narrow for the word — which still leaves a space before the age column. + The five-cell indent covers the select screen's pointer column (2 cells, drawn on choice + rows but not separators) plus the marker lane (3 cells), so each header lands exactly + over its column. UNREAD borrows its lane's trailing gap — the badge lane itself is one + cell too narrow for the word — which still leaves a space before the age column. + + Resolved against the render width (the header row is pinned, so it must stay one row): + on a terminal too narrow for the whole line, ``LAST MESSAGE`` gives its cells back a + word at a time rather than the line wrapping or losing the label (see + :func:`~meshterm.ui.menus.column_header`). """ - return ( - " " - + "CONVERSATION".ljust(_LABEL_WIDTH + 2) - + "UNREAD".ljust(_BADGE_WIDTH + 2) - + f"{'AGE':>{_AGE_WIDTH}}" - + " LAST MESSAGE" + return column_header( + [ + Lane("CONVERSATION", _LABEL_WIDTH + 2), + Lane("UNREAD", _BADGE_WIDTH + 2), + Lane("AGE", _AGE_WIDTH + 2), + Lane(("LAST MESSAGE", "LAST MSG", "LAST")), + ], + width, + indent=5, ) diff --git a/meshterm/ui/channels.py b/meshterm/ui/channels.py index 80e2923..d09750e 100644 --- a/meshterm/ui/channels.py +++ b/meshterm/ui/channels.py @@ -575,7 +575,9 @@ def _menu_items( items: list = [] if slots: name_w = min(_NAME_WIDTH_MAX, max(len("CHANNEL"), *(len(s.name) for s in slots))) - items.append(Separator(_lanes_header(name_w))) + # The lane names are this block's only landmark (its section carries no ── heading ──), + # so they pin overhead while the slots scroll and give way to Organize/Add a channel. + items.append(Separator(_lanes_header(name_w), heading=True)) for slot in slots: items.append(Choice(title=_slot_row(ctx, slot, stats, name_w), value=slot.idx)) else: diff --git a/meshterm/ui/chat.py b/meshterm/ui/chat.py index 19ea60f..e26886a 100644 --- a/meshterm/ui/chat.py +++ b/meshterm/ui/chat.py @@ -263,9 +263,11 @@ class ChatScreen(Screen): view (channels only; direct threads never select). """ lines: list[str] = [] - # Record each day divider as a sticky-header candidate, so the divider governing the - # topmost visible message is re-pinned to the top row once it scrolls off — the same - # base Screen.sticky_header the conversation picker uses for its section headings. + # Record each day divider as a sticky block of its own one row, so the divider + # governing the topmost visible message is re-pinned to the top row once it scrolls + # off — the same base Screen.sticky_block the conversation picker uses for its + # section headings. A day has nothing to say beyond its date, so the block is the + # divider alone; a select list's heading may carry its description along. self._sticky_headers = [] prev_group: Optional[tuple[bool, str]] = None prev_day = None @@ -283,7 +285,7 @@ class ChatScreen(Screen): divider = render_lines( Text(f"── {stamp:%a} {stamp:%b} {stamp.day} ──", style="muted"), width ) - self._sticky_headers.append((len(lines), divider[0])) + self._sticky_headers.append((len(lines), [divider[0]])) lines += divider if new_day or group != prev_group: if not new_day and lines: diff --git a/meshterm/ui/config_editor.py b/meshterm/ui/config_editor.py index 78723ff..79b57f0 100644 --- a/meshterm/ui/config_editor.py +++ b/meshterm/ui/config_editor.py @@ -59,6 +59,7 @@ from .menus import ( back_rows, confirm_discard, exit_rows, + lane_header, lane_row, menu_rows, section_heading, @@ -341,12 +342,13 @@ def _menu_items( label_w = max(cell_len(label) for _, rows in sections for label, _, _, _ in rows) value_w = max(cell_len(value.plain) for _, rows in sections for _, value, _, _ in rows) - # The header leads with two spaces to clear the select screen's pointer column, so - # each heading lands exactly over its lane. + # The shared editor header (menus.lane_header): each label over its own lane, clear of + # the pointer column, abbreviating rather than wrapping where the terminal is too narrow + # for the full words. It is pinned for the whole list — the lanes mean the same in every + # category — so a scrolled row keeps both its column header and its section heading + # overhead (see Screen.sticky_rows). items: list = [ - Separator( - " " + "SETTING".ljust(label_w + 2) + "VALUE".ljust(value_w + 2) + "DESCRIPTION" - ) + Separator(lambda w: lane_header(label_w, value_w, w), pinned=True) ] for category, rows in sections: items.append(section_heading(category)) diff --git a/meshterm/ui/contactlist.py b/meshterm/ui/contactlist.py index c9af6b3..9fbdfe8 100644 --- a/meshterm/ui/contactlist.py +++ b/meshterm/ui/contactlist.py @@ -403,7 +403,11 @@ class ContactListScreen(SelectScreen): below them reorders (see :func:`_ordered`). Tail rows (a purge action, the exit group) close the list, past every contact whatever the sort.""" items: list = list(self._lead) - items.append(Separator(_header(self._name_w, self._sort, self._show_traced))) + # The lane names lead the contacts as their landmark, so they pin overhead while the + # list scrolls — a row deep in the sort can still be read off its columns. + items.append( + Separator(_header(self._name_w, self._sort, self._show_traced), heading=True) + ) pinned = [row for row in self._contact_rows if row.you] rest = [row for row in self._contact_rows if not row.you] for row in (*pinned, *_ordered(rest, self._sort)): diff --git a/meshterm/ui/device_picker.py b/meshterm/ui/device_picker.py index 7e8f3ef..d63b2ef 100644 --- a/meshterm/ui/device_picker.py +++ b/meshterm/ui/device_picker.py @@ -573,13 +573,15 @@ def _build_items( hardware_w = max(hardware_w, len("HARDWARE")) # A muted, aligned header. The leading spaces mirror the row pointer (2) and the star - # column (2) so the labels sit above their columns. + # column (2) so the labels sit above their columns. It leads the device rows as their + # landmark, so a long detection list keeps the lane names overhead as it scrolls. header = Separator( " " + _pad("DEVICE", name_w) + " " + _pad(port_label, port_w) + " " + _pad("TYPE", type_w) - + " " + "HARDWARE" + + " " + "HARDWARE", + heading=True, ) items: list = [header] diff --git a/meshterm/ui/menu.py b/meshterm/ui/menu.py index fcec12e..eeaad62 100644 --- a/meshterm/ui/menu.py +++ b/meshterm/ui/menu.py @@ -28,6 +28,7 @@ from ..persistence.logging import get_logger from ..tools import all_tools from .surface import TuiUi from .braillechart import activity_peak, activity_sparkline +from .menus import section_heading from .theme import make_console from .widgets import battery_cell from .tui import ( @@ -432,7 +433,7 @@ async def _menu_loop(ctx: AppContext, session: TuiSession) -> None: for tool in tools: if tool.category != current_category: current_category = tool.category - items.append(Separator(f"── {current_category} ──", style="accent")) + items.append(section_heading(current_category)) label = _label(tool) row = Text(label) row.append(" " * (name_w - cell_len(label) + 2)) diff --git a/meshterm/ui/menus.py b/meshterm/ui/menus.py index 23387ae..11f24cf 100644 --- a/meshterm/ui/menus.py +++ b/meshterm/ui/menus.py @@ -15,6 +15,9 @@ furniture, so the app's exit language and row alignment stay uniform by construc lanes, padded in display cells so double-width emoji can't skew the description column (the Device actions presentation). * :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 + :func:`lane_header`, the ready-made header for :func:`lane_row`'s lanes. * :func:`changes_phrase` — ``"1 staged change"`` / ``"3 staged changes"``. * :func:`confirm_discard` — the shared are-you-sure dialog for leaving staged changes. @@ -25,7 +28,8 @@ line above it; ``✓``/``✗`` (U+2713/U+2717) are THE status marks, styled ``ok from __future__ import annotations -from typing import TYPE_CHECKING, Any, Iterable, Union +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any, Iterable, Sequence, Union from rich.cells import cell_len from rich.text import Text @@ -126,6 +130,90 @@ def lane_row(label: str, value: Text, help_text: str, label_w: int, value_w: int return row +@dataclass(frozen=True) +class Lane: + """One lane of a column header: its label, any shorter forms, and its width. + + Attributes: + label: The lane's label — a plain string, or its forms longest-first + (``("DESCRIPTION", "DESC")``) for a lane that can give cells back on a narrow + terminal. Only a lane the line actually overruns is ever shortened. + width: Cells the label is padded to — the lane's own width *plus* the gap before + the next lane, so a label wider than its column absorbs that gap instead of + shifting every lane after it right (``UNREAD`` over a narrower badge lane). + Zero (the default) for a trailing lane, which just runs to the edge. + """ + + label: Union[str, Sequence[str]] + width: int = 0 + + @property + def forms(self) -> tuple[str, ...]: + """The lane's labels, longest first (a bare string is its own only form).""" + return (self.label,) if isinstance(self.label, str) else tuple(self.label) + + +def column_header(lanes: Sequence[Lane], width: int, *, indent: int = 2) -> str: + """The column-header line over a lane-aligned list, fitted to ``width``. + + THE header builder for every list that pads its rows into columns (the two setting + editors, the chat picker). Lanes are laid out left to right at their own widths, after + ``indent`` cells clearing the pointer column, so each label lands exactly over the lane + it names. + + A header is one row and stays one row. Where the line overruns ``width`` the lanes fall + back to their shorter labels — from the right, since the fixed lanes are padded to their + rows' content and only a trailing lane can actually give a cell back — and a line that + still won't fit is ellipsized. It never wraps: a pinned header (see + :attr:`~meshterm.ui.tui.select.Separator.pinned`) is drawn outside the body slice, where + a second row would cost the content one. + + Args: + lanes: The lanes in display order. + width: Cells the line has to fit into — the screen's render width. + indent: Leading pad in cells: the select screen's 2-cell pointer column, plus any + glyph lane the rows draw before their first value. + + Returns: + The header line, at most ``width`` cells wide. + """ + picked = [0] * len(lanes) + + def line() -> str: + out = " " * indent + for lane, form in zip(lanes, picked): + label = lane.forms[form] + out += label + " " * max(0, lane.width - cell_len(label)) + return out + + at = len(lanes) - 1 + while at >= 0 and cell_len(line()) > width: + if picked[at] + 1 < len(lanes[at].forms): + picked[at] += 1 # this lane has something shorter to offer — take it + else: + at -= 1 # spent; ask the lane to its left + text = line() + return fit_cells(text, width) if cell_len(text) > width else text + + +def lane_header(label_w: int, value_w: int, width: int) -> str: + """The SETTING / VALUE / DESCRIPTION header over :func:`lane_row`'s lanes. + + The row builder's header twin, shared by the two editor lists (device configuration + and repeater admin) so they head identical lanes identically. ``DESCRIPTION`` shortens + to ``DESC`` where the two value lanes leave it no room — long setting labels and a + staged ``current → new`` value can push the full word past a 72-column terminal. + """ + return column_header( + [ + Lane("SETTING", label_w + 2), + Lane("VALUE", value_w + 2), + Lane(("DESCRIPTION", "DESC")), + ], + width, + ) + + def changes_phrase(count: int) -> str: """``"1 staged change"`` / ``"3 staged changes"`` for dialogs and menu rows.""" return f"{count} staged change{'' if count == 1 else 's'}" @@ -164,8 +252,13 @@ def section_heading(label: str) -> Separator: The one form every grouped list's headings take (the main menu's categories, the config editor's setting groups, Watchtower's Alerts/Watched nodes, Courier's Outbox/Finished), so sections read the same on every screen. + + It is also what makes a heading a *landmark*: the row is marked + :attr:`~meshterm.ui.tui.select.Separator.heading`, so it re-pins to the top row once its + section scrolls under it and the Ctrl+PageUp/PageDown jumps step by it. Building the row + by hand is how a section loses that — go through here. """ - return Separator(f"── {label} ──", style="accent") + return Separator(f"── {label} ──", style="accent", heading=True) def fit_cells(text: str, width: int, *, align: str = "left") -> str: @@ -195,11 +288,14 @@ def fit_cells(text: str, width: int, *, align: str = "left") -> str: __all__ = [ + "Lane", "back_rows", "changes_phrase", + "column_header", "confirm_discard", "exit_rows", "fit_cells", + "lane_header", "lane_row", "menu_rows", "section_heading", diff --git a/meshterm/ui/repeater_admin.py b/meshterm/ui/repeater_admin.py index e08721f..af9ecaf 100644 --- a/meshterm/ui/repeater_admin.py +++ b/meshterm/ui/repeater_admin.py @@ -36,7 +36,14 @@ from ..core.remote_config import ( reply_is_error, settings_by_category, ) -from .menus import confirm_discard, exit_rows, lane_row, menu_rows, section_heading +from .menus import ( + confirm_discard, + exit_rows, + lane_header, + lane_row, + menu_rows, + section_heading, +) from .trace_screen import TracingDialog from .tui import Choice, Separator from .tui.spinner import Spinner @@ -239,10 +246,11 @@ def _menu_items( label_w = max(cell_len(label) for _, rows in sections for label, _, _, _ in rows) value_w = max(cell_len(value.plain) for _, rows in sections for _, value, _, _ in rows) + # The same pinned, self-fitting header the local editor heads its lanes with: it stays + # on screen under the category headings for the whole list, and abbreviates instead of + # wrapping when a long cached value leaves the last label no room (menus.lane_header). items: list = [ - Separator( - " " + "SETTING".ljust(label_w + 2) + "VALUE".ljust(value_w + 2) + "DESCRIPTION" - ) + Separator(lambda w: lane_header(label_w, value_w, w), pinned=True) ] for category, rows in sections: items.append(section_heading(category)) diff --git a/meshterm/ui/trace_screen.py b/meshterm/ui/trace_screen.py index 0bda737..065a97a 100644 --- a/meshterm/ui/trace_screen.py +++ b/meshterm/ui/trace_screen.py @@ -96,7 +96,7 @@ from ..services import trace_runner from ..services.records import first_repeated_edge from ..services.topology import render_forced_spec from .braillechart import meter -from .menus import back_rows +from .menus import back_rows, section_heading from .theme import snr_style from .tui.render import render_lines, render_to_ansi from .tui.screen import ListWindow, Screen @@ -1871,9 +1871,7 @@ async def _open_session( ) return None - items: list = [ - Separator("── Candidate paths · from received evidence ──", style="accent") - ] + items: list = [section_heading("Candidate paths · from received evidence")] for scenario in scenarios: items.append( Choice( @@ -1919,7 +1917,7 @@ async def _open_session( if not outcomes: return None result_items: list = [ - Separator("── Ranked · reliability, then bottleneck SNR ──", style="accent") + section_heading("Ranked · reliability, then bottleneck SNR") ] for rank, outcome in enumerate(outcomes, start=1): result_items.append(Choice(title=outcome_title(rank, outcome), value=outcome)) diff --git a/meshterm/ui/tui/frame.py b/meshterm/ui/tui/frame.py index 9cd0baa..b7d6b42 100644 --- a/meshterm/ui/tui/frame.py +++ b/meshterm/ui/tui/frame.py @@ -20,15 +20,37 @@ from .render import render_lines from .screen import Screen +#: How many times :func:`_visible_slice` re-settles the scroll against the rows a screen +#: pins above it. Each pin costs a content row, so gaining one can push the highlighted row +#: back out of view and call for another nudge; two or three passes always reach a fixed +#: point at the pin counts screens actually use (a column header and a section heading). +_PIN_SETTLE_PASSES = 3 + + +def _window_start(scroll: int, total: int, viewport: int, pinned: int) -> int: + """The body line the visible window starts at, given ``pinned`` reserved top rows. + + Normally the scroll offset itself. Scrolled fully to the bottom, the reserved rows must + not cost the *last* body lines (a chat's input row would vanish exactly when the + transcript fills the screen), so the window slides down by as many rows as are pinned — + the lines it drops are at the top, right under the pins, where they are stale. + """ + cap = max(1, viewport - pinned) + if scroll >= total - viewport and total > cap: + return min(scroll + pinned, total - cap) + return scroll + + def _visible_slice(screen: Screen, lines: list[str], viewport: int) -> tuple[list[str], bool, bool]: """Clamp the screen's scroll and return the visible lines plus clip flags. Keeps the screen's cursor line in view (for select/text screens) and clamps the scroll offset to the content, then pads the slice to exactly ``viewport`` rows so the panel - always fills its allotted height. When the screen offers a sticky header (a grouped list's - section heading that has scrolled off), it is pinned to the top row: that reserves one row, - so the cursor is kept within the remaining ``viewport - 1`` and the bottom clamp is relaxed - by one so the final content row can still reach the last visible line. + always fills its allotted height. Any sticky rows the screen offers (a grouped list's + section heading that has scrolled off, over a table's column header — see + :meth:`Screen.sticky_rows`) are pinned to the top rows: each reserves one row, so the + cursor is kept within the remaining ``viewport - pinned`` and the bottom clamp is relaxed + by as many so the final content row can still reach the last visible line. Args: screen: The screen being rendered (its ``scroll`` is adjusted in place). @@ -52,28 +74,32 @@ def _visible_slice(screen: Screen, lines: list[str], viewport: int) -> tuple[lis scroll = cursor - viewport + 1 scroll = max(0, min(scroll, max(0, total - viewport))) - # A pinned section heading takes the top row, leaving one fewer for content; nudge the - # scroll down if the cursor would fall in that reserved row, then re-check the heading - # (crossing a section boundary can change which one is pinned, or drop it entirely). - sticky = screen.sticky_header(scroll) if scroll > 0 else None - if sticky is not None: - cap = max(1, viewport - 1) - if cursor is not None and cursor >= scroll + cap: - scroll = min(cursor - cap + 1, max(0, total - cap)) - sticky = screen.sticky_header(scroll) if scroll > 0 else None + # Each pinned row takes a top row, leaving that many fewer for content: nudge the scroll + # down if the cursor would fall in the reserved rows, then re-ask — moving can change + # which heading governs (crossing a section boundary pins another, or none), and a pin + # gained that way reserves one more row, which can call for a further nudge. Settles + # within _PIN_SETTLE_PASSES, since a screen pins at most a column header and a heading. + pinned = screen.sticky_rows(scroll) if scroll > 0 else [] + for _ in range(_PIN_SETTLE_PASSES): + cap = max(1, viewport - len(pinned)) + if not pinned or cursor is None or cursor < scroll + cap: + break + scroll = min(cursor - cap + 1, max(0, total - cap)) + pinned = screen.sticky_rows(scroll) if scroll > 0 else [] screen.scroll = scroll - if sticky is not None: - cap = max(1, viewport - 1) - start = scroll - if scroll >= total - viewport and total > cap: - # Scrolled fully to the bottom: the pinned header's reserved row must not - # cost the *last* body line (a chat's input row would vanish exactly when - # the transcript fills the screen). Slide the window down one instead — - # the dropped row is at the top, right under the pin, where it's stale. - start = min(scroll + 1, total - cap) - visible = [sticky] + lines[start : start + cap] + if pinned: + start = _window_start(scroll, total, viewport, len(pinned)) + if start != scroll: + # The window slid down off the scroll offset, so the pins must describe the row + # it now *starts* at — otherwise a section heading among the dropped lines would + # simply vanish instead of being pinned. Re-ask, then re-settle the start against + # however many rows that reserves (never unpinning: the slide depends on it). + pinned = screen.sticky_rows(start) or pinned + start = _window_start(scroll, total, viewport, len(pinned)) + cap = max(1, viewport - len(pinned)) + visible = pinned + lines[start : start + cap] more_below = start + cap < total visible = visible + [""] * (viewport - len(visible)) return visible, True, more_below diff --git a/meshterm/ui/tui/screen.py b/meshterm/ui/tui/screen.py index da6dae9..0610901 100644 --- a/meshterm/ui/tui/screen.py +++ b/meshterm/ui/tui/screen.py @@ -63,10 +63,17 @@ class Screen: """Initialize scroll state and the (later-assigned) result future.""" self.scroll = 0 self.future: Optional[asyncio.Future] = None - # (body-line index, rendered ANSI line) for each header eligible to be pinned to the - # top row once it scrolls off. A screen that wants sticky headers rebuilds this list - # while rendering its body (see :meth:`sticky_header`); the default is no headers. - self._sticky_headers: list[tuple[int, str]] = [] + # (body-line index, rendered ANSI lines) for each section landmark eligible to be + # pinned to the top rows once it scrolls off. A block is usually one line — a section + # heading, a day divider — but may carry the rows that belong with it (a heading and + # the description under it), which pin together as they scroll off, in order. A screen + # that wants sticky headers rebuilds this list while rendering its body (see + # :meth:`sticky_block`); the default is no landmarks. + self._sticky_headers: list[tuple[int, list[str]]] = [] + # The one header that pins for the *whole* list rather than for its section — a + # table's column header, which means nothing scrolled off (see :meth:`sticky_rows`). + # Recorded the same way, as (body-line index, rendered line); ``None`` for none. + self._pinned_header: Optional[tuple[int, str]] = None # The last render's body height and viewport, recorded by the frame (:meth:`note_metrics`) # so the shared scroll helpers can page by a screenful of the *current* terminal and # clamp to the content without every caller threading the sizes through. @@ -136,30 +143,62 @@ class Screen: """ return 0 - def sticky_header(self, scroll: int) -> Optional[str]: - """An already-rendered body line to pin to the top row once ``scroll`` moves past it. + def sticky_block(self, scroll: int) -> list[str]: + """The already-rendered body lines to pin as ``scroll`` moves past a section landmark. - Lets a grouped list keep its current section heading in view after the heading itself - has scrolled off — a select screen's ``Channels``/``Direct`` divider, or the chat - transcript's ``── Wed Jul 8 ──`` day divider. ``scroll`` is the offset the body is - about to be sliced at; the frame draws the returned line as the top row. + Lets a grouped list keep its current section overhead after the section's own rows have + scrolled off — a select screen's ``Channels``/``Direct`` divider, the Trophy case's + discipline heading *and the description under it*, the chat transcript's + ``── Wed Jul 8 ──`` day divider. ``scroll`` is the offset the body is about to be + sliced at; the returned lines are drawn as top rows, under any whole-list header pinned + over them (:meth:`sticky_rows` composes them for the frame). - The shared rule: among the headers a screen recorded in :attr:`_sticky_headers` while - rendering, find the last one at or above ``scroll`` (the one *governing* the top visible - row) and pin it — unless it is itself the top visible row (nothing to duplicate) or there - is none above. A screen opts in simply by populating :attr:`_sticky_headers`; the empty - default means no pinning. + The shared rule: among the blocks a screen recorded in :attr:`_sticky_headers` while + rendering, find the last one starting at or above ``scroll`` (the one *governing* the + top visible row) and pin exactly the rows of it that ``scroll`` has passed. So a block + hands its rows over one at a time as they leave — the heading pins while its + description is still the top content row, and the two pin together once both are gone — + and the pinned rows always continue seamlessly into the body below. A screen opts in + simply by populating :attr:`_sticky_headers`; the empty default means no pinning. + + A block never takes more than half the viewport: the rows are given up from the *end*, + so the heading — the row that says which section this is — is the last thing dropped on + a short terminal. """ - governing: Optional[str] = None - governing_at = -1 - for idx, line in self._sticky_headers: - if idx <= scroll: - governing, governing_at = line, idx + governing: Optional[tuple[int, list[str]]] = None + for entry in self._sticky_headers: + if entry[0] <= scroll: + governing = entry else: - break # headers are recorded in body order; nothing past here can govern - if governing is None or governing_at == scroll: - return None # no header above, or it's already the top visible row - return governing + break # blocks are recorded in body order; nothing past here can govern + if governing is None: + return [] # no landmark above the top visible row + at, rows = governing + keep = max(1, self._scroll_viewport // 2) + return rows[: min(scroll - at, keep)] + + def sticky_rows(self, scroll: int) -> list[str]: + """Every already-rendered line to pin above the body sliced at ``scroll``. + + What the frame actually draws, top-down: the whole-list header from + :attr:`_pinned_header` (a table's column header — the lane names, which mean the + same everywhere in the list) once it has scrolled off, then the governing section + block from :meth:`sticky_block`. A screen with only section headings pins one + line; a grouped table pins both, so a scrolled row can still be read off its lanes + *and* placed in its group. + + Args: + scroll: The offset the body is about to be sliced at. + + Returns: + The lines to pin, in draw order (empty for nothing to pin). Each one costs the + body a row, so the frame reserves exactly as many as come back. + """ + rows: list[str] = [] + if self._pinned_header is not None and self._pinned_header[0] < scroll: + rows.append(self._pinned_header[1]) + rows.extend(self.sticky_block(scroll)) + return rows # --- input --------------------------------------------------------------- diff --git a/meshterm/ui/tui/select.py b/meshterm/ui/tui/select.py index 98a091b..e50f5c8 100644 --- a/meshterm/ui/tui/select.py +++ b/meshterm/ui/tui/select.py @@ -112,18 +112,47 @@ class Separator: title: The row's text — a plain string drawn uniformly in :attr:`style`, or a Rich :class:`~rich.text.Text` carrying its own spans (for a column header that lights just its active sort column, say), rendered as-authored with ``style`` ignored. + It may instead be a callable taking the **render width** and returning either + — unlike :attr:`Choice.title`'s zero-argument callable — so a column header can + size its labels to the terminal it is being drawn on (see + :func:`~meshterm.ui.menus.column_header`). style: Theme style a *string* title is drawn in. Section headings pass ``"accent"`` so they read as highlighted landmarks; the default ``"muted"`` fits the structural rows (blank spacers, column-header lines, inline notes). A ``Text`` title styles itself, so this is unused for one. + pinned: Whether this row stays on screen for the *whole* list once scrolled past, + above any section heading pinned under it — for a column header, whose lane + names mean the same in every section (see + :meth:`~meshterm.ui.tui.screen.Screen.sticky_rows`). Off by default: an + ordinary separator only pins while its own section is on screen. At most one + row per list should set it; the last one recorded wins. + heading: Whether this row is a *section landmark*: it re-pins to the top row while + its own section is scrolled through, and it delimits the Ctrl+PageUp/PageDown + section jumps. Off by default, because most separators label nothing below them + — a blank spacer, an empty-state note, a discipline's wrapped description — and + pinning one of those overhead would say nothing while costing a content row (and + would shadow the heading it sits under). Set through + :func:`~meshterm.ui.menus.section_heading`, or by hand on a column header that + *is* its block's only landmark. """ - title: Union[str, Text] + title: Union[str, Text, Callable[[int], Union[str, Text]]] style: str = "muted" + pinned: bool = False + heading: bool = False + + def text(self, width: int) -> Union[str, Text]: + """The row's content at ``width`` cells, resolving a width-aware title.""" + return self.title(width) if callable(self.title) else self.title Item = "Choice | Separator" +#: The width handed to a width-aware :class:`Separator` when a *natural* width is being +#: measured rather than a real terminal one (:attr:`SelectScreen.dialog_width`) — wide +#: enough that a self-fitting column header returns its fullest form. +_UNBOUNDED = 10_000 + #: The navigation actions that move the highlight to another row, so an ``hscroll`` list #: drops the current row's horizontal shift (each row scrolls on its own — see #: :meth:`SelectScreen.handle`). The filter edits reset it in their own branches. @@ -349,13 +378,15 @@ class SelectScreen(Screen): caps this to the space available, and this is only read for a *floating* select — the full-screen base menu is laid out by ``compose_base`` and ignores it. The footer is measured at its fullest — with the delete-hint atom folded in — so a deletable row - surfacing that hint never widens the box mid-navigation. + surfacing that hint never widens the box mid-navigation. A width-aware separator is + measured at its fullest too (see :data:`_UNBOUNDED`): the box asks for room for the + whole header, and the header only abbreviates once the *terminal* caps the box. """ footer = _splice_hint(self._footer_base, self._delete_hint) if self._delete_hint \ else self._footer_base widths = [cell_len(self.title), cell_len(footer), cell_len(self._prompt)] for item in self._items: - label = item.title if isinstance(item, Separator) else item.label + label = item.text(_UNBOUNDED) if isinstance(item, Separator) else item.label widths.append(cell_len(_plain(label)) + 2) # + the "❯ " / " " pointer column if isinstance(item, Choice) and item.detail_label is not None: widths.append(cell_len(_plain(item.detail_label)) + 2) # same hanging indent @@ -387,10 +418,20 @@ class SelectScreen(Screen): lines.extend(plines) lines.append("") prefix = len(plines) + 1 - # Record each section heading as a sticky-header candidate, so one that scrolls off is - # re-pinned to the top row by the base Screen.sticky_header. Separators survive - # filtering (see _rows), so the pinning keeps working while the list narrows. + # Record each section heading (a Separator that says it is one) as a sticky block, so + # one that scrolls off is re-pinned to the top rows by the base Screen.sticky_block — + # and a pinned separator (a column header) as the whole-list header pinned above it. + # A heading's block runs on through the separators that *immediately* follow it, before + # the section's first row: prose written there is the section's preamble (the Trophy + # case's "what this discipline scores"), so it belongs overhead with the heading rather + # than scrolling away from the rows it explains. Everything else — blank spacers, + # empty-state notes under a section that has rows, a stray line between choices — is + # the landmark of nothing and stays out of the running, so the rows pinned overhead + # are always the section that governs. Separators survive filtering (see _rows), so + # the pinning keeps working while the list narrows. self._sticky_headers = [] + self._pinned_header = None + block: Optional[list[str]] = None # the heading block still taking rows, if any if self._filter: lines.append(render_to_ansi(Text(f"/{self._filter}", style="warn"), width)) # A row's detail line (see Choice.detail) can make it two lines tall, so the cursor @@ -401,12 +442,31 @@ class SelectScreen(Screen): # A Text title carries its own spans (a two-colour column header); a plain # string is drawn uniformly in the separator's style. Separators never # h-scroll — the shift rides the highlighted choice row alone. - title = item.title - heading = title if isinstance(title, Text) else Text(title, style=item.style) - sep = render_to_ansi(heading, width) - self._sticky_headers.append((len(lines), sep)) - lines.append(sep) + title = item.text(width) + content = title if isinstance(title, Text) else Text(title, style=item.style) + if item.pinned: + # A pinned header is drawn *outside* the body slice and is exactly one + # row tall, so it crops like a row rather than wrapping — a column + # header too wide for the terminal ellipsizes instead of stealing a + # second reserved row from the content. + drawn = [render_to_ansi(content, width, no_wrap=True)] + # A whole-list header stands outside the section run too: it pins above + # the section headings rather than taking a turn among them, and so is + # no section boundary for the Ctrl+PageUp/PageDown jumps either. + self._pinned_header = (len(lines), drawn[0]) + else: + # A prose separator (a note above a startup list) may wrap; each row it + # takes is its own body line, so the viewport still counts them all — and + # every one of them joins the block, wrapped continuations included. + drawn = render_lines(content, width) + if item.heading: + block = list(drawn) + self._sticky_headers.append((len(lines), block)) + elif block is not None: + block.extend(drawn) # the heading's preamble, pinned with it + lines.extend(drawn) continue + block = None # a row closes the heading's block; prose past here is its own is_sel = item is selected if is_sel: cursor_at = len(lines) diff --git a/tests/test_chat.py b/tests/test_chat.py index 00ac261..ad1d2c1 100644 --- a/tests/test_chat.py +++ b/tests/test_chat.py @@ -945,15 +945,20 @@ def _two_day_messages(): return day1 + day2 -def test_chat_sticky_header_pins_the_governing_day_divider() -> None: - """The day divider above the top row pins there once it scrolls off (like the picker).""" +def test_chat_sticky_block_pins_the_governing_day_divider() -> None: + """The day divider above the top row pins there once it scrolls off (like the picker). + + A day is its divider and nothing else, so each block is that one row — where a select + list's heading may carry its description along. + """ screen = _screen(_StubSession(), send=None, messages=_two_day_messages()) screen.render_body(60) - (idx0, div0), (idx1, div1) = screen._sticky_headers - assert screen.sticky_header(0) is None # first divider is itself the top row - assert screen.sticky_header(idx1 - 1) == div0 # still within day one — its divider pins - assert screen.sticky_header(idx1) is None # day two's divider is now the top row - assert screen.sticky_header(idx1 + 1) == div1 # scrolled past it — day two's pins + (idx0, day0), (idx1, day1) = screen._sticky_headers + assert len(day0) == 1 and len(day1) == 1 # one divider, no preamble under it + assert screen.sticky_block(0) == [] # first divider is itself the top row + assert screen.sticky_block(idx1 - 1) == day0 # still within day one — its divider pins + assert screen.sticky_block(idx1) == [] # day two's divider is now the top row + assert screen.sticky_block(idx1 + 1) == day1 # scrolled past it — day two's pins def test_chat_frame_pins_a_day_divider_when_stuck_to_the_newest() -> None: @@ -1452,6 +1457,50 @@ async def test_picker_lists_companions_only(repo: Repository) -> None: assert "Ally" in direct and "Mystery" in direct and "Tower" not in direct +async def test_picker_pins_its_column_header_over_the_group_heading( + repo: Repository, +) -> None: + """Scrolled into Direct, the lane names stay overhead with ``👤 Direct`` under them.""" + import re + from types import SimpleNamespace + + from meshterm.tools.chat import ChatTool + from meshterm.ui.tui import SelectScreen, frame + + ansi = re.compile(r"\x1b\[[0-9;]*m") + contacts = [ + Contact(name=f"Peer{i:02d}", public_key=f"{i:02x}" + "0" * 62, node_type=1) + for i in range(12) + ] + + class _Ui: + def __init__(self) -> None: + self.items = None + + async def select(self, title, items, **kw): + self.items = items + return None + + ctx = SimpleNamespace( + devstate=_PickerDevstate(contacts), repo=repo, ui=_Ui(), chat=_PickerChat() + ) + await ChatTool()._pick_conversation(ctx) + + header = ctx.ui.items[0] + assert header.pinned # the lanes mean the same in both groups — pinned for the list + screen = SelectScreen("Chat", ctx.ui.items, wrap=False) + for _ in range(8): # down past the Direct heading + screen.handle("down") + visible, above, _below = frame._visible_slice(screen, screen.render_body(72), 8) + top = [ansi.sub("", row).strip() for row in visible[:2]] + assert top[0].startswith("CONVERSATION") and top[0].endswith("LAST MESSAGE") + assert top[1] == "── 👤 Direct ──" + assert above is True + # Too narrow for the whole line, the trailing label shortens — never wraps. + assert header.text(50).endswith("LAST MSG") + assert "\n" not in header.text(40) + + async def test_picker_del_deletes_history_after_a_red_confirm(repo: Repository) -> None: """Del on a contacted thread: red destructive confirm, history gone, unread cleared, and the re-entered picker's row is hollow (no longer deletable).""" diff --git a/tests/test_config_editor.py b/tests/test_config_editor.py index afbed50..49bf350 100644 --- a/tests/test_config_editor.py +++ b/tests/test_config_editor.py @@ -441,6 +441,24 @@ async def test_editor_clean_close_needs_no_confirmation(ctx: AppContext) -> None assert await edit_config(ctx) is None +async def test_editor_menu_pins_the_column_header_over_the_category(ctx: AppContext) -> None: + """Scrolled deep, the lane names stay overhead with the category heading under them.""" + from meshterm.ui.tui import SelectScreen, frame + + ui = _install(ctx, [("select", "__cancel__")]) + assert await edit_config(ctx) is None + menu = ui.session.pushed[0] + # Re-open the same rows highlighting a row in the last category, so the list scrolls + # past both the column header and the earlier headings. + deep = SelectScreen(menu.title, menu._items, default="__advert_flood__", wrap=False) + visible, above, _below = frame._visible_slice(deep, deep.render_body(100), 6) + top = [_ANSI.sub("", row).strip() for row in visible[:2]] + assert top[0].startswith("SETTING") and top[0].endswith("DESCRIPTION") + assert top[1] == "── Background adverts ──" + assert above is True + assert any("Flood advert" in _ANSI.sub("", row) for row in visible) + + async def test_editor_location_typed_coordinates_stage_both_axes(ctx: AppContext) -> None: """Typing a coordinate pair stages latitude and longitude together.""" _install(ctx, [ diff --git a/tests/test_menus.py b/tests/test_menus.py index c94e7c6..600ebbf 100644 --- a/tests/test_menus.py +++ b/tests/test_menus.py @@ -10,10 +10,13 @@ from __future__ import annotations from rich.text import Text from meshterm.ui.menus import ( + Lane, back_rows, changes_phrase, + column_header, exit_rows, fit_cells, + lane_header, menu_rows, section_heading, ) @@ -82,6 +85,54 @@ def test_changes_phrase_pluralizes() -> None: assert changes_phrase(2) == "2 staged changes" +def test_column_header_lays_each_label_over_its_lane() -> None: + """Lanes pad to their own width under the pointer indent, so labels sit over columns.""" + header = column_header([Lane("NAME", 8), Lane("KEY", 6), Lane("HEARD")], 40) + assert header == " NAME KEY HEARD" + + +def test_column_header_abbreviates_from_the_right_to_fit() -> None: + """Too narrow for the full labels, lanes give their shorter forms — never a wrap.""" + from rich.cells import cell_len + + lanes = [Lane("SETTING", 10), Lane(("DESCRIPTION", "DESC", "?"))] + assert column_header(lanes, 40) == " SETTING DESCRIPTION" # room for the full word + assert column_header(lanes, 20) == " SETTING DESC" # one step shorter, and it fits + assert column_header(lanes, 13) == " SETTING ?" # the last form still fits + # Nothing left to give: the line crops rather than wrapping onto a second row. + tight = column_header(lanes, 10) + assert cell_len(tight) == 10 and tight.endswith("…") and "\n" not in tight + + +def test_column_header_only_shortens_the_lanes_it_has_to() -> None: + """A lane keeps its full label while a lane to its right can still give cells back.""" + from rich.cells import cell_len + + lanes = [Lane(("CONVERSATION", "CHAT"), 14), Lane(("LAST MESSAGE", "LAST MSG", "LAST"))] + assert column_header(lanes, 24) == " CONVERSATION LAST MSG" + assert column_header(lanes, 20) == " CONVERSATION LAST" + # Only once the right-hand lane is spent does the left one abbreviate — and a line that + # still cannot fit crops (its padded lanes have no cells to give), never wraps. + tight = column_header(lanes, 14) + assert tight.startswith(" CHAT") and tight.endswith("…") and cell_len(tight) == 14 + + +def test_lane_header_heads_the_editor_lanes_and_shortens_description() -> None: + """The shared editor header matches lane_row's lanes and abbreviates the last label.""" + from meshterm.ui.menus import lane_row + + row = lane_row("Node name", Text("MockCompanion"), "Advertised name", 12, 20) + header = lane_header(12, 20, 80) + assert header.startswith(" SETTING") + assert header.index("VALUE") == 2 + 12 + 2 # the pointer indent, then the label lane + assert header.index("DESCRIPTION") == 2 + 12 + 2 + 20 + 2 + # The row's own lanes start where the header's labels do (both padded the same way, + # the header offset by the pointer column the rows draw for themselves). + assert row.plain.index("MockCompanion") == header.index("VALUE") - 2 + assert row.plain.index("Advertised name") == header.index("DESCRIPTION") - 2 + assert lane_header(12, 20, 44).endswith("DESC") # no room for the word — abbreviate + + def test_fit_cells_measures_display_cells_not_characters() -> None: """Padding and truncation count display cells, so wide glyphs can't skew lanes.""" from rich.cells import cell_len diff --git a/tests/test_repeater_admin.py b/tests/test_repeater_admin.py index f765182..9b273e8 100644 --- a/tests/test_repeater_admin.py +++ b/tests/test_repeater_admin.py @@ -294,3 +294,40 @@ def test_cli_screen_timeout_note_frees_the_prompt() -> None: screen.failed("no reply within 10 s") assert not screen.busy assert "no reply within 10 s" in "\n".join(screen.render_body(80)) + + +# --- the editor menu's column header -------------------------------------------------- + + +def test_admin_menu_pins_the_column_header_over_the_category() -> None: + """Scrolled deep, the lane names stay overhead with the category heading under them.""" + import re + + from meshterm.ui.repeater_admin import _menu_items + from meshterm.ui.tui import frame + + ansi = re.compile(r"\x1b\[[0-9;]*m") + title, items = _menu_items(NODE, {}, {}) + screen = SelectScreen(title, items, wrap=False) + for _ in range(18): # down past the first categories + screen.handle("down") + visible, above, _below = frame._visible_slice(screen, screen.render_body(72), 10) + top = [ansi.sub("", row).strip() for row in visible[:2]] + assert top[0].startswith("SETTING") and top[0].endswith("DESCRIPTION") + assert top[1].startswith("──") # the category the highlighted row sits in + assert above is True + + +def test_admin_menu_header_abbreviates_rather_than_wrapping() -> None: + """Too narrow for the whole line, the last label shortens — the header stays one row.""" + from rich.cells import cell_len + + from meshterm.ui.repeater_admin import _menu_items + + _title, items = _menu_items(NODE, {}, {}) + header = items[0] + assert header.pinned + full = header.text(100) + assert full.endswith("DESCRIPTION") + narrow = header.text(cell_len(full) - 2) + assert narrow.endswith("DESC") and "\n" not in narrow diff --git a/tests/test_tui.py b/tests/test_tui.py index 7f56cdc..dd24b1d 100644 --- a/tests/test_tui.py +++ b/tests/test_tui.py @@ -19,6 +19,7 @@ from rich.table import Table from rich.text import Text from meshterm import copyright_notice +from meshterm.ui.menus import section_heading from meshterm.ui.tui import frame, glow from meshterm.ui.tui.glow import apply_corner_glow from meshterm.ui.tui.progress import ProgressScreen @@ -222,9 +223,9 @@ def test_select_pageup_pagedown_jump_by_a_screenful() -> None: def _grouped_menu(default: object = None) -> SelectScreen: """A two-section menu long enough that each section scrolls past a small viewport.""" - items: list = [Separator("── Channels ──")] + items: list = [section_heading("Channels")] items += [Choice(f"chan{i}", ("c", i)) for i in range(6)] - items += [Separator("── Direct ──")] + items += [section_heading("Direct")] items += [Choice(f"peer{i}", ("d", i)) for i in range(8)] return SelectScreen("pick", items, default=default) @@ -254,6 +255,82 @@ def test_select_does_not_pin_a_heading_that_is_still_visible() -> None: assert above is False # top of the list; no pinned duplicate and no "more above" +def _trophy_shaped() -> SelectScreen: + """The Trophy case's shape: a heading, its description, then that board's rows.""" + items: list = [section_heading("Longest haul")] + items += [Separator(f" description line {i}", style="muted") for i in range(2)] + items += [Choice(f"rec{i}", ("l", i)) for i in range(6)] + items += [section_heading("Widest arc"), Separator(" no records yet", style="muted")] + items += [Choice(f"arc{i}", ("a", i)) for i in range(6)] + return SelectScreen("Trophy case", items, default=("l", 5), wrap=False) + + +def _blocks(screen: SelectScreen) -> list[list[str]]: + """Each recorded sticky block's rows, as plain text.""" + return [ + [Text.from_ansi(line).plain.strip() for line in rows] + for _idx, rows in screen._sticky_headers + ] + + +def test_select_blocks_a_heading_with_the_prose_written_under_it() -> None: + """A heading's landmark runs on through the separators that immediately follow it. + + The Trophy case's shape: each discipline's ``── heading ──`` is followed by its wrapped + description, which explains the rows below and so belongs overhead with the heading — + while prose that follows a *row* (a stray note, the exit group's blank) labels nothing + and is no landmark at all. + """ + screen = _trophy_shaped() + screen.render_body(40) + assert _blocks(screen) == [ + ["── Longest haul ──", "description line 0", "description line 1"], + ["── Widest arc ──", "no records yet"], + ] + + +def test_select_pins_a_block_row_only_once_it_has_scrolled_off() -> None: + """A block hands its rows over one at a time, so the pins continue into the body. + + While the description is still the top content row the heading alone pins over it; once + both are gone the two pin together. Never the prose alone — the row that says *which* + section this is leads whatever is overhead. + """ + screen = _trophy_shaped() + screen.render_body(40) + screen.note_metrics(total=20, viewport=12) + plain = lambda scroll: [ # noqa: E731 - a one-liner reader for the assertions below + Text.from_ansi(line).plain.strip() for line in screen.sticky_rows(scroll) + ] + assert plain(0) == [] # the heading is the top row itself; nothing to duplicate + assert plain(1) == ["── Longest haul ──"] # its description is still on screen + assert plain(2) == ["── Longest haul ──", "description line 0"] + assert plain(4) == [ + "── Longest haul ──", "description line 0", "description line 1", + ] + # A block never eats more than half the viewport — the rows go from the end, so the + # heading is the last thing a short terminal gives up. + screen.note_metrics(total=20, viewport=4) + assert plain(4) == ["── Longest haul ──", "description line 0"] + screen.note_metrics(total=20, viewport=2) + assert plain(4) == ["── Longest haul ──"] + + +def test_select_pins_the_heading_not_the_prose_beneath_it() -> None: + """The pinned rows always *lead* with the heading, never the last muted line under it.""" + screen = _trophy_shaped() + assert _top_plain(screen, viewport=6) == "── Longest haul ──" + # And the empty-state note can't stand in for its heading either. + assert _top_plain(_reselect(screen, ("a", 4)), viewport=6) == "── Widest arc ──" + + +def _reselect(screen: SelectScreen, value: object) -> SelectScreen: + """Move a select screen's highlight to ``value`` (by walking Down to it).""" + while screen._choices()[screen._index].value != value: + screen.handle("down") + return screen + + def test_select_pinned_heading_keeps_the_last_row_reachable() -> None: """Even with a heading pinned, the bottom choice stays fully visible (not clipped).""" screen = _grouped_menu() @@ -265,20 +342,114 @@ def test_select_pinned_heading_keeps_the_last_row_reachable() -> None: assert below is False # and we know we're at the bottom -def test_screen_sticky_header_picks_the_governing_recorded_header() -> None: - """The base Screen.sticky_header logic is generic over any recorded headers list. +def _columned_menu(default: object = None) -> SelectScreen: + """A grouped menu led by a pinned column header, like the config editor's.""" + items: list = [Separator(" SETTING VALUE", pinned=True)] + items += [section_heading("Channels")] + items += [Choice(f"chan{i}", ("c", i)) for i in range(6)] + items += [section_heading("Direct")] + items += [Choice(f"peer{i}", ("d", i)) for i in range(8)] + return SelectScreen("pick", items, default=default, wrap=False) + + +def test_select_pins_a_column_header_above_the_section_heading() -> None: + """A pinned column header rides the whole list, the governing heading under it.""" + screen = _columned_menu(default=("d", 6)) # deep in the second section + lines = screen.render_body(40) + visible, above, _below = frame._visible_slice(screen, lines, 7) + assert [Text.from_ansi(row).plain.strip() for row in visible[:2]] == [ + "SETTING VALUE", # the lanes, pinned for every section + "── Direct ──", # over the section the highlight is in + ] + assert above is True + assert any("peer6" in Text.from_ansi(row).plain for row in visible) # highlight in view + # The pinned header is no section landmark — only the two headings are. + assert _blocks(screen) == [["── Channels ──"], ["── Direct ──"]] + + +def test_select_column_header_shows_itself_at_the_top_and_pins_alone() -> None: + """Unscrolled it just draws; past it, it pins even before any heading scrolls off.""" + screen = _columned_menu() # highlight on the first choice — the list sits at the top + lines = screen.render_body(40) + visible, above, _below = frame._visible_slice(screen, lines, 8) + assert Text.from_ansi(visible[0]).plain.strip() == "SETTING VALUE" + assert above is False # nothing pinned over the real row, nothing above it + # Scrolled one row on, the header pins while its own section heading is still the top + # content row — so it is the only pin. + assert screen.sticky_rows(1) == [screen._pinned_header[1]] + + +def test_select_pinned_column_header_keeps_the_last_row_reachable() -> None: + """Two pinned rows still leave the bottom choice fully visible (not clipped).""" + screen = _columned_menu() + screen.handle("end") # highlight the final choice + lines = screen.render_body(40) + visible, _above, below = frame._visible_slice(screen, lines, 7) + assert Text.from_ansi(visible[0]).plain.strip() == "SETTING VALUE" + assert any("peer7" in Text.from_ansi(row).plain for row in visible) + assert below is False + + +def test_select_resolves_a_width_aware_separator_at_the_render_width() -> None: + """A callable separator title is handed the render width, so a header can fit itself.""" + screen = SelectScreen( + "pick", [Separator(lambda w: f"HEADER@{w}", pinned=True), Choice("row", 1)] + ) + assert Text.from_ansi(screen.render_body(30)[0]).plain.strip() == "HEADER@30" + assert Text.from_ansi(screen.render_body(48)[0]).plain.strip() == "HEADER@48" + # Natural-width measurement asks for the fullest form, not a terminal-sized one, so the + # box is sized to the whole header and only the terminal can force it to abbreviate. + natural = SelectScreen( + "pick", + [Separator(lambda w: "H" * min(w, 120), pinned=True), Choice("row", 1)], + footer_hint="Esc back", + ) + assert natural.dialog_width >= 120 + + +def test_select_pinned_header_crops_where_a_plain_separator_wraps() -> None: + """A pinned row must stay exactly one row: too wide, it ellipsizes rather than wraps.""" + wide = "SETTING" + " " * 40 + "DESCRIPTION" + screen = SelectScreen("pick", [Separator(wide, pinned=True), Choice("row", 1)]) + lines = screen.render_body(24) + assert screen._pinned_header == (0, lines[0]) + assert Text.from_ansi(lines[0]).plain.rstrip().endswith("…") + assert len(lines) == 2 # the header and the one choice — nothing wrapped onto a row + # An ordinary separator still wraps, each row of it counted as its own body line. + plain = SelectScreen("pick", [Separator(wide), Choice("row", 1)]) + assert len(plain.render_body(24)) == 3 + + +def test_screen_sticky_rows_stack_the_pinned_header_over_the_section_heading() -> None: + """The shared rule composing both pins: whole-list header first, then the section's.""" + screen = Screen() + screen.note_metrics(total=40, viewport=12) + screen._pinned_header = (0, "COLUMNS") + screen._sticky_headers = [(1, ["A"]), (5, ["B"])] + assert screen.sticky_rows(0) == [] # nothing has scrolled off yet + assert screen.sticky_rows(1) == ["COLUMNS"] # heading A is itself the top row + assert screen.sticky_rows(3) == ["COLUMNS", "A"] # inside section A + assert screen.sticky_rows(9) == ["COLUMNS", "B"] # below every heading → the last one + assert Screen().sticky_rows(9) == [] # nothing recorded → nothing pinned + + +def test_screen_sticky_block_picks_the_governing_recorded_block() -> None: + """The base Screen.sticky_block logic is generic over any recorded landmark list. Both the select list and the chat transcript reuse it by populating ``_sticky_headers``; - this exercises the shared rule directly: pin the last header at or above the offset, unless - it *is* the top row or none sits above it. + this exercises the shared rule directly: take the last block starting at or above the + offset, and pin exactly the rows of it the offset has passed. """ screen = Screen() - screen._sticky_headers = [(0, "A"), (5, "B"), (12, "C")] - assert screen.sticky_header(0) is None # header A is itself the top row - assert screen.sticky_header(3) == "A" # scrolled past A, before B → A governs - assert screen.sticky_header(5) is None # header B is now the top row - assert screen.sticky_header(20) == "C" # below every header → the last one pins - assert Screen().sticky_header(9) is None # no recorded headers → nothing to pin + screen.note_metrics(total=40, viewport=12) + screen._sticky_headers = [(0, ["A"]), (5, ["B", "b"]), (12, ["C"])] + assert screen.sticky_block(0) == [] # block A is itself the top row + assert screen.sticky_block(3) == ["A"] # scrolled past A, before B → A governs + assert screen.sticky_block(5) == [] # block B's heading is now the top row + assert screen.sticky_block(6) == ["B"] # its second row is still on screen + assert screen.sticky_block(7) == ["B", "b"] # both gone → both pin + assert screen.sticky_block(20) == ["C"] # below every block → the last one pins + assert Screen().sticky_block(9) == [] # no recorded landmarks → nothing to pin def test_select_ctrl_page_jumps_between_sections() -> None: @@ -313,7 +484,7 @@ def test_screen_section_scroll_walks_recorded_headers() -> None: """Ctrl+PageUp/PageDown move the scroll offset between recorded section boundaries.""" screen = Screen() screen.note_metrics(total=100, viewport=10) - screen._sticky_headers = [(0, "A"), (20, "B"), (60, "C")] + screen._sticky_headers = [(0, ["A"]), (20, ["B"]), (60, ["C"])] screen.scroll_to_next_section() assert screen.scroll == 20 # from the top → start of section B screen.scroll_to_next_section()