use std::{cell::RefCell, rc::Rc, sync::Arc};
use cranpose_core::{MutableState, NodeId, State};
use cranpose_foundation::modifier_element;
use crate::{
density::Density,
modifier::Modifier,
text::{TextLayoutOptions, TextOptions, TextOverflow, TextStyle},
text_modifier_node::{TextModifierElement, TextModifierNode, shared_text_style},
widgets::{layout::NodeModifier, nodes::LayoutNode},
};
#[derive(Clone)]
pub struct DynamicTextSource(Rc<dyn Fn() -> crate::text::AnnotatedString>);
impl DynamicTextSource {
pub fn new<F>(resolver: F) -> Self
where
F: Fn() -> crate::text::AnnotatedString + 'static,
{
Self(Rc::new(resolver))
}
fn resolve(&self) -> crate::text::AnnotatedString {
(self.0)()
}
}
impl PartialEq for DynamicTextSource {
fn eq(&self, other: &Self) -> bool {
Rc::ptr_eq(&self.0, &other.0)
}
}
#[derive(Clone, PartialEq)]
pub enum TextSource {
Static(crate::text::AnnotatedString),
Dynamic(DynamicTextSource),
}
impl TextSource {
fn resolve(self) -> crate::text::AnnotatedString {
match self {
Self::Static(text) => text,
Self::Dynamic(dynamic) => dynamic.resolve(),
}
}
}
const SPARE_ROOM_KEPT: usize = 8;
#[doc(hidden)]
pub enum StaticText {
Owned(String),
Borrowed(&'static str),
Annotated(crate::text::AnnotatedString),
}
impl Default for StaticText {
fn default() -> Self {
Self::Borrowed("")
}
}
impl Clone for StaticText {
#[inline(never)]
fn clone(&self) -> Self {
match self {
Self::Owned(text) => Self::Owned(text.clone()),
Self::Borrowed(text) => Self::Borrowed(text),
Self::Annotated(text) => Self::Annotated(text.clone()),
}
}
}
impl PartialEq for StaticText {
#[inline(never)]
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Self::Owned(text), Self::Owned(other)) => text == other,
(Self::Borrowed(text), Self::Borrowed(other)) => text == other,
(Self::Annotated(text), Self::Annotated(other)) => text == other,
_ => false,
}
}
}
impl StaticText {
pub(crate) fn is(&self, shown: &crate::text::AnnotatedString) -> bool {
match self {
Self::Owned(text) => shown.is_plain(text),
Self::Borrowed(text) => shown.is_plain(text),
Self::Annotated(text) => shown == text,
}
}
fn into_annotated(self) -> crate::text::AnnotatedString {
let context = crate::render_state::current_app_context();
match self {
Self::Owned(mut text) => {
if text.capacity() - text.len() > SPARE_ROOM_KEPT {
text.shrink_to_fit();
}
match context {
Some(context) => context.text.plain_string(text),
None => crate::text::AnnotatedString::new(text),
}
}
Self::Borrowed(text) => {
context.map_or_else(|| text.into(), |context| context.text.plain_text(text))
}
Self::Annotated(text) => text,
}
}
}
#[doc(hidden)]
pub trait IntoTextSource {
fn into_text_source(self) -> TextSource;
fn into_static_text(self) -> Result<StaticText, Self>
where
Self: Sized,
{
Err(self)
}
fn into_composed_text(self) -> crate::text::AnnotatedString
where
Self: Sized,
{
self.into_text_source().resolve()
}
}
impl IntoTextSource for StaticText {
fn into_text_source(self) -> TextSource {
TextSource::Static(self.into_annotated())
}
fn into_static_text(self) -> Result<StaticText, Self> {
Ok(self)
}
}
impl IntoTextSource for String {
fn into_text_source(self) -> TextSource {
TextSource::Static(crate::text::AnnotatedString::from(self))
}
fn into_static_text(self) -> Result<StaticText, Self> {
Ok(StaticText::Owned(self))
}
}
impl IntoTextSource for &'static str {
fn into_text_source(self) -> TextSource {
TextSource::Static(crate::text::AnnotatedString::from(self))
}
fn into_static_text(self) -> Result<StaticText, Self> {
Ok(StaticText::Borrowed(self))
}
}
impl IntoTextSource for crate::text::AnnotatedString {
fn into_text_source(self) -> TextSource {
TextSource::Static(self)
}
fn into_static_text(self) -> Result<StaticText, Self> {
Ok(StaticText::Annotated(self))
}
}
fn reading(text: impl Fn() -> String + 'static) -> TextSource {
TextSource::Dynamic(DynamicTextSource::new(move || {
crate::text::AnnotatedString::from(text())
}))
}
macro_rules! state_text_source {
($state:ident) => {
impl<T> IntoTextSource for $state<T>
where
T: ToString + Clone + 'static,
{
fn into_text_source(self) -> TextSource {
reading(move || self.with(T::to_string))
}
fn into_composed_text(self) -> crate::text::AnnotatedString {
StaticText::Owned(self.with(T::to_string)).into_annotated()
}
}
};
}
state_text_source!(State);
state_text_source!(MutableState);
impl<F> IntoTextSource for F
where
F: Fn() -> String + 'static,
{
fn into_text_source(self) -> TextSource {
reading(self)
}
fn into_composed_text(self) -> crate::text::AnnotatedString {
StaticText::Owned(self()).into_annotated()
}
}
impl IntoTextSource for DynamicTextSource {
fn into_text_source(self) -> TextSource {
TextSource::Dynamic(self)
}
}
fn text_node_modifier(modifier: Modifier, element: TextModifierElement) -> Modifier {
modifier.then(Modifier::from_dyn_element(modifier_element(element)))
}
fn text_layout_inputs(
style: Arc<TextStyle>,
options: TextLayoutOptions,
) -> (Arc<TextStyle>, TextLayoutOptions) {
#[cfg(feature = "localization")]
let style = crate::localization::apply_shared_text_locale(style);
(style, options.normalized())
}
#[track_caller]
fn compose_text<S>(
text: S,
modifier: Modifier,
style: Arc<TextStyle>,
options: TextLayoutOptions,
) -> NodeId
where
S: IntoTextSource + Clone + PartialEq + 'static,
{
match text.into_static_text() {
Ok(fixed)
if crate::widgets::selection_container::current_selection_registrar().is_none() =>
{
static_text::Text(fixed, modifier, style, options)
}
Ok(fixed) => text_group::Text(fixed, modifier, style, options),
Err(text) => text_group::Text(text, modifier, style, options),
}
}
struct TextNodeModifier {
modifier: Modifier,
text: RefCell<StaticText>,
style: Arc<TextStyle>,
options: TextLayoutOptions,
density: Density,
}
impl TextNodeModifier {
fn shared_text(&self) -> crate::text::AnnotatedString {
let mut text = self.text.borrow_mut();
if let StaticText::Annotated(shown) = &*text {
return shown.clone();
}
let shown = std::mem::take(&mut *text).into_annotated();
*text = StaticText::Annotated(shown.clone());
shown
}
fn element(&self) -> TextModifierElement {
TextModifierElement::with_shared_style(
self.shared_text(),
Arc::clone(&self.style),
self.options,
self.density,
)
}
fn show_in(&mut self, node: &LayoutNode) -> Option<bool> {
let last = node.node_after(&self.modifier)?;
let mut last = last.borrow_mut();
let text_node = last.as_any_mut().downcast_mut::<TextModifierNode>()?;
let text = self.text.get_mut();
if text_node.shows(text, &self.style, self.options, self.density) {
return Some(false);
}
if cfg!(feature = "inspection") {
return None;
}
let shown = std::mem::take(text).into_annotated();
text_node.show(shown, &self.style, self.options, self.density);
Some(true)
}
}
impl NodeModifier for TextNodeModifier {
fn provided_locals(&self) -> Vec<cranpose_core::ProvidedValue> {
self.modifier.provided_composition_locals()
}
fn to_modifier(&self) -> Modifier {
text_node_modifier(self.modifier.clone(), self.element())
}
fn set_on(&mut self, node: &mut LayoutNode) {
match self.show_in(node) {
Some(true) => node.note_last_node_updated(),
Some(false) => {}
None => node.set_modifier(self.to_modifier()),
}
}
}
mod static_text {
use std::{cell::RefCell, sync::Arc};
use cranpose_core::NodeId;
use super::{StaticText, TextNodeModifier, text_layout_inputs};
use crate::{
composable,
modifier::Modifier,
text::{TextLayoutOptions, TextStyle},
widgets::layout::{LayoutEnvironment, compose_empty_layout},
};
#[composable(no_skip)]
pub(super) fn Text(
text: StaticText,
modifier: Modifier,
style: Arc<TextStyle>,
options: TextLayoutOptions,
) -> NodeId {
let (style, options) = text_layout_inputs(style, options);
let environment = LayoutEnvironment::current();
compose_empty_layout(
TextNodeModifier {
modifier,
text: RefCell::new(text),
style,
options,
density: environment.density,
},
environment,
)
}
}
mod text_group {
use std::{cell::RefCell, sync::Arc};
use cranpose_core::NodeId;
use super::{IntoTextSource, StaticText, TextNodeModifier, text_layout_inputs};
use crate::{
composable,
modifier::Modifier,
text::{TextLayoutOptions, TextStyle},
widgets::layout::{LayoutEnvironment, compose_empty_layout},
};
#[composable]
pub(super) fn Text<S>(
text: S,
modifier: Modifier,
style: Arc<TextStyle>,
options: TextLayoutOptions,
) -> NodeId
where
S: IntoTextSource + Clone + PartialEq + 'static,
{
text_node(text.into_composed_text(), modifier, style, options)
}
#[inline(never)]
fn text_node(
text: crate::text::AnnotatedString,
modifier: Modifier,
style: Arc<TextStyle>,
options: TextLayoutOptions,
) -> NodeId {
let (style, options) = text_layout_inputs(style, options);
let environment = LayoutEnvironment::current();
let modifier = match crate::widgets::selection_container::current_selection_registrar() {
Some(registrar) => modifier.then(crate::widgets::selection_container::selectable_text(
registrar,
text.clone(),
Arc::clone(&style),
options,
)),
None => modifier,
};
compose_empty_layout(
TextNodeModifier {
modifier,
text: RefCell::new(StaticText::Annotated(text)),
style,
options,
density: environment.density,
},
environment,
)
}
}
#[track_caller]
#[expect(non_snake_case, reason = "names follow Compose's casing")]
#[expect(
clippy::needless_pass_by_value,
reason = "Compose's Text takes its style by value; the function shares it without a copy"
)]
pub fn BasicTextWithOptions<S>(
text: S,
modifier: Modifier,
style: TextStyle,
options: TextLayoutOptions,
) -> NodeId
where
S: IntoTextSource + Clone + PartialEq + 'static,
{
compose_text(text, modifier, shared_text_style(&style), options)
}
#[track_caller]
#[expect(non_snake_case, reason = "names follow Compose's casing")]
#[expect(
clippy::needless_pass_by_value,
reason = "Compose's Text takes its style by value; the function shares it without a copy"
)]
pub fn BasicText<S>(
text: S,
modifier: Modifier,
style: TextStyle,
overflow: TextOverflow,
soft_wrap: bool,
max_lines: usize,
min_lines: usize,
) -> NodeId
where
S: IntoTextSource + Clone + PartialEq + 'static,
{
compose_text(
text,
modifier,
shared_text_style(&style),
TextLayoutOptions {
overflow,
soft_wrap,
max_lines,
min_lines,
},
)
}
#[track_caller]
#[expect(non_snake_case, reason = "names follow Compose's casing")]
#[expect(
clippy::needless_pass_by_value,
reason = "Compose's Text takes its style by value; the function shares it without a copy"
)]
pub fn TextWithOptions<S>(
value: S,
modifier: Modifier,
style: TextStyle,
options: TextOptions,
) -> NodeId
where
S: IntoTextSource + Clone + PartialEq + 'static,
{
compose_text(
value,
modifier,
shared_text_style(&style),
TextLayoutOptions::from(options),
)
}
#[track_caller]
#[expect(non_snake_case, reason = "names follow Compose's casing")]
#[expect(
clippy::needless_pass_by_value,
reason = "Compose's Text takes its style by value; the function shares it without a copy"
)]
pub fn Text<S>(value: S, modifier: Modifier, style: TextStyle) -> NodeId
where
S: IntoTextSource + Clone + PartialEq + 'static,
{
compose_text(
value,
modifier,
shared_text_style(&style),
TextLayoutOptions::from(TextOptions::default()),
)
}
#[cfg(test)]
#[path = "tests/text_tests.rs"]
mod tests;