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, ThemeTextToken};
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 label = code_header_language_text_style(self.theme);
1232                ctx.draw_text(
1233                    Rect::new(
1234                        bounds.x() + CODE_INSET,
1235                        bounds.y() + 7.0,
1236                        (bounds.width() - 80.0).max(1.0),
1237                        label.line_height,
1238                    ),
1239                    language.as_deref().unwrap_or("plain text"),
1240                    label,
1241                );
1242                let action = code_header_action_text_style(self.theme);
1243                ctx.draw_text(
1244                    Rect::new(
1245                        bounds.max_x() - 42.0,
1246                        bounds.y() + 7.0,
1247                        38.0,
1248                        action.line_height,
1249                    ),
1250                    "Copy",
1251                    action,
1252                );
1253            }
1254            RichDocumentBlockKind::Attachment(_) => {
1255                ctx.fill_rect(bounds, self.theme.palette.control);
1256                ctx.stroke_rect(bounds, self.theme.palette.border, StrokeStyle::new(1.0));
1257            }
1258            RichDocumentBlockKind::Extension(extension) => {
1259                let (background, _) = self.status_colors(extension.status);
1260                ctx.fill_rect(bounds, background);
1261                ctx.stroke_rect(bounds, self.theme.palette.border, StrokeStyle::new(1.0));
1262                let expanded = self
1263                    .state
1264                    .inner
1265                    .borrow()
1266                    .expanded
1267                    .get(&block.id)
1268                    .copied()
1269                    .unwrap_or(extension.initially_expanded);
1270                let mut disclosure = self.theme.text_style(self.theme.palette.text_muted);
1271                disclosure.weight = FontWeight::SEMIBOLD;
1272                ctx.draw_text(
1273                    Rect::new(
1274                        bounds.x() + STRUCTURED_INSET,
1275                        bounds.y() + STRUCTURED_INSET,
1276                        16.0,
1277                        disclosure.line_height,
1278                    ),
1279                    if expanded { "▾" } else { "▸" },
1280                    disclosure,
1281                );
1282            }
1283            RichDocumentBlockKind::ThematicBreak => {
1284                ctx.fill_rect(
1285                    Rect::new(bounds.x(), bounds.y() + 4.0, bounds.width(), 1.0),
1286                    self.theme.palette.border,
1287                );
1288            }
1289            _ => {}
1290        }
1291
1292        let Some(layout) = &self.layout else {
1293            return;
1294        };
1295        let text_bounds = self.text_bounds(bounds, &block.kind);
1296        let origin = self.layout_origin(bounds, &block.kind);
1297        ctx.push_clip_rect(text_bounds);
1298        let selection = self.selection_range(block.id, layout.text().len());
1299        if !selection.is_empty() {
1300            for rect in layout.selection_rects(selection) {
1301                ctx.fill_rect(
1302                    rect.translate(origin.to_vector()),
1303                    self.theme.palette.selection,
1304                );
1305            }
1306        }
1307        ctx.draw_persistent_text_layout(origin, layout);
1308        if let Some(resolver) = &self.image_resolver {
1309            for target in inline_targets(&block.kind) {
1310                let InlineTarget::Image { range, image } = target else {
1311                    continue;
1312                };
1313                let Some(handle) = resolver(&image) else {
1314                    continue;
1315                };
1316                for rect in layout.selection_rects(range) {
1317                    let rect = rect.translate(origin.to_vector());
1318                    ctx.fill_rect(rect, self.theme.palette.surface);
1319                    ctx.draw_image(rect, handle);
1320                }
1321            }
1322        }
1323        ctx.pop_clip();
1324    }
1325
1326    fn semantics(&self, ctx: &mut SemanticsCtx) {
1327        let block = self.block.get();
1328        let _ = self.state.revision.get();
1329        let role = match block.kind {
1330            RichDocumentBlockKind::Paragraph { .. } => SemanticsRole::Paragraph,
1331            RichDocumentBlockKind::Heading { .. } => SemanticsRole::Heading,
1332            RichDocumentBlockKind::BlockQuote { .. } => SemanticsRole::GenericContainer,
1333            RichDocumentBlockKind::List { .. } => SemanticsRole::List,
1334            RichDocumentBlockKind::CodeBlock { .. } => SemanticsRole::Code,
1335            RichDocumentBlockKind::ThematicBreak => SemanticsRole::Separator,
1336            RichDocumentBlockKind::Attachment(_) => SemanticsRole::Attachment,
1337            RichDocumentBlockKind::Extension(_) => SemanticsRole::Status,
1338        };
1339        let mut node = SemanticsNode::new(ctx.widget_id(), role, ctx.bounds());
1340        node.name = Some(block.plain_text());
1341        match &block.kind {
1342            RichDocumentBlockKind::Heading { level, .. } => {
1343                node.description = Some(format!("Heading level {level}"));
1344            }
1345            RichDocumentBlockKind::CodeBlock { language, .. } => {
1346                node.description = Some(format!(
1347                    "{} code block",
1348                    language.as_deref().unwrap_or("Plain text")
1349                ));
1350            }
1351            RichDocumentBlockKind::Attachment(attachment) => {
1352                node.actions.push(SemanticsAction::Activate);
1353                node.description = attachment.description.clone().or_else(|| {
1354                    attachment
1355                        .media_type
1356                        .as_ref()
1357                        .map(|media_type| format!("Attachment, {media_type}"))
1358                });
1359            }
1360            RichDocumentBlockKind::Extension(extension) => {
1361                let expanded = self
1362                    .state
1363                    .inner
1364                    .borrow()
1365                    .expanded
1366                    .get(&block.id)
1367                    .copied()
1368                    .unwrap_or(extension.initially_expanded);
1369                node.name = Some(extension.title.clone());
1370                if expanded && !extension.body.is_empty() {
1371                    node.value = Some(SemanticsValue::Text(extension.body.clone()));
1372                }
1373                node.state.expanded = Some(expanded);
1374                node.state.busy = matches!(
1375                    extension.status,
1376                    RichDocumentStatus::Pending | RichDocumentStatus::Running
1377                );
1378                node.actions.push(if expanded {
1379                    SemanticsAction::Collapse
1380                } else {
1381                    SemanticsAction::Expand
1382                });
1383                node.description = extension.summary.clone();
1384            }
1385            _ => {}
1386        }
1387        ctx.push(node);
1388
1389        if let RichDocumentBlockKind::List { items, .. } = &block.kind {
1390            for (index, item) in items.iter().enumerate() {
1391                let Some(id) = self
1392                    .semantic_ids
1393                    .get(&SemanticPart::ListItem(index))
1394                    .copied()
1395                else {
1396                    continue;
1397                };
1398                let mut child = SemanticsNode::new(id, SemanticsRole::ListItem, ctx.bounds());
1399                child.parent = Some(ctx.widget_id());
1400                child.name = Some(item.plain_text());
1401                child.state.checked = item.checked.map(|checked| {
1402                    if checked {
1403                        sui_core::ToggleState::Checked
1404                    } else {
1405                        sui_core::ToggleState::Unchecked
1406                    }
1407                });
1408                ctx.push(child);
1409            }
1410        }
1411
1412        for (index, target) in inline_targets(&block.kind).into_iter().enumerate() {
1413            match target {
1414                InlineTarget::Link {
1415                    destination, label, ..
1416                } => {
1417                    let Some(id) = self.semantic_ids.get(&SemanticPart::Link(index)).copied()
1418                    else {
1419                        continue;
1420                    };
1421                    let mut link = SemanticsNode::new(id, SemanticsRole::Link, ctx.bounds());
1422                    link.parent = Some(ctx.widget_id());
1423                    link.name = Some(label);
1424                    link.value = Some(SemanticsValue::Text(destination));
1425                    link.actions.push(SemanticsAction::Activate);
1426                    ctx.push(link);
1427                }
1428                InlineTarget::Image {
1429                    image: inline_image,
1430                    ..
1431                } => {
1432                    let Some(id) = self.semantic_ids.get(&SemanticPart::Image(index)).copied()
1433                    else {
1434                        continue;
1435                    };
1436                    let mut image = SemanticsNode::new(id, SemanticsRole::Image, ctx.bounds());
1437                    image.parent = Some(ctx.widget_id());
1438                    image.name = Some(inline_image.alt);
1439                    image.value = Some(SemanticsValue::Text(inline_image.source));
1440                    image.actions.push(SemanticsAction::Activate);
1441                    ctx.push(image);
1442                }
1443            }
1444        }
1445
1446        if let RichDocumentBlockKind::CodeBlock { .. } = block.kind
1447            && let Some(id) = self.semantic_ids.get(&SemanticPart::Copy).copied()
1448        {
1449            let mut copy = SemanticsNode::new(
1450                id,
1451                SemanticsRole::Button,
1452                Rect::new(
1453                    ctx.bounds().max_x() - 52.0,
1454                    ctx.bounds().y(),
1455                    52.0,
1456                    CODE_HEADER_HEIGHT,
1457                ),
1458            );
1459            copy.parent = Some(ctx.widget_id());
1460            copy.name = Some("Copy code".to_string());
1461            copy.actions.push(SemanticsAction::Copy);
1462            ctx.push(copy);
1463        }
1464    }
1465}
1466
1467fn text_style_for_token(mut style: TextStyle, token: ThemeTextToken) -> TextStyle {
1468    style.font_size = token.size.max(1.0);
1469    style.line_height = token.line_height.max(1.0);
1470    style
1471}
1472
1473fn heading_text_style(theme: DefaultTheme, level: u8) -> TextStyle {
1474    let token = match level {
1475        1 => theme.text._3xl,
1476        2 => theme.text._2xl,
1477        3 => theme.text.xl,
1478        4 => theme.text.lg,
1479        _ => theme.text.base,
1480    };
1481    let mut style = text_style_for_token(theme.body_text_style(), token);
1482    style.weight = FontWeight::BOLD;
1483    style
1484}
1485
1486fn code_header_language_text_style(theme: DefaultTheme) -> TextStyle {
1487    text_style_for_token(
1488        theme.mono_text_style(theme.palette.text_muted),
1489        theme.text.sm,
1490    )
1491}
1492
1493fn code_header_action_text_style(theme: DefaultTheme) -> TextStyle {
1494    text_style_for_token(
1495        theme.text_style(theme.palette.accent_soft_text),
1496        theme.text.sm,
1497    )
1498}
1499
1500fn block_document(
1501    kind: &RichDocumentBlockKind,
1502    theme: DefaultTheme,
1503    highlighter: &dyn RichSyntaxHighlighter,
1504    expanded: bool,
1505) -> TextDocument {
1506    match kind {
1507        RichDocumentBlockKind::Paragraph { spans } => {
1508            document_from_spans(spans, theme.body_text_style(), theme)
1509        }
1510        RichDocumentBlockKind::Heading { level, spans } => {
1511            document_from_spans(spans, heading_text_style(theme, *level), theme)
1512        }
1513        RichDocumentBlockKind::BlockQuote { spans, .. } => {
1514            let mut style = theme.body_text_style();
1515            style.color = theme.palette.text_muted;
1516            style.style = FontStyle::Italic;
1517            document_from_spans(spans, style, theme)
1518        }
1519        RichDocumentBlockKind::List { start, items } => {
1520            let mut spans = Vec::new();
1521            let mut next = start.unwrap_or(1);
1522            for (index, item) in items.iter().enumerate() {
1523                if index > 0 {
1524                    spans.push(TextSpan::new("\n", theme.body_text_style()));
1525                }
1526                let marker = match item.checked {
1527                    Some(true) => "☑ ".to_string(),
1528                    Some(false) => "☐ ".to_string(),
1529                    None if start.is_some() => {
1530                        let marker = format!("{next}. ");
1531                        next = next.saturating_add(1);
1532                        marker
1533                    }
1534                    None => "• ".to_string(),
1535                };
1536                let mut marker_style = theme.body_text_style();
1537                marker_style.color = theme.palette.text_muted;
1538                spans.push(TextSpan::new(marker, marker_style));
1539                spans.extend(styled_spans(&item.spans, theme.body_text_style(), theme));
1540            }
1541            document_from_text_spans(spans)
1542        }
1543        RichDocumentBlockKind::CodeBlock { language, code } => {
1544            let base = theme.mono_text_style(theme.palette.text);
1545            let highlights = highlighter.highlight(language.as_deref(), code);
1546            document_from_text_spans(syntax_spans(code, &highlights, base, theme))
1547        }
1548        RichDocumentBlockKind::ThematicBreak => TextDocument::new(),
1549        RichDocumentBlockKind::Attachment(attachment) => {
1550            let mut spans = vec![TextSpan::new(format!("📎 {}", attachment.name), {
1551                let mut style = theme.body_text_style();
1552                style.weight = FontWeight::SEMIBOLD;
1553                style
1554            })];
1555            if let Some(description) = &attachment.description {
1556                let mut style = theme.body_text_style();
1557                style.color = theme.palette.text_muted;
1558                spans.push(TextSpan::new(format!("\n{description}"), style));
1559            }
1560            document_from_text_spans(spans)
1561        }
1562        RichDocumentBlockKind::Extension(extension) => {
1563            let mut title = theme.body_text_style();
1564            title.weight = FontWeight::SEMIBOLD;
1565            let mut spans = vec![TextSpan::new(extension.title.clone(), title)];
1566            if let Some(summary) = &extension.summary {
1567                let mut style = theme.body_text_style();
1568                style.color = theme.palette.text_muted;
1569                spans.push(TextSpan::new(format!("\n{summary}"), style));
1570            }
1571            if expanded && !extension.body.is_empty() {
1572                spans.push(TextSpan::new(
1573                    format!("\n\n{}", extension.body),
1574                    theme.mono_text_style(theme.palette.text),
1575                ));
1576            }
1577            document_from_text_spans(spans)
1578        }
1579    }
1580}
1581
1582fn document_from_spans(
1583    spans: &[RichDocumentSpan],
1584    base: TextStyle,
1585    theme: DefaultTheme,
1586) -> TextDocument {
1587    document_from_text_spans(styled_spans(spans, base, theme))
1588}
1589
1590fn document_from_text_spans(spans: Vec<TextSpan>) -> TextDocument {
1591    let mut paragraphs = Vec::new();
1592    let mut current = Vec::new();
1593    let mut empty_line_style = spans
1594        .first()
1595        .map(|span| span.style.clone())
1596        .unwrap_or_default();
1597
1598    for span in spans {
1599        empty_line_style = span.style.clone();
1600        let mut remainder = span.text.as_str();
1601        while let Some(newline) = remainder.find('\n') {
1602            if newline > 0 {
1603                current.push(TextSpan::new(&remainder[..newline], span.style.clone()));
1604            }
1605            if current.is_empty() {
1606                current.push(TextSpan::new("", span.style.clone()));
1607            }
1608            paragraphs.push(TextParagraph::from_spans(std::mem::take(&mut current)));
1609            remainder = &remainder[newline + 1..];
1610        }
1611        if !remainder.is_empty() {
1612            current.push(TextSpan::new(remainder, span.style));
1613        }
1614    }
1615
1616    if current.is_empty() {
1617        current.push(TextSpan::new("", empty_line_style));
1618    }
1619    paragraphs.push(TextParagraph::from_spans(current));
1620    TextDocument { paragraphs }
1621}
1622
1623fn styled_spans(spans: &[RichDocumentSpan], base: TextStyle, theme: DefaultTheme) -> Vec<TextSpan> {
1624    spans
1625        .iter()
1626        .map(|span| {
1627            let mut style = base.clone();
1628            if span.style.strong {
1629                style.weight = FontWeight::BOLD;
1630            }
1631            if span.style.emphasis {
1632                style.style = FontStyle::Italic;
1633            }
1634            match &span.kind {
1635                RichInlineKind::Code => {
1636                    style.font_families = Some(theme.fonts.mono.into());
1637                    style.color = theme.palette.accent_soft_text;
1638                }
1639                RichInlineKind::Link(_) => {
1640                    style.color = theme.palette.accent_soft_text;
1641                    style.weight = FontWeight::SEMIBOLD;
1642                }
1643                RichInlineKind::Image(_) => {
1644                    style.color = theme.palette.text_muted;
1645                    style.style = FontStyle::Italic;
1646                }
1647                RichInlineKind::Text => {}
1648            }
1649            TextSpan::new(span.text.clone(), style)
1650        })
1651        .collect()
1652}
1653
1654fn syntax_spans(
1655    source: &str,
1656    highlights: &[RichSyntaxSpan],
1657    base: TextStyle,
1658    theme: DefaultTheme,
1659) -> Vec<TextSpan> {
1660    let mut highlights = highlights
1661        .iter()
1662        .filter_map(|span| {
1663            let start = clamp_boundary(source, span.range.start);
1664            let end = clamp_boundary(source, span.range.end).max(start);
1665            (start < end).then_some((start..end, span.kind))
1666        })
1667        .collect::<Vec<_>>();
1668    highlights.sort_by_key(|(range, _)| range.start);
1669    let mut output = Vec::new();
1670    let mut cursor = 0;
1671    for (range, kind) in highlights {
1672        if range.start < cursor {
1673            continue;
1674        }
1675        if cursor < range.start {
1676            output.push(TextSpan::new(&source[cursor..range.start], base.clone()));
1677        }
1678        let mut style = base.clone();
1679        style.color = syntax_color(theme, kind);
1680        output.push(TextSpan::new(&source[range.clone()], style));
1681        cursor = range.end;
1682    }
1683    if cursor < source.len() {
1684        output.push(TextSpan::new(&source[cursor..], base.clone()));
1685    }
1686    if output.is_empty() {
1687        output.push(TextSpan::new(source, base));
1688    }
1689    output
1690}
1691
1692fn syntax_color(theme: DefaultTheme, kind: RichSyntaxTokenKind) -> sui_core::Color {
1693    match kind {
1694        RichSyntaxTokenKind::Keyword | RichSyntaxTokenKind::Header => {
1695            theme.palette.accent_soft_text
1696        }
1697        RichSyntaxTokenKind::String | RichSyntaxTokenKind::Added => theme.palette.success_soft_text,
1698        RichSyntaxTokenKind::Number | RichSyntaxTokenKind::Property => theme.palette.info_soft_text,
1699        RichSyntaxTokenKind::Comment => theme.palette.text_muted,
1700        RichSyntaxTokenKind::Type | RichSyntaxTokenKind::Function => {
1701            theme.palette.warning_soft_text
1702        }
1703        RichSyntaxTokenKind::Removed => theme.palette.danger_soft_text,
1704    }
1705}
1706
1707fn inline_targets(kind: &RichDocumentBlockKind) -> Vec<InlineTarget> {
1708    let spans = match kind {
1709        RichDocumentBlockKind::Paragraph { spans }
1710        | RichDocumentBlockKind::Heading { spans, .. }
1711        | RichDocumentBlockKind::BlockQuote { spans, .. } => {
1712            spans.iter().map(|span| (span, 0_usize)).collect::<Vec<_>>()
1713        }
1714        RichDocumentBlockKind::List { start, items } => {
1715            let mut offset = 0;
1716            let mut next = start.unwrap_or(1);
1717            let mut flattened = Vec::new();
1718            for (item_index, item) in items.iter().enumerate() {
1719                if item_index > 0 {
1720                    offset += 1;
1721                }
1722                offset += match item.checked {
1723                    Some(_) => "☐ ".len(),
1724                    None if start.is_some() => {
1725                        let len = format!("{next}. ").len();
1726                        next = next.saturating_add(1);
1727                        len
1728                    }
1729                    None => "• ".len(),
1730                };
1731                for span in &item.spans {
1732                    flattened.push((span, offset));
1733                    offset += span.text.len();
1734                }
1735            }
1736            flattened
1737        }
1738        _ => Vec::new(),
1739    };
1740    let mut offset = 0;
1741    let mut targets = Vec::new();
1742    for (span, explicit_offset) in spans {
1743        if explicit_offset > 0 {
1744            offset = explicit_offset;
1745        }
1746        let range = offset..offset + span.text.len();
1747        match &span.kind {
1748            RichInlineKind::Link(link) => targets.push(InlineTarget::Link {
1749                range,
1750                destination: link.destination.clone(),
1751                label: span.text.clone(),
1752            }),
1753            RichInlineKind::Image(image) => targets.push(InlineTarget::Image {
1754                range,
1755                image: image.clone(),
1756            }),
1757            RichInlineKind::Text | RichInlineKind::Code => {}
1758        }
1759        offset += span.text.len();
1760    }
1761    targets
1762}
1763
1764fn selection_range_for(
1765    selection: &DocumentSelection,
1766    block: RichBlockId,
1767    text_len: usize,
1768) -> Range<usize> {
1769    let (Some(anchor), Some(focus)) = (selection.anchor, selection.focus) else {
1770        return 0..0;
1771    };
1772    let Some(anchor_index) = selection.order.iter().position(|id| *id == anchor.block) else {
1773        return 0..0;
1774    };
1775    let Some(focus_index) = selection.order.iter().position(|id| *id == focus.block) else {
1776        return 0..0;
1777    };
1778    let Some(block_index) = selection.order.iter().position(|id| *id == block) else {
1779        return 0..0;
1780    };
1781    let ((start_index, start_offset), (end_index, end_offset)) =
1782        if (anchor_index, anchor.offset) <= (focus_index, focus.offset) {
1783            ((anchor_index, anchor.offset), (focus_index, focus.offset))
1784        } else {
1785            ((focus_index, focus.offset), (anchor_index, anchor.offset))
1786        };
1787    if block_index < start_index || block_index > end_index {
1788        return 0..0;
1789    }
1790    let start = if block_index == start_index {
1791        start_offset.min(text_len)
1792    } else {
1793        0
1794    };
1795    let end = if block_index == end_index {
1796        end_offset.min(text_len)
1797    } else {
1798        text_len
1799    };
1800    start.min(end)..end.max(start)
1801}
1802
1803fn clamp_boundary(text: &str, offset: usize) -> usize {
1804    let mut offset = offset.min(text.len());
1805    while !text.is_char_boundary(offset) {
1806        offset = offset.saturating_sub(1);
1807    }
1808    offset
1809}
1810
1811fn scroll_delta_to_offset(delta: ScrollDelta) -> Vector {
1812    match delta {
1813        ScrollDelta::Lines(delta) => Vector::new(delta.x * 40.0, delta.y * 40.0),
1814        ScrollDelta::Pixels(delta) => delta,
1815    }
1816}
1817
1818fn next_semantic_id() -> WidgetId {
1819    WidgetId::new(SYNTHETIC_RICH_DOCUMENT_TAG | NEXT_SYNTHETIC_ID.fetch_add(1, Ordering::Relaxed))
1820}
1821
1822#[cfg(test)]
1823mod tests {
1824    use std::{cell::Cell, cell::RefCell, rc::Rc};
1825
1826    use sui_core::{
1827        Event, ImageHandle, Point, PointerButton, PointerButtons, PointerEvent, PointerEventKind,
1828        ScrollDelta, SemanticsAction, SemanticsActionRequest, SemanticsNode, SemanticsRole,
1829        SemanticsValue, Size, Vector, WindowEvent,
1830    };
1831    use sui_layout::Constraints;
1832    use sui_reactive::Signal;
1833    use sui_runtime::{
1834        Application, CommandDelivery, CommandTarget, MeasureCtx, Runtime, SemanticsCtx, Widget,
1835        WindowBuilder,
1836    };
1837    use sui_scene::{RegisteredImage, SceneCommand};
1838
1839    use super::{
1840        RichDocumentBlock, RichDocumentBlockKind, RichDocumentModel, RichDocumentRenderContext,
1841        RichDocumentRendererRegistry, RichDocumentView, RichDocumentViewState,
1842        code_header_action_text_style, code_header_language_text_style, heading_text_style,
1843        syntax_color,
1844    };
1845    use crate::RichSyntaxTokenKind;
1846    use crate::{
1847        DefaultTheme, RichAttachment, RichExtensionBlock, TEXT_COMMAND, TextCommand, ThemeTextToken,
1848    };
1849    use sui_text::FontWeight;
1850
1851    fn runtime<W>(root: W) -> (Runtime, sui_core::WindowId)
1852    where
1853        W: Widget + 'static,
1854    {
1855        let runtime = Application::new()
1856            .window(WindowBuilder::new().title("Rich document").root(root))
1857            .build()
1858            .expect("rich document runtime should build");
1859        let window_id = runtime.window_ids()[0];
1860        (runtime, window_id)
1861    }
1862
1863    fn node<'a>(nodes: &'a [SemanticsNode], role: SemanticsRole, name: &str) -> &'a SemanticsNode {
1864        nodes
1865            .iter()
1866            .find(|node| node.role == role && node.name.as_deref() == Some(name))
1867            .unwrap_or_else(|| panic!("missing {role:?} semantics named {name:?}"))
1868    }
1869
1870    fn primary_pointer(kind: PointerEventKind, position: Point, pressed: bool) -> Event {
1871        let mut pointer = PointerEvent::new(kind, position);
1872        pointer.pointer_id = 7;
1873        pointer.button = Some(PointerButton::Primary);
1874        pointer.buttons = if pressed {
1875            PointerButtons::new(1)
1876        } else {
1877            PointerButtons::NONE
1878        };
1879        Event::Pointer(pointer)
1880    }
1881
1882    #[test]
1883    fn heading_text_styles_follow_theme_ramp_pairs() {
1884        let theme = DefaultTheme::default();
1885        let expected = [
1886            (1, theme.text._3xl),
1887            (2, theme.text._2xl),
1888            (3, theme.text.xl),
1889            (4, theme.text.lg),
1890            (5, theme.text.base),
1891            (6, theme.text.base),
1892        ];
1893
1894        for (level, token) in expected {
1895            let style = heading_text_style(theme, level);
1896            assert_eq!(style.font_size, token.size);
1897            assert_eq!(style.line_height, token.line_height);
1898            assert_eq!(style.weight, FontWeight::BOLD);
1899        }
1900    }
1901
1902    #[test]
1903    fn code_header_text_styles_use_complete_small_token_pair() {
1904        let mut theme = DefaultTheme::default();
1905        theme.text.sm = ThemeTextToken {
1906            size: 11.0,
1907            line_height: 16.0,
1908        };
1909
1910        let language = code_header_language_text_style(theme);
1911        let action = code_header_action_text_style(theme);
1912
1913        assert_eq!(language.font_size, theme.text.sm.size);
1914        assert_eq!(language.line_height, theme.text.sm.line_height);
1915        assert_eq!(language.color, theme.palette.text_muted);
1916        assert_eq!(
1917            language.font_families,
1918            theme
1919                .mono_text_style(theme.palette.text_muted)
1920                .font_families
1921        );
1922        assert_eq!(action.font_size, theme.text.sm.size);
1923        assert_eq!(action.line_height, theme.text.sm.line_height);
1924        assert_eq!(action.color, theme.palette.accent_soft_text);
1925        assert_eq!(
1926            action.font_families,
1927            theme
1928                .text_style(theme.palette.accent_soft_text)
1929                .font_families
1930        );
1931    }
1932
1933    #[test]
1934    fn code_block_syntax_colors_use_on_surface_status_text() {
1935        for theme in [
1936            DefaultTheme::default(),
1937            DefaultTheme::dark(),
1938            DefaultTheme::high_contrast(),
1939        ] {
1940            assert_eq!(
1941                syntax_color(theme, RichSyntaxTokenKind::String),
1942                theme.palette.success_soft_text
1943            );
1944            assert_eq!(
1945                syntax_color(theme, RichSyntaxTokenKind::Added),
1946                theme.palette.success_soft_text
1947            );
1948            assert_eq!(
1949                syntax_color(theme, RichSyntaxTokenKind::Number),
1950                theme.palette.info_soft_text
1951            );
1952            assert_eq!(
1953                syntax_color(theme, RichSyntaxTokenKind::Property),
1954                theme.palette.info_soft_text
1955            );
1956            assert_eq!(
1957                syntax_color(theme, RichSyntaxTokenKind::Type),
1958                theme.palette.warning_soft_text
1959            );
1960            assert_eq!(
1961                syntax_color(theme, RichSyntaxTokenKind::Function),
1962                theme.palette.warning_soft_text
1963            );
1964            assert_eq!(
1965                syntax_color(theme, RichSyntaxTokenKind::Removed),
1966                theme.palette.danger_soft_text
1967            );
1968            assert_eq!(
1969                syntax_color(theme, RichSyntaxTokenKind::Keyword),
1970                theme.palette.accent_soft_text
1971            );
1972            assert_eq!(
1973                syntax_color(theme, RichSyntaxTokenKind::Header),
1974                theme.palette.accent_soft_text
1975            );
1976            assert_eq!(
1977                syntax_color(theme, RichSyntaxTokenKind::Comment),
1978                theme.palette.text_muted
1979            );
1980        }
1981    }
1982
1983    #[test]
1984    fn streaming_append_retains_completed_block_widget_identity() {
1985        let model = RichDocumentModel::from_markdown("# Stable\n\nStreaming");
1986        let (mut runtime, window_id) = runtime(RichDocumentView::new(model.clone()));
1987        let first = runtime.render(window_id).unwrap();
1988        let heading_id = node(&first.semantics, SemanticsRole::Heading, "Stable").id;
1989        let paragraph_id = node(&first.semantics, SemanticsRole::Paragraph, "Streaming").id;
1990
1991        model.append_markdown(" text\n\n- next");
1992        let second = runtime.render(window_id).unwrap();
1993        assert_eq!(
1994            node(&second.semantics, SemanticsRole::Heading, "Stable").id,
1995            heading_id
1996        );
1997        assert_eq!(
1998            node(
1999                &second.semantics,
2000                SemanticsRole::Paragraph,
2001                "Streaming text"
2002            )
2003            .id,
2004            paragraph_id
2005        );
2006        assert!(
2007            second
2008                .semantics
2009                .iter()
2010                .any(|node| node.role == SemanticsRole::List)
2011        );
2012    }
2013
2014    #[test]
2015    fn document_semantics_expose_links_images_code_status_and_attachments() {
2016        let model = RichDocumentModel::from_markdown(
2017            "# Report\n\nRead [docs](https://example.test) and ![plot](plot.png).\n\n- one\n- [x] two\n\n```rust\nlet n = 42;\n```",
2018        );
2019        model.append_attachment(RichAttachment::new("results.csv"));
2020        let mut extension = RichExtensionBlock::new("tool-call", "Search");
2021        extension.summary = Some("3 results".to_string());
2022        extension.body = "structured payload".to_string();
2023        model.append_extension(extension);
2024
2025        let opened = Rc::new(RefCell::new(Vec::new()));
2026        let opened_link = Rc::clone(&opened);
2027        let images = Rc::new(RefCell::new(Vec::new()));
2028        let opened_image = Rc::clone(&images);
2029        let (mut runtime, window_id) = runtime(
2030            RichDocumentView::new(model)
2031                .on_link(move |destination| opened_link.borrow_mut().push(destination.to_string()))
2032                .on_image(move |source| opened_image.borrow_mut().push(source.to_string())),
2033        );
2034        let first = runtime.render(window_id).unwrap();
2035        assert!(
2036            first
2037                .semantics
2038                .iter()
2039                .any(|node| node.role == SemanticsRole::Document)
2040        );
2041        assert!(
2042            first
2043                .semantics
2044                .iter()
2045                .any(|node| node.role == SemanticsRole::ListItem && node.state.checked.is_some())
2046        );
2047        assert!(
2048            first
2049                .semantics
2050                .iter()
2051                .any(|node| node.role == SemanticsRole::Attachment)
2052        );
2053
2054        let link = node(&first.semantics, SemanticsRole::Link, "docs");
2055        assert_eq!(
2056            link.value,
2057            Some(SemanticsValue::Text("https://example.test".to_string()))
2058        );
2059        let link_id = link.id;
2060        let image_id = node(&first.semantics, SemanticsRole::Image, "plot").id;
2061        let copy = node(&first.semantics, SemanticsRole::Button, "Copy code");
2062        assert!(copy.actions.contains(&SemanticsAction::Copy));
2063        let copy_id = copy.id;
2064        let status = node(&first.semantics, SemanticsRole::Status, "Search");
2065        assert_eq!(status.state.expanded, Some(false));
2066        let status_id = status.id;
2067
2068        assert!(
2069            runtime
2070                .handle_semantics_action(window_id, link_id, SemanticsActionRequest::Activate)
2071                .unwrap()
2072        );
2073        assert!(
2074            runtime
2075                .handle_semantics_action(window_id, image_id, SemanticsActionRequest::Activate)
2076                .unwrap()
2077        );
2078        assert_eq!(opened.borrow().as_slice(), &["https://example.test"]);
2079        assert_eq!(images.borrow().as_slice(), &["plot.png"]);
2080
2081        assert!(
2082            runtime
2083                .handle_semantics_action(window_id, copy_id, SemanticsActionRequest::Copy)
2084                .unwrap()
2085        );
2086        assert_eq!(runtime.clipboard().text().as_deref(), Some("let n = 42;\n"));
2087
2088        assert!(
2089            runtime
2090                .handle_semantics_action(window_id, status_id, SemanticsActionRequest::Expand)
2091                .unwrap()
2092        );
2093        let expanded = runtime.render(window_id).unwrap();
2094        let status = node(&expanded.semantics, SemanticsRole::Status, "Search");
2095        assert_eq!(status.id, status_id);
2096        assert_eq!(status.state.expanded, Some(true));
2097        assert_eq!(
2098            status.value,
2099            Some(SemanticsValue::Text("structured payload".to_string()))
2100        );
2101    }
2102
2103    #[test]
2104    fn overflowing_code_block_scrolls_horizontally() {
2105        let model = RichDocumentModel::from_markdown(
2106            "```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```",
2107        );
2108        let (mut runtime, window_id) = runtime(RichDocumentView::new(model));
2109        runtime
2110            .handle_event(
2111                window_id,
2112                Event::Window(WindowEvent::Resized(Size::new(320.0, 240.0))),
2113            )
2114            .unwrap();
2115        let first = runtime.render(window_id).unwrap();
2116        let code = first
2117            .semantics
2118            .iter()
2119            .find(|node| node.role == SemanticsRole::Code)
2120            .expect("code semantics");
2121        assert!(
2122            code.bounds.height() > 100.0,
2123            "multiline code should retain every visual line, bounds={:?}",
2124            code.bounds
2125        );
2126        let first_origin = first
2127            .frame
2128            .scene
2129            .commands()
2130            .iter()
2131            .filter_map(|command| match command {
2132                SceneCommand::DrawShapedText(text) => Some(text),
2133                _ => None,
2134            })
2135            .max_by(|left, right| left.bounds.width().total_cmp(&right.bounds.width()))
2136            .map(|text| text.origin)
2137            .expect("code text draw");
2138
2139        let code_center = Point::new(
2140            code.bounds.x() + code.bounds.width() * 0.5,
2141            code.bounds.y() + code.bounds.height() * 0.5,
2142        );
2143        let mut scroll = PointerEvent::new(PointerEventKind::Scroll, code_center);
2144        scroll.scroll_delta = Some(ScrollDelta::Pixels(Vector::new(-180.0, 0.0)));
2145        runtime
2146            .handle_event(window_id, Event::Pointer(scroll))
2147            .unwrap();
2148        let second = runtime.render(window_id).unwrap();
2149        let second_origin = second
2150            .frame
2151            .scene
2152            .commands()
2153            .iter()
2154            .filter_map(|command| match command {
2155                SceneCommand::DrawShapedText(text) => Some(text),
2156                _ => None,
2157            })
2158            .max_by(|left, right| left.bounds.width().total_cmp(&right.bounds.width()))
2159            .map(|text| text.origin)
2160            .expect("scrolled code text draw");
2161
2162        assert!(
2163            second_origin.x < first_origin.x,
2164            "expected code origin to move left, before={first_origin:?}, after={second_origin:?}"
2165        );
2166    }
2167
2168    #[test]
2169    fn inline_image_resolver_paints_registered_image() {
2170        let handle = ImageHandle::new(71);
2171        let model = RichDocumentModel::from_markdown("![plot](asset:plot)");
2172        let mut application = Application::new();
2173        application
2174            .register_image(
2175                handle,
2176                RegisteredImage::from_rgba8(8, 8, vec![255; 8 * 8 * 4]).unwrap(),
2177            )
2178            .unwrap();
2179        let mut runtime =
2180            application
2181                .window(WindowBuilder::new().title("Inline image").root(
2182                    RichDocumentView::new(model).image_resolver(move |image| {
2183                        (image.source == "asset:plot").then_some(handle)
2184                    }),
2185                ))
2186                .build()
2187                .unwrap();
2188        let output = runtime.render(runtime.window_ids()[0]).unwrap();
2189        let mut draws = 0;
2190        output.frame.scene.visit_commands(&mut |command| {
2191            if matches!(command, SceneCommand::DrawImage { source, .. } if source.image == handle) {
2192                draws += 1;
2193            }
2194        });
2195        assert_eq!(draws, 1);
2196    }
2197
2198    #[test]
2199    fn pointer_drag_selects_text_across_multiple_blocks() {
2200        let model = RichDocumentModel::from_markdown("# First block\n\nSecond block");
2201        let state = RichDocumentViewState::new();
2202        let (mut runtime, window_id) = runtime(RichDocumentView::new(model).state(state.clone()));
2203        let first = runtime.render(window_id).unwrap();
2204        let heading = node(&first.semantics, SemanticsRole::Heading, "First block");
2205        let paragraph = node(&first.semantics, SemanticsRole::Paragraph, "Second block");
2206        let start = Point::new(heading.bounds.x() + 4.0, heading.bounds.y() + 4.0);
2207        let end = Point::new(
2208            paragraph.bounds.max_x() - 4.0,
2209            paragraph.bounds.y() + paragraph.bounds.height() * 0.5,
2210        );
2211
2212        runtime
2213            .handle_event(
2214                window_id,
2215                primary_pointer(PointerEventKind::Down, start, true),
2216            )
2217            .unwrap();
2218        runtime
2219            .handle_event(
2220                window_id,
2221                primary_pointer(PointerEventKind::Move, end, true),
2222            )
2223            .unwrap();
2224        runtime
2225            .handle_event(window_id, primary_pointer(PointerEventKind::Up, end, false))
2226            .unwrap();
2227
2228        let selected = state.selected_text().expect("cross-block selection");
2229        assert!(selected.contains("First block"), "selected {selected:?}");
2230        assert!(selected.contains("Second block"), "selected {selected:?}");
2231
2232        runtime.handle_command(
2233            CommandTarget::FocusedWidget(window_id),
2234            CommandDelivery::Directed,
2235            TEXT_COMMAND,
2236            TextCommand::Copy,
2237        );
2238        assert_eq!(
2239            runtime.clipboard().text().as_deref(),
2240            Some(selected.as_str())
2241        );
2242    }
2243
2244    struct ExtensionProbe {
2245        block: Signal<RichDocumentBlock>,
2246        measures: Option<Rc<Cell<usize>>>,
2247    }
2248
2249    impl Widget for ExtensionProbe {
2250        fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
2251            let _ = ctx.observe(&self.block);
2252            if let Some(measures) = &self.measures {
2253                measures.set(measures.get() + 1);
2254            }
2255            constraints.clamp(Size::new(160.0, 32.0))
2256        }
2257
2258        fn semantics(&self, ctx: &mut SemanticsCtx) {
2259            let block = self.block.get();
2260            let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Status, ctx.bounds());
2261            node.name = Some(format!("Custom: {}", block.plain_text()));
2262            ctx.push(node);
2263        }
2264    }
2265
2266    #[test]
2267    fn extension_registry_updates_payload_without_replacing_renderer_widget() {
2268        let registry = RichDocumentRendererRegistry::new();
2269        registry.register(
2270            "extension:tool-call",
2271            |context: RichDocumentRenderContext| ExtensionProbe {
2272                block: context.block,
2273                measures: None,
2274            },
2275        );
2276        let model = RichDocumentModel::new();
2277        let id = model.append_extension(RichExtensionBlock::new("tool-call", "Pending"));
2278        let (mut runtime, window_id) =
2279            runtime(RichDocumentView::new(model.clone()).renderer_registry(registry));
2280        let first = runtime.render(window_id).unwrap();
2281        let widget_id = node(&first.semantics, SemanticsRole::Status, "Custom: Pending").id;
2282
2283        let mut completed = RichExtensionBlock::new("tool-call", "Complete");
2284        completed.body = "42".to_string();
2285        assert!(model.update_structured(id, RichDocumentBlockKind::Extension(completed)));
2286        let second = runtime.render(window_id).unwrap();
2287        assert_eq!(
2288            node(
2289                &second.semantics,
2290                SemanticsRole::Status,
2291                "Custom: Complete\n42"
2292            )
2293            .id,
2294            widget_id
2295        );
2296    }
2297
2298    #[test]
2299    fn tail_update_does_not_remeasure_retained_prefix_renderer() {
2300        let registry = RichDocumentRendererRegistry::new();
2301        let measures = Rc::new(Cell::new(0));
2302        let renderer_measures = Rc::clone(&measures);
2303        registry.register(
2304            "extension:tool-call",
2305            move |context: RichDocumentRenderContext| ExtensionProbe {
2306                block: context.block,
2307                measures: Some(Rc::clone(&renderer_measures)),
2308            },
2309        );
2310        let model = RichDocumentModel::new();
2311        model.append_extension(RichExtensionBlock::new("tool-call", "Stable prefix"));
2312        model.append_markdown("Streaming");
2313        let (mut runtime, window_id) =
2314            runtime(RichDocumentView::new(model.clone()).renderer_registry(registry));
2315        runtime.render(window_id).unwrap();
2316        let initial_measures = measures.get();
2317
2318        model.append_markdown(" tail");
2319        runtime.render(window_id).unwrap();
2320        assert_eq!(measures.get(), initial_measures);
2321    }
2322}