Skip to main content

cranpose_ui/
text_modifier_node.rs

1//! Text modifier node implementation following Jetpack Compose's TextStringSimpleNode architecture.
2//!
3//! This module implements text content as a modifier node rather than as a measure policy,
4//! matching the Jetpack Compose pattern where text is treated as visual content (like background)
5//! rather than as a layout strategy.
6//!
7//! # Architecture
8//!
9//! In Jetpack Compose, `BasicText` uses:
10//! ```kotlin
11//! Layout(modifier.then(TextStringSimpleElement(...)), EmptyMeasurePolicy)
12//! ```
13//!
14//! Where `TextStringSimpleNode` implements:
15//! - `LayoutModifierNode` - handles text measurement
16//! - `DrawModifierNode` - handles text drawing
17//! - `SemanticsModifierNode` - provides text content for accessibility
18//!
19//! This follows the principle that `MeasurePolicy` is for child layout, while modifier nodes
20//! handle content rendering and measurement.
21
22use crate::text::{AnnotatedString, TextLayoutOptions, TextStyle};
23use cranpose_foundation::{
24    Constraints, DelegatableNode, DrawModifierNode, DrawScope, InvalidationKind,
25    LayoutModifierNode, Measurable, MeasurementProxy, ModifierNode, ModifierNodeContext,
26    ModifierNodeElement, NodeCapabilities, NodeState, SemanticsConfiguration, SemanticsNode, Size,
27};
28use std::cell::{Cell, RefCell};
29use std::hash::{Hash, Hasher};
30use std::rc::Rc;
31
32/// Node that stores text content and handles measurement, drawing, and semantics.
33///
34/// This node implements three capabilities:
35/// - **Layout**: Measures text and returns appropriate size
36/// - **Draw**: Renders the text (placeholder for now)
37/// - **Semantics**: Provides text content for accessibility
38///
39/// Matches Jetpack Compose: `TextStringSimpleNode` in
40/// `compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/text/modifiers/TextStringSimpleNode.kt`
41#[derive(Debug)]
42pub struct TextModifierNode {
43    layout: Rc<TextPreparedLayoutOwner>,
44    state: NodeState,
45}
46
47const PREPARED_LAYOUT_CACHE_CAPACITY: usize = 4;
48
49#[derive(Clone, Debug)]
50struct TextPreparedLayoutCacheEntry {
51    max_width_bits: Option<u32>,
52    layout: crate::text::PreparedTextLayout,
53}
54
55#[derive(Debug)]
56struct TextPreparedLayoutOwner {
57    text: Rc<AnnotatedString>,
58    style: TextStyle,
59    options: TextLayoutOptions,
60    node_id: Cell<Option<cranpose_core::NodeId>>,
61    cache: RefCell<Vec<TextPreparedLayoutCacheEntry>>,
62}
63
64#[derive(Clone, Debug)]
65pub(crate) struct TextPreparedLayoutHandle {
66    owner: Rc<TextPreparedLayoutOwner>,
67}
68
69impl TextPreparedLayoutOwner {
70    fn new(
71        text: Rc<AnnotatedString>,
72        style: TextStyle,
73        options: TextLayoutOptions,
74        node_id: Option<cranpose_core::NodeId>,
75    ) -> Self {
76        Self {
77            text,
78            style,
79            options: options.normalized(),
80            node_id: Cell::new(node_id),
81            cache: RefCell::new(Vec::new()),
82        }
83    }
84
85    fn text(&self) -> &str {
86        self.text.text.as_str()
87    }
88
89    fn annotated_text(&self) -> Rc<AnnotatedString> {
90        self.text.clone()
91    }
92
93    fn annotated_string(&self) -> AnnotatedString {
94        (*self.text).clone()
95    }
96
97    fn style(&self) -> &TextStyle {
98        &self.style
99    }
100
101    fn options(&self) -> TextLayoutOptions {
102        self.options
103    }
104
105    fn node_id(&self) -> Option<cranpose_core::NodeId> {
106        self.node_id.get()
107    }
108
109    fn set_node_id(&self, node_id: Option<cranpose_core::NodeId>) {
110        if self.node_id.replace(node_id) != node_id {
111            self.cache.borrow_mut().clear();
112        }
113    }
114
115    fn prepare(&self, max_width: Option<f32>) -> crate::text::PreparedTextLayout {
116        let normalized_max_width = max_width.filter(|width| width.is_finite() && *width > 0.0);
117        let max_width_bits = normalized_max_width.map(f32::to_bits);
118
119        {
120            let mut cache = self.cache.borrow_mut();
121            if let Some(index) = cache
122                .iter()
123                .position(|entry| entry.max_width_bits == max_width_bits)
124            {
125                let entry = cache.remove(index);
126                let prepared = entry.layout.clone();
127                cache.insert(0, entry);
128                return prepared;
129            }
130        }
131
132        let prepared = crate::text::prepare_text_layout_for_node(
133            self.node_id(),
134            self.text.as_ref(),
135            &self.style,
136            self.options,
137            normalized_max_width,
138        );
139
140        let mut cache = self.cache.borrow_mut();
141        cache.insert(
142            0,
143            TextPreparedLayoutCacheEntry {
144                max_width_bits,
145                layout: prepared.clone(),
146            },
147        );
148        cache.truncate(PREPARED_LAYOUT_CACHE_CAPACITY);
149        prepared
150    }
151
152    fn measure_text_content(&self, max_width: Option<f32>) -> Size {
153        let prepared = self.prepare(max_width);
154        Size {
155            width: prepared.metrics.width,
156            height: prepared.metrics.height,
157        }
158    }
159}
160
161impl TextPreparedLayoutHandle {
162    fn new(owner: Rc<TextPreparedLayoutOwner>) -> Self {
163        Self { owner }
164    }
165
166    pub(crate) fn prepare(&self, max_width: Option<f32>) -> crate::text::PreparedTextLayout {
167        self.owner.prepare(max_width)
168    }
169
170    fn measure_text_content(&self, max_width: Option<f32>) -> Size {
171        self.owner.measure_text_content(max_width)
172    }
173}
174
175impl TextModifierNode {
176    pub fn new(text: Rc<AnnotatedString>, style: TextStyle, options: TextLayoutOptions) -> Self {
177        Self {
178            layout: Rc::new(TextPreparedLayoutOwner::new(text, style, options, None)),
179            state: NodeState::new(),
180        }
181    }
182
183    pub fn text(&self) -> &str {
184        self.layout.text()
185    }
186
187    pub fn annotated_text(&self) -> Rc<AnnotatedString> {
188        self.layout.annotated_text()
189    }
190
191    pub fn annotated_string(&self) -> AnnotatedString {
192        self.layout.annotated_string()
193    }
194
195    pub fn style(&self) -> &TextStyle {
196        self.layout.style()
197    }
198
199    pub fn options(&self) -> TextLayoutOptions {
200        self.layout.options()
201    }
202
203    fn measure_text_content(&self, max_width: Option<f32>) -> Size {
204        self.layout.measure_text_content(max_width)
205    }
206
207    pub(crate) fn prepared_layout_handle(&self) -> TextPreparedLayoutHandle {
208        TextPreparedLayoutHandle::new(self.layout.clone())
209    }
210}
211
212impl DelegatableNode for TextModifierNode {
213    fn node_state(&self) -> &NodeState {
214        &self.state
215    }
216}
217
218impl ModifierNode for TextModifierNode {
219    fn on_attach(&mut self, context: &mut dyn ModifierNodeContext) {
220        self.layout.set_node_id(context.node_id());
221        // Invalidate layout and draw when text node is attached
222        context.invalidate(InvalidationKind::Layout);
223        context.invalidate(InvalidationKind::Draw);
224        context.invalidate(InvalidationKind::Semantics);
225    }
226
227    fn on_detach(&mut self) {
228        self.layout.set_node_id(None);
229    }
230
231    fn as_draw_node(&self) -> Option<&dyn DrawModifierNode> {
232        Some(self)
233    }
234
235    fn as_draw_node_mut(&mut self) -> Option<&mut dyn DrawModifierNode> {
236        Some(self)
237    }
238
239    fn as_semantics_node(&self) -> Option<&dyn SemanticsNode> {
240        Some(self)
241    }
242
243    fn as_semantics_node_mut(&mut self) -> Option<&mut dyn SemanticsNode> {
244        Some(self)
245    }
246
247    fn as_layout_node(&self) -> Option<&dyn LayoutModifierNode> {
248        Some(self)
249    }
250
251    fn as_layout_node_mut(&mut self) -> Option<&mut dyn LayoutModifierNode> {
252        Some(self)
253    }
254}
255
256impl LayoutModifierNode for TextModifierNode {
257    fn measure(
258        &self,
259        _context: &mut dyn ModifierNodeContext,
260        _measurable: &dyn Measurable,
261        constraints: Constraints,
262    ) -> cranpose_ui_layout::LayoutModifierMeasureResult {
263        // Measure the text content
264        let max_width = constraints
265            .max_width
266            .is_finite()
267            .then_some(constraints.max_width);
268        let text_size = self.measure_text_content(max_width);
269
270        // Constrain text size to the provided constraints
271        let width = text_size
272            .width
273            .clamp(constraints.min_width, constraints.max_width);
274        let height = text_size
275            .height
276            .clamp(constraints.min_height, constraints.max_height);
277
278        // Text is a leaf node - return the text size directly with no offset
279        // We don't call measurable.measure() because there's no wrapped content
280        // (Text uses EmptyMeasurePolicy which has no children)
281        cranpose_ui_layout::LayoutModifierMeasureResult::with_size(Size { width, height })
282    }
283
284    fn min_intrinsic_width(&self, _measurable: &dyn Measurable, _height: f32) -> f32 {
285        self.measure_text_content(None).width
286    }
287
288    fn max_intrinsic_width(&self, _measurable: &dyn Measurable, _height: f32) -> f32 {
289        self.measure_text_content(None).width
290    }
291
292    fn min_intrinsic_height(&self, _measurable: &dyn Measurable, _width: f32) -> f32 {
293        self.measure_text_content(Some(_width).filter(|w| w.is_finite() && *w > 0.0))
294            .height
295    }
296
297    fn max_intrinsic_height(&self, _measurable: &dyn Measurable, _width: f32) -> f32 {
298        self.measure_text_content(Some(_width).filter(|w| w.is_finite() && *w > 0.0))
299            .height
300    }
301
302    fn create_measurement_proxy(&self) -> Option<Box<dyn MeasurementProxy>> {
303        Some(Box::new(TextMeasurementProxy {
304            layout: self.prepared_layout_handle(),
305        }))
306    }
307}
308
309/// Measurement proxy for TextModifierNode that snapshots live state.
310///
311/// Phase 2: Instead of reconstructing nodes via `TextModifierNode::new()`, this proxy
312/// directly implements measurement logic using the snapshotted text content.
313struct TextMeasurementProxy {
314    layout: TextPreparedLayoutHandle,
315}
316
317impl TextMeasurementProxy {
318    /// Measure the text content dimensions.
319    /// Matches TextModifierNode::measure_text_content() logic.
320    fn measure_text_content(&self, max_width: Option<f32>) -> Size {
321        self.layout.measure_text_content(max_width)
322    }
323}
324
325impl MeasurementProxy for TextMeasurementProxy {
326    fn measure_proxy(
327        &self,
328        _context: &mut dyn ModifierNodeContext,
329        _measurable: &dyn Measurable,
330        constraints: Constraints,
331    ) -> cranpose_ui_layout::LayoutModifierMeasureResult {
332        // Directly implement text measurement logic (no node reconstruction)
333        let max_width = constraints
334            .max_width
335            .is_finite()
336            .then_some(constraints.max_width);
337        let text_size = self.measure_text_content(max_width);
338
339        // Constrain text size to the provided constraints
340        let width = text_size
341            .width
342            .clamp(constraints.min_width, constraints.max_width);
343        let height = text_size
344            .height
345            .clamp(constraints.min_height, constraints.max_height);
346
347        // Text is a leaf node - return the text size directly with no offset
348        cranpose_ui_layout::LayoutModifierMeasureResult::with_size(Size { width, height })
349    }
350
351    fn min_intrinsic_width_proxy(&self, _measurable: &dyn Measurable, _height: f32) -> f32 {
352        self.measure_text_content(None).width
353    }
354
355    fn max_intrinsic_width_proxy(&self, _measurable: &dyn Measurable, _height: f32) -> f32 {
356        self.measure_text_content(None).width
357    }
358
359    fn min_intrinsic_height_proxy(&self, _measurable: &dyn Measurable, _width: f32) -> f32 {
360        self.measure_text_content(Some(_width).filter(|w| w.is_finite() && *w > 0.0))
361            .height
362    }
363
364    fn max_intrinsic_height_proxy(&self, _measurable: &dyn Measurable, _width: f32) -> f32 {
365        self.measure_text_content(Some(_width).filter(|w| w.is_finite() && *w > 0.0))
366            .height
367    }
368}
369
370impl DrawModifierNode for TextModifierNode {
371    fn draw(&self, _draw_scope: &mut dyn DrawScope) {
372        // In a full implementation, this would:
373        // 1. Get the text paragraph layout cache
374        // 2. Paint the text using draw_scope canvas
375        //
376        // For now, this is a placeholder. The actual rendering will be handled
377        // by the renderer which can read text from the modifier chain.
378        //
379        // Future: Implement actual text drawing here using DrawScope
380    }
381}
382
383impl SemanticsNode for TextModifierNode {
384    fn merge_semantics(&self, config: &mut SemanticsConfiguration) {
385        // Provide text content for accessibility
386        config.content_description = Some(self.text().to_string());
387    }
388}
389
390/// Element that creates and updates TextModifierNode instances.
391///
392/// This follows the modifier element pattern where the element is responsible for:
393/// - Creating new nodes (via `create`)
394/// - Updating existing nodes when properties change (via `update`)
395/// - Declaring capabilities (LAYOUT | DRAW | SEMANTICS)
396///
397/// Matches Jetpack Compose: `TextStringSimpleElement` in BasicText.kt
398#[derive(Debug, Clone, PartialEq)]
399pub struct TextModifierElement {
400    text: Rc<AnnotatedString>,
401    style: TextStyle,
402    options: TextLayoutOptions,
403}
404
405impl TextModifierElement {
406    pub fn new(text: Rc<AnnotatedString>, style: TextStyle, options: TextLayoutOptions) -> Self {
407        Self {
408            text,
409            style,
410            options: options.normalized(),
411        }
412    }
413}
414
415impl Hash for TextModifierElement {
416    fn hash<H: Hasher>(&self, state: &mut H) {
417        self.text.render_hash().hash(state);
418        self.style.render_hash().hash(state);
419        self.options.hash(state);
420    }
421}
422
423impl ModifierNodeElement for TextModifierElement {
424    type Node = TextModifierNode;
425
426    fn create(&self) -> Self::Node {
427        TextModifierNode::new(self.text.clone(), self.style.clone(), self.options)
428    }
429
430    fn update(&self, node: &mut Self::Node) {
431        let current = node.layout.as_ref();
432        if current.text != self.text
433            || current.style != self.style
434            || current.options != self.options
435        {
436            node.layout = Rc::new(TextPreparedLayoutOwner::new(
437                self.text.clone(),
438                self.style.clone(),
439                self.options,
440                current.node_id(),
441            ));
442            // Text/Style changed - need to invalidate layout, draw, and semantics
443            // Note: In the full implementation, we would call context.invalidate here
444            // but update() doesn't currently have access to context.
445            // The invalidation will happen on the next recomposition when the node
446            // is reconciled.
447        }
448    }
449
450    fn capabilities(&self) -> NodeCapabilities {
451        // Text nodes participate in layout, drawing, and semantics
452        NodeCapabilities::LAYOUT | NodeCapabilities::DRAW | NodeCapabilities::SEMANTICS
453    }
454}
455
456#[cfg(test)]
457mod tests {
458    use super::*;
459    use crate::text::TextUnit;
460    use crate::text_layout_result::TextLayoutResult;
461    use cranpose_core::NodeId;
462    use cranpose_foundation::BasicModifierNodeContext;
463    use std::collections::hash_map::DefaultHasher;
464    use std::sync::mpsc;
465
466    fn hash_of(element: &TextModifierElement) -> u64 {
467        let mut hasher = DefaultHasher::new();
468        element.hash(&mut hasher);
469        hasher.finish()
470    }
471
472    struct RecordingPreparedLayoutMeasurer {
473        recorded: std::rc::Rc<std::cell::RefCell<Vec<Option<NodeId>>>>,
474    }
475
476    impl crate::text::TextMeasurer for RecordingPreparedLayoutMeasurer {
477        fn measure(
478            &self,
479            _text: &crate::text::AnnotatedString,
480            _style: &TextStyle,
481        ) -> crate::text::TextMetrics {
482            crate::text::TextMetrics {
483                width: 12.0,
484                height: 18.0,
485                line_height: 18.0,
486                line_count: 1,
487            }
488        }
489
490        fn prepare_with_options_for_node(
491            &self,
492            node_id: Option<NodeId>,
493            text: &crate::text::AnnotatedString,
494            _style: &TextStyle,
495            _options: TextLayoutOptions,
496            _max_width: Option<f32>,
497        ) -> crate::text::PreparedTextLayout {
498            self.recorded.borrow_mut().push(node_id);
499            crate::text::PreparedTextLayout {
500                text: text.clone(),
501                visual_style: TextStyle::default(),
502                metrics: crate::text::TextMetrics {
503                    width: 12.0,
504                    height: 18.0,
505                    line_height: 18.0,
506                    line_count: 1,
507                },
508                did_overflow: false,
509            }
510        }
511
512        fn get_offset_for_position(
513            &self,
514            _text: &crate::text::AnnotatedString,
515            _style: &TextStyle,
516            _x: f32,
517            _y: f32,
518        ) -> usize {
519            0
520        }
521
522        fn get_cursor_x_for_offset(
523            &self,
524            _text: &crate::text::AnnotatedString,
525            _style: &TextStyle,
526            _offset: usize,
527        ) -> f32 {
528            0.0
529        }
530
531        fn layout(
532            &self,
533            _text: &crate::text::AnnotatedString,
534            _style: &TextStyle,
535        ) -> TextLayoutResult {
536            panic!("layout is not used in this test");
537        }
538    }
539
540    #[test]
541    fn hash_changes_when_style_changes() {
542        let text = Rc::new(AnnotatedString::from("Hello"));
543        let element_a = TextModifierElement::new(
544            text.clone(),
545            TextStyle::default(),
546            TextLayoutOptions::default(),
547        );
548        let style_b = TextStyle {
549            span_style: crate::text::SpanStyle {
550                font_size: TextUnit::Sp(18.0),
551                ..Default::default()
552            },
553            ..Default::default()
554        };
555        let element_b = TextModifierElement::new(text, style_b, TextLayoutOptions::default());
556
557        assert_ne!(element_a, element_b);
558        assert_ne!(hash_of(&element_a), hash_of(&element_b));
559    }
560
561    #[test]
562    fn hash_matches_for_equal_elements() {
563        let style = TextStyle {
564            span_style: crate::text::SpanStyle {
565                font_size: TextUnit::Sp(14.0),
566                letter_spacing: TextUnit::Em(0.1),
567                ..Default::default()
568            },
569            ..Default::default()
570        };
571        let options = TextLayoutOptions::default();
572        let text = Rc::new(AnnotatedString::from("Hash me"));
573        let element_a = TextModifierElement::new(text.clone(), style.clone(), options);
574        let element_b = TextModifierElement::new(text, style, options);
575
576        assert_eq!(element_a, element_b);
577        assert_eq!(hash_of(&element_a), hash_of(&element_b));
578    }
579
580    #[test]
581    fn measure_uses_attached_node_identity() {
582        let (tx, rx) = mpsc::channel();
583
584        std::thread::spawn(move || {
585            let recorded = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
586            crate::text::set_text_measurer(RecordingPreparedLayoutMeasurer {
587                recorded: recorded.clone(),
588            });
589
590            let mut node = TextModifierNode::new(
591                Rc::new(AnnotatedString::from("identity")),
592                TextStyle::default(),
593                TextLayoutOptions::default(),
594            );
595            let mut context = BasicModifierNodeContext::new();
596            context.set_node_id(Some(77));
597            node.on_attach(&mut context);
598
599            let size = node.measure_text_content(Some(96.0));
600            tx.send((recorded.borrow().clone(), size.width, size.height))
601                .expect("send measurement result");
602        });
603
604        let (recorded, width, height) = rx.recv().expect("receive measurement result");
605        assert_eq!(recorded, vec![Some(77)]);
606        assert_eq!(width, 12.0);
607        assert_eq!(height, 18.0);
608    }
609
610    #[test]
611    fn prepared_layout_cache_reuses_node_snapshot() {
612        let (tx, rx) = mpsc::channel();
613
614        std::thread::spawn(move || {
615            let recorded = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
616            crate::text::set_text_measurer(RecordingPreparedLayoutMeasurer {
617                recorded: recorded.clone(),
618            });
619
620            let mut node = TextModifierNode::new(
621                Rc::new(AnnotatedString::from("reuse")),
622                TextStyle::default(),
623                TextLayoutOptions::default(),
624            );
625            let mut context = BasicModifierNodeContext::new();
626            context.set_node_id(Some(88));
627            node.on_attach(&mut context);
628
629            let measured = node.measure_text_content(Some(120.0));
630            let prepared = node.prepared_layout_handle().prepare(Some(120.0));
631            tx.send((
632                recorded.borrow().clone(),
633                measured.width,
634                measured.height,
635                prepared.metrics.width,
636                prepared.metrics.height,
637            ))
638            .expect("send cached layout result");
639        });
640
641        let (recorded, measured_width, measured_height, prepared_width, prepared_height) =
642            rx.recv().expect("receive cached layout result");
643        assert_eq!(recorded, vec![Some(88)]);
644        assert_eq!(measured_width, prepared_width);
645        assert_eq!(measured_height, prepared_height);
646    }
647
648    #[test]
649    fn semantics_uses_source_text_for_scaled_overflow() {
650        let node = TextModifierNode::new(
651            Rc::new(AnnotatedString::from("Save Cranpose WebP")),
652            TextStyle::default(),
653            TextLayoutOptions {
654                overflow: crate::text::TextOverflow::ScaleDown {
655                    min_font_size_sp: 9.0,
656                },
657                soft_wrap: false,
658                max_lines: 1,
659                min_lines: 1,
660            },
661        );
662        let mut config = SemanticsConfiguration::default();
663
664        node.merge_semantics(&mut config);
665
666        assert_eq!(
667            config.content_description.as_deref(),
668            Some("Save Cranpose WebP")
669        );
670    }
671}