Skip to content

Commit 4518dd8

Browse files
karkarlCopilot
andauthored
improve(chat): make prose and simple lists one selectable text block (#997)
* Render chat bubbles through per-message RichTextBlock for continuous selection Chat prose was rendered as many separate TextBlocks, so a user could not drag-select text across paragraphs of one message. Add a poolable RichTextBlock primitive to the in-house FunctionalUI reconciler and route both assistant and user message text through one RichTextBlock per message (a Paragraph per block), giving each message a single continuous, selection-friendly text scope while keeping chat virtualizable. - FunctionalUI: RichTextBlockElement record, RichTextBlock() factory, Set(Action<RichTextBlock>), reconciler arm, ConfigureRichTextBlock (leaves Blocks to the setter), ApplyModifiers case. - ChatMarkdownRenderer: coalesce consecutive paragraph/heading blocks into one RichTextBlock; lone text blocks stay TextBlocks; lists/code/tables/etc stay separate selectable siblings. Structural block-run cache preserves active selection across re-renders independent of AST-cache eviction. Inert posture preserved (AppendInlines only). - OpenClawChatTimeline: user bubble renders as a single-Paragraph RichTextBlock preserving font, foreground, wrap and SelectionHighlightColor. - Tests: FunctionalUI primitive tests, renderer coalescing tests, updated user-bubble contract + virtualization proof text collection. Co-authored-by: Copilot App <[email protected]> * Coalesce simple lists into the selectable RichTextBlock Extend the assistant-bubble text coalescing so simple (text-only, possibly nested) bullet/ordered/task lists flow into the same per-message RichTextBlock as surrounding prose, making paragraphs + headings + list items one continuous drag-selection scope. Lists whose items carry a code block, table, blockquote, thematic break, or raw block stay as their own Grid-based selectable island (RenderList), preserving that chrome. List items render as hanging-indent Paragraphs inside the shared RichTextBlock: a per-item marker (task box, ordered number, bullet), fixed hanging indent so wrapped lines / continuation paragraphs align at the content column, per-level indentation for nesting, and heading formatting preserved for heading list items. Extend the selection-preservation cache (BlockEqual) with structural ListEqual so the bounded AST cache evicting and re-parsing an unchanged message does not force a Blocks rebuild that would wipe the active selection. Update MarkdownRendererCoalesceTests / MarkdownRendererListTests: simple lists now assert RichTextBlock coalescing; the issue #636 Grid wrap guards retarget to complex (blockquote-bearing) lists that still use the Grid island path. Co-authored-by: Copilot App <[email protected]> * test(chat): prove selection-scope contract on the live WinUI renderer Add a deterministic UI-thread proof that mounts the shipping OpenClawChatTimeline through the real FunctionalUI reconciler and renders one assistant message mixing prose paragraphs, a bullet list, a trailing paragraph, a fenced code block, and a table. It asserts prose + list + trailing coalesce into a single RichTextBlock (one continuous selection scope) while the code block and table remain their own island TextBlocks. This closes the record-level gap where headless WinRT could not activate FontFamily for code/table islands, and serves as the automated stand-in for the interactive native drag-select recording requested in review. Co-authored-by: Copilot App <[email protected]> --------- Co-authored-by: Copilot App <[email protected]>
1 parent d57047e commit 4518dd8

9 files changed

Lines changed: 830 additions & 41 deletions

File tree

‎src/OpenClaw.Tray.WinUI/Chat/Markdown/ChatMarkdownRenderer.cs‎

Lines changed: 308 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -51,16 +51,74 @@ public static class ChatMarkdownRenderer
5151
if (document.Blocks.Count == 0)
5252
return null;
5353

54-
if (document.Blocks.Count == 1)
55-
return RenderBlock(document.Blocks[0]);
56-
57-
var children = new List<Element?>(document.Blocks.Count);
58-
foreach (var block in document.Blocks)
54+
// Coalesce maximal runs of consecutive mergeable blocks (paragraphs,
55+
// headings, and "simple" bullet/numbered lists) into a single
56+
// RichTextBlock so the whole run is one continuous text-selection scope
57+
// — a drag can select across paragraphs AND list items. Blocks that
58+
// carry their own chrome (code cards, table grids, block-quote borders,
59+
// rules) — and any list that contains such a block — stay as their own
60+
// selectable sibling controls, keeping their existing layout.
61+
var blocks = document.Blocks;
62+
var segments = new List<Element?>(blocks.Count);
63+
int i = 0;
64+
while (i < blocks.Count)
5965
{
60-
var rendered = RenderBlock(block);
61-
if (rendered is not null) children.Add(rendered);
66+
if (IsMergeable(blocks[i]))
67+
{
68+
int start = i;
69+
while (i < blocks.Count && IsMergeable(blocks[i])) i++;
70+
int count = i - start;
71+
if (count == 1 && blocks[start] is MdParagraph or MdHeading)
72+
{
73+
// A lone paragraph / heading keeps the lightweight
74+
// single-TextBlock shape (already internally selectable) —
75+
// no behavior change.
76+
var single = RenderBlock(blocks[start]);
77+
if (single is not null) segments.Add(single);
78+
}
79+
else
80+
{
81+
// Multi-block prose runs — and any run containing a list —
82+
// become one continuous RichTextBlock so paragraphs,
83+
// headings, and list items share a single selection scope.
84+
var run = new List<MdBlock>(count);
85+
for (int j = start; j < i; j++) run.Add(blocks[j]);
86+
segments.Add(TextRunRichBlock(run));
87+
}
88+
}
89+
else
90+
{
91+
var rendered = RenderBlock(blocks[i]);
92+
if (rendered is not null) segments.Add(rendered);
93+
i++;
94+
}
6295
}
63-
return VStack(8.0, children.ToArray());
96+
97+
if (segments.Count == 0) return null;
98+
if (segments.Count == 1) return segments[0];
99+
return VStack(8.0, segments.ToArray());
100+
}
101+
102+
// Blocks that can flow into one continuous RichTextBlock: prose (paragraphs,
103+
// headings) and "simple" lists whose items contain only more mergeable
104+
// blocks. A list containing a code block, table, block quote, thematic
105+
// break, or raw block is NOT mergeable — it keeps its own layout as a
106+
// sibling island so that chrome (code cards, table grids) survives and the
107+
// list's non-text children stay selectable in their native form.
108+
private static bool IsMergeable(MdBlock block) => block switch
109+
{
110+
MdParagraph => true,
111+
MdHeading => true,
112+
MdList list => IsSimpleList(list),
113+
_ => false,
114+
};
115+
116+
private static bool IsSimpleList(MdList list)
117+
{
118+
foreach (var item in list.Items)
119+
foreach (var child in item.Children)
120+
if (!IsMergeable(child)) return false;
121+
return true;
64122
}
65123

66124
public static Element? Render(string? markdown)
@@ -245,6 +303,248 @@ private static Element RenderHeading(MdHeading heading)
245303
private static Element RenderParagraph(MdParagraph paragraph) =>
246304
InlinesTextBlock(paragraph.Inlines).FontSize(BodyFontSize);
247305

306+
// ────────────────────────────────────────────────────────────────────
307+
// Coalesced text run → single selectable RichTextBlock
308+
// ────────────────────────────────────────────────────────────────────
309+
310+
private const double ParagraphSpacing = 8.0;
311+
312+
// Cache the block run applied to each RichTextBlock so re-renders with
313+
// identical content skip the Blocks.Clear()+rebuild round trip. Clearing
314+
// Blocks while the user has an active selection wipes it (same failure mode
315+
// the TextBlock inline cache guards against). Equality is structural
316+
// (see BlockRunsEqual) so it holds even after the bounded AST cache evicts
317+
// and re-parses an unchanged message into fresh block instances.
318+
private static readonly ConditionalWeakTable<RichTextBlock, IReadOnlyList<MdBlock>>
319+
s_blocksCache = new();
320+
321+
private static RichTextBlockElement TextRunRichBlock(IReadOnlyList<MdBlock> blocks) =>
322+
RichTextBlock().Set(rtb =>
323+
{
324+
rtb.TextWrapping = TextWrapping.Wrap;
325+
rtb.IsTextSelectionEnabled = true;
326+
ApplyBlocks(rtb, blocks);
327+
});
328+
329+
private static void ApplyBlocks(RichTextBlock rtb, IReadOnlyList<MdBlock> blocks)
330+
{
331+
if (rtb.Blocks.Count > 0
332+
&& s_blocksCache.TryGetValue(rtb, out var cached)
333+
&& BlockRunsEqual(cached, blocks))
334+
{
335+
return;
336+
}
337+
s_blocksCache.AddOrUpdate(rtb, blocks);
338+
rtb.Blocks.Clear();
339+
foreach (var block in blocks)
340+
{
341+
switch (block)
342+
{
343+
case MdParagraph:
344+
case MdHeading:
345+
{
346+
var p = BuildParagraph(block);
347+
p.Margin = new Thickness(0, TopGap(rtb, ParagraphSpacing), 0, 0);
348+
rtb.Blocks.Add(p);
349+
break;
350+
}
351+
case MdList list:
352+
AppendList(rtb, list, level: 1);
353+
break;
354+
}
355+
}
356+
}
357+
358+
// Vertical gap before the next paragraph: none for the very first paragraph
359+
// in the RichTextBlock, otherwise the supplied gap. Keeping this off the
360+
// first paragraph avoids a leading blank strip at the top of the bubble.
361+
private static double TopGap(RichTextBlock rtb, double gap) =>
362+
rtb.Blocks.Count == 0 ? 0.0 : gap;
363+
364+
// ────────────────────────────────────────────────────────────────────
365+
// Lists coalesced into the shared RichTextBlock (hanging-indent
366+
// paragraphs) — one continuous selection scope with the surrounding
367+
// prose. Only reached for "simple" lists (see IsSimpleList); lists that
368+
// carry chrome-bearing children render via RenderList as their own island.
369+
// ────────────────────────────────────────────────────────────────────
370+
371+
private const double ListIndentPerLevel = 18.0;
372+
private const double ListItemSpacing = 3.0;
373+
// Fixed offset from a list item's marker column to its text/content column.
374+
// Applied as a hanging indent (negative TextIndent on the marker line) so
375+
// wrapped lines and continuation paragraphs align under the text rather than
376+
// back at the marker — approximating the Grid path's Auto/Star columns with
377+
// the flat Paragraph model (which has no per-item measured marker width).
378+
private const double ListHangingIndent = 18.0;
379+
// Marker → text separator. En space gives a stable, font-independent gap
380+
// after the bullet / number without relying on tab stops (which Paragraph
381+
// does not expose).
382+
private const string ListMarkerGap = "\u2002";
383+
384+
private static void AppendList(RichTextBlock rtb, MdList list, int level)
385+
{
386+
bool ordered = list.Marker == MdListMarker.Ordered;
387+
int number = ordered ? list.StartNumber : 0;
388+
for (int idx = 0; idx < list.Items.Count; idx++)
389+
{
390+
var item = list.Items[idx];
391+
string marker = item.TaskState switch
392+
{
393+
MdTaskState.Checked => "\u2611",
394+
MdTaskState.Unchecked => "\u2610",
395+
_ => ordered ? $"{number}." : "\u2022",
396+
};
397+
if (ordered) number++;
398+
// A top-level list's first item gets the fuller paragraph gap so the
399+
// list separates from preceding prose; every other item uses the
400+
// tighter inter-item gap.
401+
double leadGap = (level == 1 && idx == 0) ? ParagraphSpacing : ListItemSpacing;
402+
AppendListItem(rtb, item, marker, level, leadGap);
403+
}
404+
}
405+
406+
private static void AppendListItem(
407+
RichTextBlock rtb, MdListItem item, string marker, int level, double leadGap)
408+
{
409+
double indent = ListIndentPerLevel * level;
410+
bool markerEmitted = false;
411+
foreach (var child in item.Children)
412+
{
413+
double gap = markerEmitted ? ListItemSpacing : leadGap;
414+
switch (child)
415+
{
416+
case MdParagraph p:
417+
rtb.Blocks.Add(BuildListParagraph(
418+
rtb, p.Inlines, indent, markerEmitted ? null : marker, gap));
419+
markerEmitted = true;
420+
break;
421+
case MdHeading h:
422+
{
423+
int hidx = Math.Clamp(h.Level - 1, 0, HeadingFontSizes.Length - 1);
424+
rtb.Blocks.Add(BuildListParagraph(
425+
rtb, h.Inlines, indent, markerEmitted ? null : marker, gap,
426+
HeadingFontSizes[hidx], semiBold: true));
427+
markerEmitted = true;
428+
break;
429+
}
430+
case MdList nested:
431+
if (!markerEmitted)
432+
{
433+
rtb.Blocks.Add(BuildListParagraph(
434+
rtb, Array.Empty<MdInline>(), indent, marker, leadGap));
435+
markerEmitted = true;
436+
}
437+
AppendList(rtb, nested, level + 1);
438+
break;
439+
}
440+
}
441+
if (!markerEmitted)
442+
{
443+
// Empty item — still emit the marker so numbering stays consistent.
444+
rtb.Blocks.Add(BuildListParagraph(
445+
rtb, Array.Empty<MdInline>(), indent, marker, leadGap));
446+
}
447+
}
448+
449+
private static Paragraph BuildListParagraph(
450+
RichTextBlock rtb, IReadOnlyList<MdInline> inlines, double indent,
451+
string? marker, double gap, double fontSize = BodyFontSize, bool semiBold = false)
452+
{
453+
var p = new Paragraph
454+
{
455+
FontSize = fontSize,
456+
// Content column sits a fixed hanging offset past the marker indent
457+
// so wrapped lines / continuation paragraphs align under the text.
458+
Margin = new Thickness(indent + ListHangingIndent, TopGap(rtb, gap), 0, 0),
459+
};
460+
if (semiBold) p.FontWeight = MUIText.FontWeights.SemiBold;
461+
if (marker is not null)
462+
{
463+
// Hanging indent: pull the marker line back to the marker column
464+
// while wrapped lines stay at the content column set by Margin.
465+
p.TextIndent = -ListHangingIndent;
466+
p.Inlines.Add(new Run { Text = marker + ListMarkerGap });
467+
}
468+
AppendInlines(p.Inlines, inlines);
469+
return p;
470+
}
471+
472+
// Compare coalesced text runs structurally rather than via record equality.
473+
// MdParagraph / MdHeading records compare their MdInline lists by reference,
474+
// so two equivalent-but-distinct block instances (produced when the bounded
475+
// GetOrParse AST cache evicts and re-parses an unchanged message) would
476+
// compare unequal and needlessly rebuild Blocks — wiping the active
477+
// selection. MdInline subtypes are value-comparable, so comparing the inline
478+
// sequences by value keeps the selection-preservation guarantee independent
479+
// of parser-cache residency.
480+
private static bool BlockRunsEqual(IReadOnlyList<MdBlock> a, IReadOnlyList<MdBlock> b)
481+
{
482+
if (ReferenceEquals(a, b)) return true;
483+
if (a.Count != b.Count) return false;
484+
for (int i = 0; i < a.Count; i++)
485+
{
486+
if (!BlockEqual(a[i], b[i])) return false;
487+
}
488+
return true;
489+
}
490+
491+
private static bool BlockEqual(MdBlock a, MdBlock b) => (a, b) switch
492+
{
493+
(MdHeading ha, MdHeading hb) => ha.Level == hb.Level && ha.Inlines.SequenceEqual(hb.Inlines),
494+
(MdParagraph pa, MdParagraph pb) => pa.Inlines.SequenceEqual(pb.Inlines),
495+
(MdList la, MdList lb) => ListEqual(la, lb),
496+
_ => a.Equals(b),
497+
};
498+
499+
// Structural list comparison mirroring BlockEqual's rationale: MdList /
500+
// MdListItem records compare their child collections BY REFERENCE, so a
501+
// re-parsed-but-identical list would otherwise force a Blocks rebuild and
502+
// wipe the active selection. Recurse through items and their block children
503+
// (nested lists included) comparing inline content by value.
504+
private static bool ListEqual(MdList a, MdList b)
505+
{
506+
if (a.Marker != b.Marker || a.StartNumber != b.StartNumber) return false;
507+
if (a.Items.Count != b.Items.Count) return false;
508+
for (int i = 0; i < a.Items.Count; i++)
509+
{
510+
var ia = a.Items[i];
511+
var ib = b.Items[i];
512+
if (ia.TaskState != ib.TaskState) return false;
513+
if (ia.Children.Count != ib.Children.Count) return false;
514+
for (int j = 0; j < ia.Children.Count; j++)
515+
if (!BlockEqual(ia.Children[j], ib.Children[j])) return false;
516+
}
517+
return true;
518+
}
519+
520+
private static Paragraph BuildParagraph(MdBlock block)
521+
{
522+
switch (block)
523+
{
524+
case MdHeading heading:
525+
{
526+
int idx = Math.Clamp(heading.Level - 1, 0, HeadingFontSizes.Length - 1);
527+
var p = new Paragraph
528+
{
529+
FontSize = HeadingFontSizes[idx],
530+
FontWeight = MUIText.FontWeights.SemiBold,
531+
};
532+
AppendInlines(p.Inlines, heading.Inlines);
533+
return p;
534+
}
535+
case MdParagraph paragraph:
536+
{
537+
var p = new Paragraph { FontSize = BodyFontSize };
538+
AppendInlines(p.Inlines, paragraph.Inlines);
539+
return p;
540+
}
541+
default:
542+
// Only paragraphs / headings reach this method — lists flow
543+
// through AppendList, other blocks render as sibling islands.
544+
return new Paragraph { FontSize = BodyFontSize };
545+
}
546+
}
547+
248548
private static Element RenderBlockQuote(MdBlockQuote quote)
249549
{
250550
var children = new List<Element?>(quote.Children.Count);

‎src/OpenClaw.Tray.WinUI/Chat/OpenClawChatTimeline.cs‎

Lines changed: 29 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -312,6 +312,28 @@ private static void ApplyPlainSelectableInlines(TextBlock textBlock, string? tex
312312
textBlock.Inlines.Add(new Run { Text = normalized });
313313
}
314314

315+
// RichTextBlock analog of the user-bubble plain-text cache. Selection lives
316+
// on the RichTextBlock, so re-applying identical text must NOT clear Blocks
317+
// (that wipes the active selection). Skip the rebuild when the run is
318+
// unchanged and a paragraph is still present.
319+
private static readonly System.Runtime.CompilerServices.ConditionalWeakTable<RichTextBlock, string>
320+
s_userParagraphCache = new();
321+
322+
private static void ApplyPlainSelectableParagraph(RichTextBlock richTextBlock, string? text)
323+
{
324+
var normalized = text ?? string.Empty;
325+
if (richTextBlock.Blocks.Count > 0
326+
&& s_userParagraphCache.TryGetValue(richTextBlock, out var cached)
327+
&& cached == normalized)
328+
return;
329+
s_userParagraphCache.AddOrUpdate(richTextBlock, normalized);
330+
richTextBlock.Blocks.Clear();
331+
var paragraph = new Paragraph();
332+
if (normalized.Length > 0)
333+
paragraph.Inlines.Add(new Run { Text = normalized });
334+
richTextBlock.Blocks.Add(paragraph);
335+
}
336+
315337
// Cache parsed markdown text per TextBlock to avoid re-clearing and
316338
// rebuilding Inlines on every re-render when message content is stable.
317339
private static readonly System.Runtime.CompilerServices.ConditionalWeakTable<TextBlock, string>
@@ -1155,7 +1177,7 @@ Element RenderUserEntry(ChatTimelineItem entry, bool startsBurst, bool endsBurst
11551177
bool isHighContrast = TryDetectHighContrast();
11561178
var selectionHighlightBrush = GetUserBubbleSelectionBrush(isHighContrast);
11571179
bubbleChildren.Add(
1158-
TextBlock(string.Empty)
1180+
RichTextBlock()
11591181
.Set(t =>
11601182
{
11611183
t.TextWrapping = TextWrapping.Wrap;
@@ -1187,14 +1209,12 @@ Element RenderUserEntry(ChatTimelineItem entry, bool startsBurst, bool endsBurst
11871209
// color the OS guarantees contrasts with both
11881210
// surfaces.
11891211
t.SelectionHighlightColor = selectionHighlightBrush;
1190-
// Render through Inlines (a single Run) rather
1191-
// than the .Text property. This matches the
1192-
// assistant bubble's selection-safe path and
1193-
// sidesteps a WinUI bug where setting Text on a
1194-
// selection-enabled TextBlock during a re-render
1195-
// triggered by the mouse-up that ends a drag-
1196-
// select leaves the glyph layer visually empty.
1197-
ApplyPlainSelectableInlines(t, messageText);
1212+
// Render the message as a single Paragraph (one Run)
1213+
// so the whole user message is one continuous
1214+
// selection scope — matching the assistant bubble's
1215+
// RichTextBlock append-block pattern. The plain-text
1216+
// run keeps the bubble inert (no markdown / links).
1217+
ApplyPlainSelectableParagraph(t, messageText);
11981218
}));
11991219
}
12001220
Element content;

0 commit comments

Comments
 (0)