Steady read-aloud highlight and a calmer default pace

The spoken word is now painted behind unchanged text instead of
restyling the paragraph, so words never reshape, shift or rewrap as the
highlight moves. Revealing the word measures its own boxes against the
visible area, so a reversed transcript no longer jumps for a word already
in view. Sentence breaks the reading adds no longer map onto the next
item's first letter. 1.0x now reads at 0.8 of the platform's normal rate.
This commit is contained in:
2026-11-13 09:41:02 +00:00
parent b2736683e7
commit df0614e2f7
7 changed files with 310 additions and 78 deletions
@@ -28,34 +28,92 @@ SpeechRange? spokenSourceIn(
return (start: range.start + lead, end: range.end + lead);
}
/// [text] as spans whose characters with source [offsets] inside [range] are
/// filled with [fill]; plain text when nothing in it is spoken.
TextSpan spokenTextSpan(
String text,
List<int> offsets,
SpeechRange? range,
Color fill,
) {
if (range == null || offsets.isEmpty) return TextSpan(text: text);
bool spoken(int index) =>
offsets[index] >= range.start && offsets[index] < range.end;
final children = <InlineSpan>[];
var runStart = 0;
for (var index = 1; index <= text.length; index += 1) {
if (index < text.length && spoken(index) == spoken(runStart)) continue;
children.add(
TextSpan(
text: text.substring(runStart, index),
style: spoken(runStart) ? TextStyle(backgroundColor: fill) : null,
),
);
runStart = index;
/// Paints the spoken word's highlight behind the rendered text.
///
/// The text itself is never restyled while speaking: splitting a paragraph
/// into differently styled runs changes how it is shaped, so words would
/// shift and lines rewrap as the highlight moves. Instead this painter, under
/// the text, looks up the spoken characters' boxes in the laid-out paragraphs
/// ([segments]) and fills them; each new word only repaints.
class SpokenWordPainter extends CustomPainter {
SpokenWordPainter({
required this.anchor,
required this.segments,
required this.range,
required this.color,
super.repaint,
});
/// The key of the [CustomPaint] this painter draws in.
final GlobalKey anchor;
final List<MarkdownSpokenSegment> segments;
final SpeechRange? Function() range;
final Color color;
@override
void paint(Canvas canvas, Size size) {
final spoken = range();
final box = anchor.currentContext?.findRenderObject();
if (spoken == null || box is! RenderBox || !box.attached) return;
final fill = Paint()..color = color;
for (final rect in spokenWordRects(segments, spoken, box)) {
canvas.drawRRect(
RRect.fromRectAndRadius(rect.inflate(1.5), const Radius.circular(4)),
fill,
);
}
}
return TextSpan(children: children);
@override
bool shouldRepaint(SpokenWordPainter oldDelegate) =>
oldDelegate.color != color || !identical(oldDelegate.segments, segments);
}
/// The boxes, in [ancestor]'s coordinates, of the rendered characters whose
/// source offsets fall inside [range].
List<Rect> spokenWordRects(
List<MarkdownSpokenSegment> segments,
SpeechRange range,
RenderBox ancestor,
) {
final rects = <Rect>[];
for (final segment in segments) {
if (segment.sourceStart >= range.end || segment.sourceEnd <= range.start) {
continue;
}
int? first;
var last = 0;
for (var index = 0; index < segment.offsets.length; index += 1) {
final offset = segment.offsets[index];
if (offset >= range.start && offset < range.end) {
first ??= index;
last = index + 1;
}
}
if (first == null) continue;
final paragraph = _paragraphIn(segment.key.currentContext);
if (paragraph == null || !paragraph.attached || !paragraph.hasSize) {
continue;
}
final transform = paragraph.getTransformTo(ancestor);
for (final box in paragraph.getBoxesForSelection(
TextSelection(
baseOffset: segment.renderedStart + first,
extentOffset: segment.renderedStart + last,
),
)) {
rects.add(MatrixUtils.transformRect(transform, box.toRect()));
}
}
return rects;
}
/// Scrolls [scroll] just enough to show the spoken [range] when it has left
/// the viewport; a word already in view never moves the transcript.
///
/// The word's own boxes are measured against the visible area directly, in
/// the viewport's coordinates, so a reversed or multi-sliver transcript
/// scrolls only by the distance the word is out of view.
void revealSpokenWord(
ScrollPosition scroll,
List<MarkdownSpokenSegment> segments,
@@ -69,23 +127,33 @@ void revealSpokenWord(
)
.firstOrNull;
final paragraph = _paragraphIn(segment?.key.currentContext);
if (segment == null || paragraph == null) return;
final boxes = paragraph.getBoxesForSelection(
TextSelection(
baseOffset: segment.renderedStart,
extentOffset: segment.renderedEnd,
),
);
if (paragraph == null || !paragraph.attached) return;
final viewport = RenderAbstractViewport.maybeOf(paragraph);
if (boxes.isEmpty || viewport == null) return;
final rect = boxes.first.toRect().inflate(_revealMargin);
final leading = viewport.getOffsetToReveal(paragraph, 0, rect: rect).offset;
final trailing = viewport.getOffsetToReveal(paragraph, 1, rect: rect).offset;
final low = leading < trailing ? leading : trailing;
final high = leading < trailing ? trailing : leading;
final target = scroll.pixels
.clamp(low, high)
.clamp(scroll.minScrollExtent, scroll.maxScrollExtent);
if (viewport is! RenderBox || !(viewport as RenderBox).hasSize) return;
final box = viewport as RenderBox;
final rects = spokenWordRects(segments, range, box);
if (rects.isEmpty) return;
final word = rects.reduce((a, b) => a.expandToInclude(b));
final vertical = scroll.axis == Axis.vertical;
final extent = vertical ? box.size.height : box.size.width;
final start = vertical ? word.top : word.left;
final end = vertical ? word.bottom : word.right;
// Positive when the word must move toward the start of the view.
final double delta;
if (start < _revealMargin) {
delta = start - _revealMargin;
} else if (end > extent - _revealMargin) {
delta = end - (extent - _revealMargin);
} else {
return;
}
final reversed =
scroll.axisDirection == AxisDirection.up ||
scroll.axisDirection == AxisDirection.left;
final target = (scroll.pixels + (reversed ? -delta : delta)).clamp(
scroll.minScrollExtent,
scroll.maxScrollExtent,
);
if ((target - scroll.pixels).abs() < 1) return;
if (reduceMotion) {
scroll.jumpTo(target);
@@ -170,12 +238,16 @@ class MarkdownSpokenSegment {
this.sourceStart,
this.sourceEnd,
this.renderedStart,
this.renderedEnd,
);
this.renderedEnd, [
this.offsets = const [],
]);
final GlobalKey key;
final int sourceStart;
final int sourceEnd;
final int renderedStart;
final int renderedEnd;
/// Each rendered character's offset in the source, in order.
final List<int> offsets;
}
@@ -54,8 +54,6 @@ class _ChatMarkdownViewState extends State<ChatMarkdownView> {
ModalRoute<dynamic>? _route;
var _sourceCursor = 0;
/// The source range of [ChatMarkdownView.text] being spoken, while building.
SpeechRange? _highlight;
SpeechRange? _revealed;
final _textKeys = <GlobalKey>[];
var _textCount = 0;
@@ -103,21 +101,33 @@ class _ChatMarkdownViewState extends State<ChatMarkdownView> {
final range = spokenSourceIn(speech, widget.messageId, widget.text);
if (range == null) {
_revealed = null;
return _rendered ?? _buildRendered(context, null);
}
if (range != _revealed) {
} else if (range != _revealed) {
_revealed = range;
WidgetsBinding.instance.addPostFrameCallback((_) => _reveal(range));
}
return _buildRendered(context, range);
// The text is built once and never restyled while speaking; the
// spoken word is painted behind it, so nothing shifts or rewraps.
final rendered = _rendered ??= _buildRendered(context);
return CustomPaint(
key: _paintKey,
painter: SpokenWordPainter(
anchor: _paintKey,
segments: _segments,
range: () => spokenSourceIn(speech, widget.messageId, widget.text),
color: Theme.of(context).colorScheme.primaryContainer,
repaint: Listenable.merge([speech, speech.word]),
),
child: rendered,
);
},
);
}
Widget _buildRendered(BuildContext context, SpeechRange? range) {
final _paintKey = GlobalKey();
Widget _buildRendered(BuildContext context) {
_sourceCursor = 0;
_textCount = 0;
_highlight = range;
_segments.clear();
final gap = chatParagraphGap(context);
final blocks = chatMarkdownCache.blocksFor(widget.text);
@@ -147,7 +157,7 @@ class _ChatMarkdownViewState extends State<ChatMarkdownView> {
),
),
);
if (range == null) _rendered = rendered;
_rendered = rendered;
return rendered;
}
@@ -394,19 +404,15 @@ class _ChatMarkdownViewState extends State<ChatMarkdownView> {
_segments.add(
MarkdownSpokenSegment(
source.key,
offsets.first,
offsets.last + 1,
offsets.reduce((a, b) => a < b ? a : b),
offsets.reduce((a, b) => a > b ? a : b) + 1,
renderedStart,
source.visibleOffset,
offsets,
),
);
}
return spokenTextSpan(
text,
offsets,
_highlight,
Theme.of(context).colorScheme.primaryContainer,
);
return TextSpan(text: text);
}
void _reveal(SpeechRange range) {