1use 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#[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 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 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 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 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
309struct TextMeasurementProxy {
314 layout: TextPreparedLayoutHandle,
315}
316
317impl TextMeasurementProxy {
318 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 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 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 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 }
381}
382
383impl SemanticsNode for TextModifierNode {
384 fn merge_semantics(&self, config: &mut SemanticsConfiguration) {
385 config.content_description = Some(self.text().to_string());
387 }
388}
389
390#[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 }
448 }
449
450 fn capabilities(&self) -> NodeCapabilities {
451 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 metrics: crate::text::TextMetrics {
502 width: 12.0,
503 height: 18.0,
504 line_height: 18.0,
505 line_count: 1,
506 },
507 did_overflow: false,
508 }
509 }
510
511 fn get_offset_for_position(
512 &self,
513 _text: &crate::text::AnnotatedString,
514 _style: &TextStyle,
515 _x: f32,
516 _y: f32,
517 ) -> usize {
518 0
519 }
520
521 fn get_cursor_x_for_offset(
522 &self,
523 _text: &crate::text::AnnotatedString,
524 _style: &TextStyle,
525 _offset: usize,
526 ) -> f32 {
527 0.0
528 }
529
530 fn layout(
531 &self,
532 _text: &crate::text::AnnotatedString,
533 _style: &TextStyle,
534 ) -> TextLayoutResult {
535 panic!("layout is not used in this test");
536 }
537 }
538
539 #[test]
540 fn hash_changes_when_style_changes() {
541 let text = Rc::new(AnnotatedString::from("Hello"));
542 let element_a = TextModifierElement::new(
543 text.clone(),
544 TextStyle::default(),
545 TextLayoutOptions::default(),
546 );
547 let style_b = TextStyle {
548 span_style: crate::text::SpanStyle {
549 font_size: TextUnit::Sp(18.0),
550 ..Default::default()
551 },
552 ..Default::default()
553 };
554 let element_b = TextModifierElement::new(text, style_b, TextLayoutOptions::default());
555
556 assert_ne!(element_a, element_b);
557 assert_ne!(hash_of(&element_a), hash_of(&element_b));
558 }
559
560 #[test]
561 fn hash_matches_for_equal_elements() {
562 let style = TextStyle {
563 span_style: crate::text::SpanStyle {
564 font_size: TextUnit::Sp(14.0),
565 letter_spacing: TextUnit::Em(0.1),
566 ..Default::default()
567 },
568 ..Default::default()
569 };
570 let options = TextLayoutOptions::default();
571 let text = Rc::new(AnnotatedString::from("Hash me"));
572 let element_a = TextModifierElement::new(text.clone(), style.clone(), options);
573 let element_b = TextModifierElement::new(text, style, options);
574
575 assert_eq!(element_a, element_b);
576 assert_eq!(hash_of(&element_a), hash_of(&element_b));
577 }
578
579 #[test]
580 fn measure_uses_attached_node_identity() {
581 let (tx, rx) = mpsc::channel();
582
583 std::thread::spawn(move || {
584 let recorded = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
585 crate::text::set_text_measurer(RecordingPreparedLayoutMeasurer {
586 recorded: recorded.clone(),
587 });
588
589 let mut node = TextModifierNode::new(
590 Rc::new(AnnotatedString::from("identity")),
591 TextStyle::default(),
592 TextLayoutOptions::default(),
593 );
594 let mut context = BasicModifierNodeContext::new();
595 context.set_node_id(Some(77));
596 node.on_attach(&mut context);
597
598 let size = node.measure_text_content(Some(96.0));
599 tx.send((recorded.borrow().clone(), size.width, size.height))
600 .expect("send measurement result");
601 });
602
603 let (recorded, width, height) = rx.recv().expect("receive measurement result");
604 assert_eq!(recorded, vec![Some(77)]);
605 assert_eq!(width, 12.0);
606 assert_eq!(height, 18.0);
607 }
608
609 #[test]
610 fn prepared_layout_cache_reuses_node_snapshot() {
611 let (tx, rx) = mpsc::channel();
612
613 std::thread::spawn(move || {
614 let recorded = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
615 crate::text::set_text_measurer(RecordingPreparedLayoutMeasurer {
616 recorded: recorded.clone(),
617 });
618
619 let mut node = TextModifierNode::new(
620 Rc::new(AnnotatedString::from("reuse")),
621 TextStyle::default(),
622 TextLayoutOptions::default(),
623 );
624 let mut context = BasicModifierNodeContext::new();
625 context.set_node_id(Some(88));
626 node.on_attach(&mut context);
627
628 let measured = node.measure_text_content(Some(120.0));
629 let prepared = node.prepared_layout_handle().prepare(Some(120.0));
630 tx.send((
631 recorded.borrow().clone(),
632 measured.width,
633 measured.height,
634 prepared.metrics.width,
635 prepared.metrics.height,
636 ))
637 .expect("send cached layout result");
638 });
639
640 let (recorded, measured_width, measured_height, prepared_width, prepared_height) =
641 rx.recv().expect("receive cached layout result");
642 assert_eq!(recorded, vec![Some(88)]);
643 assert_eq!(measured_width, prepared_width);
644 assert_eq!(measured_height, prepared_height);
645 }
646}