lurq 0.65.1

A Rust UI toolkit with typed components, retained state, reactive signals, GPU rendering, and DevTools.
Documentation
//! An AI label: the mark on what a model made, or on what asks one.

use std::sync::Arc;

use super::{
  icons, names,
  part_style::Length,
  recipe::{Case, Name, Recipe, ResolvedPart, ResolvedRecipe},
  shared::{IconChoice, glyph, one_line, shown_icon},
  theme::{Themed, current_theme},
};
use crate::{
  app::theme::{BorderSize, PaletteColor, RadiusSize, Theme, TypographyStyle},
  components::Row,
  layout::{Alignment, layout_kind::Justify, text_style::FontWeight},
  node::{Element, border::Border},
};

/// How tall an AI label is: 18, 22 or 26.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum AiLabelSize {
  /// 18: in a row of a table, beside a small text.
  Sm,
  /// 22: the design's, beside a title or a field's label.
  #[default]
  Md,
  /// 26: beside the heading of a page.
  Lg,
}

names!(AiLabelSize {
  Sm => "sm",
  Md => "md",
  Lg => "lg",
});

/// The parts of an AI label a recipe styles.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum AiLabelPart {
  /// The label itself: its fill, its edge and its height.
  Root,
  /// The icon before the word.
  Icon,
  /// The word.
  Label,
}

names!(AiLabelPart {
  Root => "root",
  Icon => "icon",
  Label => "label",
});

/// The states of an AI label a recipe styles. It has nothing the pointer or
/// the keyboard does to it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum AiLabelState {
  /// It has an icon before its word.
  Icon,
}

names!(AiLabelState {
  Icon => "icon",
});

/// What builds an AI label's nodes: a theme's in place of the default one.
pub type AiLabelRenderer = Arc<dyn Fn(AiLabelView) -> Element + Send + Sync>;

/// An AI label: the mark on what a model made or filled in, and on what asks
/// one. A summary that was generated, a field that was suggested, a button
/// that drafts a reply.
///
/// ```
/// use lurq::ui::{AiLabel, AiLabelSize};
///
/// let plain = AiLabel::new();
/// // Said otherwise, and called by more than it draws.
/// let draft = AiLabel::new().text("Draft").label("Drafted by the assistant");
/// let small = AiLabel::new().size(AiLabelSize::Sm).icon(None);
/// ```
///
/// It draws sparkles and "AI" in the info color on its muted fill, with an
/// edge of the info color. It is read and not operated: it takes no press,
/// no focus and no stop of Tab, and to tooling that reads the tree it is a
/// note called by its label, or by its word where it has none. What explains
/// it stands on it as on any element: a [`Tooltip`](super::Tooltip) mounted
/// on it, or a [`Toggletip`](super::Toggletip) beside it.
pub struct AiLabel {
  text: Arc<str>,
  label: Option<Arc<str>>,
  icon: Option<IconChoice>,
  size: Name,
  states: Vec<Name>,
  rules: Recipe,
  id: Option<Arc<str>>,
  key: Option<Arc<str>>,
}

impl AiLabel {
  /// A label that says "AI" after sparkles.
  pub fn new() -> Self {
    Self {
      text: super::current_locale().common.ai.clone(),
      label: None,
      icon: None,
      size: AiLabelSize::default().into(),
      states: Vec::new(),
      rules: Recipe::new(),
      id: None,
      key: None,
    }
  }

  /// The word it draws in place of "AI": the app's word for it, or the word in another language.
  pub fn text(mut self, text: &str) -> Self {
    self.text = Arc::from(text);
    self
  }

  /// What it is called to tooling that reads the tree, where that is more than the word it draws:
  /// "Generated by AI".
  pub fn label(mut self, label: &str) -> Self {
    self.label = Some(Arc::from(label));
    self
  }

  /// The icon before the word, by its name in the theme's set, in place of the sparkles; `None` for no icon.
  pub fn icon(mut self, icon: impl Into<IconChoice>) -> Self {
    self.icon = Some(icon.into());
    self
  }

  /// An [`AiLabelSize`], or a size the theme's recipe names.
  pub fn size(mut self, size: impl Into<Name>) -> Self {
    self.size = size.into();
    self
  }

  /// Puts the label in a state the theme's recipe names, or takes it out.
  pub fn state(mut self, state: impl Into<Name>, on: bool) -> Self {
    let state = state.into();
    self.states.retain(|held| *held != state);
    if on {
      self.states.push(state);
    }
    self
  }

  /// Styles one part of this label over what the theme gives it.
  pub fn style(mut self, part: impl Into<Name>, style: impl FnOnce(super::PartStyle) -> super::PartStyle) -> Self {
    self.rules = self.rules.base(part, style);
    self
  }

  /// Lays rules over the theme's recipe for this label: what the component it is in says of it in this place.
  pub fn rules(mut self, rules: &Recipe) -> Self {
    self.rules = self.rules.extend(rules);
    self
  }

  /// The id of the label's root.
  pub fn id(mut self, id: impl Into<Arc<str>>) -> Self {
    self.id = Some(id.into());
    self
  }

  pub fn key(mut self, key: impl Into<Arc<str>>) -> Self {
    self.key = Some(key.into());
    self
  }

  /// Builds the label in `theme`. Converting it into an element does this in
  /// the theme of what is being rendered.
  pub fn build(self, theme: &Theme) -> Element {
    let icon = shown_icon(self.icon, icons::SPARKLES);
    let case = Case {
      variant: None,
      size: Some(self.size),
      density: None,
      breakpoint: super::current_breakpoint(),
      states: self.states.clone(),
    }
    .state(AiLabelState::Icon, icon.is_some());
    let view = AiLabelView {
      text: self.text,
      label: self.label,
      icon,
      size: self.size,
      recipe: theme
        .resolve::<AiLabel>(&case, Some(&self.rules))
        .owned_by(self.id.as_ref()),
      id: self.id,
      key: self.key,
    };
    match theme.renderer::<AiLabel>() {
      Some(renderer) => renderer(view),
      None => view.render(),
    }
  }
}

impl Default for AiLabel {
  fn default() -> Self {
    Self::new()
  }
}

impl From<AiLabel> for Element {
  fn from(label: AiLabel) -> Self {
    label.build(&current_theme())
  }
}

/// An AI label as a renderer sees it: what it was given and the style of its parts.
pub struct AiLabelView {
  /// The word it draws.
  pub text: Arc<str>,
  /// What it is called to tooling, where the app said more than the word.
  pub label: Option<Arc<str>>,
  /// The name of its icon; `None` where it has none.
  pub icon: Option<Name>,
  pub size: Name,
  /// The style of each part of this label.
  pub recipe: ResolvedRecipe,
  id: Option<Arc<str>>,
  key: Option<Arc<str>>,
}

impl AiLabelView {
  /// The style of a part, as this label is to be drawn.
  pub fn part(&self, part: impl Into<Name>) -> ResolvedPart {
    self.recipe.part(part)
  }

  pub fn theme(&self) -> &Theme {
    self.recipe.theme()
  }

  /// What the label is called to tooling: its label, or the word it draws.
  pub fn name(&self) -> Arc<str> {
    self.label.clone().unwrap_or_else(|| self.text.clone())
  }

  /// The root in the style of its part, with nothing in it yet: a note to tooling, called by
  /// [`name`](Self::name).
  pub fn root(&self) -> Row {
    let mut root = Row::new()
      .align_items(Alignment::Center)
      .justify(Justify::Center)
      .part(&self.part(AiLabelPart::Root))
      .describe("a11y_role", "note")
      .describe("a11y_name", self.name());
    if let Some(id) = &self.id {
      root = root.id(id.clone());
    }
    if let Some(key) = &self.key {
      root = root.key(key.clone());
    }
    root
  }

  /// How the default renderer builds an AI label: the icon it has, and the word on one line, which ends in an
  /// ellipsis in a room too narrow for it.
  pub fn render(self) -> Element {
    let mut root = self.root();
    if let Some(name) = self.icon {
      root = root.child(glyph(&self.part(AiLabelPart::Icon), name, false));
    }
    root.child(one_line(&self.part(AiLabelPart::Label), &self.text)).into()
  }
}

impl crate::ui::Styled for AiLabel {
  type Component = Self;

  fn rules(self, rules: &crate::ui::Recipe) -> Self {
    Self::rules(self, rules)
  }

  fn state(self, state: impl Into<crate::ui::Name>, on: bool) -> Self {
    Self::state(self, state, on)
  }
}

impl Themed for AiLabel {
  const NAME: &'static str = "ai_label";
  type Renderer = AiLabelRenderer;

  fn parts() -> crate::ui::Declared {
    AiLabelPart::declared()
  }

  fn states() -> crate::ui::Declared {
    AiLabelState::declared()
  }

  /// The design's AI label (`pencil/lurq-design-system.pen`, AI Label): 22
  /// high with the small radius, on `InfoMuted` in an edge of 1 in `Info`,
  /// padded 8, with sparkles of 12 4 before "AI" in 11 at 600, both in
  /// `Info`. The board draws the one size; small is 18, padded 6, at 10 with
  /// an icon of 10, and large 26, padded 10, at 12 with an icon of 14, the
  /// steps of a badge. It is no wider than the room it has.
  fn recipe() -> Recipe {
    use AiLabelPart::{Icon, Label, Root};
    use PaletteColor::{Info, InfoMuted};
    Recipe::new()
      .base(Root, |s| {
        s.height(22.0)
          .max_width(Length::Fill)
          .padding_x(8.0)
          .gap(4.0)
          .radius(RadiusSize::Sm)
          .background(InfoMuted)
          .foreground(Info)
          .border(Border::inside(BorderSize::Sm, Info))
      })
      .base(Icon, |s| s.square(12.0).foreground(Info))
      .base(Label, |s| {
        s.typography(TypographyStyle::Caption)
          .font_size(11.0)
          .weight(FontWeight::SemiBold)
          .foreground(Info)
      })
      .size(AiLabelSize::Sm, Root, |s| s.height(18.0).padding_x(6.0).gap(3.0))
      .size(AiLabelSize::Sm, Icon, |s| s.square(10.0))
      .size(AiLabelSize::Sm, Label, |s| s.font_size(10.0))
      .size(AiLabelSize::Lg, Root, |s| s.height(26.0).padding_x(10.0).gap(5.0))
      .size(AiLabelSize::Lg, Icon, |s| s.square(14.0))
      .size(AiLabelSize::Lg, Label, |s| s.font_size(12.0))
  }
}