Hang wrapped chat lines and color @mentions
Wrapped message bodies now align their continuation lines under the body of the first line instead of falling back to the timestamp gutter, via a new render_hanging helper. And an @[Name] token primed by the reply flow renders as a bare @Name in that sender's stable hue, so a mention reads cleanly and is tied to the person it names. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
1 parent
fb3c7a15e2
commit
5b7fe854cb
3 files changed
+131
-15
No files matched your search
+50
-15
@@ -26,7 +26,7 @@ from ..core.events import EventKind, MeshEvent
|
||||
from ..core.models import ChatMessage, Contact, Conversation, Message, utcnow
|
||||
from .theme import snr_style
|
||||
from .tui.prompt import _LineEditor
|
||||
from .tui.render import render_lines
|
||||
from .tui.render import render_hanging, render_lines
|
||||
from .tui.screen import CANCEL, Screen
|
||||
from .tui.spinner import Spinner
|
||||
|
||||
@@ -59,6 +59,11 @@ _SENDER_COLORS = (
|
||||
#: be followed by ``": "`` — conservative enough to leave ``http://…`` and ``note:x`` alone.
|
||||
_SENDER_PREFIX = re.compile(r"^([^\s:][^:]{0,19}):[ \t]+(.*)$", re.DOTALL)
|
||||
|
||||
#: Matches an ``@[Name]`` mention token, as the reply flow primes into the compose line (see
|
||||
#: :meth:`ChatScreen._begin_reply`). The transcript renders each as a bare ``@Name`` colored
|
||||
#: in that sender's hue instead of showing the literal brackets. Name is 1–20 non-``]`` chars.
|
||||
_MENTION = re.compile(r"@\[([^\]]{1,20})\]")
|
||||
|
||||
|
||||
#: Delivery-state indicators for a *resolved* outbound direct message, shown at the end of
|
||||
#: its line: acknowledged, or transmitted-but-unacknowledged (retryable via Ctrl-R). While
|
||||
@@ -320,7 +325,7 @@ class ChatScreen(Screen):
|
||||
selected = idx == self._selected
|
||||
if selected:
|
||||
self._selected_line = len(lines)
|
||||
lines += render_lines(self._body_line(body, message, selected=selected), width)
|
||||
lines += self._body_lines(body, message, width, selected=selected)
|
||||
prev_group, prev_day = group, day
|
||||
return lines
|
||||
|
||||
@@ -342,32 +347,62 @@ class ChatScreen(Screen):
|
||||
"""Build the sender header that starts a group, colored per sender."""
|
||||
return Text(sender, style=self._sender_style(sender, is_self=is_self))
|
||||
|
||||
def _body_line(self, body: str, message: ChatMessage, *, selected: bool = False) -> Text:
|
||||
"""Build one indented message line, each stamped with its own time.
|
||||
def _body_lines(
|
||||
self, body: str, message: ChatMessage, width: int, *, selected: bool = False
|
||||
) -> list[str]:
|
||||
"""Render one message to ANSI lines, stamped with its own time and hanging-indented.
|
||||
|
||||
The per-message timestamp lives here (not on the group header) so every message
|
||||
shows the time it was actually sent, even when several are grouped under one
|
||||
sender — otherwise a run of same-sender messages would appear to share one time.
|
||||
When ``selected``, the line is marked as the reply target (matching the select
|
||||
screen's ``❯`` pointer and brand highlight).
|
||||
A long body wraps with a hanging indent so continuation lines align under the body
|
||||
rather than under the timestamp gutter. When ``selected``, the line is marked as the
|
||||
reply target (matching the select screen's ``❯`` pointer and brand highlight).
|
||||
"""
|
||||
stamp = message.created_at.astimezone()
|
||||
line = Text()
|
||||
line.append("❯ " if selected else " ", style="brand" if selected else None)
|
||||
line.append(f"{stamp:%H:%M} ", style="brand" if selected else "muted")
|
||||
line.append(body, style="brand" if selected else None)
|
||||
prefix = Text()
|
||||
prefix.append("❯ " if selected else " ", style="brand" if selected else None)
|
||||
prefix.append(f"{stamp:%H:%M} ", style="brand" if selected else "muted")
|
||||
body_text = self._body_text(body, message, selected=selected)
|
||||
return render_hanging(prefix, body_text, width, indent=prefix.cell_len)
|
||||
|
||||
def _body_text(self, body: str, message: ChatMessage, *, selected: bool) -> Text:
|
||||
"""Build the styled body of a message: mentions colored, then any trailing glyphs."""
|
||||
text = self._render_mentions(body, selected=selected)
|
||||
if message.outbound:
|
||||
# Direct messages track per-message delivery (spin → ✅/❌, retryable); channel
|
||||
# broadcasts have no ack, so only flag one that failed to leave the companion.
|
||||
if message.is_channel:
|
||||
if message.acked is False:
|
||||
line.append(" ⚠ no ack", style="warn")
|
||||
text.append(" ⚠ no ack", style="warn")
|
||||
else:
|
||||
line.append(" ")
|
||||
line.append(self._delivery_glyph(message.acked))
|
||||
text.append(" ")
|
||||
text.append_text(self._delivery_glyph(message.acked))
|
||||
if message.snr is not None:
|
||||
line.append(f" {message.snr:+.0f} dB", style=snr_style(message.snr))
|
||||
return line
|
||||
text.append(f" {message.snr:+.0f} dB", style=snr_style(message.snr))
|
||||
return text
|
||||
|
||||
def _render_mentions(self, body: str, *, selected: bool) -> Text:
|
||||
"""Render body text, rewriting each ``@[Name]`` token to a ``@Name`` in its hue.
|
||||
|
||||
The reply flow primes the compose line with an ``@[Name]`` token (see
|
||||
:meth:`_begin_reply`); here it reads back as a bare ``@Name`` colored in that
|
||||
sender's stable hue, so a mention is visually tied to the person it names. Text
|
||||
around the mentions keeps the line's base style (brand when the message is the
|
||||
picked reply target, otherwise unstyled).
|
||||
"""
|
||||
base = "brand" if selected else None
|
||||
text = Text()
|
||||
pos = 0
|
||||
for match in _MENTION.finditer(body):
|
||||
if match.start() > pos:
|
||||
text.append(body[pos : match.start()], style=base)
|
||||
name = match.group(1)
|
||||
text.append(f"@{name}", style=self._sender_style(name))
|
||||
pos = match.end()
|
||||
if pos < len(body):
|
||||
text.append(body[pos:], style=base)
|
||||
return text
|
||||
|
||||
def _delivery_glyph(self, acked: Optional[bool]) -> Text:
|
||||
"""Map an outbound direct message's ``acked`` state to its trailing glyph.
|
||||
|
||||
@@ -14,6 +14,7 @@ from __future__ import annotations
|
||||
from io import StringIO
|
||||
|
||||
from rich.console import Console, RenderableType
|
||||
from rich.text import Text
|
||||
|
||||
from ..theme import MESH_THEME
|
||||
|
||||
@@ -90,3 +91,34 @@ def render_lines(renderable: RenderableType, width: int, *, no_wrap: bool = Fals
|
||||
if lines and lines[-1] == "":
|
||||
lines.pop()
|
||||
return lines
|
||||
|
||||
|
||||
def render_hanging(prefix: Text, body: Text, width: int, *, indent: int) -> list[str]:
|
||||
"""Render ``prefix + body`` at ``width``, wrapping the body with a hanging indent.
|
||||
|
||||
The first visual line carries ``prefix`` followed by the body; every wrapped
|
||||
continuation line is padded by ``indent`` columns so it aligns under the body rather
|
||||
than falling back to column zero. Used by the chat transcript so a wrapped message
|
||||
lines up with its own first line instead of with the timestamp gutter.
|
||||
|
||||
Args:
|
||||
prefix: The leading run (e.g. a pointer + timestamp) shown once, on the first line.
|
||||
body: The wrappable message text; styling (mentions, glyphs) is preserved.
|
||||
width: Total render width in columns.
|
||||
indent: Columns to indent continuation lines by (typically ``prefix.cell_len``).
|
||||
|
||||
Returns:
|
||||
The rendered lines, newline-free.
|
||||
"""
|
||||
width = max(1, width)
|
||||
console = _console(width)
|
||||
avail = max(1, width - indent)
|
||||
wrapped = list(body.wrap(console, avail)) or [Text("")]
|
||||
pad = " " * indent
|
||||
combined = Text()
|
||||
for i, line in enumerate(wrapped):
|
||||
if i:
|
||||
combined.append("\n")
|
||||
combined.append_text(prefix if i == 0 else Text(pad))
|
||||
combined.append_text(line)
|
||||
return render_lines(combined, width)
|
||||
@@ -615,6 +615,55 @@ def test_chat_screen_shows_delivery_glyphs() -> None:
|
||||
assert "Ctrl-R" in screen.footer_hint
|
||||
|
||||
|
||||
def test_wrapped_body_hangs_under_the_first_line() -> None:
|
||||
"""A body too long for the width wraps with a hanging indent under its own first line."""
|
||||
from datetime import datetime, timezone
|
||||
|
||||
base = datetime(2026, 7, 5, 14, 24, tzinfo=timezone.utc)
|
||||
# A run of short words guarantees several wrap points at a narrow width.
|
||||
text = " ".join(["word"] * 20)
|
||||
messages = [ChatMessage(text=text, peer="d4e5f6a7", created_at=base)]
|
||||
screen = _screen(_StubSession(), send=None, messages=messages)
|
||||
body_lines = [_strip_ansi(l) for l in screen._body_lines(text, messages[0], 30)]
|
||||
|
||||
assert len(body_lines) > 1 # it actually wrapped
|
||||
stamp = base.astimezone().strftime("%H:%M")
|
||||
indent = body_lines[0].index(stamp) + len(stamp) + 2 # gutter: " HH:MM "
|
||||
first_word = body_lines[0].index("word")
|
||||
assert first_word == indent
|
||||
# Continuation lines start their text at the same column as the first line's body.
|
||||
for cont in body_lines[1:]:
|
||||
assert cont.startswith(" " * indent)
|
||||
assert cont[indent] != " " # text resumes exactly under the body, not the gutter
|
||||
|
||||
|
||||
def test_at_mention_renders_as_name_in_sender_hue() -> None:
|
||||
"""An ``@[Name]`` token renders as a bare ``@Name`` colored in that sender's hue."""
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from meshterm.ui.chat import _SENDER_COLORS
|
||||
|
||||
base = datetime(2026, 7, 5, 14, 24, tzinfo=timezone.utc)
|
||||
conv = Conversation(label="#public", is_channel=True, channel_idx=0)
|
||||
message = ChatMessage(
|
||||
text="Bob: @[Alice] you around?", is_channel=True, channel_idx=0, created_at=base
|
||||
)
|
||||
screen = ChatScreen(conv, [message], send=None, names={}, session=_StubSession())
|
||||
_, body = screen._sender_and_body(message)
|
||||
text = screen._render_mentions(body, selected=False)
|
||||
|
||||
assert "@Alice" in text.plain # bracketed token collapsed to a bare mention
|
||||
assert "@[Alice]" not in text.plain and "[Alice]" not in text.plain
|
||||
# The "@Alice" run carries Alice's palette hue (the same the header would use).
|
||||
hue = screen._sender_style("Alice")
|
||||
assert hue in _SENDER_COLORS
|
||||
at = text.plain.index("@Alice")
|
||||
hue_spans = [
|
||||
s for s in text.spans if s.style == hue and s.start <= at and at + len("@Alice") <= s.end
|
||||
]
|
||||
assert hue_spans
|
||||
|
||||
|
||||
def test_direct_transcript_groups_under_sender_headers() -> None:
|
||||
"""Direct chats use the same grouped layout as channels: one header per sender run."""
|
||||
from datetime import datetime, timezone
|
||||
|
||||
Reference in new issue
Block a user