1use std::{cell::RefCell, rc::Rc, sync::Arc};
9
10use cranpose_core::{MutableState, NodeId, State};
11use cranpose_foundation::modifier_element;
12
13use crate::{
14 density::Density,
15 modifier::Modifier,
16 text::{TextLayoutOptions, TextOptions, TextOverflow, TextStyle},
17 text_modifier_node::{TextModifierElement, TextModifierNode, shared_text_style},
18 widgets::{layout::NodeModifier, nodes::LayoutNode},
19};
20
21#[derive(Clone)]
24pub struct DynamicTextSource(Rc<dyn Fn() -> crate::text::AnnotatedString>);
25
26impl DynamicTextSource {
27 pub fn new<F>(resolver: F) -> Self
29 where
30 F: Fn() -> crate::text::AnnotatedString + 'static,
31 {
32 Self(Rc::new(resolver))
33 }
34
35 fn resolve(&self) -> crate::text::AnnotatedString {
36 (self.0)()
37 }
38}
39
40impl PartialEq for DynamicTextSource {
41 fn eq(&self, other: &Self) -> bool {
42 Rc::ptr_eq(&self.0, &other.0)
43 }
44}
45
46#[derive(Clone, PartialEq)]
48pub enum TextSource {
49 Static(crate::text::AnnotatedString),
51 Dynamic(DynamicTextSource),
53}
54
55impl TextSource {
56 fn resolve(self) -> crate::text::AnnotatedString {
57 match self {
58 Self::Static(text) => text,
59 Self::Dynamic(dynamic) => dynamic.resolve(),
60 }
61 }
62}
63
64const SPARE_ROOM_KEPT: usize = 8;
67
68#[doc(hidden)]
72pub enum StaticText {
73 Owned(String),
76 Borrowed(&'static str),
79 Annotated(crate::text::AnnotatedString),
81}
82
83impl Default for StaticText {
84 fn default() -> Self {
85 Self::Borrowed("")
86 }
87}
88
89impl Clone for StaticText {
92 #[inline(never)]
93 fn clone(&self) -> Self {
94 match self {
95 Self::Owned(text) => Self::Owned(text.clone()),
96 Self::Borrowed(text) => Self::Borrowed(text),
97 Self::Annotated(text) => Self::Annotated(text.clone()),
98 }
99 }
100}
101
102impl PartialEq for StaticText {
103 #[inline(never)]
104 fn eq(&self, other: &Self) -> bool {
105 match (self, other) {
106 (Self::Owned(text), Self::Owned(other)) => text == other,
107 (Self::Borrowed(text), Self::Borrowed(other)) => text == other,
108 (Self::Annotated(text), Self::Annotated(other)) => text == other,
109 _ => false,
110 }
111 }
112}
113
114impl StaticText {
115 pub(crate) fn is(&self, shown: &crate::text::AnnotatedString) -> bool {
116 match self {
117 Self::Owned(text) => shown.is_plain(text),
118 Self::Borrowed(text) => shown.is_plain(text),
119 Self::Annotated(text) => shown == text,
120 }
121 }
122
123 fn into_annotated(self) -> crate::text::AnnotatedString {
128 let context = crate::render_state::current_app_context();
129 match self {
130 Self::Owned(mut text) => {
131 if text.capacity() - text.len() > SPARE_ROOM_KEPT {
132 text.shrink_to_fit();
133 }
134 match context {
135 Some(context) => context.text.plain_string(text),
136 None => crate::text::AnnotatedString::new(text),
137 }
138 }
139 Self::Borrowed(text) => {
140 context.map_or_else(|| text.into(), |context| context.text.plain_text(text))
141 }
142 Self::Annotated(text) => text,
143 }
144 }
145}
146
147#[doc(hidden)]
148pub trait IntoTextSource {
149 fn into_text_source(self) -> TextSource;
150
151 fn into_static_text(self) -> Result<StaticText, Self>
154 where
155 Self: Sized,
156 {
157 Err(self)
158 }
159
160 fn into_composed_text(self) -> crate::text::AnnotatedString
163 where
164 Self: Sized,
165 {
166 self.into_text_source().resolve()
167 }
168}
169
170impl IntoTextSource for StaticText {
171 fn into_text_source(self) -> TextSource {
172 TextSource::Static(self.into_annotated())
173 }
174
175 fn into_static_text(self) -> Result<StaticText, Self> {
176 Ok(self)
177 }
178}
179
180impl IntoTextSource for String {
181 fn into_text_source(self) -> TextSource {
182 TextSource::Static(crate::text::AnnotatedString::from(self))
183 }
184
185 fn into_static_text(self) -> Result<StaticText, Self> {
186 Ok(StaticText::Owned(self))
187 }
188}
189
190impl IntoTextSource for &'static str {
191 fn into_text_source(self) -> TextSource {
192 TextSource::Static(crate::text::AnnotatedString::from(self))
193 }
194
195 fn into_static_text(self) -> Result<StaticText, Self> {
196 Ok(StaticText::Borrowed(self))
197 }
198}
199
200impl IntoTextSource for crate::text::AnnotatedString {
201 fn into_text_source(self) -> TextSource {
202 TextSource::Static(self)
203 }
204
205 fn into_static_text(self) -> Result<StaticText, Self> {
206 Ok(StaticText::Annotated(self))
207 }
208}
209
210fn reading(text: impl Fn() -> String + 'static) -> TextSource {
212 TextSource::Dynamic(DynamicTextSource::new(move || {
213 crate::text::AnnotatedString::from(text())
214 }))
215}
216
217macro_rules! state_text_source {
222 ($state:ident) => {
223 impl<T> IntoTextSource for $state<T>
224 where
225 T: ToString + Clone + 'static,
226 {
227 fn into_text_source(self) -> TextSource {
228 reading(move || self.with(T::to_string))
229 }
230
231 fn into_composed_text(self) -> crate::text::AnnotatedString {
232 StaticText::Owned(self.with(T::to_string)).into_annotated()
233 }
234 }
235 };
236}
237
238state_text_source!(State);
239state_text_source!(MutableState);
240
241impl<F> IntoTextSource for F
242where
243 F: Fn() -> String + 'static,
244{
245 fn into_text_source(self) -> TextSource {
246 reading(self)
247 }
248
249 fn into_composed_text(self) -> crate::text::AnnotatedString {
250 StaticText::Owned(self()).into_annotated()
251 }
252}
253
254impl IntoTextSource for DynamicTextSource {
255 fn into_text_source(self) -> TextSource {
256 TextSource::Dynamic(self)
257 }
258}
259
260fn text_node_modifier(modifier: Modifier, element: TextModifierElement) -> Modifier {
263 modifier.then(Modifier::from_dyn_element(modifier_element(element)))
264}
265
266fn text_layout_inputs(
269 style: Arc<TextStyle>,
270 options: TextLayoutOptions,
271) -> (Arc<TextStyle>, TextLayoutOptions) {
272 #[cfg(feature = "localization")]
273 let style = crate::localization::apply_shared_text_locale(style);
274 (style, options.normalized())
275}
276
277#[track_caller]
280fn compose_text<S>(
281 text: S,
282 modifier: Modifier,
283 style: Arc<TextStyle>,
284 options: TextLayoutOptions,
285) -> NodeId
286where
287 S: IntoTextSource + Clone + PartialEq + 'static,
288{
289 match text.into_static_text() {
290 Ok(fixed)
291 if crate::widgets::selection_container::current_selection_registrar().is_none() =>
292 {
293 static_text::Text(fixed, modifier, style, options)
294 }
295 Ok(fixed) => text_group::Text(fixed, modifier, style, options),
296 Err(text) => text_group::Text(text, modifier, style, options),
297 }
298}
299
300struct TextNodeModifier {
304 modifier: Modifier,
305 text: RefCell<StaticText>,
308 style: Arc<TextStyle>,
309 options: TextLayoutOptions,
310 density: Density,
311}
312
313impl TextNodeModifier {
314 fn shared_text(&self) -> crate::text::AnnotatedString {
317 let mut text = self.text.borrow_mut();
318 if let StaticText::Annotated(shown) = &*text {
319 return shown.clone();
320 }
321 let shown = std::mem::take(&mut *text).into_annotated();
322 *text = StaticText::Annotated(shown.clone());
323 shown
324 }
325
326 fn element(&self) -> TextModifierElement {
327 TextModifierElement::with_shared_style(
328 self.shared_text(),
329 Arc::clone(&self.style),
330 self.options,
331 self.density,
332 )
333 }
334
335 fn show_in(&mut self, node: &LayoutNode) -> Option<bool> {
342 let last = node.node_after(&self.modifier)?;
343 let mut last = last.borrow_mut();
344 let text_node = last.as_any_mut().downcast_mut::<TextModifierNode>()?;
345 let text = self.text.get_mut();
346 if text_node.shows(text, &self.style, self.options, self.density) {
347 return Some(false);
348 }
349 if cfg!(feature = "inspection") {
350 return None;
351 }
352 let shown = std::mem::take(text).into_annotated();
353 text_node.show(shown, &self.style, self.options, self.density);
354 Some(true)
355 }
356}
357
358impl NodeModifier for TextNodeModifier {
359 fn provided_locals(&self) -> Vec<cranpose_core::ProvidedValue> {
360 self.modifier.provided_composition_locals()
361 }
362
363 fn to_modifier(&self) -> Modifier {
364 text_node_modifier(self.modifier.clone(), self.element())
365 }
366
367 fn set_on(&mut self, node: &mut LayoutNode) {
368 match self.show_in(node) {
371 Some(true) => node.note_last_node_updated(),
372 Some(false) => {}
373 None => node.set_modifier(self.to_modifier()),
374 }
375 }
376}
377
378mod static_text {
381 use std::{cell::RefCell, sync::Arc};
382
383 use cranpose_core::NodeId;
384
385 use super::{StaticText, TextNodeModifier, text_layout_inputs};
386 use crate::{
387 composable,
388 modifier::Modifier,
389 text::{TextLayoutOptions, TextStyle},
390 widgets::layout::{LayoutEnvironment, compose_empty_layout},
391 };
392
393 #[composable(no_skip)]
397 pub(super) fn Text(
398 text: StaticText,
399 modifier: Modifier,
400 style: Arc<TextStyle>,
401 options: TextLayoutOptions,
402 ) -> NodeId {
403 let (style, options) = text_layout_inputs(style, options);
404 let environment = LayoutEnvironment::current();
405 compose_empty_layout(
406 TextNodeModifier {
407 modifier,
408 text: RefCell::new(text),
409 style,
410 options,
411 density: environment.density,
412 },
413 environment,
414 )
415 }
416}
417
418mod text_group {
423 use std::{cell::RefCell, sync::Arc};
424
425 use cranpose_core::NodeId;
426
427 use super::{IntoTextSource, StaticText, TextNodeModifier, text_layout_inputs};
428 use crate::{
429 composable,
430 modifier::Modifier,
431 text::{TextLayoutOptions, TextStyle},
432 widgets::layout::{LayoutEnvironment, compose_empty_layout},
433 };
434
435 #[composable]
439 pub(super) fn Text<S>(
440 text: S,
441 modifier: Modifier,
442 style: Arc<TextStyle>,
443 options: TextLayoutOptions,
444 ) -> NodeId
445 where
446 S: IntoTextSource + Clone + PartialEq + 'static,
447 {
448 text_node(text.into_composed_text(), modifier, style, options)
449 }
450
451 #[inline(never)]
454 fn text_node(
455 text: crate::text::AnnotatedString,
456 modifier: Modifier,
457 style: Arc<TextStyle>,
458 options: TextLayoutOptions,
459 ) -> NodeId {
460 let (style, options) = text_layout_inputs(style, options);
461 let environment = LayoutEnvironment::current();
462 let modifier = match crate::widgets::selection_container::current_selection_registrar() {
463 Some(registrar) => modifier.then(crate::widgets::selection_container::selectable_text(
464 registrar,
465 text.clone(),
466 Arc::clone(&style),
467 options,
468 )),
469 None => modifier,
470 };
471 compose_empty_layout(
472 TextNodeModifier {
473 modifier,
474 text: RefCell::new(StaticText::Annotated(text)),
475 style,
476 options,
477 density: environment.density,
478 },
479 environment,
480 )
481 }
482}
483
484#[track_caller]
486#[expect(non_snake_case, reason = "names follow Compose's casing")]
487#[expect(
488 clippy::needless_pass_by_value,
489 reason = "Compose's Text takes its style by value; the function shares it without a copy"
490)]
491pub fn BasicTextWithOptions<S>(
492 text: S,
493 modifier: Modifier,
494 style: TextStyle,
495 options: TextLayoutOptions,
496) -> NodeId
497where
498 S: IntoTextSource + Clone + PartialEq + 'static,
499{
500 compose_text(text, modifier, shared_text_style(&style), options)
501}
502
503#[track_caller]
506#[expect(non_snake_case, reason = "names follow Compose's casing")]
507#[expect(
508 clippy::needless_pass_by_value,
509 reason = "Compose's Text takes its style by value; the function shares it without a copy"
510)]
511pub fn BasicText<S>(
512 text: S,
513 modifier: Modifier,
514 style: TextStyle,
515 overflow: TextOverflow,
516 soft_wrap: bool,
517 max_lines: usize,
518 min_lines: usize,
519) -> NodeId
520where
521 S: IntoTextSource + Clone + PartialEq + 'static,
522{
523 compose_text(
524 text,
525 modifier,
526 shared_text_style(&style),
527 TextLayoutOptions {
528 overflow,
529 soft_wrap,
530 max_lines,
531 min_lines,
532 },
533 )
534}
535
536#[track_caller]
538#[expect(non_snake_case, reason = "names follow Compose's casing")]
539#[expect(
540 clippy::needless_pass_by_value,
541 reason = "Compose's Text takes its style by value; the function shares it without a copy"
542)]
543pub fn TextWithOptions<S>(
544 value: S,
545 modifier: Modifier,
546 style: TextStyle,
547 options: TextOptions,
548) -> NodeId
549where
550 S: IntoTextSource + Clone + PartialEq + 'static,
551{
552 compose_text(
553 value,
554 modifier,
555 shared_text_style(&style),
556 TextLayoutOptions::from(options),
557 )
558}
559
560#[track_caller]
578#[expect(non_snake_case, reason = "names follow Compose's casing")]
579#[expect(
580 clippy::needless_pass_by_value,
581 reason = "Compose's Text takes its style by value; the function shares it without a copy"
582)]
583pub fn Text<S>(value: S, modifier: Modifier, style: TextStyle) -> NodeId
584where
585 S: IntoTextSource + Clone + PartialEq + 'static,
586{
587 compose_text(
588 value,
589 modifier,
590 shared_text_style(&style),
591 TextLayoutOptions::from(TextOptions::default()),
592 )
593}
594
595#[cfg(test)]
596#[path = "tests/text_tests.rs"]
597mod tests;