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