Skip to main content

sui_widgets/rich_document/
view.rs

1use std::{
2    cell::RefCell,
3    collections::{HashMap, HashSet},
4    ops::Range,
5    rc::Rc,
6    sync::atomic::{AtomicU64, Ordering},
7};
8
9use sui_core::{
10    Event, ImageHandle, InvalidationKind, InvalidationRequest, InvalidationTarget, KeyState, Point,
11    PointerButton, PointerEvent, PointerEventKind, PointerKind, Rect, ScrollDelta, SemanticsAction,
12    SemanticsActionRequest, SemanticsNode, SemanticsRole, SemanticsValue, Size, Vector, WidgetId,
13};
14use sui_layout::Constraints;
15use sui_reactive::Signal;
16use sui_runtime::{
17    ArrangeCtx, Command, EventCtx, EventPhase, MeasureCtx, PaintCtx, SemanticsCtx, Widget,
18    WidgetPod, WidgetPodMutVisitor, WidgetPodVisitor,
19};
20use sui_text::{
21    FontStyle, FontWeight, PersistentTextLayout, TextDocument, TextLayoutRequest, TextParagraph,
22    TextSpan, TextStyle,
23};
24
25use super::{
26    BasicSyntaxHighlighter, RichBlockId, RichDocumentBlock, RichDocumentBlockKind,
27    RichDocumentModel, RichDocumentSpan, RichDocumentStatus, RichInlineImage, RichInlineKind,
28    RichSyntaxHighlighter, RichSyntaxSpan, RichSyntaxTokenKind,
29};
30use crate::containers::TOUCH_SCROLL_DRAG_THRESHOLD;
31use crate::frame::{snap_to_pixels, stroke_border};
32use crate::{DefaultTheme, TextCommand, ThemeTextToken};
33
34const BLOCK_GAP: f32 = 8.0;
35const TEXT_INSET: f32 = 2.0;
36const QUOTE_INSET: f32 = 14.0;
37const CODE_INSET: f32 = 10.0;
38const CODE_HEADER_HEIGHT: f32 = 30.0;
39const STRUCTURED_INSET: f32 = 10.0;
40const SYNTHETIC_RICH_DOCUMENT_TAG: u64 = 0x2d << 46;
41static NEXT_SYNTHETIC_ID: AtomicU64 = AtomicU64::new(1);
42
43type Renderer = Rc<dyn Fn(RichDocumentRenderContext) -> WidgetPod>;
44// Shared with block views, which pass their event context on.
45type StringAction = Rc<RefCell<Box<dyn FnMut(&mut EventCtx, &str)>>>;
46type BlockAction = Rc<RefCell<Box<dyn FnMut(&mut EventCtx, RichBlockId)>>>;
47type ImageResolver = Rc<dyn Fn(&RichInlineImage) -> Option<ImageHandle>>;
48
49/// Context passed to an application-defined rich-document block renderer.
50///
51/// The `block` signal preserves the renderer widget's identity while the
52/// structured payload changes. Observe it with the relevant widget context
53/// (`ctx.observe` or `ctx.observe_with`) to declare invalidation dependencies.
54#[derive(Clone)]
55pub struct RichDocumentRenderContext {
56    pub block: Signal<RichDocumentBlock>,
57    pub state: RichDocumentViewState,
58    pub theme: DefaultTheme,
59}
60
61/// Registry of block renderers keyed by architecture-neutral names.
62///
63/// Markdown blocks use built-in renderers. Applications typically register
64/// extension keys such as `extension:tool-call`, `extension:diff`, or
65/// `extension:operation-log` without coupling SUI to a chat schema.
66#[derive(Clone, Default)]
67pub struct RichDocumentRendererRegistry {
68    renderers: Rc<RefCell<HashMap<String, Renderer>>>,
69}
70
71impl RichDocumentRendererRegistry {
72    pub fn new() -> Self {
73        Self::default()
74    }
75
76    pub fn register<F, W>(&self, key: impl Into<String>, renderer: F)
77    where
78        F: Fn(RichDocumentRenderContext) -> W + 'static,
79        W: Widget + 'static,
80    {
81        self.renderers.borrow_mut().insert(
82            key.into(),
83            Rc::new(move |context| WidgetPod::new(renderer(context))),
84        );
85    }
86
87    pub fn unregister(&self, key: &str) -> bool {
88        self.renderers.borrow_mut().remove(key).is_some()
89    }
90
91    pub fn contains(&self, key: &str) -> bool {
92        self.renderers.borrow().contains_key(key)
93    }
94
95    fn renderer(&self, key: &str) -> Option<Renderer> {
96        self.renderers.borrow().get(key).cloned()
97    }
98}
99
100#[derive(Clone, Copy, Debug, PartialEq, Eq)]
101struct DocumentPoint {
102    block: RichBlockId,
103    offset: usize,
104}
105
106#[derive(Clone, Debug, PartialEq, Eq)]
107enum PressedInline {
108    Link(String),
109    Image(String),
110}
111
112#[derive(Clone, Debug, Default)]
113struct DocumentSelection {
114    anchor: Option<DocumentPoint>,
115    focus: Option<DocumentPoint>,
116    order: Vec<RichBlockId>,
117    selected_text: String,
118}
119
120#[derive(Default)]
121struct ViewStateInner {
122    selection: DocumentSelection,
123    expanded: HashMap<RichBlockId, bool>,
124}
125
126/// Shareable retained state for a [`RichDocumentView`].
127///
128/// The state owns document-spanning selection and expansion state separately
129/// from Markdown content, so structural streaming updates do not reset either.
130#[derive(Clone)]
131pub struct RichDocumentViewState {
132    inner: Rc<RefCell<ViewStateInner>>,
133    revision: Signal<u64>,
134}
135
136impl RichDocumentViewState {
137    pub fn new() -> Self {
138        Self {
139            inner: Rc::new(RefCell::new(ViewStateInner::default())),
140            revision: Signal::named("RichDocumentViewState", 0),
141        }
142    }
143
144    pub fn selected_text(&self) -> Option<String> {
145        let text = self.inner.borrow().selection.selected_text.clone();
146        (!text.is_empty()).then_some(text)
147    }
148
149    pub fn clear_selection(&self) -> bool {
150        let changed = {
151            let mut inner = self.inner.borrow_mut();
152            let changed = inner.selection.anchor.is_some()
153                || inner.selection.focus.is_some()
154                || !inner.selection.selected_text.is_empty();
155            inner.selection.anchor = None;
156            inner.selection.focus = None;
157            inner.selection.selected_text.clear();
158            changed
159        };
160        if changed {
161            self.bump_revision();
162        }
163        changed
164    }
165
166    pub fn is_expanded(&self, block: RichBlockId) -> bool {
167        self.inner
168            .borrow()
169            .expanded
170            .get(&block)
171            .copied()
172            .unwrap_or(false)
173    }
174
175    pub fn set_expanded(&self, block: RichBlockId, expanded: bool) -> bool {
176        let changed = self.inner.borrow_mut().expanded.insert(block, expanded) != Some(expanded);
177        if changed {
178            self.bump_revision();
179        }
180        changed
181    }
182
183    pub fn toggle_expanded(&self, block: RichBlockId) -> bool {
184        let expanded = !self.is_expanded(block);
185        self.set_expanded(block, expanded);
186        expanded
187    }
188
189    fn bump_revision(&self) {
190        let next = self.revision.get().wrapping_add(1);
191        let _ = self.revision.set(next);
192    }
193
194    fn set_order(&self, order: Vec<RichBlockId>) {
195        let mut inner = self.inner.borrow_mut();
196        inner.selection.order = order;
197        let live = inner
198            .selection
199            .order
200            .iter()
201            .copied()
202            .collect::<HashSet<_>>();
203        inner.expanded.retain(|id, _| live.contains(id));
204        if inner
205            .selection
206            .anchor
207            .is_some_and(|point| !live.contains(&point.block))
208            || inner
209                .selection
210                .focus
211                .is_some_and(|point| !live.contains(&point.block))
212        {
213            inner.selection.anchor = None;
214            inner.selection.focus = None;
215            inner.selection.selected_text.clear();
216        }
217    }
218
219    fn selection(&self) -> DocumentSelection {
220        self.inner.borrow().selection.clone()
221    }
222
223    fn set_selection(&self, anchor: DocumentPoint, focus: DocumentPoint, text: String) {
224        let mut inner = self.inner.borrow_mut();
225        if inner.selection.anchor == Some(anchor)
226            && inner.selection.focus == Some(focus)
227            && inner.selection.selected_text == text
228        {
229            return;
230        }
231        inner.selection.anchor = Some(anchor);
232        inner.selection.focus = Some(focus);
233        inner.selection.selected_text = text;
234        drop(inner);
235        self.bump_revision();
236    }
237}
238
239impl Default for RichDocumentViewState {
240    fn default() -> Self {
241        Self::new()
242    }
243}
244
245#[derive(Clone)]
246struct BlockTextHandle {
247    block: RichBlockId,
248    bounds: Rect,
249    /// Where the text layout starts before it scrolls sideways.
250    origin: Point,
251    layout: Option<PersistentTextLayout>,
252    text: String,
253    /// How far a code block's text has scrolled sideways, shared so the
254    /// document's touch pans and hit tests see what the block draws.
255    horizontal_offset: f32,
256    max_horizontal_offset: f32,
257}
258
259impl BlockTextHandle {
260    fn new(block: RichBlockId) -> Self {
261        Self {
262            block,
263            bounds: Rect::ZERO,
264            origin: Point::ZERO,
265            layout: None,
266            text: String::new(),
267            horizontal_offset: 0.0,
268            max_horizontal_offset: 0.0,
269        }
270    }
271
272    fn point(&self, point: Point, strict: bool) -> Option<DocumentPoint> {
273        if strict && !self.bounds.contains(point) {
274            return None;
275        }
276        let layout = self.layout.as_ref()?;
277        let cursor = layout.hit_test_point(Point::new(
278            point.x - self.origin.x + self.horizontal_offset,
279            point.y - self.origin.y,
280        ));
281        Some(DocumentPoint {
282            block: self.block,
283            offset: cursor.utf8_offset.min(self.text.len()),
284        })
285    }
286
287    /// Scrolls the text sideways by `delta`, as far as it overflows,
288    /// reporting whether it moved.
289    fn scroll_horizontally(&mut self, delta: f32) -> bool {
290        let next = (self.horizontal_offset + delta).clamp(0.0, self.max_horizontal_offset);
291        if (next - self.horizontal_offset).abs() <= f32::EPSILON {
292            return false;
293        }
294        self.horizontal_offset = next;
295        true
296    }
297}
298
299/// A touch that went down on a code block whose text overflows sideways.
300/// Once it moves mostly sideways it pans the code; moving any other way
301/// leaves it to select text or scroll an enclosing view, as before.
302#[derive(Clone, Copy)]
303struct CodePan {
304    pointer_id: u64,
305    block: RichBlockId,
306    start: Point,
307    /// Where the touch was at its last move, once it pans.
308    last: Option<Point>,
309}
310
311struct RetainedBlock {
312    key: String,
313    value: Signal<RichDocumentBlock>,
314    pod: WidgetPod,
315    text: Rc<RefCell<BlockTextHandle>>,
316}
317
318/// Retained, selectable, incrementally updating rich-document widget.
319pub struct RichDocumentView {
320    model: RichDocumentModel,
321    state: RichDocumentViewState,
322    registry: RichDocumentRendererRegistry,
323    theme: DefaultTheme,
324    theme_reader: Option<Rc<dyn Fn() -> DefaultTheme>>,
325    highlighter: Rc<dyn RichSyntaxHighlighter>,
326    blocks: HashMap<RichBlockId, RetainedBlock>,
327    order: Vec<RichBlockId>,
328    measured_heights: HashMap<RichBlockId, f32>,
329    dragging: bool,
330    drag_anchor: Option<DocumentPoint>,
331    pressed_inline: Option<(RichBlockId, PressedInline)>,
332    code_pan: Option<CodePan>,
333    on_link: Option<StringAction>,
334    on_image: Option<StringAction>,
335    image_resolver: Option<ImageResolver>,
336    on_attachment: Option<BlockAction>,
337}
338
339impl RichDocumentView {
340    pub fn new(model: RichDocumentModel) -> Self {
341        Self {
342            model,
343            state: RichDocumentViewState::new(),
344            registry: RichDocumentRendererRegistry::new(),
345            theme: DefaultTheme::default(),
346            theme_reader: None,
347            highlighter: Rc::new(BasicSyntaxHighlighter),
348            blocks: HashMap::new(),
349            order: Vec::new(),
350            measured_heights: HashMap::new(),
351            dragging: false,
352            drag_anchor: None,
353            pressed_inline: None,
354            code_pan: None,
355            on_link: None,
356            on_image: None,
357            image_resolver: None,
358            on_attachment: None,
359        }
360    }
361
362    pub fn state(mut self, state: RichDocumentViewState) -> Self {
363        self.state = state;
364        self
365    }
366
367    pub fn renderer_registry(mut self, registry: RichDocumentRendererRegistry) -> Self {
368        self.registry = registry;
369        self
370    }
371
372    pub fn theme(mut self, theme: DefaultTheme) -> Self {
373        self.theme = theme;
374        self.theme_reader = None;
375        self
376    }
377
378    pub fn theme_when<F>(mut self, theme: F) -> Self
379    where
380        F: Fn() -> DefaultTheme + 'static,
381    {
382        self.theme_reader = Some(Rc::new(theme));
383        self
384    }
385
386    pub fn syntax_highlighter<H>(mut self, highlighter: H) -> Self
387    where
388        H: RichSyntaxHighlighter + 'static,
389    {
390        self.highlighter = Rc::new(highlighter);
391        self
392    }
393
394    pub fn on_link<F>(mut self, mut callback: F) -> Self
395    where
396        F: FnMut(&str) + 'static,
397    {
398        self.on_link = Some(Rc::new(RefCell::new(Box::new(
399            move |_: &mut EventCtx, value: &str| callback(value),
400        ))));
401        self
402    }
403
404    /// [`Self::on_link`], with the event context first. Setting either
405    /// replaces the other.
406    pub fn on_link_with_ctx<F>(mut self, callback: F) -> Self
407    where
408        F: FnMut(&mut EventCtx, &str) + 'static,
409    {
410        self.on_link = Some(Rc::new(RefCell::new(Box::new(callback))));
411        self
412    }
413
414    pub fn on_image<F>(mut self, mut callback: F) -> Self
415    where
416        F: FnMut(&str) + 'static,
417    {
418        self.on_image = Some(Rc::new(RefCell::new(Box::new(
419            move |_: &mut EventCtx, value: &str| callback(value),
420        ))));
421        self
422    }
423
424    /// [`Self::on_image`], with the event context first. Setting either
425    /// replaces the other.
426    pub fn on_image_with_ctx<F>(mut self, callback: F) -> Self
427    where
428        F: FnMut(&mut EventCtx, &str) + 'static,
429    {
430        self.on_image = Some(Rc::new(RefCell::new(Box::new(callback))));
431        self
432    }
433
434    /// Resolve Markdown image sources to images registered with the runtime.
435    ///
436    /// Until a source resolves, the default renderer keeps the image's alt
437    /// text as an inline placeholder with full image semantics.
438    pub fn image_resolver<F>(mut self, resolver: F) -> Self
439    where
440        F: Fn(&RichInlineImage) -> Option<ImageHandle> + 'static,
441    {
442        self.image_resolver = Some(Rc::new(resolver));
443        self
444    }
445
446    pub fn on_attachment<F>(mut self, mut callback: F) -> Self
447    where
448        F: FnMut(RichBlockId) + 'static,
449    {
450        self.on_attachment = Some(Rc::new(RefCell::new(Box::new(
451            move |_: &mut EventCtx, value: RichBlockId| callback(value),
452        ))));
453        self
454    }
455
456    /// [`Self::on_attachment`], with the event context first. Setting either
457    /// replaces the other.
458    pub fn on_attachment_with_ctx<F>(mut self, callback: F) -> Self
459    where
460        F: FnMut(&mut EventCtx, RichBlockId) + 'static,
461    {
462        self.on_attachment = Some(Rc::new(RefCell::new(Box::new(callback))));
463        self
464    }
465
466    pub fn model(&self) -> &RichDocumentModel {
467        &self.model
468    }
469
470    pub fn view_state(&self) -> &RichDocumentViewState {
471        &self.state
472    }
473
474    fn sync_blocks(&mut self) {
475        if let Some(theme) = self.theme_reader.as_ref().map(|reader| reader())
476            && theme != self.theme
477        {
478            self.theme = theme;
479            self.blocks.clear();
480            self.measured_heights.clear();
481        }
482        let blocks = self.model.blocks();
483        let order = blocks.iter().map(|block| block.id).collect::<Vec<_>>();
484        let live = order.iter().copied().collect::<HashSet<_>>();
485        self.blocks.retain(|id, _| live.contains(id));
486        self.measured_heights.retain(|id, _| live.contains(id));
487
488        for block in blocks {
489            let key = block.renderer_key();
490            if let Some(retained) = self.blocks.get_mut(&block.id)
491                && retained.key == key
492            {
493                continue;
494            }
495            let signal = self
496                .model
497                .block_signal(block.id)
498                .unwrap_or_else(|| Signal::named("DetachedRichDocumentBlock", block.clone()));
499            let text = Rc::new(RefCell::new(BlockTextHandle::new(block.id)));
500            let context = RichDocumentRenderContext {
501                block: signal.clone(),
502                state: self.state.clone(),
503                theme: self.theme,
504            };
505            let pod = self.registry.renderer(&key).map_or_else(
506                || {
507                    WidgetPod::new(DefaultBlockView::new(
508                        signal.clone(),
509                        self.state.clone(),
510                        Rc::clone(&text),
511                        self.theme,
512                        Rc::clone(&self.highlighter),
513                        self.on_link.clone(),
514                        self.on_image.clone(),
515                        self.image_resolver.clone(),
516                        self.on_attachment.clone(),
517                    ))
518                },
519                |renderer| renderer(context),
520            );
521            self.blocks.insert(
522                block.id,
523                RetainedBlock {
524                    key,
525                    value: signal,
526                    pod,
527                    text,
528                },
529            );
530        }
531        self.order = order;
532        self.state.set_order(self.order.clone());
533    }
534
535    fn point_at(&self, point: Point, strict: bool) -> Option<DocumentPoint> {
536        if strict {
537            return self.order.iter().find_map(|id| {
538                self.blocks
539                    .get(id)
540                    .and_then(|block| block.text.borrow().point(point, true))
541            });
542        }
543        let mut nearest: Option<(f32, Rc<RefCell<BlockTextHandle>>)> = None;
544        for id in &self.order {
545            let Some(block) = self.blocks.get(id) else {
546                continue;
547            };
548            let handle = block.text.borrow();
549            if handle.layout.is_none() {
550                continue;
551            }
552            if handle.bounds.contains(point) {
553                return handle.point(point, false);
554            }
555            let distance = if point.y < handle.bounds.y() {
556                handle.bounds.y() - point.y
557            } else {
558                point.y - handle.bounds.max_y()
559            };
560            if nearest.as_ref().is_none_or(|(best, _)| distance < *best) {
561                nearest = Some((distance, Rc::clone(&block.text)));
562            }
563        }
564        nearest.and_then(|(_, handle)| handle.borrow().point(point, false))
565    }
566
567    fn selection_text(&self, anchor: DocumentPoint, focus: DocumentPoint) -> String {
568        let Some(anchor_index) = self.order.iter().position(|id| *id == anchor.block) else {
569            return String::new();
570        };
571        let Some(focus_index) = self.order.iter().position(|id| *id == focus.block) else {
572            return String::new();
573        };
574        let (start, end) = if (anchor_index, anchor.offset) <= (focus_index, focus.offset) {
575            (anchor, focus)
576        } else {
577            (focus, anchor)
578        };
579        let start_index = self
580            .order
581            .iter()
582            .position(|id| *id == start.block)
583            .unwrap_or(0);
584        let end_index = self
585            .order
586            .iter()
587            .position(|id| *id == end.block)
588            .unwrap_or(start_index);
589        let mut parts = Vec::new();
590        for id in &self.order[start_index..=end_index] {
591            let Some(block) = self.blocks.get(id) else {
592                continue;
593            };
594            let handle = block.text.borrow();
595            let text = handle.text.as_str();
596            let range = if *id == start.block && *id == end.block {
597                clamp_boundary(text, start.offset)..clamp_boundary(text, end.offset)
598            } else if *id == start.block {
599                clamp_boundary(text, start.offset)..text.len()
600            } else if *id == end.block {
601                0..clamp_boundary(text, end.offset)
602            } else {
603                0..text.len()
604            };
605            if let Some(part) = text.get(range) {
606                parts.push(part.to_string());
607            }
608        }
609        parts.join("\n\n")
610    }
611
612    fn update_selection(&self, anchor: DocumentPoint, focus: DocumentPoint) {
613        let text = self.selection_text(anchor, focus);
614        self.state.set_selection(anchor, focus, text);
615    }
616
617    fn inline_at(&self, point: DocumentPoint) -> Option<PressedInline> {
618        let block = self.blocks.get(&point.block)?.value.get();
619        inline_targets(&block.kind)
620            .into_iter()
621            .find_map(|target| match target {
622                InlineTarget::Link {
623                    range, destination, ..
624                } if range.contains(&point.offset) => Some(PressedInline::Link(destination)),
625                InlineTarget::Image { range, image } if range.contains(&point.offset) => {
626                    Some(PressedInline::Image(image.source))
627                }
628                _ => None,
629            })
630    }
631
632    fn copy_selection(&self, ctx: &mut EventCtx) -> bool {
633        let Some(text) = self.state.selected_text() else {
634            return false;
635        };
636        ctx.set_clipboard_text(text);
637        true
638    }
639
640    fn select_all(&self) -> bool {
641        let first = self.order.iter().find_map(|id| {
642            self.blocks.get(id).and_then(|block| {
643                let handle = block.text.borrow();
644                (!handle.text.is_empty()).then_some(DocumentPoint {
645                    block: *id,
646                    offset: 0,
647                })
648            })
649        });
650        let last = self.order.iter().rev().find_map(|id| {
651            self.blocks.get(id).and_then(|block| {
652                let handle = block.text.borrow();
653                (!handle.text.is_empty()).then_some(DocumentPoint {
654                    block: *id,
655                    offset: handle.text.len(),
656                })
657            })
658        });
659        if let (Some(first), Some(last)) = (first, last) {
660            self.update_selection(first, last);
661            true
662        } else {
663            false
664        }
665    }
666
667    /// The pan a touch going down at `pointer` may start, when it lands on
668    /// a code block whose text overflows sideways.
669    fn code_pan_at(&self, pointer: &PointerEvent) -> Option<CodePan> {
670        if pointer.pointer_kind != PointerKind::Touch {
671            return None;
672        }
673        self.order.iter().find_map(|id| {
674            let block = self.blocks.get(id)?;
675            (block.pod.bounds().contains(pointer.position)
676                && block.text.borrow().max_horizontal_offset > 0.0)
677                .then_some(CodePan {
678                    pointer_id: pointer.pointer_id,
679                    block: *id,
680                    start: pointer.position,
681                    last: None,
682                })
683        })
684    }
685
686    /// Follows the touch of a code pan, reporting whether the pan took
687    /// `pointer`, which then neither selects nor reaches enclosing views.
688    fn follow_code_pan(&mut self, ctx: &mut EventCtx, pointer: &PointerEvent) -> bool {
689        let Some(mut pan) = self
690            .code_pan
691            .filter(|pan| pan.pointer_id == pointer.pointer_id)
692        else {
693            return false;
694        };
695        match pointer.kind {
696            PointerEventKind::Move => {
697                let from = match pan.last {
698                    Some(last) => last,
699                    None => {
700                        let moved = pointer.position - pan.start;
701                        if moved.x.hypot(moved.y) < TOUCH_SCROLL_DRAG_THRESHOLD {
702                            // Too short to tell a pan from a selection yet:
703                            // hold any selection where the touch went down.
704                            if self.dragging {
705                                ctx.set_handled();
706                            }
707                            return self.dragging;
708                        }
709                        if moved.x.abs() <= moved.y.abs() {
710                            self.code_pan = None;
711                            return false;
712                        }
713                        self.dragging = false;
714                        self.drag_anchor = None;
715                        self.pressed_inline = None;
716                        ctx.request_pointer_capture(pointer.pointer_id);
717                        // The code follows the touch from where it went down.
718                        pan.start
719                    }
720                };
721                pan.last = Some(pointer.position);
722                self.code_pan = Some(pan);
723                self.scroll_code_block(ctx, pan.block, from.x - pointer.position.x);
724                ctx.set_handled();
725                true
726            }
727            PointerEventKind::Up | PointerEventKind::Cancel => {
728                self.code_pan = None;
729                if pan.last.is_none() {
730                    return false;
731                }
732                ctx.release_pointer_capture(pointer.pointer_id);
733                ctx.set_handled();
734                true
735            }
736            _ => false,
737        }
738    }
739
740    fn scroll_code_block(&self, ctx: &mut EventCtx, block: RichBlockId, delta: f32) {
741        let Some(block) = self.blocks.get(&block) else {
742            return;
743        };
744        if block.text.borrow_mut().scroll_horizontally(delta) {
745            ctx.request(InvalidationRequest::new(
746                InvalidationTarget::Widget(block.pod.id()),
747                InvalidationKind::Paint,
748            ));
749        }
750    }
751}
752
753impl Widget for RichDocumentView {
754    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
755        if let Event::Pointer(pointer) = event
756            && ctx.phase() != EventPhase::Bubble
757        {
758            if self.follow_code_pan(ctx, pointer) {
759                return;
760            }
761            match pointer.kind {
762                PointerEventKind::Down if pointer.button == Some(PointerButton::Primary) => {
763                    // A new primary touch ends any pan whose release went
764                    // elsewhere.
765                    if pointer.is_primary {
766                        self.code_pan = self.code_pan_at(pointer);
767                    }
768                    if let Some(point) = self.point_at(pointer.position, true) {
769                        let selection = self.state.selection();
770                        let anchor = if pointer.modifiers.shift {
771                            selection.anchor.unwrap_or(point)
772                        } else {
773                            point
774                        };
775                        self.dragging = true;
776                        self.drag_anchor = Some(anchor);
777                        self.pressed_inline =
778                            self.inline_at(point).map(|action| (point.block, action));
779                        self.update_selection(anchor, point);
780                        ctx.request_focus();
781                        ctx.request_pointer_capture(pointer.pointer_id);
782                        ctx.request_paint();
783                        ctx.request_semantics();
784                        ctx.set_handled();
785                    }
786                }
787                PointerEventKind::Move
788                    if self.dragging && pointer.buttons.contains(PointerButton::Primary) =>
789                {
790                    if let (Some(anchor), Some(focus)) =
791                        (self.drag_anchor, self.point_at(pointer.position, false))
792                    {
793                        if focus != anchor {
794                            self.pressed_inline = None;
795                        }
796                        self.update_selection(anchor, focus);
797                        ctx.request_paint();
798                        ctx.request_semantics();
799                        ctx.set_handled();
800                    }
801                }
802                PointerEventKind::Up
803                    if self.dragging && pointer.button == Some(PointerButton::Primary) =>
804                {
805                    let focus = self.point_at(pointer.position, false);
806                    let activate = self.pressed_inline.take().and_then(|(block, action)| {
807                        focus
808                            .filter(|point| point.block == block)
809                            .filter(|point| self.inline_at(*point).as_ref() == Some(&action))
810                            .map(|_| action)
811                    });
812                    self.dragging = false;
813                    self.drag_anchor = None;
814                    ctx.release_pointer_capture(pointer.pointer_id);
815                    match activate {
816                        Some(PressedInline::Link(destination)) => {
817                            if let Some(callback) = &self.on_link {
818                                (callback.borrow_mut())(ctx, &destination);
819                            }
820                        }
821                        Some(PressedInline::Image(source)) => {
822                            if let Some(callback) = &self.on_image {
823                                (callback.borrow_mut())(ctx, &source);
824                            }
825                        }
826                        None => {}
827                    }
828                    ctx.request_paint();
829                    ctx.request_semantics();
830                    ctx.set_handled();
831                }
832                PointerEventKind::Cancel if self.dragging => {
833                    self.dragging = false;
834                    self.drag_anchor = None;
835                    self.pressed_inline = None;
836                    ctx.release_pointer_capture(pointer.pointer_id);
837                    ctx.set_handled();
838                }
839                _ => {}
840            }
841            return;
842        }
843
844        match event {
845            Event::Keyboard(key) if ctx.is_focused() && key.state == KeyState::Pressed => {
846                let command = key.modifiers.control || key.modifiers.meta;
847                match key.key.as_str() {
848                    "a" | "A" if command => {
849                        if self.select_all() {
850                            ctx.request_paint();
851                            ctx.request_semantics();
852                            ctx.set_handled();
853                        }
854                    }
855                    "c" | "C" if command => {
856                        if self.copy_selection(ctx) {
857                            ctx.set_handled();
858                        }
859                    }
860                    "Escape" if self.state.clear_selection() => {
861                        ctx.request_paint();
862                        ctx.request_semantics();
863                        ctx.set_handled();
864                    }
865                    _ => {}
866                }
867            }
868            Event::Semantics(semantics)
869                if semantics.target == ctx.widget_id()
870                    && semantics.action == SemanticsActionRequest::Copy
871                    && self.copy_selection(ctx) =>
872            {
873                ctx.set_handled();
874            }
875            _ => {}
876        }
877    }
878
879    fn command(&mut self, ctx: &mut EventCtx, command: &Command<'_>) {
880        let Some(command) = TextCommand::from_command(command) else {
881            return;
882        };
883        match command {
884            TextCommand::Copy => {
885                if self.copy_selection(ctx) {
886                    ctx.set_handled();
887                }
888            }
889            TextCommand::SelectAll => {
890                if self.select_all() {
891                    ctx.request_paint();
892                    ctx.request_semantics();
893                    ctx.set_handled();
894                }
895            }
896            TextCommand::Cut | TextCommand::Paste => {}
897        }
898    }
899
900    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
901        let _ = ctx.observe(self.model.structure_observable());
902        self.sync_blocks();
903        let child_constraints =
904            Constraints::new(Size::ZERO, Size::new(constraints.max.width, f32::INFINITY));
905        let mut width = 0.0_f32;
906        let mut height = 0.0_f32;
907        for (index, id) in self.order.iter().enumerate() {
908            let Some(block) = self.blocks.get_mut(id) else {
909                continue;
910            };
911            let size = block.pod.measure(ctx, child_constraints);
912            width = width.max(size.width);
913            height += size.height;
914            self.measured_heights.insert(*id, size.height);
915            if index + 1 < self.order.len() {
916                height += BLOCK_GAP;
917            }
918        }
919        let selection = self.state.selection();
920        if let (Some(anchor), Some(focus)) = (selection.anchor, selection.focus) {
921            self.update_selection(anchor, focus);
922        }
923        constraints.clamp(Size::new(width, height))
924    }
925
926    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
927        let mut y = bounds.y();
928        for id in &self.order {
929            let height = self.measured_heights.get(id).copied().unwrap_or(0.0);
930            if let Some(block) = self.blocks.get_mut(id) {
931                block
932                    .pod
933                    .arrange(ctx, Rect::new(bounds.x(), y, bounds.width(), height));
934            }
935            y += height + BLOCK_GAP;
936        }
937    }
938
939    fn paint(&self, ctx: &mut PaintCtx) {
940        for id in &self.order {
941            if let Some(block) = self.blocks.get(id) {
942                block.pod.paint(ctx);
943            }
944        }
945    }
946
947    fn accepts_focus(&self) -> bool {
948        true
949    }
950
951    fn semantics(&self, ctx: &mut SemanticsCtx) {
952        let mut document =
953            SemanticsNode::new(ctx.widget_id(), SemanticsRole::Document, ctx.bounds());
954        document.name = Some("Rich document".to_string());
955        if self.state.selected_text().is_some() {
956            document.actions.push(SemanticsAction::Copy);
957        }
958        ctx.push(document);
959        for id in &self.order {
960            if let Some(block) = self.blocks.get(id) {
961                block.pod.semantics(ctx);
962            }
963        }
964    }
965
966    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
967        for id in &self.order {
968            if let Some(block) = self.blocks.get(id) {
969                visitor.visit(&block.pod);
970            }
971        }
972    }
973
974    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
975        for id in self.order.clone() {
976            if let Some(block) = self.blocks.get_mut(&id) {
977                visitor.visit(&mut block.pod);
978            }
979        }
980    }
981}
982
983#[derive(Clone, Debug, PartialEq, Eq, Hash)]
984enum SemanticPart {
985    Copy,
986    Link(usize),
987    Image(usize),
988    ListItem(usize),
989}
990
991#[derive(Clone)]
992enum InlineTarget {
993    Link {
994        range: Range<usize>,
995        destination: String,
996        label: String,
997    },
998    Image {
999        range: Range<usize>,
1000        image: RichInlineImage,
1001    },
1002}
1003
1004struct DefaultBlockView {
1005    block: Signal<RichDocumentBlock>,
1006    state: RichDocumentViewState,
1007    text_handle: Rc<RefCell<BlockTextHandle>>,
1008    theme: DefaultTheme,
1009    highlighter: Rc<dyn RichSyntaxHighlighter>,
1010    layout: Option<PersistentTextLayout>,
1011    semantic_ids: HashMap<SemanticPart, WidgetId>,
1012    on_link: Option<StringAction>,
1013    on_image: Option<StringAction>,
1014    image_resolver: Option<ImageResolver>,
1015    on_attachment: Option<BlockAction>,
1016}
1017
1018impl DefaultBlockView {
1019    #[allow(clippy::too_many_arguments)]
1020    fn new(
1021        block: Signal<RichDocumentBlock>,
1022        state: RichDocumentViewState,
1023        text_handle: Rc<RefCell<BlockTextHandle>>,
1024        theme: DefaultTheme,
1025        highlighter: Rc<dyn RichSyntaxHighlighter>,
1026        on_link: Option<StringAction>,
1027        on_image: Option<StringAction>,
1028        image_resolver: Option<ImageResolver>,
1029        on_attachment: Option<BlockAction>,
1030    ) -> Self {
1031        Self {
1032            block,
1033            state,
1034            text_handle,
1035            theme,
1036            highlighter,
1037            layout: None,
1038            semantic_ids: HashMap::new(),
1039            on_link,
1040            on_image,
1041            image_resolver,
1042            on_attachment,
1043        }
1044    }
1045
1046    fn semantic_id(&mut self, part: SemanticPart) -> WidgetId {
1047        *self
1048            .semantic_ids
1049            .entry(part)
1050            .or_insert_with(next_semantic_id)
1051    }
1052
1053    fn sync_semantic_ids(&mut self, block: &RichDocumentBlock) {
1054        let mut live = HashSet::new();
1055        for (index, target) in inline_targets(&block.kind).into_iter().enumerate() {
1056            let part = match target {
1057                InlineTarget::Link { .. } => SemanticPart::Link(index),
1058                InlineTarget::Image { .. } => SemanticPart::Image(index),
1059            };
1060            live.insert(part.clone());
1061            self.semantic_id(part);
1062        }
1063        if let RichDocumentBlockKind::List { items, .. } = &block.kind {
1064            for index in 0..items.len() {
1065                let part = SemanticPart::ListItem(index);
1066                live.insert(part.clone());
1067                self.semantic_id(part);
1068            }
1069        }
1070        if matches!(block.kind, RichDocumentBlockKind::CodeBlock { .. }) {
1071            live.insert(SemanticPart::Copy);
1072            self.semantic_id(SemanticPart::Copy);
1073        }
1074        self.semantic_ids.retain(|part, _| live.contains(part));
1075    }
1076
1077    fn text_insets(&self, kind: &RichDocumentBlockKind) -> (f32, f32, f32, f32) {
1078        match kind {
1079            RichDocumentBlockKind::BlockQuote { .. } => {
1080                (QUOTE_INSET, TEXT_INSET, TEXT_INSET, TEXT_INSET)
1081            }
1082            RichDocumentBlockKind::CodeBlock { .. } => (
1083                CODE_INSET,
1084                CODE_HEADER_HEIGHT + CODE_INSET,
1085                CODE_INSET,
1086                CODE_INSET,
1087            ),
1088            RichDocumentBlockKind::Attachment(_) => (
1089                STRUCTURED_INSET,
1090                STRUCTURED_INSET,
1091                STRUCTURED_INSET,
1092                STRUCTURED_INSET,
1093            ),
1094            RichDocumentBlockKind::Extension(_) => (
1095                STRUCTURED_INSET + 20.0,
1096                STRUCTURED_INSET,
1097                STRUCTURED_INSET,
1098                STRUCTURED_INSET,
1099            ),
1100            RichDocumentBlockKind::ThematicBreak => (0.0, 0.0, 0.0, 0.0),
1101            _ => (TEXT_INSET, TEXT_INSET, TEXT_INSET, TEXT_INSET),
1102        }
1103    }
1104
1105    /// Where the text layout starts in `bounds`, before it scrolls sideways.
1106    fn layout_origin(&self, bounds: Rect, kind: &RichDocumentBlockKind) -> Point {
1107        let (left, top, _, _) = self.text_insets(kind);
1108        let layout_x = self
1109            .layout
1110            .as_ref()
1111            .map(|layout| layout.measurement().bounds.x())
1112            .unwrap_or(0.0);
1113        Point::new(bounds.x() + left - layout_x, bounds.y() + top)
1114    }
1115
1116    fn text_bounds(&self, bounds: Rect, kind: &RichDocumentBlockKind) -> Rect {
1117        let (left, top, right, bottom) = self.text_insets(kind);
1118        Rect::new(
1119            bounds.x() + left,
1120            bounds.y() + top,
1121            (bounds.width() - left - right).max(0.0),
1122            (bounds.height() - top - bottom).max(0.0),
1123        )
1124    }
1125
1126    fn selection_range(&self, block: RichBlockId, text_len: usize) -> Range<usize> {
1127        let selection = self.state.selection();
1128        selection_range_for(&selection, block, text_len)
1129    }
1130
1131    fn status_colors(&self, status: RichDocumentStatus) -> (sui_core::Color, sui_core::Color) {
1132        match status {
1133            RichDocumentStatus::Neutral => (self.theme.palette.control, self.theme.palette.text),
1134            RichDocumentStatus::Pending => (
1135                self.theme.palette.control_hover,
1136                self.theme.palette.text_muted,
1137            ),
1138            RichDocumentStatus::Running => (
1139                self.theme.palette.info_soft,
1140                self.theme.palette.info_soft_text,
1141            ),
1142            RichDocumentStatus::Success => (
1143                self.theme.palette.success_soft,
1144                self.theme.palette.success_soft_text,
1145            ),
1146            RichDocumentStatus::Warning => (
1147                self.theme.palette.warning_soft,
1148                self.theme.palette.warning_soft_text,
1149            ),
1150            RichDocumentStatus::Error => (
1151                self.theme.palette.danger_soft,
1152                self.theme.palette.danger_soft_text,
1153            ),
1154        }
1155    }
1156
1157    fn invoke_semantic_target(
1158        &mut self,
1159        target: WidgetId,
1160        action: &SemanticsActionRequest,
1161        ctx: &mut EventCtx,
1162    ) -> bool {
1163        let block = self.block.get();
1164        if self.semantic_ids.get(&SemanticPart::Copy) == Some(&target)
1165            && *action == SemanticsActionRequest::Copy
1166            && let RichDocumentBlockKind::CodeBlock { code, .. } = &block.kind
1167        {
1168            ctx.set_clipboard_text(code);
1169            return true;
1170        }
1171        for (index, inline) in inline_targets(&block.kind).into_iter().enumerate() {
1172            let part = match inline {
1173                InlineTarget::Link { .. } => SemanticPart::Link(index),
1174                InlineTarget::Image { .. } => SemanticPart::Image(index),
1175            };
1176            if self.semantic_ids.get(&part) != Some(&target)
1177                || *action != SemanticsActionRequest::Activate
1178            {
1179                continue;
1180            }
1181            match inline {
1182                InlineTarget::Link { destination, .. } => {
1183                    if let Some(callback) = &self.on_link {
1184                        (callback.borrow_mut())(ctx, &destination);
1185                    }
1186                }
1187                InlineTarget::Image {
1188                    image: inline_image,
1189                    ..
1190                } => {
1191                    if let Some(callback) = &self.on_image {
1192                        (callback.borrow_mut())(ctx, &inline_image.source);
1193                    }
1194                }
1195            }
1196            return true;
1197        }
1198        false
1199    }
1200}
1201
1202impl Widget for DefaultBlockView {
1203    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
1204        if ctx.phase() == EventPhase::Capture {
1205            return;
1206        }
1207        let block = self.block.get();
1208        match event {
1209            Event::Pointer(pointer)
1210                if pointer.kind == PointerEventKind::Scroll
1211                    && ctx.bounds().contains(pointer.position)
1212                    && matches!(block.kind, RichDocumentBlockKind::CodeBlock { .. }) =>
1213            {
1214                let delta = pointer
1215                    .scroll_delta
1216                    .map(scroll_delta_to_offset)
1217                    .unwrap_or(pointer.delta);
1218                let axis = if delta.x.abs() > f32::EPSILON {
1219                    delta.x
1220                } else if pointer.modifiers.shift {
1221                    delta.y
1222                } else {
1223                    0.0
1224                };
1225                if self.text_handle.borrow_mut().scroll_horizontally(-axis) {
1226                    ctx.request_paint();
1227                    ctx.request_semantics();
1228                    ctx.set_handled();
1229                }
1230            }
1231            Event::Pointer(pointer)
1232                if pointer.kind == PointerEventKind::Down
1233                    && pointer.button == Some(PointerButton::Primary)
1234                    && matches!(block.kind, RichDocumentBlockKind::CodeBlock { .. })
1235                    && pointer.position.y <= ctx.bounds().y() + CODE_HEADER_HEIGHT
1236                    && pointer.position.x >= ctx.bounds().max_x() - 56.0 =>
1237            {
1238                if let RichDocumentBlockKind::CodeBlock { code, .. } = &block.kind {
1239                    ctx.set_clipboard_text(code);
1240                    ctx.set_handled();
1241                }
1242            }
1243            Event::Pointer(pointer)
1244                if pointer.kind == PointerEventKind::Down
1245                    && pointer.button == Some(PointerButton::Primary)
1246                    && matches!(block.kind, RichDocumentBlockKind::Attachment(_))
1247                    && ctx.bounds().contains(pointer.position) =>
1248            {
1249                if let Some(callback) = &self.on_attachment {
1250                    (callback.borrow_mut())(ctx, block.id);
1251                }
1252                ctx.set_handled();
1253            }
1254            Event::Pointer(pointer)
1255                if pointer.kind == PointerEventKind::Down
1256                    && pointer.button == Some(PointerButton::Primary)
1257                    && matches!(block.kind, RichDocumentBlockKind::Extension(_))
1258                    && ctx.bounds().contains(pointer.position) =>
1259            {
1260                if let RichDocumentBlockKind::Extension(extension) = &block.kind {
1261                    let current = self
1262                        .state
1263                        .inner
1264                        .borrow()
1265                        .expanded
1266                        .get(&block.id)
1267                        .copied()
1268                        .unwrap_or(extension.initially_expanded);
1269                    self.state.set_expanded(block.id, !current);
1270                }
1271                ctx.request_measure();
1272                ctx.request_paint();
1273                ctx.request_semantics();
1274                ctx.set_handled();
1275            }
1276            Event::Semantics(semantics) => {
1277                let handled = if semantics.target == ctx.widget_id() {
1278                    match (&block.kind, &semantics.action) {
1279                        (
1280                            RichDocumentBlockKind::Attachment(_),
1281                            SemanticsActionRequest::Activate,
1282                        ) => {
1283                            if let Some(callback) = &self.on_attachment {
1284                                (callback.borrow_mut())(ctx, block.id);
1285                            }
1286                            true
1287                        }
1288                        (RichDocumentBlockKind::Extension(_), SemanticsActionRequest::Expand) => {
1289                            self.state.set_expanded(block.id, true);
1290                            true
1291                        }
1292                        (RichDocumentBlockKind::Extension(_), SemanticsActionRequest::Collapse) => {
1293                            self.state.set_expanded(block.id, false);
1294                            true
1295                        }
1296                        _ => false,
1297                    }
1298                } else {
1299                    self.invoke_semantic_target(semantics.target, &semantics.action, ctx)
1300                };
1301                if handled {
1302                    ctx.request_measure();
1303                    ctx.request_paint();
1304                    ctx.request_semantics();
1305                    ctx.set_handled();
1306                }
1307            }
1308            _ => {}
1309        }
1310    }
1311
1312    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
1313        let block = ctx.observe(&self.block);
1314        let _ = ctx.observe(&self.state.revision);
1315        self.sync_semantic_ids(&block);
1316        if matches!(block.kind, RichDocumentBlockKind::ThematicBreak) {
1317            self.layout = None;
1318            let size = constraints.clamp(Size::new(constraints.max.width, 9.0));
1319            let mut handle = self.text_handle.borrow_mut();
1320            handle.text.clear();
1321            handle.layout = None;
1322            return size;
1323        }
1324
1325        let expanded = match &block.kind {
1326            RichDocumentBlockKind::Extension(extension) => self
1327                .state
1328                .inner
1329                .borrow()
1330                .expanded
1331                .get(&block.id)
1332                .copied()
1333                .unwrap_or(extension.initially_expanded),
1334            _ => false,
1335        };
1336        let document = block_document(&block.kind, self.theme, self.highlighter.as_ref(), expanded);
1337        let text = document.plain_text();
1338        let (left, top, right, bottom) = self.text_insets(&block.kind);
1339        let available_width = (constraints.max.width - left - right).max(1.0);
1340        let request = if matches!(block.kind, RichDocumentBlockKind::CodeBlock { .. }) {
1341            TextLayoutRequest::new(document)
1342        } else {
1343            TextLayoutRequest::new(document).with_box_size(Size::new(available_width, 1.0))
1344        };
1345        let handle = self.layout.as_ref().map(PersistentTextLayout::handle);
1346        self.layout = ctx
1347            .layout()
1348            .layout_document_persistent(handle, request)
1349            .ok();
1350        let (measured_width, measured_height) = self
1351            .layout
1352            .as_ref()
1353            .map(|layout| {
1354                let measurement = layout.measurement();
1355                (measurement.width, measurement.height)
1356            })
1357            .unwrap_or((0.0, 0.0));
1358        let height = measured_height + top + bottom;
1359        let width = if constraints.max.width.is_finite() {
1360            constraints.max.width
1361        } else {
1362            measured_width + left + right
1363        };
1364        let size = constraints.clamp(Size::new(width, height));
1365        let mut shared = self.text_handle.borrow_mut();
1366        shared.text = text;
1367        shared.layout = self.layout.clone();
1368        shared.max_horizontal_offset =
1369            if matches!(block.kind, RichDocumentBlockKind::CodeBlock { .. }) {
1370                (measured_width - available_width).max(0.0)
1371            } else {
1372                0.0
1373            };
1374        shared.horizontal_offset = shared.horizontal_offset.min(shared.max_horizontal_offset);
1375        size
1376    }
1377
1378    fn arrange(&mut self, _ctx: &mut ArrangeCtx, bounds: Rect) {
1379        let block = self.block.get();
1380        let mut shared = self.text_handle.borrow_mut();
1381        shared.bounds = self.text_bounds(bounds, &block.kind);
1382        shared.origin = self.layout_origin(bounds, &block.kind);
1383    }
1384
1385    fn paint(&self, ctx: &mut PaintCtx) {
1386        let block = self.block.get();
1387        let _ = self.state.revision.get();
1388        let bounds = ctx.bounds();
1389        match &block.kind {
1390            RichDocumentBlockKind::BlockQuote { .. } => {
1391                ctx.fill_rect(
1392                    Rect::new(bounds.x() + 2.0, bounds.y(), 3.0, bounds.height()),
1393                    self.theme.palette.accent,
1394                );
1395            }
1396            RichDocumentBlockKind::CodeBlock { language, .. } => {
1397                let frame = snap_to_pixels(ctx, bounds);
1398                ctx.fill_rect(frame, self.theme.surfaces.window_subtle);
1399                stroke_border(ctx, frame, 0.0, 1.0, self.theme.surfaces.border_subtle);
1400                ctx.fill_rect(
1401                    Rect::new(bounds.x(), bounds.y(), bounds.width(), CODE_HEADER_HEIGHT),
1402                    self.theme.surfaces.surface_2,
1403                );
1404                let label = code_header_language_text_style(self.theme);
1405                ctx.draw_text(
1406                    Rect::new(
1407                        bounds.x() + CODE_INSET,
1408                        bounds.y() + 7.0,
1409                        (bounds.width() - 80.0).max(1.0),
1410                        label.line_height,
1411                    ),
1412                    language.as_deref().unwrap_or("plain text"),
1413                    label,
1414                );
1415                let action = code_header_action_text_style(self.theme);
1416                ctx.draw_text(
1417                    Rect::new(
1418                        bounds.max_x() - 42.0,
1419                        bounds.y() + 7.0,
1420                        38.0,
1421                        action.line_height,
1422                    ),
1423                    "Copy",
1424                    action,
1425                );
1426            }
1427            RichDocumentBlockKind::Attachment(_) => {
1428                let frame = snap_to_pixels(ctx, bounds);
1429                ctx.fill_rect(frame, self.theme.palette.control);
1430                stroke_border(ctx, frame, 0.0, 1.0, self.theme.palette.border);
1431            }
1432            RichDocumentBlockKind::Extension(extension) => {
1433                let (background, _) = self.status_colors(extension.status);
1434                let frame = snap_to_pixels(ctx, bounds);
1435                ctx.fill_rect(frame, background);
1436                stroke_border(ctx, frame, 0.0, 1.0, self.theme.palette.border);
1437                let expanded = self
1438                    .state
1439                    .inner
1440                    .borrow()
1441                    .expanded
1442                    .get(&block.id)
1443                    .copied()
1444                    .unwrap_or(extension.initially_expanded);
1445                let mut disclosure = self.theme.text_style(self.theme.palette.text_muted);
1446                disclosure.weight = FontWeight::SEMIBOLD;
1447                ctx.draw_text(
1448                    Rect::new(
1449                        bounds.x() + STRUCTURED_INSET,
1450                        bounds.y() + STRUCTURED_INSET,
1451                        16.0,
1452                        disclosure.line_height,
1453                    ),
1454                    if expanded { "▾" } else { "▸" },
1455                    disclosure,
1456                );
1457            }
1458            RichDocumentBlockKind::ThematicBreak => {
1459                ctx.fill_rect(
1460                    Rect::new(bounds.x(), bounds.y() + 4.0, bounds.width(), 1.0),
1461                    self.theme.palette.border,
1462                );
1463            }
1464            _ => {}
1465        }
1466
1467        let Some(layout) = &self.layout else {
1468            return;
1469        };
1470        let text_bounds = self.text_bounds(bounds, &block.kind);
1471        let horizontal_offset = self.text_handle.borrow().horizontal_offset;
1472        let origin = self.layout_origin(bounds, &block.kind) + Vector::new(-horizontal_offset, 0.0);
1473        ctx.push_clip_rect(text_bounds);
1474        let selection = self.selection_range(block.id, layout.text().len());
1475        if !selection.is_empty() {
1476            for rect in layout.selection_rects(selection) {
1477                ctx.fill_rect(
1478                    rect.translate(origin.to_vector()),
1479                    self.theme.palette.selection,
1480                );
1481            }
1482        }
1483        ctx.draw_persistent_text_layout(origin, layout);
1484        if let Some(resolver) = &self.image_resolver {
1485            for target in inline_targets(&block.kind) {
1486                let InlineTarget::Image { range, image } = target else {
1487                    continue;
1488                };
1489                let Some(handle) = resolver(&image) else {
1490                    continue;
1491                };
1492                for rect in layout.selection_rects(range) {
1493                    let rect = rect.translate(origin.to_vector());
1494                    ctx.fill_rect(rect, self.theme.palette.surface);
1495                    ctx.draw_image(rect, handle);
1496                }
1497            }
1498        }
1499        ctx.pop_clip();
1500    }
1501
1502    fn semantics(&self, ctx: &mut SemanticsCtx) {
1503        let block = self.block.get();
1504        let _ = self.state.revision.get();
1505        let role = match block.kind {
1506            RichDocumentBlockKind::Paragraph { .. } => SemanticsRole::Paragraph,
1507            RichDocumentBlockKind::Heading { .. } => SemanticsRole::Heading,
1508            RichDocumentBlockKind::BlockQuote { .. } => SemanticsRole::GenericContainer,
1509            RichDocumentBlockKind::List { .. } => SemanticsRole::List,
1510            RichDocumentBlockKind::CodeBlock { .. } => SemanticsRole::Code,
1511            RichDocumentBlockKind::ThematicBreak => SemanticsRole::Separator,
1512            RichDocumentBlockKind::Attachment(_) => SemanticsRole::Attachment,
1513            RichDocumentBlockKind::Extension(_) => SemanticsRole::Status,
1514        };
1515        let mut node = SemanticsNode::new(ctx.widget_id(), role, ctx.bounds());
1516        node.name = Some(block.plain_text());
1517        match &block.kind {
1518            RichDocumentBlockKind::Heading { level, .. } => {
1519                node.description = Some(format!("Heading level {level}"));
1520            }
1521            RichDocumentBlockKind::CodeBlock { language, .. } => {
1522                node.description = Some(format!(
1523                    "{} code block",
1524                    language.as_deref().unwrap_or("Plain text")
1525                ));
1526            }
1527            RichDocumentBlockKind::Attachment(attachment) => {
1528                node.actions.push(SemanticsAction::Activate);
1529                node.description = attachment.description.clone().or_else(|| {
1530                    attachment
1531                        .media_type
1532                        .as_ref()
1533                        .map(|media_type| format!("Attachment, {media_type}"))
1534                });
1535            }
1536            RichDocumentBlockKind::Extension(extension) => {
1537                let expanded = self
1538                    .state
1539                    .inner
1540                    .borrow()
1541                    .expanded
1542                    .get(&block.id)
1543                    .copied()
1544                    .unwrap_or(extension.initially_expanded);
1545                node.name = Some(extension.title.clone());
1546                if expanded && !extension.body.is_empty() {
1547                    node.value = Some(SemanticsValue::Text(extension.body.clone()));
1548                }
1549                node.state.expanded = Some(expanded);
1550                node.state.busy = matches!(
1551                    extension.status,
1552                    RichDocumentStatus::Pending | RichDocumentStatus::Running
1553                );
1554                node.actions.push(if expanded {
1555                    SemanticsAction::Collapse
1556                } else {
1557                    SemanticsAction::Expand
1558                });
1559                node.description = extension.summary.clone();
1560            }
1561            _ => {}
1562        }
1563        ctx.push(node);
1564
1565        if let RichDocumentBlockKind::List { items, .. } = &block.kind {
1566            for (index, item) in items.iter().enumerate() {
1567                let Some(id) = self
1568                    .semantic_ids
1569                    .get(&SemanticPart::ListItem(index))
1570                    .copied()
1571                else {
1572                    continue;
1573                };
1574                let mut child = SemanticsNode::new(id, SemanticsRole::ListItem, ctx.bounds());
1575                child.parent = Some(ctx.widget_id());
1576                child.name = Some(item.plain_text());
1577                child.state.checked = item.checked.map(|checked| {
1578                    if checked {
1579                        sui_core::ToggleState::Checked
1580                    } else {
1581                        sui_core::ToggleState::Unchecked
1582                    }
1583                });
1584                ctx.push(child);
1585            }
1586        }
1587
1588        for (index, target) in inline_targets(&block.kind).into_iter().enumerate() {
1589            match target {
1590                InlineTarget::Link {
1591                    destination, label, ..
1592                } => {
1593                    let Some(id) = self.semantic_ids.get(&SemanticPart::Link(index)).copied()
1594                    else {
1595                        continue;
1596                    };
1597                    let mut link = SemanticsNode::new(id, SemanticsRole::Link, ctx.bounds());
1598                    link.parent = Some(ctx.widget_id());
1599                    link.name = Some(label);
1600                    link.value = Some(SemanticsValue::Text(destination));
1601                    link.actions.push(SemanticsAction::Activate);
1602                    ctx.push(link);
1603                }
1604                InlineTarget::Image {
1605                    image: inline_image,
1606                    ..
1607                } => {
1608                    let Some(id) = self.semantic_ids.get(&SemanticPart::Image(index)).copied()
1609                    else {
1610                        continue;
1611                    };
1612                    let mut image = SemanticsNode::new(id, SemanticsRole::Image, ctx.bounds());
1613                    image.parent = Some(ctx.widget_id());
1614                    image.name = Some(inline_image.alt);
1615                    image.value = Some(SemanticsValue::Text(inline_image.source));
1616                    image.actions.push(SemanticsAction::Activate);
1617                    ctx.push(image);
1618                }
1619            }
1620        }
1621
1622        if let RichDocumentBlockKind::CodeBlock { .. } = block.kind
1623            && let Some(id) = self.semantic_ids.get(&SemanticPart::Copy).copied()
1624        {
1625            let mut copy = SemanticsNode::new(
1626                id,
1627                SemanticsRole::Button,
1628                Rect::new(
1629                    ctx.bounds().max_x() - 52.0,
1630                    ctx.bounds().y(),
1631                    52.0,
1632                    CODE_HEADER_HEIGHT,
1633                ),
1634            );
1635            copy.parent = Some(ctx.widget_id());
1636            copy.name = Some("Copy code".to_string());
1637            copy.actions.push(SemanticsAction::Copy);
1638            ctx.push(copy);
1639        }
1640    }
1641}
1642
1643fn text_style_for_token(mut style: TextStyle, token: ThemeTextToken) -> TextStyle {
1644    style.font_size = token.size.max(1.0);
1645    style.line_height = token.line_height.max(1.0);
1646    style
1647}
1648
1649fn heading_text_style(theme: DefaultTheme, level: u8) -> TextStyle {
1650    let token = match level {
1651        1 => theme.text._3xl,
1652        2 => theme.text._2xl,
1653        3 => theme.text.xl,
1654        4 => theme.text.lg,
1655        _ => theme.text.base,
1656    };
1657    let mut style = text_style_for_token(theme.body_text_style(), token);
1658    style.weight = FontWeight::BOLD;
1659    style
1660}
1661
1662fn code_header_language_text_style(theme: DefaultTheme) -> TextStyle {
1663    text_style_for_token(
1664        theme.mono_text_style(theme.palette.text_muted),
1665        theme.text.sm,
1666    )
1667}
1668
1669fn code_header_action_text_style(theme: DefaultTheme) -> TextStyle {
1670    text_style_for_token(
1671        theme.text_style(theme.palette.accent_soft_text),
1672        theme.text.sm,
1673    )
1674}
1675
1676fn block_document(
1677    kind: &RichDocumentBlockKind,
1678    theme: DefaultTheme,
1679    highlighter: &dyn RichSyntaxHighlighter,
1680    expanded: bool,
1681) -> TextDocument {
1682    match kind {
1683        RichDocumentBlockKind::Paragraph { spans } => {
1684            document_from_spans(spans, theme.body_text_style(), theme)
1685        }
1686        RichDocumentBlockKind::Heading { level, spans } => {
1687            document_from_spans(spans, heading_text_style(theme, *level), theme)
1688        }
1689        RichDocumentBlockKind::BlockQuote { spans, .. } => {
1690            let mut style = theme.body_text_style();
1691            style.color = theme.palette.text_muted;
1692            style.style = FontStyle::Italic;
1693            document_from_spans(spans, style, theme)
1694        }
1695        RichDocumentBlockKind::List { start, items } => {
1696            let mut spans = Vec::new();
1697            let mut next = start.unwrap_or(1);
1698            for (index, item) in items.iter().enumerate() {
1699                if index > 0 {
1700                    spans.push(TextSpan::new("\n", theme.body_text_style()));
1701                }
1702                let marker = match item.checked {
1703                    Some(true) => "☑ ".to_string(),
1704                    Some(false) => "☐ ".to_string(),
1705                    None if start.is_some() => {
1706                        let marker = format!("{next}. ");
1707                        next = next.saturating_add(1);
1708                        marker
1709                    }
1710                    None => "• ".to_string(),
1711                };
1712                let mut marker_style = theme.body_text_style();
1713                marker_style.color = theme.palette.text_muted;
1714                spans.push(TextSpan::new(marker, marker_style));
1715                spans.extend(styled_spans(&item.spans, theme.body_text_style(), theme));
1716            }
1717            document_from_text_spans(spans)
1718        }
1719        RichDocumentBlockKind::CodeBlock { language, code } => {
1720            let base = theme.mono_text_style(theme.palette.text);
1721            let highlights = highlighter.highlight(language.as_deref(), code);
1722            document_from_text_spans(syntax_spans(code, &highlights, base, theme))
1723        }
1724        RichDocumentBlockKind::ThematicBreak => TextDocument::new(),
1725        RichDocumentBlockKind::Attachment(attachment) => {
1726            let mut spans = vec![TextSpan::new(format!("📎 {}", attachment.name), {
1727                let mut style = theme.body_text_style();
1728                style.weight = FontWeight::SEMIBOLD;
1729                style
1730            })];
1731            if let Some(description) = &attachment.description {
1732                let mut style = theme.body_text_style();
1733                style.color = theme.palette.text_muted;
1734                spans.push(TextSpan::new(format!("\n{description}"), style));
1735            }
1736            document_from_text_spans(spans)
1737        }
1738        RichDocumentBlockKind::Extension(extension) => {
1739            let mut title = theme.body_text_style();
1740            title.weight = FontWeight::SEMIBOLD;
1741            let mut spans = vec![TextSpan::new(extension.title.clone(), title)];
1742            if let Some(summary) = &extension.summary {
1743                let mut style = theme.body_text_style();
1744                style.color = theme.palette.text_muted;
1745                spans.push(TextSpan::new(format!("\n{summary}"), style));
1746            }
1747            if expanded && !extension.body.is_empty() {
1748                spans.push(TextSpan::new(
1749                    format!("\n\n{}", extension.body),
1750                    theme.mono_text_style(theme.palette.text),
1751                ));
1752            }
1753            document_from_text_spans(spans)
1754        }
1755    }
1756}
1757
1758fn document_from_spans(
1759    spans: &[RichDocumentSpan],
1760    base: TextStyle,
1761    theme: DefaultTheme,
1762) -> TextDocument {
1763    document_from_text_spans(styled_spans(spans, base, theme))
1764}
1765
1766fn document_from_text_spans(spans: Vec<TextSpan>) -> TextDocument {
1767    let mut paragraphs = Vec::new();
1768    let mut current = Vec::new();
1769    let mut empty_line_style = spans
1770        .first()
1771        .map(|span| span.style.clone())
1772        .unwrap_or_default();
1773
1774    for span in spans {
1775        empty_line_style = span.style.clone();
1776        let mut remainder = span.text.as_str();
1777        while let Some(newline) = remainder.find('\n') {
1778            if newline > 0 {
1779                current.push(TextSpan::new(&remainder[..newline], span.style.clone()));
1780            }
1781            if current.is_empty() {
1782                current.push(TextSpan::new("", span.style.clone()));
1783            }
1784            paragraphs.push(TextParagraph::from_spans(std::mem::take(&mut current)));
1785            remainder = &remainder[newline + 1..];
1786        }
1787        if !remainder.is_empty() {
1788            current.push(TextSpan::new(remainder, span.style));
1789        }
1790    }
1791
1792    if current.is_empty() {
1793        current.push(TextSpan::new("", empty_line_style));
1794    }
1795    paragraphs.push(TextParagraph::from_spans(current));
1796    TextDocument { paragraphs }
1797}
1798
1799fn styled_spans(spans: &[RichDocumentSpan], base: TextStyle, theme: DefaultTheme) -> Vec<TextSpan> {
1800    spans
1801        .iter()
1802        .map(|span| {
1803            let mut style = base.clone();
1804            if span.style.strong {
1805                style.weight = FontWeight::BOLD;
1806            }
1807            if span.style.emphasis {
1808                style.style = FontStyle::Italic;
1809            }
1810            match &span.kind {
1811                RichInlineKind::Code => {
1812                    style.font_families = Some(theme.fonts.mono.into());
1813                    style.color = theme.palette.accent_soft_text;
1814                }
1815                RichInlineKind::Link(_) => {
1816                    style.color = theme.palette.accent_soft_text;
1817                    style.weight = FontWeight::SEMIBOLD;
1818                }
1819                RichInlineKind::Image(_) => {
1820                    style.color = theme.palette.text_muted;
1821                    style.style = FontStyle::Italic;
1822                }
1823                RichInlineKind::Text => {}
1824            }
1825            TextSpan::new(span.text.clone(), style)
1826        })
1827        .collect()
1828}
1829
1830fn syntax_spans(
1831    source: &str,
1832    highlights: &[RichSyntaxSpan],
1833    base: TextStyle,
1834    theme: DefaultTheme,
1835) -> Vec<TextSpan> {
1836    let mut highlights = highlights
1837        .iter()
1838        .filter_map(|span| {
1839            let start = clamp_boundary(source, span.range.start);
1840            let end = clamp_boundary(source, span.range.end).max(start);
1841            (start < end).then_some((start..end, span.kind))
1842        })
1843        .collect::<Vec<_>>();
1844    highlights.sort_by_key(|(range, _)| range.start);
1845    let mut output = Vec::new();
1846    let mut cursor = 0;
1847    for (range, kind) in highlights {
1848        if range.start < cursor {
1849            continue;
1850        }
1851        if cursor < range.start {
1852            output.push(TextSpan::new(&source[cursor..range.start], base.clone()));
1853        }
1854        let mut style = base.clone();
1855        style.color = syntax_color(theme, kind);
1856        output.push(TextSpan::new(&source[range.clone()], style));
1857        cursor = range.end;
1858    }
1859    if cursor < source.len() {
1860        output.push(TextSpan::new(&source[cursor..], base.clone()));
1861    }
1862    if output.is_empty() {
1863        output.push(TextSpan::new(source, base));
1864    }
1865    output
1866}
1867
1868fn syntax_color(theme: DefaultTheme, kind: RichSyntaxTokenKind) -> sui_core::Color {
1869    match kind {
1870        RichSyntaxTokenKind::Keyword | RichSyntaxTokenKind::Header => {
1871            theme.palette.accent_soft_text
1872        }
1873        RichSyntaxTokenKind::String | RichSyntaxTokenKind::Added => theme.palette.success_soft_text,
1874        RichSyntaxTokenKind::Number | RichSyntaxTokenKind::Property => theme.palette.info_soft_text,
1875        RichSyntaxTokenKind::Comment => theme.palette.text_muted,
1876        RichSyntaxTokenKind::Type | RichSyntaxTokenKind::Function => {
1877            theme.palette.warning_soft_text
1878        }
1879        RichSyntaxTokenKind::Removed => theme.palette.danger_soft_text,
1880    }
1881}
1882
1883fn inline_targets(kind: &RichDocumentBlockKind) -> Vec<InlineTarget> {
1884    let spans = match kind {
1885        RichDocumentBlockKind::Paragraph { spans }
1886        | RichDocumentBlockKind::Heading { spans, .. }
1887        | RichDocumentBlockKind::BlockQuote { spans, .. } => {
1888            spans.iter().map(|span| (span, 0_usize)).collect::<Vec<_>>()
1889        }
1890        RichDocumentBlockKind::List { start, items } => {
1891            let mut offset = 0;
1892            let mut next = start.unwrap_or(1);
1893            let mut flattened = Vec::new();
1894            for (item_index, item) in items.iter().enumerate() {
1895                if item_index > 0 {
1896                    offset += 1;
1897                }
1898                offset += match item.checked {
1899                    Some(_) => "☐ ".len(),
1900                    None if start.is_some() => {
1901                        let len = format!("{next}. ").len();
1902                        next = next.saturating_add(1);
1903                        len
1904                    }
1905                    None => "• ".len(),
1906                };
1907                for span in &item.spans {
1908                    flattened.push((span, offset));
1909                    offset += span.text.len();
1910                }
1911            }
1912            flattened
1913        }
1914        _ => Vec::new(),
1915    };
1916    let mut offset = 0;
1917    let mut targets = Vec::new();
1918    for (span, explicit_offset) in spans {
1919        if explicit_offset > 0 {
1920            offset = explicit_offset;
1921        }
1922        let range = offset..offset + span.text.len();
1923        match &span.kind {
1924            RichInlineKind::Link(link) => targets.push(InlineTarget::Link {
1925                range,
1926                destination: link.destination.clone(),
1927                label: span.text.clone(),
1928            }),
1929            RichInlineKind::Image(image) => targets.push(InlineTarget::Image {
1930                range,
1931                image: image.clone(),
1932            }),
1933            RichInlineKind::Text | RichInlineKind::Code => {}
1934        }
1935        offset += span.text.len();
1936    }
1937    targets
1938}
1939
1940fn selection_range_for(
1941    selection: &DocumentSelection,
1942    block: RichBlockId,
1943    text_len: usize,
1944) -> Range<usize> {
1945    let (Some(anchor), Some(focus)) = (selection.anchor, selection.focus) else {
1946        return 0..0;
1947    };
1948    let Some(anchor_index) = selection.order.iter().position(|id| *id == anchor.block) else {
1949        return 0..0;
1950    };
1951    let Some(focus_index) = selection.order.iter().position(|id| *id == focus.block) else {
1952        return 0..0;
1953    };
1954    let Some(block_index) = selection.order.iter().position(|id| *id == block) else {
1955        return 0..0;
1956    };
1957    let ((start_index, start_offset), (end_index, end_offset)) =
1958        if (anchor_index, anchor.offset) <= (focus_index, focus.offset) {
1959            ((anchor_index, anchor.offset), (focus_index, focus.offset))
1960        } else {
1961            ((focus_index, focus.offset), (anchor_index, anchor.offset))
1962        };
1963    if block_index < start_index || block_index > end_index {
1964        return 0..0;
1965    }
1966    let start = if block_index == start_index {
1967        start_offset.min(text_len)
1968    } else {
1969        0
1970    };
1971    let end = if block_index == end_index {
1972        end_offset.min(text_len)
1973    } else {
1974        text_len
1975    };
1976    start.min(end)..end.max(start)
1977}
1978
1979fn clamp_boundary(text: &str, offset: usize) -> usize {
1980    let mut offset = offset.min(text.len());
1981    while !text.is_char_boundary(offset) {
1982        offset = offset.saturating_sub(1);
1983    }
1984    offset
1985}
1986
1987fn scroll_delta_to_offset(delta: ScrollDelta) -> Vector {
1988    match delta {
1989        ScrollDelta::Lines(delta) => Vector::new(delta.x * 40.0, delta.y * 40.0),
1990        ScrollDelta::Pixels(delta) => delta,
1991    }
1992}
1993
1994fn next_semantic_id() -> WidgetId {
1995    WidgetId::new(SYNTHETIC_RICH_DOCUMENT_TAG | NEXT_SYNTHETIC_ID.fetch_add(1, Ordering::Relaxed))
1996}
1997
1998#[cfg(test)]
1999mod tests {
2000    use std::{cell::Cell, cell::RefCell, rc::Rc};
2001
2002    use sui_core::{
2003        Event, ImageHandle, Point, PointerButton, PointerButtons, PointerEvent, PointerEventKind,
2004        PointerKind, Rect, ScrollDelta, SemanticsAction, SemanticsActionRequest, SemanticsNode,
2005        SemanticsRole, SemanticsValue, Size, Vector, WindowEvent, WindowId,
2006    };
2007    use sui_layout::Constraints;
2008    use sui_reactive::Signal;
2009    use sui_runtime::{
2010        Application, CommandDelivery, CommandTarget, MeasureCtx, RenderOutput, Runtime,
2011        SemanticsCtx, Widget, WindowBuilder,
2012    };
2013    use sui_scene::{Brush, RegisteredImage, SceneCommand};
2014
2015    use super::{
2016        CODE_HEADER_HEIGHT, CODE_INSET, RichDocumentBlock, RichDocumentBlockKind,
2017        RichDocumentModel, RichDocumentRenderContext, RichDocumentRendererRegistry,
2018        RichDocumentView, RichDocumentViewState, code_header_action_text_style,
2019        code_header_language_text_style, heading_text_style, syntax_color,
2020    };
2021    use crate::RichSyntaxTokenKind;
2022    use crate::{
2023        DefaultTheme, RichAttachment, RichExtensionBlock, ScrollState, ScrollView, SizedBox,
2024        TEXT_COMMAND, TextCommand, ThemeTextToken,
2025    };
2026    use sui_text::FontWeight;
2027
2028    fn runtime<W>(root: W) -> (Runtime, sui_core::WindowId)
2029    where
2030        W: Widget + 'static,
2031    {
2032        let runtime = Application::new()
2033            .window(WindowBuilder::new().title("Rich document").root(root))
2034            .build()
2035            .expect("rich document runtime should build");
2036        let window_id = runtime.window_ids()[0];
2037        (runtime, window_id)
2038    }
2039
2040    fn node<'a>(nodes: &'a [SemanticsNode], role: SemanticsRole, name: &str) -> &'a SemanticsNode {
2041        nodes
2042            .iter()
2043            .find(|node| node.role == role && node.name.as_deref() == Some(name))
2044            .unwrap_or_else(|| panic!("missing {role:?} semantics named {name:?}"))
2045    }
2046
2047    fn primary_pointer(kind: PointerEventKind, position: Point, pressed: bool) -> Event {
2048        let mut pointer = PointerEvent::new(kind, position);
2049        pointer.pointer_id = 7;
2050        pointer.button = Some(PointerButton::Primary);
2051        pointer.buttons = if pressed {
2052            PointerButtons::new(1)
2053        } else {
2054            PointerButtons::NONE
2055        };
2056        Event::Pointer(pointer)
2057    }
2058
2059    #[test]
2060    fn heading_text_styles_follow_theme_ramp_pairs() {
2061        let theme = DefaultTheme::default();
2062        let expected = [
2063            (1, theme.text._3xl),
2064            (2, theme.text._2xl),
2065            (3, theme.text.xl),
2066            (4, theme.text.lg),
2067            (5, theme.text.base),
2068            (6, theme.text.base),
2069        ];
2070
2071        for (level, token) in expected {
2072            let style = heading_text_style(theme, level);
2073            assert_eq!(style.font_size, token.size);
2074            assert_eq!(style.line_height, token.line_height);
2075            assert_eq!(style.weight, FontWeight::BOLD);
2076        }
2077    }
2078
2079    #[test]
2080    fn code_header_text_styles_use_complete_small_token_pair() {
2081        let mut theme = DefaultTheme::default();
2082        theme.text.sm = ThemeTextToken {
2083            size: 11.0,
2084            line_height: 16.0,
2085        };
2086
2087        let language = code_header_language_text_style(theme);
2088        let action = code_header_action_text_style(theme);
2089
2090        assert_eq!(language.font_size, theme.text.sm.size);
2091        assert_eq!(language.line_height, theme.text.sm.line_height);
2092        assert_eq!(language.color, theme.palette.text_muted);
2093        assert_eq!(
2094            language.font_families,
2095            theme
2096                .mono_text_style(theme.palette.text_muted)
2097                .font_families
2098        );
2099        assert_eq!(action.font_size, theme.text.sm.size);
2100        assert_eq!(action.line_height, theme.text.sm.line_height);
2101        assert_eq!(action.color, theme.palette.accent_soft_text);
2102        assert_eq!(
2103            action.font_families,
2104            theme
2105                .text_style(theme.palette.accent_soft_text)
2106                .font_families
2107        );
2108    }
2109
2110    #[test]
2111    fn code_block_syntax_colors_use_on_surface_status_text() {
2112        for theme in [
2113            DefaultTheme::default(),
2114            DefaultTheme::dark(),
2115            DefaultTheme::high_contrast(),
2116        ] {
2117            assert_eq!(
2118                syntax_color(theme, RichSyntaxTokenKind::String),
2119                theme.palette.success_soft_text
2120            );
2121            assert_eq!(
2122                syntax_color(theme, RichSyntaxTokenKind::Added),
2123                theme.palette.success_soft_text
2124            );
2125            assert_eq!(
2126                syntax_color(theme, RichSyntaxTokenKind::Number),
2127                theme.palette.info_soft_text
2128            );
2129            assert_eq!(
2130                syntax_color(theme, RichSyntaxTokenKind::Property),
2131                theme.palette.info_soft_text
2132            );
2133            assert_eq!(
2134                syntax_color(theme, RichSyntaxTokenKind::Type),
2135                theme.palette.warning_soft_text
2136            );
2137            assert_eq!(
2138                syntax_color(theme, RichSyntaxTokenKind::Function),
2139                theme.palette.warning_soft_text
2140            );
2141            assert_eq!(
2142                syntax_color(theme, RichSyntaxTokenKind::Removed),
2143                theme.palette.danger_soft_text
2144            );
2145            assert_eq!(
2146                syntax_color(theme, RichSyntaxTokenKind::Keyword),
2147                theme.palette.accent_soft_text
2148            );
2149            assert_eq!(
2150                syntax_color(theme, RichSyntaxTokenKind::Header),
2151                theme.palette.accent_soft_text
2152            );
2153            assert_eq!(
2154                syntax_color(theme, RichSyntaxTokenKind::Comment),
2155                theme.palette.text_muted
2156            );
2157        }
2158    }
2159
2160    #[test]
2161    fn streaming_append_retains_completed_block_widget_identity() {
2162        let model = RichDocumentModel::from_markdown("# Stable\n\nStreaming");
2163        let (mut runtime, window_id) = runtime(RichDocumentView::new(model.clone()));
2164        let first = runtime.render(window_id).unwrap();
2165        let heading_id = node(&first.semantics, SemanticsRole::Heading, "Stable").id;
2166        let paragraph_id = node(&first.semantics, SemanticsRole::Paragraph, "Streaming").id;
2167
2168        model.append_markdown(" text\n\n- next");
2169        let second = runtime.render(window_id).unwrap();
2170        assert_eq!(
2171            node(&second.semantics, SemanticsRole::Heading, "Stable").id,
2172            heading_id
2173        );
2174        assert_eq!(
2175            node(
2176                &second.semantics,
2177                SemanticsRole::Paragraph,
2178                "Streaming text"
2179            )
2180            .id,
2181            paragraph_id
2182        );
2183        assert!(
2184            second
2185                .semantics
2186                .iter()
2187                .any(|node| node.role == SemanticsRole::List)
2188        );
2189    }
2190
2191    #[test]
2192    fn document_semantics_expose_links_images_code_status_and_attachments() {
2193        let model = RichDocumentModel::from_markdown(
2194            "# Report\n\nRead [docs](https://example.test) and ![plot](plot.png).\n\n- one\n- [x] two\n\n```rust\nlet n = 42;\n```",
2195        );
2196        model.append_attachment(RichAttachment::new("results.csv"));
2197        let mut extension = RichExtensionBlock::new("tool-call", "Search");
2198        extension.summary = Some("3 results".to_string());
2199        extension.body = "structured payload".to_string();
2200        model.append_extension(extension);
2201
2202        let opened = Rc::new(RefCell::new(Vec::new()));
2203        let opened_link = Rc::clone(&opened);
2204        let images = Rc::new(RefCell::new(Vec::new()));
2205        let opened_image = Rc::clone(&images);
2206        let (mut runtime, window_id) = runtime(
2207            RichDocumentView::new(model)
2208                .on_link(move |destination| opened_link.borrow_mut().push(destination.to_string()))
2209                .on_image(move |source| opened_image.borrow_mut().push(source.to_string())),
2210        );
2211        let first = runtime.render(window_id).unwrap();
2212        assert!(
2213            first
2214                .semantics
2215                .iter()
2216                .any(|node| node.role == SemanticsRole::Document)
2217        );
2218        assert!(
2219            first
2220                .semantics
2221                .iter()
2222                .any(|node| node.role == SemanticsRole::ListItem && node.state.checked.is_some())
2223        );
2224        assert!(
2225            first
2226                .semantics
2227                .iter()
2228                .any(|node| node.role == SemanticsRole::Attachment)
2229        );
2230
2231        let link = node(&first.semantics, SemanticsRole::Link, "docs");
2232        assert_eq!(
2233            link.value,
2234            Some(SemanticsValue::Text("https://example.test".to_string()))
2235        );
2236        let link_id = link.id;
2237        let image_id = node(&first.semantics, SemanticsRole::Image, "plot").id;
2238        let copy = node(&first.semantics, SemanticsRole::Button, "Copy code");
2239        assert!(copy.actions.contains(&SemanticsAction::Copy));
2240        let copy_id = copy.id;
2241        let status = node(&first.semantics, SemanticsRole::Status, "Search");
2242        assert_eq!(status.state.expanded, Some(false));
2243        let status_id = status.id;
2244
2245        assert!(
2246            runtime
2247                .handle_semantics_action(window_id, link_id, SemanticsActionRequest::Activate)
2248                .unwrap()
2249        );
2250        assert!(
2251            runtime
2252                .handle_semantics_action(window_id, image_id, SemanticsActionRequest::Activate)
2253                .unwrap()
2254        );
2255        assert_eq!(opened.borrow().as_slice(), &["https://example.test"]);
2256        assert_eq!(images.borrow().as_slice(), &["plot.png"]);
2257
2258        assert!(
2259            runtime
2260                .handle_semantics_action(window_id, copy_id, SemanticsActionRequest::Copy)
2261                .unwrap()
2262        );
2263        assert_eq!(runtime.clipboard().text().as_deref(), Some("let n = 42;\n"));
2264
2265        assert!(
2266            runtime
2267                .handle_semantics_action(window_id, status_id, SemanticsActionRequest::Expand)
2268                .unwrap()
2269        );
2270        let expanded = runtime.render(window_id).unwrap();
2271        let status = node(&expanded.semantics, SemanticsRole::Status, "Search");
2272        assert_eq!(status.id, status_id);
2273        assert_eq!(status.state.expanded, Some(true));
2274        assert_eq!(
2275            status.value,
2276            Some(SemanticsValue::Text("structured payload".to_string()))
2277        );
2278    }
2279
2280    #[test]
2281    fn overflowing_code_block_scrolls_horizontally() {
2282        let model = RichDocumentModel::from_markdown(
2283            "```rust\nfn answer() -> u32 {\n    let diagnostic_context = \"a deliberately long code line that must overflow a narrow rich document viewport\";\n    42\n}\n```",
2284        );
2285        let (mut runtime, window_id) = runtime(RichDocumentView::new(model));
2286        runtime
2287            .handle_event(
2288                window_id,
2289                Event::Window(WindowEvent::Resized(Size::new(320.0, 240.0))),
2290            )
2291            .unwrap();
2292        let first = runtime.render(window_id).unwrap();
2293        let code = first
2294            .semantics
2295            .iter()
2296            .find(|node| node.role == SemanticsRole::Code)
2297            .expect("code semantics");
2298        assert!(
2299            code.bounds.height() > 100.0,
2300            "multiline code should retain every visual line, bounds={:?}",
2301            code.bounds
2302        );
2303        let first_origin = first
2304            .frame
2305            .scene
2306            .commands()
2307            .iter()
2308            .filter_map(|command| match command {
2309                SceneCommand::DrawShapedText(text) => Some(text),
2310                _ => None,
2311            })
2312            .max_by(|left, right| left.bounds.width().total_cmp(&right.bounds.width()))
2313            .map(|text| text.origin)
2314            .expect("code text draw");
2315
2316        let code_center = Point::new(
2317            code.bounds.x() + code.bounds.width() * 0.5,
2318            code.bounds.y() + code.bounds.height() * 0.5,
2319        );
2320        let mut scroll = PointerEvent::new(PointerEventKind::Scroll, code_center);
2321        scroll.scroll_delta = Some(ScrollDelta::Pixels(Vector::new(-180.0, 0.0)));
2322        runtime
2323            .handle_event(window_id, Event::Pointer(scroll))
2324            .unwrap();
2325        let second = runtime.render(window_id).unwrap();
2326        let second_origin = second
2327            .frame
2328            .scene
2329            .commands()
2330            .iter()
2331            .filter_map(|command| match command {
2332                SceneCommand::DrawShapedText(text) => Some(text),
2333                _ => None,
2334            })
2335            .max_by(|left, right| left.bounds.width().total_cmp(&right.bounds.width()))
2336            .map(|text| text.origin)
2337            .expect("scrolled code text draw");
2338
2339        assert!(
2340            second_origin.x < first_origin.x,
2341            "expected code origin to move left, before={first_origin:?}, after={second_origin:?}"
2342        );
2343    }
2344
2345    /// A one-line code block far wider than the 320-pixel windows below.
2346    const LONG_CODE: &str = "```text\nlet diagnostic_context = \"a deliberately long code line that overflows a narrow rich document\";\n```";
2347
2348    fn touch_pointer(kind: PointerEventKind, position: Point, delta: Vector) -> Event {
2349        let mut pointer = PointerEvent::new(kind, position);
2350        pointer.pointer_id = 11;
2351        pointer.pointer_kind = PointerKind::Touch;
2352        pointer.delta = delta;
2353        match kind {
2354            PointerEventKind::Down => {
2355                pointer.button = Some(PointerButton::Primary);
2356                pointer.buttons = PointerButtons::new(1);
2357            }
2358            PointerEventKind::Move => pointer.buttons = PointerButtons::new(1),
2359            PointerEventKind::Up => pointer.button = Some(PointerButton::Primary),
2360            _ => {}
2361        }
2362        Event::Pointer(pointer)
2363    }
2364
2365    /// Touches `from`, drags halfway and then on to `to`, and lifts.
2366    fn touch_drag(runtime: &mut Runtime, window_id: WindowId, from: Point, to: Point) {
2367        let halfway = Point::new((from.x + to.x) * 0.5, (from.y + to.y) * 0.5);
2368        runtime
2369            .handle_event(
2370                window_id,
2371                touch_pointer(PointerEventKind::Down, from, Vector::ZERO),
2372            )
2373            .unwrap();
2374        for (previous, next) in [(from, halfway), (halfway, to)] {
2375            runtime
2376                .handle_event(
2377                    window_id,
2378                    touch_pointer(PointerEventKind::Move, next, next - previous),
2379                )
2380                .unwrap();
2381        }
2382        runtime
2383            .handle_event(
2384                window_id,
2385                touch_pointer(PointerEventKind::Up, to, Vector::ZERO),
2386            )
2387            .unwrap();
2388    }
2389
2390    fn sized_runtime<W>(root: W) -> (Runtime, WindowId)
2391    where
2392        W: Widget + 'static,
2393    {
2394        let (mut runtime, window_id) = runtime(root);
2395        runtime
2396            .handle_event(
2397                window_id,
2398                Event::Window(WindowEvent::Resized(Size::new(320.0, 240.0))),
2399            )
2400            .unwrap();
2401        (runtime, window_id)
2402    }
2403
2404    fn code_bounds(output: &RenderOutput) -> Rect {
2405        output
2406            .semantics
2407            .iter()
2408            .find(|node| node.role == SemanticsRole::Code)
2409            .expect("code semantics")
2410            .bounds
2411    }
2412
2413    /// Where the code block's line sits, mid-height in its text area.
2414    fn code_line_y(code: Rect) -> f32 {
2415        let top = code.y() + CODE_HEADER_HEIGHT + CODE_INSET;
2416        (top + code.max_y() - CODE_INSET) * 0.5
2417    }
2418
2419    fn code_text_origin(output: &RenderOutput) -> Point {
2420        let mut widest: Option<(f32, Point)> = None;
2421        output.frame.scene.visit_commands(&mut |command| {
2422            if let SceneCommand::DrawShapedText(text) = command
2423                && widest.is_none_or(|(width, _)| text.bounds.width() > width)
2424            {
2425                widest = Some((text.bounds.width(), text.origin));
2426            }
2427        });
2428        widest.expect("code text draw").1
2429    }
2430
2431    fn selection_rects(output: &RenderOutput) -> Vec<Rect> {
2432        let selection = DefaultTheme::default().palette.selection;
2433        let mut rects = Vec::new();
2434        output.frame.scene.visit_commands(&mut |command| {
2435            if let SceneCommand::FillRect {
2436                rect,
2437                brush: Brush::Solid(fill),
2438            } = command
2439                && *fill == selection
2440            {
2441                rects.push(*rect);
2442            }
2443        });
2444        rects
2445    }
2446
2447    fn assert_close(actual: f32, expected: f32) {
2448        assert!(
2449            (actual - expected).abs() < 0.01,
2450            "expected {expected}, got {actual}"
2451        );
2452    }
2453
2454    #[test]
2455    fn touch_drag_pans_an_overflowing_code_block_sideways() {
2456        let state = RichDocumentViewState::new();
2457        let (mut runtime, window_id) = sized_runtime(
2458            RichDocumentView::new(RichDocumentModel::from_markdown(LONG_CODE)).state(state.clone()),
2459        );
2460        let first = runtime.render(window_id).unwrap();
2461        let code = code_bounds(&first);
2462        let start = code_text_origin(&first);
2463        let from = Point::new(code.x() + code.width() * 0.75, code_line_y(code));
2464
2465        // Mostly sideways, as a finger drags.
2466        touch_drag(
2467            &mut runtime,
2468            window_id,
2469            from,
2470            Point::new(from.x - 120.0, from.y + 10.0),
2471        );
2472        let panned = code_text_origin(&runtime.render(window_id).unwrap());
2473        assert_close(panned.x, start.x - 120.0);
2474        assert_close(panned.y, start.y);
2475        assert_eq!(state.selected_text(), None, "a pan selects nothing");
2476
2477        // Back past the start, where the code stops.
2478        touch_drag(
2479            &mut runtime,
2480            window_id,
2481            from,
2482            Point::new(from.x + 200.0, from.y),
2483        );
2484        let back = code_text_origin(&runtime.render(window_id).unwrap());
2485        assert_close(back.x, start.x);
2486    }
2487
2488    #[test]
2489    fn scrolled_code_block_selects_the_text_it_shows() {
2490        let (mut runtime, window_id) = sized_runtime(RichDocumentView::new(
2491            RichDocumentModel::from_markdown(LONG_CODE),
2492        ));
2493        let first = runtime.render(window_id).unwrap();
2494        let code = code_bounds(&first);
2495        let start = code_text_origin(&first);
2496        let y = code_line_y(code);
2497        let mut wheel = PointerEvent::new(
2498            PointerEventKind::Scroll,
2499            Point::new(code.x() + code.width() * 0.5, y),
2500        );
2501        wheel.scroll_delta = Some(ScrollDelta::Pixels(Vector::new(-60.0, 0.0)));
2502        let touch = Point::new(code.x() + code.width() * 0.75, y);
2503
2504        for (scroll, offset) in [
2505            (Some(Event::Pointer(wheel)), 60.0),
2506            // A pan scrolls on from where the wheel left the code.
2507            (None, 140.0),
2508        ] {
2509            match scroll {
2510                Some(event) => runtime.handle_event(window_id, event).unwrap(),
2511                None => touch_drag(
2512                    &mut runtime,
2513                    window_id,
2514                    touch,
2515                    Point::new(touch.x - 80.0, y),
2516                ),
2517            }
2518            let scrolled = runtime.render(window_id).unwrap();
2519            assert_close(code_text_origin(&scrolled).x, start.x - offset);
2520
2521            let from = Point::new(code.x() + 60.0, y);
2522            let to = Point::new(code.x() + 180.0, y);
2523            for (kind, position, pressed) in [
2524                (PointerEventKind::Down, from, true),
2525                (PointerEventKind::Move, to, true),
2526                (PointerEventKind::Up, to, false),
2527            ] {
2528                runtime
2529                    .handle_event(window_id, primary_pointer(kind, position, pressed))
2530                    .unwrap();
2531            }
2532            let selected = selection_rects(&runtime.render(window_id).unwrap());
2533            assert_eq!(selected.len(), 1, "{selected:?}");
2534            // Within half a glyph of where the drag went.
2535            assert!(
2536                (selected[0].x() - from.x).abs() < 6.0 && (selected[0].max_x() - to.x).abs() < 6.0,
2537                "selected {:?} for a drag from {} to {} scrolled by {offset}",
2538                selected[0],
2539                from.x,
2540                to.x
2541            );
2542        }
2543    }
2544
2545    #[test]
2546    fn upright_touch_drag_on_a_code_block_selects_instead_of_panning() {
2547        let state = RichDocumentViewState::new();
2548        let (mut runtime, window_id) = sized_runtime(
2549            RichDocumentView::new(RichDocumentModel::from_markdown(format!(
2550                "{LONG_CODE}\n\nAfter the code."
2551            )))
2552            .state(state.clone()),
2553        );
2554        let first = runtime.render(window_id).unwrap();
2555        let code = code_bounds(&first);
2556        let start = code_text_origin(&first);
2557        let paragraph = node(
2558            &first.semantics,
2559            SemanticsRole::Paragraph,
2560            "After the code.",
2561        );
2562        let from = Point::new(code.x() + 120.0, code_line_y(code));
2563
2564        touch_drag(
2565            &mut runtime,
2566            window_id,
2567            from,
2568            Point::new(from.x - 20.0, paragraph.bounds.y() + 10.0),
2569        );
2570
2571        let output = runtime.render(window_id).unwrap();
2572        assert_close(code_text_origin(&output).x, start.x);
2573        let selected = state.selected_text().expect("an upright drag selects");
2574        assert!(selected.contains("After"), "selected {selected:?}");
2575    }
2576
2577    #[test]
2578    fn code_block_pans_inside_a_scroll_view_that_scrolls_upright_drags() {
2579        let markdown = std::iter::once(LONG_CODE.to_string())
2580            .chain((1..=12).map(|index| format!("Paragraph {index}")))
2581            .collect::<Vec<_>>()
2582            .join("\n\n");
2583        let scroll = ScrollState::new();
2584        let (mut runtime, window_id) = sized_runtime(
2585            SizedBox::new().size(Size::new(320.0, 200.0)).child(
2586                ScrollView::vertical(RichDocumentView::new(RichDocumentModel::from_markdown(
2587                    markdown,
2588                )))
2589                .state(scroll.clone()),
2590            ),
2591        );
2592        let first = runtime.render(window_id).unwrap();
2593        let code = code_bounds(&first);
2594        let start = code_text_origin(&first);
2595        // In the code block's margin, below its text.
2596        let from = Point::new(code.x() + code.width() * 0.75, code.max_y() - 4.0);
2597
2598        touch_drag(
2599            &mut runtime,
2600            window_id,
2601            from,
2602            Point::new(from.x - 100.0, from.y),
2603        );
2604        let panned = code_text_origin(&runtime.render(window_id).unwrap());
2605        assert_close(panned.x, start.x - 100.0);
2606        assert_eq!(scroll.current_offset(), Vector::ZERO);
2607
2608        touch_drag(
2609            &mut runtime,
2610            window_id,
2611            from,
2612            Point::new(from.x, from.y - 60.0),
2613        );
2614        assert_eq!(scroll.current_offset(), Vector::new(0.0, 60.0));
2615        let output = runtime.render(window_id).unwrap();
2616        assert_close(code_text_origin(&output).x, panned.x);
2617    }
2618
2619    #[test]
2620    fn inline_image_resolver_paints_registered_image() {
2621        let handle = ImageHandle::new(71);
2622        let model = RichDocumentModel::from_markdown("![plot](asset:plot)");
2623        let mut application = Application::new();
2624        application
2625            .register_image(
2626                handle,
2627                RegisteredImage::from_rgba8(8, 8, vec![255; 8 * 8 * 4]).unwrap(),
2628            )
2629            .unwrap();
2630        let mut runtime =
2631            application
2632                .window(WindowBuilder::new().title("Inline image").root(
2633                    RichDocumentView::new(model).image_resolver(move |image| {
2634                        (image.source == "asset:plot").then_some(handle)
2635                    }),
2636                ))
2637                .build()
2638                .unwrap();
2639        let output = runtime.render(runtime.window_ids()[0]).unwrap();
2640        let mut draws = 0;
2641        output.frame.scene.visit_commands(&mut |command| {
2642            if matches!(command, SceneCommand::DrawImage { source, .. } if source.image == handle) {
2643                draws += 1;
2644            }
2645        });
2646        assert_eq!(draws, 1);
2647    }
2648
2649    #[test]
2650    fn pointer_drag_selects_text_across_multiple_blocks() {
2651        let model = RichDocumentModel::from_markdown("# First block\n\nSecond block");
2652        let state = RichDocumentViewState::new();
2653        let (mut runtime, window_id) = runtime(RichDocumentView::new(model).state(state.clone()));
2654        let first = runtime.render(window_id).unwrap();
2655        let heading = node(&first.semantics, SemanticsRole::Heading, "First block");
2656        let paragraph = node(&first.semantics, SemanticsRole::Paragraph, "Second block");
2657        let start = Point::new(heading.bounds.x() + 4.0, heading.bounds.y() + 4.0);
2658        let end = Point::new(
2659            paragraph.bounds.max_x() - 4.0,
2660            paragraph.bounds.y() + paragraph.bounds.height() * 0.5,
2661        );
2662
2663        runtime
2664            .handle_event(
2665                window_id,
2666                primary_pointer(PointerEventKind::Down, start, true),
2667            )
2668            .unwrap();
2669        runtime
2670            .handle_event(
2671                window_id,
2672                primary_pointer(PointerEventKind::Move, end, true),
2673            )
2674            .unwrap();
2675        runtime
2676            .handle_event(window_id, primary_pointer(PointerEventKind::Up, end, false))
2677            .unwrap();
2678
2679        let selected = state.selected_text().expect("cross-block selection");
2680        assert!(selected.contains("First block"), "selected {selected:?}");
2681        assert!(selected.contains("Second block"), "selected {selected:?}");
2682
2683        runtime.handle_command(
2684            CommandTarget::FocusedWidget(window_id),
2685            CommandDelivery::Directed,
2686            TEXT_COMMAND,
2687            TextCommand::Copy,
2688        );
2689        assert_eq!(
2690            runtime.clipboard().text().as_deref(),
2691            Some(selected.as_str())
2692        );
2693    }
2694
2695    struct ExtensionProbe {
2696        block: Signal<RichDocumentBlock>,
2697        measures: Option<Rc<Cell<usize>>>,
2698    }
2699
2700    impl Widget for ExtensionProbe {
2701        fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
2702            let _ = ctx.observe(&self.block);
2703            if let Some(measures) = &self.measures {
2704                measures.set(measures.get() + 1);
2705            }
2706            constraints.clamp(Size::new(160.0, 32.0))
2707        }
2708
2709        fn semantics(&self, ctx: &mut SemanticsCtx) {
2710            let block = self.block.get();
2711            let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Status, ctx.bounds());
2712            node.name = Some(format!("Custom: {}", block.plain_text()));
2713            ctx.push(node);
2714        }
2715    }
2716
2717    #[test]
2718    fn extension_registry_updates_payload_without_replacing_renderer_widget() {
2719        let registry = RichDocumentRendererRegistry::new();
2720        registry.register(
2721            "extension:tool-call",
2722            |context: RichDocumentRenderContext| ExtensionProbe {
2723                block: context.block,
2724                measures: None,
2725            },
2726        );
2727        let model = RichDocumentModel::new();
2728        let id = model.append_extension(RichExtensionBlock::new("tool-call", "Pending"));
2729        let (mut runtime, window_id) =
2730            runtime(RichDocumentView::new(model.clone()).renderer_registry(registry));
2731        let first = runtime.render(window_id).unwrap();
2732        let widget_id = node(&first.semantics, SemanticsRole::Status, "Custom: Pending").id;
2733
2734        let mut completed = RichExtensionBlock::new("tool-call", "Complete");
2735        completed.body = "42".to_string();
2736        assert!(model.update_structured(id, RichDocumentBlockKind::Extension(completed)));
2737        let second = runtime.render(window_id).unwrap();
2738        assert_eq!(
2739            node(
2740                &second.semantics,
2741                SemanticsRole::Status,
2742                "Custom: Complete\n42"
2743            )
2744            .id,
2745            widget_id
2746        );
2747    }
2748
2749    #[test]
2750    fn tail_update_does_not_remeasure_retained_prefix_renderer() {
2751        let registry = RichDocumentRendererRegistry::new();
2752        let measures = Rc::new(Cell::new(0));
2753        let renderer_measures = Rc::clone(&measures);
2754        registry.register(
2755            "extension:tool-call",
2756            move |context: RichDocumentRenderContext| ExtensionProbe {
2757                block: context.block,
2758                measures: Some(Rc::clone(&renderer_measures)),
2759            },
2760        );
2761        let model = RichDocumentModel::new();
2762        model.append_extension(RichExtensionBlock::new("tool-call", "Stable prefix"));
2763        model.append_markdown("Streaming");
2764        let (mut runtime, window_id) =
2765            runtime(RichDocumentView::new(model.clone()).renderer_registry(registry));
2766        runtime.render(window_id).unwrap();
2767        let initial_measures = measures.get();
2768
2769        model.append_markdown(" tail");
2770        runtime.render(window_id).unwrap();
2771        assert_eq!(measures.get(), initial_measures);
2772    }
2773}