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, KeyState, Point, PointerButton, PointerEventKind, Rect, ScrollDelta,
11    SemanticsAction, SemanticsActionRequest, SemanticsNode, SemanticsRole, SemanticsValue, Size,
12    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_scene::StrokeStyle;
21use sui_text::{
22    FontStyle, FontWeight, PersistentTextLayout, TextDocument, TextLayoutRequest, TextParagraph,
23    TextSpan, TextStyle,
24};
25
26use super::{
27    BasicSyntaxHighlighter, RichBlockId, RichDocumentBlock, RichDocumentBlockKind,
28    RichDocumentModel, RichDocumentSpan, RichDocumentStatus, RichInlineImage, RichInlineKind,
29    RichSyntaxHighlighter, RichSyntaxSpan, RichSyntaxTokenKind,
30};
31use crate::{DefaultTheme, TextCommand};
32
33const BLOCK_GAP: f32 = 8.0;
34const TEXT_INSET: f32 = 2.0;
35const QUOTE_INSET: f32 = 14.0;
36const CODE_INSET: f32 = 10.0;
37const CODE_HEADER_HEIGHT: f32 = 30.0;
38const STRUCTURED_INSET: f32 = 10.0;
39const SYNTHETIC_RICH_DOCUMENT_TAG: u64 = 0x2d << 46;
40static NEXT_SYNTHETIC_ID: AtomicU64 = AtomicU64::new(1);
41
42type Renderer = Rc<dyn Fn(RichDocumentRenderContext) -> WidgetPod>;
43type StringAction = Rc<RefCell<Box<dyn FnMut(&str)>>>;
44type BlockAction = Rc<RefCell<Box<dyn FnMut(RichBlockId)>>>;
45type ImageResolver = Rc<dyn Fn(&RichInlineImage) -> Option<ImageHandle>>;
46
47/// Context passed to an application-defined rich-document block renderer.
48///
49/// The `block` signal preserves the renderer widget's identity while the
50/// structured payload changes. Observe it with the relevant widget context
51/// (`ctx.observe` or `ctx.observe_with`) to declare invalidation dependencies.
52#[derive(Clone)]
53pub struct RichDocumentRenderContext {
54    pub block: Signal<RichDocumentBlock>,
55    pub state: RichDocumentViewState,
56    pub theme: DefaultTheme,
57}
58
59/// Registry of block renderers keyed by architecture-neutral names.
60///
61/// Markdown blocks use built-in renderers. Applications typically register
62/// extension keys such as `extension:tool-call`, `extension:diff`, or
63/// `extension:operation-log` without coupling SUI to a chat schema.
64#[derive(Clone, Default)]
65pub struct RichDocumentRendererRegistry {
66    renderers: Rc<RefCell<HashMap<String, Renderer>>>,
67}
68
69impl RichDocumentRendererRegistry {
70    pub fn new() -> Self {
71        Self::default()
72    }
73
74    pub fn register<F, W>(&self, key: impl Into<String>, renderer: F)
75    where
76        F: Fn(RichDocumentRenderContext) -> W + 'static,
77        W: Widget + 'static,
78    {
79        self.renderers.borrow_mut().insert(
80            key.into(),
81            Rc::new(move |context| WidgetPod::new(renderer(context))),
82        );
83    }
84
85    pub fn unregister(&self, key: &str) -> bool {
86        self.renderers.borrow_mut().remove(key).is_some()
87    }
88
89    pub fn contains(&self, key: &str) -> bool {
90        self.renderers.borrow().contains_key(key)
91    }
92
93    fn renderer(&self, key: &str) -> Option<Renderer> {
94        self.renderers.borrow().get(key).cloned()
95    }
96}
97
98#[derive(Clone, Copy, Debug, PartialEq, Eq)]
99struct DocumentPoint {
100    block: RichBlockId,
101    offset: usize,
102}
103
104#[derive(Clone, Debug, PartialEq, Eq)]
105enum PressedInline {
106    Link(String),
107    Image(String),
108}
109
110#[derive(Clone, Debug, Default)]
111struct DocumentSelection {
112    anchor: Option<DocumentPoint>,
113    focus: Option<DocumentPoint>,
114    order: Vec<RichBlockId>,
115    selected_text: String,
116}
117
118#[derive(Default)]
119struct ViewStateInner {
120    selection: DocumentSelection,
121    expanded: HashMap<RichBlockId, bool>,
122}
123
124/// Shareable retained state for a [`RichDocumentView`].
125///
126/// The state owns document-spanning selection and expansion state separately
127/// from Markdown content, so structural streaming updates do not reset either.
128#[derive(Clone)]
129pub struct RichDocumentViewState {
130    inner: Rc<RefCell<ViewStateInner>>,
131    revision: Signal<u64>,
132}
133
134impl RichDocumentViewState {
135    pub fn new() -> Self {
136        Self {
137            inner: Rc::new(RefCell::new(ViewStateInner::default())),
138            revision: Signal::named("RichDocumentViewState", 0),
139        }
140    }
141
142    pub fn selected_text(&self) -> Option<String> {
143        let text = self.inner.borrow().selection.selected_text.clone();
144        (!text.is_empty()).then_some(text)
145    }
146
147    pub fn clear_selection(&self) -> bool {
148        let changed = {
149            let mut inner = self.inner.borrow_mut();
150            let changed = inner.selection.anchor.is_some()
151                || inner.selection.focus.is_some()
152                || !inner.selection.selected_text.is_empty();
153            inner.selection.anchor = None;
154            inner.selection.focus = None;
155            inner.selection.selected_text.clear();
156            changed
157        };
158        if changed {
159            self.bump_revision();
160        }
161        changed
162    }
163
164    pub fn is_expanded(&self, block: RichBlockId) -> bool {
165        self.inner
166            .borrow()
167            .expanded
168            .get(&block)
169            .copied()
170            .unwrap_or(false)
171    }
172
173    pub fn set_expanded(&self, block: RichBlockId, expanded: bool) -> bool {
174        let changed = self.inner.borrow_mut().expanded.insert(block, expanded) != Some(expanded);
175        if changed {
176            self.bump_revision();
177        }
178        changed
179    }
180
181    pub fn toggle_expanded(&self, block: RichBlockId) -> bool {
182        let expanded = !self.is_expanded(block);
183        self.set_expanded(block, expanded);
184        expanded
185    }
186
187    fn bump_revision(&self) {
188        let next = self.revision.get().wrapping_add(1);
189        let _ = self.revision.set(next);
190    }
191
192    fn set_order(&self, order: Vec<RichBlockId>) {
193        let mut inner = self.inner.borrow_mut();
194        inner.selection.order = order;
195        let live = inner
196            .selection
197            .order
198            .iter()
199            .copied()
200            .collect::<HashSet<_>>();
201        inner.expanded.retain(|id, _| live.contains(id));
202        if inner
203            .selection
204            .anchor
205            .is_some_and(|point| !live.contains(&point.block))
206            || inner
207                .selection
208                .focus
209                .is_some_and(|point| !live.contains(&point.block))
210        {
211            inner.selection.anchor = None;
212            inner.selection.focus = None;
213            inner.selection.selected_text.clear();
214        }
215    }
216
217    fn selection(&self) -> DocumentSelection {
218        self.inner.borrow().selection.clone()
219    }
220
221    fn set_selection(&self, anchor: DocumentPoint, focus: DocumentPoint, text: String) {
222        let mut inner = self.inner.borrow_mut();
223        if inner.selection.anchor == Some(anchor)
224            && inner.selection.focus == Some(focus)
225            && inner.selection.selected_text == text
226        {
227            return;
228        }
229        inner.selection.anchor = Some(anchor);
230        inner.selection.focus = Some(focus);
231        inner.selection.selected_text = text;
232        drop(inner);
233        self.bump_revision();
234    }
235}
236
237impl Default for RichDocumentViewState {
238    fn default() -> Self {
239        Self::new()
240    }
241}
242
243#[derive(Clone)]
244struct BlockTextHandle {
245    block: RichBlockId,
246    bounds: Rect,
247    origin: Point,
248    layout: Option<PersistentTextLayout>,
249    text: String,
250}
251
252impl BlockTextHandle {
253    fn new(block: RichBlockId) -> Self {
254        Self {
255            block,
256            bounds: Rect::ZERO,
257            origin: Point::ZERO,
258            layout: None,
259            text: String::new(),
260        }
261    }
262
263    fn point(&self, point: Point, strict: bool) -> Option<DocumentPoint> {
264        if strict && !self.bounds.contains(point) {
265            return None;
266        }
267        let layout = self.layout.as_ref()?;
268        let cursor =
269            layout.hit_test_point(Point::new(point.x - self.origin.x, point.y - self.origin.y));
270        Some(DocumentPoint {
271            block: self.block,
272            offset: cursor.utf8_offset.min(self.text.len()),
273        })
274    }
275}
276
277struct RetainedBlock {
278    key: String,
279    value: Signal<RichDocumentBlock>,
280    pod: WidgetPod,
281    text: Rc<RefCell<BlockTextHandle>>,
282}
283
284/// Retained, selectable, incrementally updating rich-document widget.
285pub struct RichDocumentView {
286    model: RichDocumentModel,
287    state: RichDocumentViewState,
288    registry: RichDocumentRendererRegistry,
289    theme: DefaultTheme,
290    highlighter: Rc<dyn RichSyntaxHighlighter>,
291    blocks: HashMap<RichBlockId, RetainedBlock>,
292    order: Vec<RichBlockId>,
293    measured_heights: HashMap<RichBlockId, f32>,
294    dragging: bool,
295    drag_anchor: Option<DocumentPoint>,
296    pressed_inline: Option<(RichBlockId, PressedInline)>,
297    on_link: Option<StringAction>,
298    on_image: Option<StringAction>,
299    image_resolver: Option<ImageResolver>,
300    on_attachment: Option<BlockAction>,
301}
302
303impl RichDocumentView {
304    pub fn new(model: RichDocumentModel) -> Self {
305        Self {
306            model,
307            state: RichDocumentViewState::new(),
308            registry: RichDocumentRendererRegistry::new(),
309            theme: DefaultTheme::default(),
310            highlighter: Rc::new(BasicSyntaxHighlighter),
311            blocks: HashMap::new(),
312            order: Vec::new(),
313            measured_heights: HashMap::new(),
314            dragging: false,
315            drag_anchor: None,
316            pressed_inline: None,
317            on_link: None,
318            on_image: None,
319            image_resolver: None,
320            on_attachment: None,
321        }
322    }
323
324    pub fn state(mut self, state: RichDocumentViewState) -> Self {
325        self.state = state;
326        self
327    }
328
329    pub fn renderer_registry(mut self, registry: RichDocumentRendererRegistry) -> Self {
330        self.registry = registry;
331        self
332    }
333
334    pub fn theme(mut self, theme: DefaultTheme) -> Self {
335        self.theme = theme;
336        self
337    }
338
339    pub fn syntax_highlighter<H>(mut self, highlighter: H) -> Self
340    where
341        H: RichSyntaxHighlighter + 'static,
342    {
343        self.highlighter = Rc::new(highlighter);
344        self
345    }
346
347    pub fn on_link<F>(mut self, callback: F) -> Self
348    where
349        F: FnMut(&str) + 'static,
350    {
351        self.on_link = Some(Rc::new(RefCell::new(Box::new(callback))));
352        self
353    }
354
355    pub fn on_image<F>(mut self, callback: F) -> Self
356    where
357        F: FnMut(&str) + 'static,
358    {
359        self.on_image = Some(Rc::new(RefCell::new(Box::new(callback))));
360        self
361    }
362
363    /// Resolve Markdown image sources to images registered with the runtime.
364    ///
365    /// Until a source resolves, the default renderer keeps the image's alt
366    /// text as an inline placeholder with full image semantics.
367    pub fn image_resolver<F>(mut self, resolver: F) -> Self
368    where
369        F: Fn(&RichInlineImage) -> Option<ImageHandle> + 'static,
370    {
371        self.image_resolver = Some(Rc::new(resolver));
372        self
373    }
374
375    pub fn on_attachment<F>(mut self, callback: F) -> Self
376    where
377        F: FnMut(RichBlockId) + 'static,
378    {
379        self.on_attachment = Some(Rc::new(RefCell::new(Box::new(callback))));
380        self
381    }
382
383    pub fn model(&self) -> &RichDocumentModel {
384        &self.model
385    }
386
387    pub fn view_state(&self) -> &RichDocumentViewState {
388        &self.state
389    }
390
391    fn sync_blocks(&mut self) {
392        let blocks = self.model.blocks();
393        let order = blocks.iter().map(|block| block.id).collect::<Vec<_>>();
394        let live = order.iter().copied().collect::<HashSet<_>>();
395        self.blocks.retain(|id, _| live.contains(id));
396        self.measured_heights.retain(|id, _| live.contains(id));
397
398        for block in blocks {
399            let key = block.renderer_key();
400            if let Some(retained) = self.blocks.get_mut(&block.id)
401                && retained.key == key
402            {
403                continue;
404            }
405            let signal = self
406                .model
407                .block_signal(block.id)
408                .unwrap_or_else(|| Signal::named("DetachedRichDocumentBlock", block.clone()));
409            let text = Rc::new(RefCell::new(BlockTextHandle::new(block.id)));
410            let context = RichDocumentRenderContext {
411                block: signal.clone(),
412                state: self.state.clone(),
413                theme: self.theme,
414            };
415            let pod = self.registry.renderer(&key).map_or_else(
416                || {
417                    WidgetPod::new(DefaultBlockView::new(
418                        signal.clone(),
419                        self.state.clone(),
420                        Rc::clone(&text),
421                        self.theme,
422                        Rc::clone(&self.highlighter),
423                        self.on_link.clone(),
424                        self.on_image.clone(),
425                        self.image_resolver.clone(),
426                        self.on_attachment.clone(),
427                    ))
428                },
429                |renderer| renderer(context),
430            );
431            self.blocks.insert(
432                block.id,
433                RetainedBlock {
434                    key,
435                    value: signal,
436                    pod,
437                    text,
438                },
439            );
440        }
441        self.order = order;
442        self.state.set_order(self.order.clone());
443    }
444
445    fn point_at(&self, point: Point, strict: bool) -> Option<DocumentPoint> {
446        if strict {
447            return self.order.iter().find_map(|id| {
448                self.blocks
449                    .get(id)
450                    .and_then(|block| block.text.borrow().point(point, true))
451            });
452        }
453        let mut nearest: Option<(f32, Rc<RefCell<BlockTextHandle>>)> = None;
454        for id in &self.order {
455            let Some(block) = self.blocks.get(id) else {
456                continue;
457            };
458            let handle = block.text.borrow();
459            if handle.layout.is_none() {
460                continue;
461            }
462            if handle.bounds.contains(point) {
463                return handle.point(point, false);
464            }
465            let distance = if point.y < handle.bounds.y() {
466                handle.bounds.y() - point.y
467            } else {
468                point.y - handle.bounds.max_y()
469            };
470            if nearest.as_ref().is_none_or(|(best, _)| distance < *best) {
471                nearest = Some((distance, Rc::clone(&block.text)));
472            }
473        }
474        nearest.and_then(|(_, handle)| handle.borrow().point(point, false))
475    }
476
477    fn selection_text(&self, anchor: DocumentPoint, focus: DocumentPoint) -> String {
478        let Some(anchor_index) = self.order.iter().position(|id| *id == anchor.block) else {
479            return String::new();
480        };
481        let Some(focus_index) = self.order.iter().position(|id| *id == focus.block) else {
482            return String::new();
483        };
484        let (start, end) = if (anchor_index, anchor.offset) <= (focus_index, focus.offset) {
485            (anchor, focus)
486        } else {
487            (focus, anchor)
488        };
489        let start_index = self
490            .order
491            .iter()
492            .position(|id| *id == start.block)
493            .unwrap_or(0);
494        let end_index = self
495            .order
496            .iter()
497            .position(|id| *id == end.block)
498            .unwrap_or(start_index);
499        let mut parts = Vec::new();
500        for id in &self.order[start_index..=end_index] {
501            let Some(block) = self.blocks.get(id) else {
502                continue;
503            };
504            let handle = block.text.borrow();
505            let text = handle.text.as_str();
506            let range = if *id == start.block && *id == end.block {
507                clamp_boundary(text, start.offset)..clamp_boundary(text, end.offset)
508            } else if *id == start.block {
509                clamp_boundary(text, start.offset)..text.len()
510            } else if *id == end.block {
511                0..clamp_boundary(text, end.offset)
512            } else {
513                0..text.len()
514            };
515            if let Some(part) = text.get(range) {
516                parts.push(part.to_string());
517            }
518        }
519        parts.join("\n\n")
520    }
521
522    fn update_selection(&self, anchor: DocumentPoint, focus: DocumentPoint) {
523        let text = self.selection_text(anchor, focus);
524        self.state.set_selection(anchor, focus, text);
525    }
526
527    fn inline_at(&self, point: DocumentPoint) -> Option<PressedInline> {
528        let block = self.blocks.get(&point.block)?.value.get();
529        inline_targets(&block.kind)
530            .into_iter()
531            .find_map(|target| match target {
532                InlineTarget::Link {
533                    range, destination, ..
534                } if range.contains(&point.offset) => Some(PressedInline::Link(destination)),
535                InlineTarget::Image { range, image } if range.contains(&point.offset) => {
536                    Some(PressedInline::Image(image.source))
537                }
538                _ => None,
539            })
540    }
541
542    fn copy_selection(&self, ctx: &mut EventCtx) -> bool {
543        let Some(text) = self.state.selected_text() else {
544            return false;
545        };
546        ctx.set_clipboard_text(text);
547        true
548    }
549
550    fn select_all(&self) -> bool {
551        let first = self.order.iter().find_map(|id| {
552            self.blocks.get(id).and_then(|block| {
553                let handle = block.text.borrow();
554                (!handle.text.is_empty()).then_some(DocumentPoint {
555                    block: *id,
556                    offset: 0,
557                })
558            })
559        });
560        let last = self.order.iter().rev().find_map(|id| {
561            self.blocks.get(id).and_then(|block| {
562                let handle = block.text.borrow();
563                (!handle.text.is_empty()).then_some(DocumentPoint {
564                    block: *id,
565                    offset: handle.text.len(),
566                })
567            })
568        });
569        if let (Some(first), Some(last)) = (first, last) {
570            self.update_selection(first, last);
571            true
572        } else {
573            false
574        }
575    }
576}
577
578impl Widget for RichDocumentView {
579    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
580        if let Event::Pointer(pointer) = event
581            && ctx.phase() != EventPhase::Bubble
582        {
583            match pointer.kind {
584                PointerEventKind::Down
585                    if pointer.button == Some(PointerButton::Primary)
586                        && let Some(point) = self.point_at(pointer.position, true) =>
587                {
588                    let selection = self.state.selection();
589                    let anchor = if pointer.modifiers.shift {
590                        selection.anchor.unwrap_or(point)
591                    } else {
592                        point
593                    };
594                    self.dragging = true;
595                    self.drag_anchor = Some(anchor);
596                    self.pressed_inline = self.inline_at(point).map(|action| (point.block, action));
597                    self.update_selection(anchor, point);
598                    ctx.request_focus();
599                    ctx.request_pointer_capture(pointer.pointer_id);
600                    ctx.request_paint();
601                    ctx.request_semantics();
602                    ctx.set_handled();
603                }
604                PointerEventKind::Move
605                    if self.dragging
606                        && pointer.buttons.contains(PointerButton::Primary)
607                        && let (Some(anchor), Some(focus)) =
608                            (self.drag_anchor, self.point_at(pointer.position, false)) =>
609                {
610                    if focus != anchor {
611                        self.pressed_inline = None;
612                    }
613                    self.update_selection(anchor, focus);
614                    ctx.request_paint();
615                    ctx.request_semantics();
616                    ctx.set_handled();
617                }
618                PointerEventKind::Up
619                    if self.dragging && pointer.button == Some(PointerButton::Primary) =>
620                {
621                    let focus = self.point_at(pointer.position, false);
622                    let activate = self.pressed_inline.take().and_then(|(block, action)| {
623                        focus
624                            .filter(|point| point.block == block)
625                            .filter(|point| self.inline_at(*point).as_ref() == Some(&action))
626                            .map(|_| action)
627                    });
628                    self.dragging = false;
629                    self.drag_anchor = None;
630                    ctx.release_pointer_capture(pointer.pointer_id);
631                    match activate {
632                        Some(PressedInline::Link(destination)) => {
633                            if let Some(callback) = &self.on_link {
634                                (callback.borrow_mut())(&destination);
635                            }
636                        }
637                        Some(PressedInline::Image(source)) => {
638                            if let Some(callback) = &self.on_image {
639                                (callback.borrow_mut())(&source);
640                            }
641                        }
642                        None => {}
643                    }
644                    ctx.request_paint();
645                    ctx.request_semantics();
646                    ctx.set_handled();
647                }
648                PointerEventKind::Cancel if self.dragging => {
649                    self.dragging = false;
650                    self.drag_anchor = None;
651                    self.pressed_inline = None;
652                    ctx.release_pointer_capture(pointer.pointer_id);
653                    ctx.set_handled();
654                }
655                _ => {}
656            }
657            return;
658        }
659
660        match event {
661            Event::Keyboard(key) if ctx.is_focused() && key.state == KeyState::Pressed => {
662                let command = key.modifiers.control || key.modifiers.meta;
663                match key.key.as_str() {
664                    "a" | "A" if command => {
665                        if self.select_all() {
666                            ctx.request_paint();
667                            ctx.request_semantics();
668                            ctx.set_handled();
669                        }
670                    }
671                    "c" | "C" if command => {
672                        if self.copy_selection(ctx) {
673                            ctx.set_handled();
674                        }
675                    }
676                    "Escape" if self.state.clear_selection() => {
677                        ctx.request_paint();
678                        ctx.request_semantics();
679                        ctx.set_handled();
680                    }
681                    _ => {}
682                }
683            }
684            Event::Semantics(semantics)
685                if semantics.target == ctx.widget_id()
686                    && semantics.action == SemanticsActionRequest::Copy
687                    && self.copy_selection(ctx) =>
688            {
689                ctx.set_handled();
690            }
691            _ => {}
692        }
693    }
694
695    fn command(&mut self, ctx: &mut EventCtx, command: &Command<'_>) {
696        let Some(command) = TextCommand::from_command(command) else {
697            return;
698        };
699        match command {
700            TextCommand::Copy => {
701                if self.copy_selection(ctx) {
702                    ctx.set_handled();
703                }
704            }
705            TextCommand::SelectAll => {
706                if self.select_all() {
707                    ctx.request_paint();
708                    ctx.request_semantics();
709                    ctx.set_handled();
710                }
711            }
712            TextCommand::Cut | TextCommand::Paste => {}
713        }
714    }
715
716    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
717        let _ = ctx.observe(self.model.structure_observable());
718        self.sync_blocks();
719        let child_constraints =
720            Constraints::new(Size::ZERO, Size::new(constraints.max.width, f32::INFINITY));
721        let mut width = 0.0_f32;
722        let mut height = 0.0_f32;
723        for (index, id) in self.order.iter().enumerate() {
724            let Some(block) = self.blocks.get_mut(id) else {
725                continue;
726            };
727            let size = block.pod.measure(ctx, child_constraints);
728            width = width.max(size.width);
729            height += size.height;
730            self.measured_heights.insert(*id, size.height);
731            if index + 1 < self.order.len() {
732                height += BLOCK_GAP;
733            }
734        }
735        let selection = self.state.selection();
736        if let (Some(anchor), Some(focus)) = (selection.anchor, selection.focus) {
737            self.update_selection(anchor, focus);
738        }
739        constraints.clamp(Size::new(width, height))
740    }
741
742    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
743        let mut y = bounds.y();
744        for id in &self.order {
745            let height = self.measured_heights.get(id).copied().unwrap_or(0.0);
746            if let Some(block) = self.blocks.get_mut(id) {
747                block
748                    .pod
749                    .arrange(ctx, Rect::new(bounds.x(), y, bounds.width(), height));
750            }
751            y += height + BLOCK_GAP;
752        }
753    }
754
755    fn paint(&self, ctx: &mut PaintCtx) {
756        for id in &self.order {
757            if let Some(block) = self.blocks.get(id) {
758                block.pod.paint(ctx);
759            }
760        }
761    }
762
763    fn accepts_focus(&self) -> bool {
764        true
765    }
766
767    fn semantics(&self, ctx: &mut SemanticsCtx) {
768        let mut document =
769            SemanticsNode::new(ctx.widget_id(), SemanticsRole::Document, ctx.bounds());
770        document.name = Some("Rich document".to_string());
771        if self.state.selected_text().is_some() {
772            document.actions.push(SemanticsAction::Copy);
773        }
774        ctx.push(document);
775        for id in &self.order {
776            if let Some(block) = self.blocks.get(id) {
777                block.pod.semantics(ctx);
778            }
779        }
780    }
781
782    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
783        for id in &self.order {
784            if let Some(block) = self.blocks.get(id) {
785                visitor.visit(&block.pod);
786            }
787        }
788    }
789
790    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
791        for id in self.order.clone() {
792            if let Some(block) = self.blocks.get_mut(&id) {
793                visitor.visit(&mut block.pod);
794            }
795        }
796    }
797}
798
799#[derive(Clone, Debug, PartialEq, Eq, Hash)]
800enum SemanticPart {
801    Copy,
802    Link(usize),
803    Image(usize),
804    ListItem(usize),
805}
806
807#[derive(Clone)]
808enum InlineTarget {
809    Link {
810        range: Range<usize>,
811        destination: String,
812        label: String,
813    },
814    Image {
815        range: Range<usize>,
816        image: RichInlineImage,
817    },
818}
819
820struct DefaultBlockView {
821    block: Signal<RichDocumentBlock>,
822    state: RichDocumentViewState,
823    text_handle: Rc<RefCell<BlockTextHandle>>,
824    theme: DefaultTheme,
825    highlighter: Rc<dyn RichSyntaxHighlighter>,
826    layout: Option<PersistentTextLayout>,
827    semantic_ids: HashMap<SemanticPart, WidgetId>,
828    horizontal_offset: f32,
829    max_horizontal_offset: f32,
830    on_link: Option<StringAction>,
831    on_image: Option<StringAction>,
832    image_resolver: Option<ImageResolver>,
833    on_attachment: Option<BlockAction>,
834}
835
836impl DefaultBlockView {
837    #[allow(clippy::too_many_arguments)]
838    fn new(
839        block: Signal<RichDocumentBlock>,
840        state: RichDocumentViewState,
841        text_handle: Rc<RefCell<BlockTextHandle>>,
842        theme: DefaultTheme,
843        highlighter: Rc<dyn RichSyntaxHighlighter>,
844        on_link: Option<StringAction>,
845        on_image: Option<StringAction>,
846        image_resolver: Option<ImageResolver>,
847        on_attachment: Option<BlockAction>,
848    ) -> Self {
849        Self {
850            block,
851            state,
852            text_handle,
853            theme,
854            highlighter,
855            layout: None,
856            semantic_ids: HashMap::new(),
857            horizontal_offset: 0.0,
858            max_horizontal_offset: 0.0,
859            on_link,
860            on_image,
861            image_resolver,
862            on_attachment,
863        }
864    }
865
866    fn semantic_id(&mut self, part: SemanticPart) -> WidgetId {
867        *self
868            .semantic_ids
869            .entry(part)
870            .or_insert_with(next_semantic_id)
871    }
872
873    fn sync_semantic_ids(&mut self, block: &RichDocumentBlock) {
874        let mut live = HashSet::new();
875        for (index, target) in inline_targets(&block.kind).into_iter().enumerate() {
876            let part = match target {
877                InlineTarget::Link { .. } => SemanticPart::Link(index),
878                InlineTarget::Image { .. } => SemanticPart::Image(index),
879            };
880            live.insert(part.clone());
881            self.semantic_id(part);
882        }
883        if let RichDocumentBlockKind::List { items, .. } = &block.kind {
884            for index in 0..items.len() {
885                let part = SemanticPart::ListItem(index);
886                live.insert(part.clone());
887                self.semantic_id(part);
888            }
889        }
890        if matches!(block.kind, RichDocumentBlockKind::CodeBlock { .. }) {
891            live.insert(SemanticPart::Copy);
892            self.semantic_id(SemanticPart::Copy);
893        }
894        self.semantic_ids.retain(|part, _| live.contains(part));
895    }
896
897    fn text_insets(&self, kind: &RichDocumentBlockKind) -> (f32, f32, f32, f32) {
898        match kind {
899            RichDocumentBlockKind::BlockQuote { .. } => {
900                (QUOTE_INSET, TEXT_INSET, TEXT_INSET, TEXT_INSET)
901            }
902            RichDocumentBlockKind::CodeBlock { .. } => (
903                CODE_INSET,
904                CODE_HEADER_HEIGHT + CODE_INSET,
905                CODE_INSET,
906                CODE_INSET,
907            ),
908            RichDocumentBlockKind::Attachment(_) => (
909                STRUCTURED_INSET,
910                STRUCTURED_INSET,
911                STRUCTURED_INSET,
912                STRUCTURED_INSET,
913            ),
914            RichDocumentBlockKind::Extension(_) => (
915                STRUCTURED_INSET + 20.0,
916                STRUCTURED_INSET,
917                STRUCTURED_INSET,
918                STRUCTURED_INSET,
919            ),
920            RichDocumentBlockKind::ThematicBreak => (0.0, 0.0, 0.0, 0.0),
921            _ => (TEXT_INSET, TEXT_INSET, TEXT_INSET, TEXT_INSET),
922        }
923    }
924
925    fn layout_origin(&self, bounds: Rect, kind: &RichDocumentBlockKind) -> Point {
926        let (left, top, _, _) = self.text_insets(kind);
927        let layout_x = self
928            .layout
929            .as_ref()
930            .map(|layout| layout.measurement().bounds.x())
931            .unwrap_or(0.0);
932        Point::new(
933            bounds.x() + left - layout_x - self.horizontal_offset,
934            bounds.y() + top,
935        )
936    }
937
938    fn text_bounds(&self, bounds: Rect, kind: &RichDocumentBlockKind) -> Rect {
939        let (left, top, right, bottom) = self.text_insets(kind);
940        Rect::new(
941            bounds.x() + left,
942            bounds.y() + top,
943            (bounds.width() - left - right).max(0.0),
944            (bounds.height() - top - bottom).max(0.0),
945        )
946    }
947
948    fn selection_range(&self, block: RichBlockId, text_len: usize) -> Range<usize> {
949        let selection = self.state.selection();
950        selection_range_for(&selection, block, text_len)
951    }
952
953    fn status_colors(&self, status: RichDocumentStatus) -> (sui_core::Color, sui_core::Color) {
954        match status {
955            RichDocumentStatus::Neutral => (self.theme.palette.control, self.theme.palette.text),
956            RichDocumentStatus::Pending => (
957                self.theme.palette.control_hover,
958                self.theme.palette.text_muted,
959            ),
960            RichDocumentStatus::Running => (
961                self.theme.palette.info_soft,
962                self.theme.palette.info_soft_text,
963            ),
964            RichDocumentStatus::Success => (
965                self.theme.palette.success_soft,
966                self.theme.palette.success_soft_text,
967            ),
968            RichDocumentStatus::Warning => (
969                self.theme.palette.warning_soft,
970                self.theme.palette.warning_soft_text,
971            ),
972            RichDocumentStatus::Error => (
973                self.theme.palette.danger_soft,
974                self.theme.palette.danger_soft_text,
975            ),
976        }
977    }
978
979    fn invoke_semantic_target(
980        &mut self,
981        target: WidgetId,
982        action: &SemanticsActionRequest,
983        ctx: &mut EventCtx,
984    ) -> bool {
985        let block = self.block.get();
986        if self.semantic_ids.get(&SemanticPart::Copy) == Some(&target)
987            && *action == SemanticsActionRequest::Copy
988            && let RichDocumentBlockKind::CodeBlock { code, .. } = &block.kind
989        {
990            ctx.set_clipboard_text(code);
991            return true;
992        }
993        for (index, inline) in inline_targets(&block.kind).into_iter().enumerate() {
994            let part = match inline {
995                InlineTarget::Link { .. } => SemanticPart::Link(index),
996                InlineTarget::Image { .. } => SemanticPart::Image(index),
997            };
998            if self.semantic_ids.get(&part) != Some(&target)
999                || *action != SemanticsActionRequest::Activate
1000            {
1001                continue;
1002            }
1003            match inline {
1004                InlineTarget::Link { destination, .. } => {
1005                    if let Some(callback) = &self.on_link {
1006                        (callback.borrow_mut())(&destination);
1007                    }
1008                }
1009                InlineTarget::Image {
1010                    image: inline_image,
1011                    ..
1012                } => {
1013                    if let Some(callback) = &self.on_image {
1014                        (callback.borrow_mut())(&inline_image.source);
1015                    }
1016                }
1017            }
1018            return true;
1019        }
1020        false
1021    }
1022}
1023
1024impl Widget for DefaultBlockView {
1025    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
1026        if ctx.phase() == EventPhase::Capture {
1027            return;
1028        }
1029        let block = self.block.get();
1030        match event {
1031            Event::Pointer(pointer)
1032                if pointer.kind == PointerEventKind::Scroll
1033                    && ctx.bounds().contains(pointer.position)
1034                    && matches!(block.kind, RichDocumentBlockKind::CodeBlock { .. }) =>
1035            {
1036                let delta = pointer
1037                    .scroll_delta
1038                    .map(scroll_delta_to_offset)
1039                    .unwrap_or(pointer.delta);
1040                let axis = if delta.x.abs() > f32::EPSILON {
1041                    delta.x
1042                } else if pointer.modifiers.shift {
1043                    delta.y
1044                } else {
1045                    0.0
1046                };
1047                let next = (self.horizontal_offset - axis).clamp(0.0, self.max_horizontal_offset);
1048                if (next - self.horizontal_offset).abs() > f32::EPSILON {
1049                    self.horizontal_offset = next;
1050                    ctx.request_paint();
1051                    ctx.request_semantics();
1052                    ctx.set_handled();
1053                }
1054            }
1055            Event::Pointer(pointer)
1056                if pointer.kind == PointerEventKind::Down
1057                    && pointer.button == Some(PointerButton::Primary)
1058                    && matches!(block.kind, RichDocumentBlockKind::CodeBlock { .. })
1059                    && pointer.position.y <= ctx.bounds().y() + CODE_HEADER_HEIGHT
1060                    && pointer.position.x >= ctx.bounds().max_x() - 56.0 =>
1061            {
1062                if let RichDocumentBlockKind::CodeBlock { code, .. } = &block.kind {
1063                    ctx.set_clipboard_text(code);
1064                    ctx.set_handled();
1065                }
1066            }
1067            Event::Pointer(pointer)
1068                if pointer.kind == PointerEventKind::Down
1069                    && pointer.button == Some(PointerButton::Primary)
1070                    && matches!(block.kind, RichDocumentBlockKind::Attachment(_))
1071                    && ctx.bounds().contains(pointer.position) =>
1072            {
1073                if let Some(callback) = &self.on_attachment {
1074                    (callback.borrow_mut())(block.id);
1075                }
1076                ctx.set_handled();
1077            }
1078            Event::Pointer(pointer)
1079                if pointer.kind == PointerEventKind::Down
1080                    && pointer.button == Some(PointerButton::Primary)
1081                    && matches!(block.kind, RichDocumentBlockKind::Extension(_))
1082                    && ctx.bounds().contains(pointer.position) =>
1083            {
1084                if let RichDocumentBlockKind::Extension(extension) = &block.kind {
1085                    let current = self
1086                        .state
1087                        .inner
1088                        .borrow()
1089                        .expanded
1090                        .get(&block.id)
1091                        .copied()
1092                        .unwrap_or(extension.initially_expanded);
1093                    self.state.set_expanded(block.id, !current);
1094                }
1095                ctx.request_measure();
1096                ctx.request_paint();
1097                ctx.request_semantics();
1098                ctx.set_handled();
1099            }
1100            Event::Semantics(semantics) => {
1101                let handled = if semantics.target == ctx.widget_id() {
1102                    match (&block.kind, &semantics.action) {
1103                        (
1104                            RichDocumentBlockKind::Attachment(_),
1105                            SemanticsActionRequest::Activate,
1106                        ) => {
1107                            if let Some(callback) = &self.on_attachment {
1108                                (callback.borrow_mut())(block.id);
1109                            }
1110                            true
1111                        }
1112                        (RichDocumentBlockKind::Extension(_), SemanticsActionRequest::Expand) => {
1113                            self.state.set_expanded(block.id, true);
1114                            true
1115                        }
1116                        (RichDocumentBlockKind::Extension(_), SemanticsActionRequest::Collapse) => {
1117                            self.state.set_expanded(block.id, false);
1118                            true
1119                        }
1120                        _ => false,
1121                    }
1122                } else {
1123                    self.invoke_semantic_target(semantics.target, &semantics.action, ctx)
1124                };
1125                if handled {
1126                    ctx.request_measure();
1127                    ctx.request_paint();
1128                    ctx.request_semantics();
1129                    ctx.set_handled();
1130                }
1131            }
1132            _ => {}
1133        }
1134    }
1135
1136    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
1137        let block = ctx.observe(&self.block);
1138        let _ = ctx.observe(&self.state.revision);
1139        self.sync_semantic_ids(&block);
1140        if matches!(block.kind, RichDocumentBlockKind::ThematicBreak) {
1141            self.layout = None;
1142            let size = constraints.clamp(Size::new(constraints.max.width, 9.0));
1143            let mut handle = self.text_handle.borrow_mut();
1144            handle.text.clear();
1145            handle.layout = None;
1146            return size;
1147        }
1148
1149        let expanded = match &block.kind {
1150            RichDocumentBlockKind::Extension(extension) => self
1151                .state
1152                .inner
1153                .borrow()
1154                .expanded
1155                .get(&block.id)
1156                .copied()
1157                .unwrap_or(extension.initially_expanded),
1158            _ => false,
1159        };
1160        let document = block_document(&block.kind, self.theme, self.highlighter.as_ref(), expanded);
1161        let text = document.plain_text();
1162        let (left, top, right, bottom) = self.text_insets(&block.kind);
1163        let available_width = (constraints.max.width - left - right).max(1.0);
1164        let request = if matches!(block.kind, RichDocumentBlockKind::CodeBlock { .. }) {
1165            TextLayoutRequest::new(document)
1166        } else {
1167            TextLayoutRequest::new(document).with_box_size(Size::new(available_width, 1.0))
1168        };
1169        let handle = self.layout.as_ref().map(PersistentTextLayout::handle);
1170        self.layout = ctx
1171            .layout()
1172            .layout_document_persistent(handle, request)
1173            .ok();
1174        let (measured_width, measured_height) = self
1175            .layout
1176            .as_ref()
1177            .map(|layout| {
1178                let measurement = layout.measurement();
1179                (measurement.width, measurement.height)
1180            })
1181            .unwrap_or((0.0, 0.0));
1182        self.max_horizontal_offset =
1183            if matches!(block.kind, RichDocumentBlockKind::CodeBlock { .. }) {
1184                (measured_width - available_width).max(0.0)
1185            } else {
1186                0.0
1187            };
1188        self.horizontal_offset = self.horizontal_offset.min(self.max_horizontal_offset);
1189        let height = measured_height + top + bottom;
1190        let width = if constraints.max.width.is_finite() {
1191            constraints.max.width
1192        } else {
1193            measured_width + left + right
1194        };
1195        let size = constraints.clamp(Size::new(width, height));
1196        let mut shared = self.text_handle.borrow_mut();
1197        shared.text = text;
1198        shared.layout = self.layout.clone();
1199        size
1200    }
1201
1202    fn arrange(&mut self, _ctx: &mut ArrangeCtx, bounds: Rect) {
1203        let block = self.block.get();
1204        let mut shared = self.text_handle.borrow_mut();
1205        shared.bounds = self.text_bounds(bounds, &block.kind);
1206        shared.origin = self.layout_origin(bounds, &block.kind);
1207    }
1208
1209    fn paint(&self, ctx: &mut PaintCtx) {
1210        let block = self.block.get();
1211        let _ = self.state.revision.get();
1212        let bounds = ctx.bounds();
1213        match &block.kind {
1214            RichDocumentBlockKind::BlockQuote { .. } => {
1215                ctx.fill_rect(
1216                    Rect::new(bounds.x() + 2.0, bounds.y(), 3.0, bounds.height()),
1217                    self.theme.palette.accent,
1218                );
1219            }
1220            RichDocumentBlockKind::CodeBlock { language, .. } => {
1221                ctx.fill_rect(bounds, self.theme.surfaces.window_subtle);
1222                ctx.stroke_rect(
1223                    bounds,
1224                    self.theme.surfaces.border_subtle,
1225                    StrokeStyle::new(1.0),
1226                );
1227                ctx.fill_rect(
1228                    Rect::new(bounds.x(), bounds.y(), bounds.width(), CODE_HEADER_HEIGHT),
1229                    self.theme.surfaces.surface_2,
1230                );
1231                let mut label = self.theme.text_style(self.theme.palette.text_muted);
1232                label.font_size = (label.font_size - 2.0).max(10.0);
1233                ctx.draw_text(
1234                    Rect::new(
1235                        bounds.x() + CODE_INSET,
1236                        bounds.y() + 7.0,
1237                        (bounds.width() - 80.0).max(1.0),
1238                        label.line_height,
1239                    ),
1240                    language.as_deref().unwrap_or("plain text"),
1241                    label,
1242                );
1243                let mut action = self.theme.text_style(self.theme.palette.accent_soft_text);
1244                action.font_size = (action.font_size - 2.0).max(10.0);
1245                ctx.draw_text(
1246                    Rect::new(
1247                        bounds.max_x() - 42.0,
1248                        bounds.y() + 7.0,
1249                        38.0,
1250                        action.line_height,
1251                    ),
1252                    "Copy",
1253                    action,
1254                );
1255            }
1256            RichDocumentBlockKind::Attachment(_) => {
1257                ctx.fill_rect(bounds, self.theme.palette.control);
1258                ctx.stroke_rect(bounds, self.theme.palette.border, StrokeStyle::new(1.0));
1259            }
1260            RichDocumentBlockKind::Extension(extension) => {
1261                let (background, _) = self.status_colors(extension.status);
1262                ctx.fill_rect(bounds, background);
1263                ctx.stroke_rect(bounds, self.theme.palette.border, StrokeStyle::new(1.0));
1264                let expanded = self
1265                    .state
1266                    .inner
1267                    .borrow()
1268                    .expanded
1269                    .get(&block.id)
1270                    .copied()
1271                    .unwrap_or(extension.initially_expanded);
1272                let mut disclosure = self.theme.text_style(self.theme.palette.text_muted);
1273                disclosure.weight = FontWeight::SEMIBOLD;
1274                ctx.draw_text(
1275                    Rect::new(
1276                        bounds.x() + STRUCTURED_INSET,
1277                        bounds.y() + STRUCTURED_INSET,
1278                        16.0,
1279                        disclosure.line_height,
1280                    ),
1281                    if expanded { "▾" } else { "▸" },
1282                    disclosure,
1283                );
1284            }
1285            RichDocumentBlockKind::ThematicBreak => {
1286                ctx.fill_rect(
1287                    Rect::new(bounds.x(), bounds.y() + 4.0, bounds.width(), 1.0),
1288                    self.theme.palette.border,
1289                );
1290            }
1291            _ => {}
1292        }
1293
1294        let Some(layout) = &self.layout else {
1295            return;
1296        };
1297        let text_bounds = self.text_bounds(bounds, &block.kind);
1298        let origin = self.layout_origin(bounds, &block.kind);
1299        ctx.push_clip_rect(text_bounds);
1300        let selection = self.selection_range(block.id, layout.text().len());
1301        if !selection.is_empty() {
1302            for rect in layout.selection_rects(selection) {
1303                ctx.fill_rect(
1304                    rect.translate(origin.to_vector()),
1305                    self.theme.palette.selection,
1306                );
1307            }
1308        }
1309        ctx.draw_persistent_text_layout(origin, layout);
1310        if let Some(resolver) = &self.image_resolver {
1311            for target in inline_targets(&block.kind) {
1312                let InlineTarget::Image { range, image } = target else {
1313                    continue;
1314                };
1315                let Some(handle) = resolver(&image) else {
1316                    continue;
1317                };
1318                for rect in layout.selection_rects(range) {
1319                    let rect = rect.translate(origin.to_vector());
1320                    ctx.fill_rect(rect, self.theme.palette.surface);
1321                    ctx.draw_image(rect, handle);
1322                }
1323            }
1324        }
1325        ctx.pop_clip();
1326    }
1327
1328    fn semantics(&self, ctx: &mut SemanticsCtx) {
1329        let block = self.block.get();
1330        let _ = self.state.revision.get();
1331        let role = match block.kind {
1332            RichDocumentBlockKind::Paragraph { .. } => SemanticsRole::Paragraph,
1333            RichDocumentBlockKind::Heading { .. } => SemanticsRole::Heading,
1334            RichDocumentBlockKind::BlockQuote { .. } => SemanticsRole::GenericContainer,
1335            RichDocumentBlockKind::List { .. } => SemanticsRole::List,
1336            RichDocumentBlockKind::CodeBlock { .. } => SemanticsRole::Code,
1337            RichDocumentBlockKind::ThematicBreak => SemanticsRole::Separator,
1338            RichDocumentBlockKind::Attachment(_) => SemanticsRole::Attachment,
1339            RichDocumentBlockKind::Extension(_) => SemanticsRole::Status,
1340        };
1341        let mut node = SemanticsNode::new(ctx.widget_id(), role, ctx.bounds());
1342        node.name = Some(block.plain_text());
1343        match &block.kind {
1344            RichDocumentBlockKind::Heading { level, .. } => {
1345                node.description = Some(format!("Heading level {level}"));
1346            }
1347            RichDocumentBlockKind::CodeBlock { language, .. } => {
1348                node.description = Some(format!(
1349                    "{} code block",
1350                    language.as_deref().unwrap_or("Plain text")
1351                ));
1352            }
1353            RichDocumentBlockKind::Attachment(attachment) => {
1354                node.actions.push(SemanticsAction::Activate);
1355                node.description = attachment.description.clone().or_else(|| {
1356                    attachment
1357                        .media_type
1358                        .as_ref()
1359                        .map(|media_type| format!("Attachment, {media_type}"))
1360                });
1361            }
1362            RichDocumentBlockKind::Extension(extension) => {
1363                let expanded = self
1364                    .state
1365                    .inner
1366                    .borrow()
1367                    .expanded
1368                    .get(&block.id)
1369                    .copied()
1370                    .unwrap_or(extension.initially_expanded);
1371                node.name = Some(extension.title.clone());
1372                if expanded && !extension.body.is_empty() {
1373                    node.value = Some(SemanticsValue::Text(extension.body.clone()));
1374                }
1375                node.state.expanded = Some(expanded);
1376                node.state.busy = matches!(
1377                    extension.status,
1378                    RichDocumentStatus::Pending | RichDocumentStatus::Running
1379                );
1380                node.actions.push(if expanded {
1381                    SemanticsAction::Collapse
1382                } else {
1383                    SemanticsAction::Expand
1384                });
1385                node.description = extension.summary.clone();
1386            }
1387            _ => {}
1388        }
1389        ctx.push(node);
1390
1391        if let RichDocumentBlockKind::List { items, .. } = &block.kind {
1392            for (index, item) in items.iter().enumerate() {
1393                let Some(id) = self
1394                    .semantic_ids
1395                    .get(&SemanticPart::ListItem(index))
1396                    .copied()
1397                else {
1398                    continue;
1399                };
1400                let mut child = SemanticsNode::new(id, SemanticsRole::ListItem, ctx.bounds());
1401                child.parent = Some(ctx.widget_id());
1402                child.name = Some(item.plain_text());
1403                child.state.checked = item.checked.map(|checked| {
1404                    if checked {
1405                        sui_core::ToggleState::Checked
1406                    } else {
1407                        sui_core::ToggleState::Unchecked
1408                    }
1409                });
1410                ctx.push(child);
1411            }
1412        }
1413
1414        for (index, target) in inline_targets(&block.kind).into_iter().enumerate() {
1415            match target {
1416                InlineTarget::Link {
1417                    destination, label, ..
1418                } => {
1419                    let Some(id) = self.semantic_ids.get(&SemanticPart::Link(index)).copied()
1420                    else {
1421                        continue;
1422                    };
1423                    let mut link = SemanticsNode::new(id, SemanticsRole::Link, ctx.bounds());
1424                    link.parent = Some(ctx.widget_id());
1425                    link.name = Some(label);
1426                    link.value = Some(SemanticsValue::Text(destination));
1427                    link.actions.push(SemanticsAction::Activate);
1428                    ctx.push(link);
1429                }
1430                InlineTarget::Image {
1431                    image: inline_image,
1432                    ..
1433                } => {
1434                    let Some(id) = self.semantic_ids.get(&SemanticPart::Image(index)).copied()
1435                    else {
1436                        continue;
1437                    };
1438                    let mut image = SemanticsNode::new(id, SemanticsRole::Image, ctx.bounds());
1439                    image.parent = Some(ctx.widget_id());
1440                    image.name = Some(inline_image.alt);
1441                    image.value = Some(SemanticsValue::Text(inline_image.source));
1442                    image.actions.push(SemanticsAction::Activate);
1443                    ctx.push(image);
1444                }
1445            }
1446        }
1447
1448        if let RichDocumentBlockKind::CodeBlock { .. } = block.kind
1449            && let Some(id) = self.semantic_ids.get(&SemanticPart::Copy).copied()
1450        {
1451            let mut copy = SemanticsNode::new(
1452                id,
1453                SemanticsRole::Button,
1454                Rect::new(
1455                    ctx.bounds().max_x() - 52.0,
1456                    ctx.bounds().y(),
1457                    52.0,
1458                    CODE_HEADER_HEIGHT,
1459                ),
1460            );
1461            copy.parent = Some(ctx.widget_id());
1462            copy.name = Some("Copy code".to_string());
1463            copy.actions.push(SemanticsAction::Copy);
1464            ctx.push(copy);
1465        }
1466    }
1467}
1468
1469fn block_document(
1470    kind: &RichDocumentBlockKind,
1471    theme: DefaultTheme,
1472    highlighter: &dyn RichSyntaxHighlighter,
1473    expanded: bool,
1474) -> TextDocument {
1475    match kind {
1476        RichDocumentBlockKind::Paragraph { spans } => {
1477            document_from_spans(spans, theme.body_text_style(), theme)
1478        }
1479        RichDocumentBlockKind::Heading { level, spans } => {
1480            let mut style = theme.body_text_style();
1481            style.font_size *= match level {
1482                1 => 1.75,
1483                2 => 1.48,
1484                3 => 1.28,
1485                4 => 1.15,
1486                _ => 1.05,
1487            };
1488            style.line_height = style.font_size * 1.3;
1489            style.weight = FontWeight::BOLD;
1490            document_from_spans(spans, style, theme)
1491        }
1492        RichDocumentBlockKind::BlockQuote { spans, .. } => {
1493            let mut style = theme.body_text_style();
1494            style.color = theme.palette.text_muted;
1495            style.style = FontStyle::Italic;
1496            document_from_spans(spans, style, theme)
1497        }
1498        RichDocumentBlockKind::List { start, items } => {
1499            let mut spans = Vec::new();
1500            let mut next = start.unwrap_or(1);
1501            for (index, item) in items.iter().enumerate() {
1502                if index > 0 {
1503                    spans.push(TextSpan::new("\n", theme.body_text_style()));
1504                }
1505                let marker = match item.checked {
1506                    Some(true) => "☑ ".to_string(),
1507                    Some(false) => "☐ ".to_string(),
1508                    None if start.is_some() => {
1509                        let marker = format!("{next}. ");
1510                        next = next.saturating_add(1);
1511                        marker
1512                    }
1513                    None => "• ".to_string(),
1514                };
1515                let mut marker_style = theme.body_text_style();
1516                marker_style.color = theme.palette.text_muted;
1517                spans.push(TextSpan::new(marker, marker_style));
1518                spans.extend(styled_spans(&item.spans, theme.body_text_style(), theme));
1519            }
1520            document_from_text_spans(spans)
1521        }
1522        RichDocumentBlockKind::CodeBlock { language, code } => {
1523            let base = theme.mono_text_style(theme.palette.text);
1524            let highlights = highlighter.highlight(language.as_deref(), code);
1525            document_from_text_spans(syntax_spans(code, &highlights, base, theme))
1526        }
1527        RichDocumentBlockKind::ThematicBreak => TextDocument::new(),
1528        RichDocumentBlockKind::Attachment(attachment) => {
1529            let mut spans = vec![TextSpan::new(format!("📎 {}", attachment.name), {
1530                let mut style = theme.body_text_style();
1531                style.weight = FontWeight::SEMIBOLD;
1532                style
1533            })];
1534            if let Some(description) = &attachment.description {
1535                let mut style = theme.body_text_style();
1536                style.color = theme.palette.text_muted;
1537                spans.push(TextSpan::new(format!("\n{description}"), style));
1538            }
1539            document_from_text_spans(spans)
1540        }
1541        RichDocumentBlockKind::Extension(extension) => {
1542            let mut title = theme.body_text_style();
1543            title.weight = FontWeight::SEMIBOLD;
1544            let mut spans = vec![TextSpan::new(extension.title.clone(), title)];
1545            if let Some(summary) = &extension.summary {
1546                let mut style = theme.body_text_style();
1547                style.color = theme.palette.text_muted;
1548                spans.push(TextSpan::new(format!("\n{summary}"), style));
1549            }
1550            if expanded && !extension.body.is_empty() {
1551                spans.push(TextSpan::new(
1552                    format!("\n\n{}", extension.body),
1553                    theme.mono_text_style(theme.palette.text),
1554                ));
1555            }
1556            document_from_text_spans(spans)
1557        }
1558    }
1559}
1560
1561fn document_from_spans(
1562    spans: &[RichDocumentSpan],
1563    base: TextStyle,
1564    theme: DefaultTheme,
1565) -> TextDocument {
1566    document_from_text_spans(styled_spans(spans, base, theme))
1567}
1568
1569fn document_from_text_spans(spans: Vec<TextSpan>) -> TextDocument {
1570    let mut paragraphs = Vec::new();
1571    let mut current = Vec::new();
1572    let mut empty_line_style = spans
1573        .first()
1574        .map(|span| span.style.clone())
1575        .unwrap_or_default();
1576
1577    for span in spans {
1578        empty_line_style = span.style.clone();
1579        let mut remainder = span.text.as_str();
1580        while let Some(newline) = remainder.find('\n') {
1581            if newline > 0 {
1582                current.push(TextSpan::new(&remainder[..newline], span.style.clone()));
1583            }
1584            if current.is_empty() {
1585                current.push(TextSpan::new("", span.style.clone()));
1586            }
1587            paragraphs.push(TextParagraph::from_spans(std::mem::take(&mut current)));
1588            remainder = &remainder[newline + 1..];
1589        }
1590        if !remainder.is_empty() {
1591            current.push(TextSpan::new(remainder, span.style));
1592        }
1593    }
1594
1595    if current.is_empty() {
1596        current.push(TextSpan::new("", empty_line_style));
1597    }
1598    paragraphs.push(TextParagraph::from_spans(current));
1599    TextDocument { paragraphs }
1600}
1601
1602fn styled_spans(spans: &[RichDocumentSpan], base: TextStyle, theme: DefaultTheme) -> Vec<TextSpan> {
1603    spans
1604        .iter()
1605        .map(|span| {
1606            let mut style = base.clone();
1607            if span.style.strong {
1608                style.weight = FontWeight::BOLD;
1609            }
1610            if span.style.emphasis {
1611                style.style = FontStyle::Italic;
1612            }
1613            match &span.kind {
1614                RichInlineKind::Code => {
1615                    style.font_families = Some(theme.fonts.mono.into());
1616                    style.color = theme.palette.accent_soft_text;
1617                }
1618                RichInlineKind::Link(_) => {
1619                    style.color = theme.palette.accent_soft_text;
1620                    style.weight = FontWeight::SEMIBOLD;
1621                }
1622                RichInlineKind::Image(_) => {
1623                    style.color = theme.palette.text_muted;
1624                    style.style = FontStyle::Italic;
1625                }
1626                RichInlineKind::Text => {}
1627            }
1628            TextSpan::new(span.text.clone(), style)
1629        })
1630        .collect()
1631}
1632
1633fn syntax_spans(
1634    source: &str,
1635    highlights: &[RichSyntaxSpan],
1636    base: TextStyle,
1637    theme: DefaultTheme,
1638) -> Vec<TextSpan> {
1639    let mut highlights = highlights
1640        .iter()
1641        .filter_map(|span| {
1642            let start = clamp_boundary(source, span.range.start);
1643            let end = clamp_boundary(source, span.range.end).max(start);
1644            (start < end).then_some((start..end, span.kind))
1645        })
1646        .collect::<Vec<_>>();
1647    highlights.sort_by_key(|(range, _)| range.start);
1648    let mut output = Vec::new();
1649    let mut cursor = 0;
1650    for (range, kind) in highlights {
1651        if range.start < cursor {
1652            continue;
1653        }
1654        if cursor < range.start {
1655            output.push(TextSpan::new(&source[cursor..range.start], base.clone()));
1656        }
1657        let mut style = base.clone();
1658        style.color = syntax_color(theme, kind);
1659        output.push(TextSpan::new(&source[range.clone()], style));
1660        cursor = range.end;
1661    }
1662    if cursor < source.len() {
1663        output.push(TextSpan::new(&source[cursor..], base.clone()));
1664    }
1665    if output.is_empty() {
1666        output.push(TextSpan::new(source, base));
1667    }
1668    output
1669}
1670
1671fn syntax_color(theme: DefaultTheme, kind: RichSyntaxTokenKind) -> sui_core::Color {
1672    match kind {
1673        RichSyntaxTokenKind::Keyword | RichSyntaxTokenKind::Header => {
1674            theme.palette.accent_soft_text
1675        }
1676        RichSyntaxTokenKind::String | RichSyntaxTokenKind::Added => theme.palette.success_text,
1677        RichSyntaxTokenKind::Number | RichSyntaxTokenKind::Property => theme.palette.info_text,
1678        RichSyntaxTokenKind::Comment => theme.palette.text_muted,
1679        RichSyntaxTokenKind::Type | RichSyntaxTokenKind::Function => theme.palette.warning_text,
1680        RichSyntaxTokenKind::Removed => theme.palette.danger_text,
1681    }
1682}
1683
1684fn inline_targets(kind: &RichDocumentBlockKind) -> Vec<InlineTarget> {
1685    let spans = match kind {
1686        RichDocumentBlockKind::Paragraph { spans }
1687        | RichDocumentBlockKind::Heading { spans, .. }
1688        | RichDocumentBlockKind::BlockQuote { spans, .. } => {
1689            spans.iter().map(|span| (span, 0_usize)).collect::<Vec<_>>()
1690        }
1691        RichDocumentBlockKind::List { start, items } => {
1692            let mut offset = 0;
1693            let mut next = start.unwrap_or(1);
1694            let mut flattened = Vec::new();
1695            for (item_index, item) in items.iter().enumerate() {
1696                if item_index > 0 {
1697                    offset += 1;
1698                }
1699                offset += match item.checked {
1700                    Some(_) => "☐ ".len(),
1701                    None if start.is_some() => {
1702                        let len = format!("{next}. ").len();
1703                        next = next.saturating_add(1);
1704                        len
1705                    }
1706                    None => "• ".len(),
1707                };
1708                for span in &item.spans {
1709                    flattened.push((span, offset));
1710                    offset += span.text.len();
1711                }
1712            }
1713            flattened
1714        }
1715        _ => Vec::new(),
1716    };
1717    let mut offset = 0;
1718    let mut targets = Vec::new();
1719    for (span, explicit_offset) in spans {
1720        if explicit_offset > 0 {
1721            offset = explicit_offset;
1722        }
1723        let range = offset..offset + span.text.len();
1724        match &span.kind {
1725            RichInlineKind::Link(link) => targets.push(InlineTarget::Link {
1726                range,
1727                destination: link.destination.clone(),
1728                label: span.text.clone(),
1729            }),
1730            RichInlineKind::Image(image) => targets.push(InlineTarget::Image {
1731                range,
1732                image: image.clone(),
1733            }),
1734            RichInlineKind::Text | RichInlineKind::Code => {}
1735        }
1736        offset += span.text.len();
1737    }
1738    targets
1739}
1740
1741fn selection_range_for(
1742    selection: &DocumentSelection,
1743    block: RichBlockId,
1744    text_len: usize,
1745) -> Range<usize> {
1746    let (Some(anchor), Some(focus)) = (selection.anchor, selection.focus) else {
1747        return 0..0;
1748    };
1749    let Some(anchor_index) = selection.order.iter().position(|id| *id == anchor.block) else {
1750        return 0..0;
1751    };
1752    let Some(focus_index) = selection.order.iter().position(|id| *id == focus.block) else {
1753        return 0..0;
1754    };
1755    let Some(block_index) = selection.order.iter().position(|id| *id == block) else {
1756        return 0..0;
1757    };
1758    let ((start_index, start_offset), (end_index, end_offset)) =
1759        if (anchor_index, anchor.offset) <= (focus_index, focus.offset) {
1760            ((anchor_index, anchor.offset), (focus_index, focus.offset))
1761        } else {
1762            ((focus_index, focus.offset), (anchor_index, anchor.offset))
1763        };
1764    if block_index < start_index || block_index > end_index {
1765        return 0..0;
1766    }
1767    let start = if block_index == start_index {
1768        start_offset.min(text_len)
1769    } else {
1770        0
1771    };
1772    let end = if block_index == end_index {
1773        end_offset.min(text_len)
1774    } else {
1775        text_len
1776    };
1777    start.min(end)..end.max(start)
1778}
1779
1780fn clamp_boundary(text: &str, offset: usize) -> usize {
1781    let mut offset = offset.min(text.len());
1782    while !text.is_char_boundary(offset) {
1783        offset = offset.saturating_sub(1);
1784    }
1785    offset
1786}
1787
1788fn scroll_delta_to_offset(delta: ScrollDelta) -> Vector {
1789    match delta {
1790        ScrollDelta::Lines(delta) => Vector::new(delta.x * 40.0, delta.y * 40.0),
1791        ScrollDelta::Pixels(delta) => delta,
1792    }
1793}
1794
1795fn next_semantic_id() -> WidgetId {
1796    WidgetId::new(SYNTHETIC_RICH_DOCUMENT_TAG | NEXT_SYNTHETIC_ID.fetch_add(1, Ordering::Relaxed))
1797}
1798
1799#[cfg(test)]
1800mod tests {
1801    use std::{cell::Cell, cell::RefCell, rc::Rc};
1802
1803    use sui_core::{
1804        Event, ImageHandle, Point, PointerButton, PointerButtons, PointerEvent, PointerEventKind,
1805        ScrollDelta, SemanticsAction, SemanticsActionRequest, SemanticsNode, SemanticsRole,
1806        SemanticsValue, Size, Vector, WindowEvent,
1807    };
1808    use sui_layout::Constraints;
1809    use sui_reactive::Signal;
1810    use sui_runtime::{
1811        Application, CommandDelivery, CommandTarget, MeasureCtx, Runtime, SemanticsCtx, Widget,
1812        WindowBuilder,
1813    };
1814    use sui_scene::{RegisteredImage, SceneCommand};
1815
1816    use super::{
1817        RichDocumentBlock, RichDocumentBlockKind, RichDocumentModel, RichDocumentRenderContext,
1818        RichDocumentRendererRegistry, RichDocumentView, RichDocumentViewState,
1819    };
1820    use crate::{RichAttachment, RichExtensionBlock, TEXT_COMMAND, TextCommand};
1821
1822    fn runtime<W>(root: W) -> (Runtime, sui_core::WindowId)
1823    where
1824        W: Widget + 'static,
1825    {
1826        let runtime = Application::new()
1827            .window(WindowBuilder::new().title("Rich document").root(root))
1828            .build()
1829            .expect("rich document runtime should build");
1830        let window_id = runtime.window_ids()[0];
1831        (runtime, window_id)
1832    }
1833
1834    fn node<'a>(nodes: &'a [SemanticsNode], role: SemanticsRole, name: &str) -> &'a SemanticsNode {
1835        nodes
1836            .iter()
1837            .find(|node| node.role == role && node.name.as_deref() == Some(name))
1838            .unwrap_or_else(|| panic!("missing {role:?} semantics named {name:?}"))
1839    }
1840
1841    fn primary_pointer(kind: PointerEventKind, position: Point, pressed: bool) -> Event {
1842        let mut pointer = PointerEvent::new(kind, position);
1843        pointer.pointer_id = 7;
1844        pointer.button = Some(PointerButton::Primary);
1845        pointer.buttons = if pressed {
1846            PointerButtons::new(1)
1847        } else {
1848            PointerButtons::NONE
1849        };
1850        Event::Pointer(pointer)
1851    }
1852
1853    #[test]
1854    fn streaming_append_retains_completed_block_widget_identity() {
1855        let model = RichDocumentModel::from_markdown("# Stable\n\nStreaming");
1856        let (mut runtime, window_id) = runtime(RichDocumentView::new(model.clone()));
1857        let first = runtime.render(window_id).unwrap();
1858        let heading_id = node(&first.semantics, SemanticsRole::Heading, "Stable").id;
1859        let paragraph_id = node(&first.semantics, SemanticsRole::Paragraph, "Streaming").id;
1860
1861        model.append_markdown(" text\n\n- next");
1862        let second = runtime.render(window_id).unwrap();
1863        assert_eq!(
1864            node(&second.semantics, SemanticsRole::Heading, "Stable").id,
1865            heading_id
1866        );
1867        assert_eq!(
1868            node(
1869                &second.semantics,
1870                SemanticsRole::Paragraph,
1871                "Streaming text"
1872            )
1873            .id,
1874            paragraph_id
1875        );
1876        assert!(
1877            second
1878                .semantics
1879                .iter()
1880                .any(|node| node.role == SemanticsRole::List)
1881        );
1882    }
1883
1884    #[test]
1885    fn document_semantics_expose_links_images_code_status_and_attachments() {
1886        let model = RichDocumentModel::from_markdown(
1887            "# Report\n\nRead [docs](https://example.test) and ![plot](plot.png).\n\n- one\n- [x] two\n\n```rust\nlet n = 42;\n```",
1888        );
1889        model.append_attachment(RichAttachment::new("results.csv"));
1890        let mut extension = RichExtensionBlock::new("tool-call", "Search");
1891        extension.summary = Some("3 results".to_string());
1892        extension.body = "structured payload".to_string();
1893        model.append_extension(extension);
1894
1895        let opened = Rc::new(RefCell::new(Vec::new()));
1896        let opened_link = Rc::clone(&opened);
1897        let images = Rc::new(RefCell::new(Vec::new()));
1898        let opened_image = Rc::clone(&images);
1899        let (mut runtime, window_id) = runtime(
1900            RichDocumentView::new(model)
1901                .on_link(move |destination| opened_link.borrow_mut().push(destination.to_string()))
1902                .on_image(move |source| opened_image.borrow_mut().push(source.to_string())),
1903        );
1904        let first = runtime.render(window_id).unwrap();
1905        assert!(
1906            first
1907                .semantics
1908                .iter()
1909                .any(|node| node.role == SemanticsRole::Document)
1910        );
1911        assert!(
1912            first
1913                .semantics
1914                .iter()
1915                .any(|node| node.role == SemanticsRole::ListItem && node.state.checked.is_some())
1916        );
1917        assert!(
1918            first
1919                .semantics
1920                .iter()
1921                .any(|node| node.role == SemanticsRole::Attachment)
1922        );
1923
1924        let link = node(&first.semantics, SemanticsRole::Link, "docs");
1925        assert_eq!(
1926            link.value,
1927            Some(SemanticsValue::Text("https://example.test".to_string()))
1928        );
1929        let link_id = link.id;
1930        let image_id = node(&first.semantics, SemanticsRole::Image, "plot").id;
1931        let copy = node(&first.semantics, SemanticsRole::Button, "Copy code");
1932        assert!(copy.actions.contains(&SemanticsAction::Copy));
1933        let copy_id = copy.id;
1934        let status = node(&first.semantics, SemanticsRole::Status, "Search");
1935        assert_eq!(status.state.expanded, Some(false));
1936        let status_id = status.id;
1937
1938        assert!(
1939            runtime
1940                .handle_semantics_action(window_id, link_id, SemanticsActionRequest::Activate)
1941                .unwrap()
1942        );
1943        assert!(
1944            runtime
1945                .handle_semantics_action(window_id, image_id, SemanticsActionRequest::Activate)
1946                .unwrap()
1947        );
1948        assert_eq!(opened.borrow().as_slice(), &["https://example.test"]);
1949        assert_eq!(images.borrow().as_slice(), &["plot.png"]);
1950
1951        assert!(
1952            runtime
1953                .handle_semantics_action(window_id, copy_id, SemanticsActionRequest::Copy)
1954                .unwrap()
1955        );
1956        assert_eq!(runtime.clipboard().text().as_deref(), Some("let n = 42;\n"));
1957
1958        assert!(
1959            runtime
1960                .handle_semantics_action(window_id, status_id, SemanticsActionRequest::Expand)
1961                .unwrap()
1962        );
1963        let expanded = runtime.render(window_id).unwrap();
1964        let status = node(&expanded.semantics, SemanticsRole::Status, "Search");
1965        assert_eq!(status.id, status_id);
1966        assert_eq!(status.state.expanded, Some(true));
1967        assert_eq!(
1968            status.value,
1969            Some(SemanticsValue::Text("structured payload".to_string()))
1970        );
1971    }
1972
1973    #[test]
1974    fn overflowing_code_block_scrolls_horizontally() {
1975        let model = RichDocumentModel::from_markdown(
1976            "```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```",
1977        );
1978        let (mut runtime, window_id) = runtime(RichDocumentView::new(model));
1979        runtime
1980            .handle_event(
1981                window_id,
1982                Event::Window(WindowEvent::Resized(Size::new(320.0, 240.0))),
1983            )
1984            .unwrap();
1985        let first = runtime.render(window_id).unwrap();
1986        let code = first
1987            .semantics
1988            .iter()
1989            .find(|node| node.role == SemanticsRole::Code)
1990            .expect("code semantics");
1991        assert!(
1992            code.bounds.height() > 100.0,
1993            "multiline code should retain every visual line, bounds={:?}",
1994            code.bounds
1995        );
1996        let first_origin = first
1997            .frame
1998            .scene
1999            .commands()
2000            .iter()
2001            .filter_map(|command| match command {
2002                SceneCommand::DrawShapedText(text) => Some(text),
2003                _ => None,
2004            })
2005            .max_by(|left, right| left.bounds.width().total_cmp(&right.bounds.width()))
2006            .map(|text| text.origin)
2007            .expect("code text draw");
2008
2009        let code_center = Point::new(
2010            code.bounds.x() + code.bounds.width() * 0.5,
2011            code.bounds.y() + code.bounds.height() * 0.5,
2012        );
2013        let mut scroll = PointerEvent::new(PointerEventKind::Scroll, code_center);
2014        scroll.scroll_delta = Some(ScrollDelta::Pixels(Vector::new(-180.0, 0.0)));
2015        runtime
2016            .handle_event(window_id, Event::Pointer(scroll))
2017            .unwrap();
2018        let second = runtime.render(window_id).unwrap();
2019        let second_origin = second
2020            .frame
2021            .scene
2022            .commands()
2023            .iter()
2024            .filter_map(|command| match command {
2025                SceneCommand::DrawShapedText(text) => Some(text),
2026                _ => None,
2027            })
2028            .max_by(|left, right| left.bounds.width().total_cmp(&right.bounds.width()))
2029            .map(|text| text.origin)
2030            .expect("scrolled code text draw");
2031
2032        assert!(
2033            second_origin.x < first_origin.x,
2034            "expected code origin to move left, before={first_origin:?}, after={second_origin:?}"
2035        );
2036    }
2037
2038    #[test]
2039    fn inline_image_resolver_paints_registered_image() {
2040        let handle = ImageHandle::new(71);
2041        let model = RichDocumentModel::from_markdown("![plot](asset:plot)");
2042        let mut application = Application::new();
2043        application
2044            .register_image(
2045                handle,
2046                RegisteredImage::from_rgba8(8, 8, vec![255; 8 * 8 * 4]).unwrap(),
2047            )
2048            .unwrap();
2049        let mut runtime =
2050            application
2051                .window(WindowBuilder::new().title("Inline image").root(
2052                    RichDocumentView::new(model).image_resolver(move |image| {
2053                        (image.source == "asset:plot").then_some(handle)
2054                    }),
2055                ))
2056                .build()
2057                .unwrap();
2058        let output = runtime.render(runtime.window_ids()[0]).unwrap();
2059        let mut draws = 0;
2060        output.frame.scene.visit_commands(&mut |command| {
2061            if matches!(command, SceneCommand::DrawImage { source, .. } if source.image == handle) {
2062                draws += 1;
2063            }
2064        });
2065        assert_eq!(draws, 1);
2066    }
2067
2068    #[test]
2069    fn pointer_drag_selects_text_across_multiple_blocks() {
2070        let model = RichDocumentModel::from_markdown("# First block\n\nSecond block");
2071        let state = RichDocumentViewState::new();
2072        let (mut runtime, window_id) = runtime(RichDocumentView::new(model).state(state.clone()));
2073        let first = runtime.render(window_id).unwrap();
2074        let heading = node(&first.semantics, SemanticsRole::Heading, "First block");
2075        let paragraph = node(&first.semantics, SemanticsRole::Paragraph, "Second block");
2076        let start = Point::new(heading.bounds.x() + 4.0, heading.bounds.y() + 4.0);
2077        let end = Point::new(
2078            paragraph.bounds.max_x() - 4.0,
2079            paragraph.bounds.y() + paragraph.bounds.height() * 0.5,
2080        );
2081
2082        runtime
2083            .handle_event(
2084                window_id,
2085                primary_pointer(PointerEventKind::Down, start, true),
2086            )
2087            .unwrap();
2088        runtime
2089            .handle_event(
2090                window_id,
2091                primary_pointer(PointerEventKind::Move, end, true),
2092            )
2093            .unwrap();
2094        runtime
2095            .handle_event(window_id, primary_pointer(PointerEventKind::Up, end, false))
2096            .unwrap();
2097
2098        let selected = state.selected_text().expect("cross-block selection");
2099        assert!(selected.contains("First block"), "selected {selected:?}");
2100        assert!(selected.contains("Second block"), "selected {selected:?}");
2101
2102        runtime.handle_command(
2103            CommandTarget::FocusedWidget(window_id),
2104            CommandDelivery::Directed,
2105            TEXT_COMMAND,
2106            TextCommand::Copy,
2107        );
2108        assert_eq!(
2109            runtime.clipboard().text().as_deref(),
2110            Some(selected.as_str())
2111        );
2112    }
2113
2114    struct ExtensionProbe {
2115        block: Signal<RichDocumentBlock>,
2116        measures: Option<Rc<Cell<usize>>>,
2117    }
2118
2119    impl Widget for ExtensionProbe {
2120        fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
2121            let _ = ctx.observe(&self.block);
2122            if let Some(measures) = &self.measures {
2123                measures.set(measures.get() + 1);
2124            }
2125            constraints.clamp(Size::new(160.0, 32.0))
2126        }
2127
2128        fn semantics(&self, ctx: &mut SemanticsCtx) {
2129            let block = self.block.get();
2130            let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Status, ctx.bounds());
2131            node.name = Some(format!("Custom: {}", block.plain_text()));
2132            ctx.push(node);
2133        }
2134    }
2135
2136    #[test]
2137    fn extension_registry_updates_payload_without_replacing_renderer_widget() {
2138        let registry = RichDocumentRendererRegistry::new();
2139        registry.register(
2140            "extension:tool-call",
2141            |context: RichDocumentRenderContext| ExtensionProbe {
2142                block: context.block,
2143                measures: None,
2144            },
2145        );
2146        let model = RichDocumentModel::new();
2147        let id = model.append_extension(RichExtensionBlock::new("tool-call", "Pending"));
2148        let (mut runtime, window_id) =
2149            runtime(RichDocumentView::new(model.clone()).renderer_registry(registry));
2150        let first = runtime.render(window_id).unwrap();
2151        let widget_id = node(&first.semantics, SemanticsRole::Status, "Custom: Pending").id;
2152
2153        let mut completed = RichExtensionBlock::new("tool-call", "Complete");
2154        completed.body = "42".to_string();
2155        assert!(model.update_structured(id, RichDocumentBlockKind::Extension(completed)));
2156        let second = runtime.render(window_id).unwrap();
2157        assert_eq!(
2158            node(
2159                &second.semantics,
2160                SemanticsRole::Status,
2161                "Custom: Complete\n42"
2162            )
2163            .id,
2164            widget_id
2165        );
2166    }
2167
2168    #[test]
2169    fn tail_update_does_not_remeasure_retained_prefix_renderer() {
2170        let registry = RichDocumentRendererRegistry::new();
2171        let measures = Rc::new(Cell::new(0));
2172        let renderer_measures = Rc::clone(&measures);
2173        registry.register(
2174            "extension:tool-call",
2175            move |context: RichDocumentRenderContext| ExtensionProbe {
2176                block: context.block,
2177                measures: Some(Rc::clone(&renderer_measures)),
2178            },
2179        );
2180        let model = RichDocumentModel::new();
2181        model.append_extension(RichExtensionBlock::new("tool-call", "Stable prefix"));
2182        model.append_markdown("Streaming");
2183        let (mut runtime, window_id) =
2184            runtime(RichDocumentView::new(model.clone()).renderer_registry(registry));
2185        runtime.render(window_id).unwrap();
2186        let initial_measures = measures.get();
2187
2188        model.append_markdown(" tail");
2189        runtime.render(window_id).unwrap();
2190        assert_eq!(measures.get(), initial_measures);
2191    }
2192}