use ferrokit_core::kept::{UiCell, UiLocal};
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::hash::{DefaultHasher, Hash, Hasher};
use std::rc::{Rc, Weak};
use crate::platform::{MainThread, Native, NativeObject, NativeScroll, NativeSplit, NativeView, Platform};
use crate::signal::{Effect, Owner, Signal, untrack};
pub trait View: 'static {
fn build(self, cx: &mut Cx) -> Node;
fn id(self, id: impl Hash) -> AnyView
where
Self: Sized,
{
let mut h = DefaultHasher::new();
id.hash(&mut h);
AnyView { id: Some(h.finish()), build: Box::new(move |cx| self.build(cx)) }
}
}
pub struct AnyView {
id: Option<u64>,
build: Box<dyn FnOnce(&mut Cx) -> Node>,
}
impl AnyView {
pub fn new(view: impl View) -> Self {
AnyView { id: None, build: Box::new(move |cx| view.build(cx)) }
}
pub(crate) fn build_node(self, cx: &mut Cx) -> Node {
let mut node = (self.build)(cx);
node.id = self.id;
node
}
}
impl View for AnyView {
fn build(self, cx: &mut Cx) -> Node {
self.build_node(cx)
}
}
pub struct Cx {
pub(crate) container: NativeView,
pub(crate) mtm: MainThread,
}
impl Cx {
pub(crate) fn new(container: NativeView) -> Self {
Cx { container, mtm: MainThread::new().expect("main thread") }
}
pub(crate) fn child(&self) -> Cx {
Cx { container: self.container.clone(), mtm: self.mtm }
}
}
thread_local! {
pub(crate) static LAYOUT_DIRTY: Cell<bool> = const { Cell::new(false) };
static LIVE_NODES: Cell<usize> = const { Cell::new(0) };
}
pub(crate) fn invalidate_layout() {
LAYOUT_DIRTY.with(|d| d.set(true));
}
#[derive(Default)]
pub(crate) struct Meta {
parent: RefCell<Weak<Meta>>,
pub(crate) ideal: Cell<Option<Size>>,
pub(crate) rect: Cell<Option<[f64; 4]>>,
pub(crate) dirty: Cell<bool>,
pub(crate) responds: RefCell<crate::commands::Responds>,
pub(crate) hidden: Cell<bool>,
hid: RefCell<Vec<NativeView>>,
}
impl Meta {
pub(crate) fn parent(&self) -> Option<Rc<Meta>> {
self.parent.borrow().upgrade()
}
pub(crate) fn set_parent(&self, parent: &Rc<Meta>) {
*self.parent.borrow_mut() = Rc::downgrade(parent);
}
pub(crate) fn mark(self: &Rc<Self>) {
let mut cur = Some(self.clone());
while let Some(m) = cur {
m.ideal.set(None);
if m.dirty.replace(true) {
break; }
cur = m.parent.borrow().upgrade();
}
invalidate_layout();
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Align {
Start,
Center,
End,
}
pub fn live_nodes() -> usize {
LIVE_NODES.with(Cell::get)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Axis {
Horizontal,
Vertical,
}
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct Size {
pub w: f64,
pub h: f64,
}
pub(crate) struct Leaf {
pub(crate) view: NativeView,
pub(crate) flex: (bool, bool),
pub(crate) min: Size,
pub(crate) content: Rc<Cell<Option<Size>>>,
pub(crate) cross_only: bool,
}
pub(crate) struct LeafHandle {
pub(crate) content: Rc<Cell<Option<Size>>>,
pub(crate) meta: Rc<Meta>,
}
pub(crate) enum Kind {
Leaf(Leaf),
Stack { axis: Axis, spacing: f64, align: Option<Align>, children: Vec<Node> },
Grid { spacing: (f64, f64), rows: Vec<Vec<Node>>, align: Vec<Align> },
Spacer,
Layers { align: (Align, Align), children: Vec<Node> },
Group(Rc<RefCell<Vec<Node>>>),
Scroll { scroll: NativeScroll, doc: NativeView, content: Box<Node> },
Split {
split: NativeSplit,
panes: Vec<(NativeView, Node)>,
position: Cell<Option<(f64, bool)>>,
trailing: Cell<Option<f64>>,
stacked: bool,
},
}
pub(crate) type LeafFn<'a> = dyn FnMut(&NativeView, &Cell<Option<Size>>, &Rc<Meta>) + 'a;
pub struct Node {
pub(crate) kind: Kind,
pub(crate) id: Option<u64>,
pub(crate) padding: (f64, f64),
pub(crate) fixed: (Option<f64>, Option<f64>),
pub(crate) min: (Option<f64>, Option<f64>),
pub(crate) shrinks: bool,
pub(crate) fill: (bool, bool),
pub(crate) meta: Rc<Meta>,
pub(crate) decor: Vec<NativeView>,
pub(crate) transition: Option<crate::Transition>,
pub(crate) matched: Option<Rc<str>>,
effects: Vec<Effect>,
keep: Vec<NativeObject>,
held: Vec<Rc<dyn std::any::Any>>,
owner: Option<Owner>,
}
impl Node {
pub(crate) fn new(kind: Kind) -> Node {
LIVE_NODES.with(|n| n.set(n.get() + 1));
let meta = Rc::new(Meta::default());
meta.dirty.set(true);
let node = Node {
kind,
id: None,
padding: (0.0, 0.0),
fixed: (None, None),
min: (None, None),
shrinks: false,
fill: (false, false),
meta,
decor: Vec::new(),
transition: None,
matched: None,
effects: Vec::new(),
keep: Vec::new(),
held: Vec::new(),
owner: None,
};
for c in node.children_static() {
c.meta.set_parent(&node.meta);
}
node
}
fn children_static(&self) -> Vec<&Node> {
match &self.kind {
Kind::Stack { children, .. } | Kind::Layers { children, .. } => children.iter().collect(),
Kind::Grid { rows, .. } => rows.iter().flatten().collect(),
Kind::Scroll { content, .. } => vec![&**content],
Kind::Split { panes, .. } => panes.iter().map(|(_, n)| n).collect(),
_ => Vec::new(),
}
}
pub(crate) fn leaf(cx: &Cx, view: NativeView, flex: (bool, bool), min: Size) -> (Node, LeafHandle) {
Native::add_subview(&cx.container, &view);
let content = Rc::new(Cell::new(None));
invalidate_layout();
let key = Native::view_key(&view);
let node = Node::new(Kind::Leaf(Leaf { view, flex, min, content: content.clone(), cross_only: false }));
crate::commands::register_leaf(key, &node.meta);
let handle = LeafHandle { content, meta: node.meta.clone() };
(node, handle)
}
pub(crate) fn build_owned(view: AnyView, cx: &mut Cx) -> Node {
let owner = Owner::new();
let mut node = owner.with(|| view.build_node(cx));
node.owner = Some(owner);
node
}
pub(crate) fn own(&mut self, effect: Effect) {
self.effects.push(effect);
}
pub(crate) fn keep(&mut self, object: NativeObject) {
self.keep.push(object);
}
pub(crate) fn leaf_views(&self, out: &mut Vec<NativeView>) {
match &self.kind {
Kind::Leaf(l) => out.push(l.view.clone()),
Kind::Scroll { scroll, .. } => out.push(Native::scroll_as_view(scroll)),
Kind::Split { panes, .. } => panes.iter().for_each(|(_, n)| n.leaf_views(out)),
Kind::Stack { children, .. } | Kind::Layers { children, .. } => children.iter().for_each(|c| c.leaf_views(out)),
Kind::Grid { rows, .. } => rows.iter().flatten().for_each(|c| c.leaf_views(out)),
Kind::Group(g) => g.borrow().iter().for_each(|c| c.leaf_views(out)),
Kind::Spacer => {}
}
}
pub(crate) fn each_leaf(&self, f: &mut LeafFn<'_>) {
match &self.kind {
Kind::Leaf(l) => f(&l.view, &l.content, &self.meta),
Kind::Stack { children, .. } | Kind::Layers { children, .. } => children.iter().for_each(|c| c.each_leaf(f)),
Kind::Grid { rows, .. } => rows.iter().flatten().for_each(|c| c.each_leaf(f)),
Kind::Group(g) => g.borrow().iter().for_each(|c| c.each_leaf(f)),
Kind::Scroll { .. } | Kind::Split { .. } | Kind::Spacer => {}
}
}
pub(crate) fn all_views(&self) -> Vec<NativeView> {
let mut out = self.decor.clone();
match &self.kind {
Kind::Leaf(l) => out.push(l.view.clone()),
Kind::Scroll { scroll, .. } => out.push(Native::scroll_as_view(scroll)),
Kind::Split { panes, .. } => panes.iter().for_each(|(_, n)| out.extend(n.all_views())),
Kind::Stack { children, .. } | Kind::Layers { children, .. } => children.iter().for_each(|c| out.extend(c.all_views())),
Kind::Grid { rows, .. } => rows.iter().flatten().for_each(|c| out.extend(c.all_views())),
Kind::Group(g) => g.borrow().iter().for_each(|c| out.extend(c.all_views())),
Kind::Spacer => {}
}
out
}
pub(crate) fn hold<V: ?Sized + 'static>(&mut self, value: Rc<V>) {
self.held.push(Rc::new(value));
}
}
thread_local! {
static LEAVING: UiCell<Option<Vec<NativeView>>> = const { UiCell::new(None) };
}
fn remove_view(view: &NativeView) {
let kept = LEAVING.try_with(|l| l.borrow_mut().as_mut().map(|l| l.push(view.clone())).is_some()).unwrap_or(false);
if !kept {
Native::remove(view);
}
}
impl Drop for Node {
fn drop(&mut self) {
LIVE_NODES.with(|n| n.set(n.get() - 1));
if let Some(id) = &self.matched {
crate::motion::matched_leaving(id, &self.all_views());
}
let leaving = self.transition.filter(|_| crate::motion::animating() && LEAVING.try_with(|l| l.borrow().is_none()).unwrap_or(false));
if leaving.is_some() {
LEAVING.with_borrow_mut(|l| *l = Some(Vec::new()));
}
self.effects.clear();
for d in &self.decor {
remove_view(d);
}
if let Kind::Scroll { scroll, .. } = &self.kind {
remove_view(&Native::scroll_as_view(scroll));
}
if let Kind::Split { split, .. } = &self.kind {
remove_view(&Native::split_as_view(split));
}
if let Kind::Leaf(l) = &self.kind {
crate::commands::unregister_leaf(Native::view_key(&l.view));
remove_view(&l.view);
if let Some(parent) = self.meta.parent.borrow().upgrade() {
parent.mark();
}
invalidate_layout();
}
if let Some(transition) = leaving {
drop(std::mem::replace(&mut self.kind, Kind::Spacer));
let views = LEAVING.with_borrow_mut(Option::take).unwrap_or_default();
crate::motion::exit(views, transition);
invalidate_layout();
}
}
}
pub trait ViewExt: View + Sized {
fn on_command(self, command: crate::Command, action: impl Fn() + 'static) -> Modified<Self> {
Modified::new(self).on_command(command, action)
}
fn on_command_when(self, command: crate::Command, enabled: impl Fn() -> bool + 'static, action: impl Fn() + 'static) -> Modified<Self> {
Modified::new(self).on_command_when(command, enabled, action)
}
fn focused_value<T: Clone + 'static>(self, name: &'static str, value: T) -> Modified<Self> {
Modified::new(self).focused_value(name, value)
}
fn padding(self, points: f64) -> Modified<Self> {
Modified::new(self).padding(points)
}
fn padding_xy(self, horizontal: f64, vertical: f64) -> Modified<Self> {
Modified::new(self).padding_xy(horizontal, vertical)
}
fn width(self, points: f64) -> Modified<Self> {
Modified::new(self).width(points)
}
fn min_width(self, points: f64) -> Modified<Self> {
Modified::new(self).min_width(points)
}
fn min_height(self, points: f64) -> Modified<Self> {
Modified::new(self).min_height(points)
}
fn height(self, points: f64) -> Modified<Self> {
Modified::new(self).height(points)
}
fn frame(self, width: f64, height: f64) -> Modified<Self> {
Modified::new(self).width(width).height(height)
}
fn fill_width(self) -> Modified<Self> {
Modified::new(self).fill_width()
}
fn fill_height(self) -> Modified<Self> {
Modified::new(self).fill_height()
}
fn popover<P: View>(self, shown: &Signal<bool>, content: impl Fn() -> P + 'static) -> Modified<Self> {
Modified::new(self).popover(shown, content)
}
fn context_menu(self, items: Vec<crate::chrome::MenuItem>) -> Modified<Self> {
Modified::new(self).context_menu(items)
}
fn accessibility_label(self, label: &str) -> Modified<Self> {
Modified::new(self).accessibility_label(label)
}
fn background(self, color: impl crate::IntoValue<crate::Color>) -> Modified<Self> {
Modified::new(self).background(color)
}
fn corner_radius(self, points: f64) -> Modified<Self> {
Modified::new(self).corner_radius(points)
}
fn border(self, color: crate::Color, width: f64) -> Modified<Self> {
Modified::new(self).border(color, width)
}
fn shadow(self, shadow: crate::Shadow) -> Modified<Self> {
Modified::new(self).shadow(shadow)
}
fn opacity(self, opacity: impl crate::IntoValue<f64>) -> Modified<Self> {
Modified::new(self).opacity(opacity)
}
fn font(self, font: crate::Font) -> Modified<Self> {
Modified::new(self).font(font)
}
fn color(self, color: impl crate::IntoValue<crate::Color>) -> Modified<Self> {
Modified::new(self).color(color)
}
fn accessibility_value(self, value: impl crate::IntoValue<String>) -> Modified<Self> {
Modified::new(self).accessibility_value(value)
}
fn material(self, material: crate::Material) -> Modified<Self> {
Modified::new(self).material(material)
}
fn glass(self, glass: crate::Glass) -> Modified<Self> {
Modified::new(self).glass(glass)
}
#[deprecated(since = "0.4.0", note = "`background` takes a closure: `.background(move || ..)`")]
fn background_when(self, color: impl Fn() -> crate::Color + 'static) -> Modified<Self> {
Modified::new(self).background(color)
}
#[deprecated(since = "0.4.0", note = "`opacity` takes a closure: `.opacity(move || ..)`")]
fn opacity_when(self, opacity: impl Fn() -> f64 + 'static) -> Modified<Self> {
Modified::new(self).opacity(opacity)
}
fn transition(self, transition: crate::Transition) -> Modified<Self> {
Modified::new(self).transition(transition)
}
fn matched_geometry(self, id: &str) -> Modified<Self> {
Modified::new(self).matched_geometry(id)
}
fn on_hover(self, action: impl Fn(bool) + 'static) -> Modified<Self> {
Modified::new(self).on_hover(action)
}
fn hover_highlight(self, color: crate::Color) -> Modified<Self> {
Modified::new(self).hover_highlight(color)
}
fn tooltip(self, text: &str) -> Modified<Self> {
Modified::new(self).tooltip(text)
}
fn hidden(self, when: impl crate::IntoValue<bool>) -> Modified<Self> {
Modified::new(self).hidden(when)
}
fn disabled(self, when: impl crate::IntoValue<bool>) -> Modified<Self> {
Modified::new(self).disabled(when)
}
fn on_click(self, action: impl Fn() + 'static) -> Modified<Self> {
Modified::new(self).on_click(action)
}
}
impl<V: View> ViewExt for V {}
pub struct Modified<V> {
view: V,
ops: Vec<Op>,
menu: Option<Vec<crate::chrome::MenuItem>>,
label: Option<String>,
responds: crate::commands::Responds,
popover: Option<crate::popover::PopoverSpec>,
opacity: Option<f64>,
opacity_when: Option<Box<dyn Fn() -> f64>>,
transition: Option<crate::Transition>,
matched: Option<Rc<str>>,
hover: Option<Rc<dyn Fn(bool)>>,
click: Option<Rc<dyn Fn()>>,
tooltip: Option<String>,
disabled: Option<crate::Value<bool>>,
hidden: Option<crate::Value<bool>>,
font: Option<crate::Font>,
color: Option<crate::Value<crate::Color>>,
ax_value: Option<crate::Value<String>>,
}
enum Op {
Padding(f64, f64),
Width(f64),
MinWidth(f64),
MinHeight(f64),
Height(f64),
FillWidth,
FillHeight,
Background(crate::Color),
Radius(f64),
Border(crate::Color, f64),
Shadow(crate::Shadow),
Backdrop(crate::material::Backdrop),
BackgroundWhen(Rc<dyn Fn() -> crate::Color>),
HoverHighlight(crate::Color),
}
impl<V: View> Modified<V> {
fn new(view: V) -> Self {
Modified { view, ops: Vec::new(), menu: None, label: None, responds: Default::default(), popover: None, opacity: None, opacity_when: None, transition: None, matched: None, hover: None, click: None, tooltip: None, disabled: None, hidden: None, font: None, color: None, ax_value: None }
}
pub fn popover<P: View>(self, shown: &Signal<bool>, content: impl Fn() -> P + 'static) -> Self {
self.popover_on(crate::Edge::Below, shown, content)
}
pub fn popover_on<P: View>(mut self, edge: crate::Edge, shown: &Signal<bool>, content: impl Fn() -> P + 'static) -> Self {
self.popover = Some(crate::popover::PopoverSpec { shown: *shown, content: Rc::new(move || AnyView::new(content())), edge });
self
}
pub fn on_command(mut self, command: crate::Command, action: impl Fn() + 'static) -> Self {
self.responds.commands.push((command, crate::commands::Handler::new(action, None)));
self
}
pub fn on_command_when(mut self, command: crate::Command, enabled: impl Fn() -> bool + 'static, action: impl Fn() + 'static) -> Self {
self.responds.commands.push((command, crate::commands::Handler::new(action, Some(Box::new(enabled)))));
self
}
pub fn focused_value<T: Clone + 'static>(mut self, name: &'static str, value: T) -> Self {
self.responds.values.push((name, Rc::new(value)));
self
}
pub fn accessibility_label(mut self, label: &str) -> Self {
self.label = Some(label.into());
self
}
pub fn context_menu(mut self, items: Vec<crate::chrome::MenuItem>) -> Self {
self.menu = Some(items);
self
}
pub fn fill_width(mut self) -> Self {
self.ops.push(Op::FillWidth);
self
}
pub fn fill_height(mut self) -> Self {
self.ops.push(Op::FillHeight);
self
}
pub fn padding(mut self, points: f64) -> Self {
self.ops.push(Op::Padding(points, points));
self
}
pub fn padding_xy(mut self, horizontal: f64, vertical: f64) -> Self {
self.ops.push(Op::Padding(horizontal, vertical));
self
}
pub fn width(mut self, points: f64) -> Self {
self.ops.push(Op::Width(points));
self
}
pub fn min_width(mut self, points: f64) -> Self {
self.ops.push(Op::MinWidth(points));
self
}
pub fn min_height(mut self, points: f64) -> Self {
self.ops.push(Op::MinHeight(points));
self
}
pub fn height(mut self, points: f64) -> Self {
self.ops.push(Op::Height(points));
self
}
pub fn background(mut self, color: impl crate::IntoValue<crate::Color>) -> Self {
self.ops.push(match color.into_value() {
crate::Value::Fixed(c) => Op::Background(c),
crate::Value::Computed(f) => Op::BackgroundWhen(f),
});
self
}
pub fn corner_radius(mut self, points: f64) -> Self {
self.ops.push(Op::Radius(points));
self
}
pub fn border(mut self, color: crate::Color, width: f64) -> Self {
self.ops.push(Op::Border(color, width));
self
}
pub fn shadow(mut self, shadow: crate::Shadow) -> Self {
self.ops.push(Op::Shadow(shadow));
self
}
pub fn opacity(mut self, opacity: impl crate::IntoValue<f64>) -> Self {
match opacity.into_value() {
crate::Value::Fixed(o) => self.opacity = Some(o),
crate::Value::Computed(f) => self.opacity_when = Some(Box::new(move || f())),
}
self
}
pub fn font(mut self, font: crate::Font) -> Self {
self.font = Some(font);
self
}
pub fn color(mut self, color: impl crate::IntoValue<crate::Color>) -> Self {
self.color = Some(color.into_value());
self
}
pub fn accessibility_value(mut self, value: impl crate::IntoValue<String>) -> Self {
self.ax_value = Some(value.into_value());
self
}
pub fn material(mut self, material: crate::Material) -> Self {
self.ops.push(Op::Backdrop(crate::material::Backdrop::Material(material)));
self
}
pub fn glass(mut self, glass: crate::Glass) -> Self {
self.ops.push(Op::Backdrop(crate::material::Backdrop::Glass(glass)));
self
}
#[deprecated(since = "0.4.0", note = "`background` takes a closure: `.background(move || ..)`")]
pub fn background_when(self, color: impl Fn() -> crate::Color + 'static) -> Self {
self.background(color)
}
#[deprecated(since = "0.4.0", note = "`opacity` takes a closure: `.opacity(move || ..)`")]
pub fn opacity_when(self, opacity: impl Fn() -> f64 + 'static) -> Self {
self.opacity(opacity)
}
pub fn matched_geometry(mut self, id: &str) -> Self {
self.matched = Some(id.into());
self
}
pub fn transition(mut self, transition: crate::Transition) -> Self {
self.transition = Some(transition);
self
}
pub fn on_hover(mut self, action: impl Fn(bool) + 'static) -> Self {
self.hover = Some(Rc::new(action));
self
}
pub fn hover_highlight(mut self, color: crate::Color) -> Self {
self.ops.push(Op::HoverHighlight(color));
self
}
pub fn tooltip(mut self, text: &str) -> Self {
self.tooltip = Some(text.into());
self
}
pub fn disabled(mut self, when: impl crate::IntoValue<bool>) -> Self {
self.disabled = Some(when.into_value());
self
}
pub fn hidden(mut self, when: impl crate::IntoValue<bool>) -> Self {
self.hidden = Some(when.into_value());
self
}
pub fn on_click(mut self, action: impl Fn() + 'static) -> Self {
self.click = Some(Rc::new(action));
self
}
}
impl<V: View> View for Modified<V> {
fn build(self, cx: &mut Cx) -> Node {
let mut node = self.view.build(cx);
let mut hover = self.hover;
let hovered = self.ops.iter().any(|o| matches!(o, Op::HoverHighlight(_))).then(|| {
let hovered = crate::Signal::new(false);
let user = hover.take();
hover = Some(Rc::new(move |on: bool| {
crate::animated(|| hovered.set(on));
if let Some(f) = &user {
f(on);
}
}));
hovered
});
let mut look = crate::surface::Look::default();
let mut has_look = false;
let mut look_when: Option<Rc<dyn Fn() -> crate::Color>> = None;
for op in self.ops {
let is_look = matches!(op, Op::Background(_) | Op::Radius(_) | Op::Border(..) | Op::Shadow(_) | Op::Backdrop(_) | Op::BackgroundWhen(_) | Op::HoverHighlight(_));
if !is_look && has_look {
node = add_surface(node, std::mem::take(&mut look), cx);
follow_background(&mut node, look_when.take());
has_look = false;
}
match op {
Op::Padding(px, py) => {
if node.padding != (0.0, 0.0) || node.fixed != (None, None) || !node.decor.is_empty() {
node = wrap(node);
}
node.padding = (px, py);
}
Op::MinWidth(w) => {
if node.min.0.is_some() {
node = wrap(node);
}
node.min.0 = Some(w);
}
Op::MinHeight(h) => {
if node.min.1.is_some() {
node = wrap(node);
}
node.min.1 = Some(h);
}
Op::Width(w) => {
if node.fixed.0.is_some() {
node = wrap(node);
}
node.fixed.0 = Some(w);
}
Op::Height(h) => {
if node.fixed.1.is_some() {
node = wrap(node);
}
node.fixed.1 = Some(h);
}
Op::FillWidth => node.fill.0 = true,
Op::FillHeight => node.fill.1 = true,
Op::Background(c) => look.background = Some(c),
Op::Radius(r) => look.radius = r,
Op::Border(c, w) => look.border = Some((c, w)),
Op::Shadow(s) => look.shadow = Some(s),
Op::Backdrop(b) => look.backdrop = Some(b),
Op::BackgroundWhen(f) => {
look.background = Some(crate::signal::untrack(|| f()));
look_when = Some(f);
}
Op::HoverHighlight(c) => {
let hovered = hovered.expect("made above");
let base: Option<Rc<dyn Fn() -> crate::Color>> = look_when.take().or_else(|| look.background.map(|b| Rc::new(move || b) as Rc<dyn Fn() -> crate::Color>));
let f: Rc<dyn Fn() -> crate::Color> = Rc::new(move || {
let under = base.as_ref().map_or(crate::Color::Clear, |b| b());
if hovered.get() && under == crate::Color::Clear { c } else { under }
});
look.background = Some(crate::signal::untrack(|| f()));
look_when = Some(f);
}
}
has_look |= is_look;
}
if has_look {
node = add_surface(node, look, cx);
follow_background(&mut node, look_when);
}
if let Some(alpha) = self.opacity {
for v in node.all_views() {
v.setAlphaValue(alpha);
}
}
if let Some(f) = self.opacity_when {
let views = node.all_views();
let first = Cell::new(true);
node.own(Effect::new(move || {
let alpha = f();
let views = views.clone();
let set = move || views.iter().for_each(|v| v.setAlphaValue(alpha));
if first.replace(false) { set() } else { crate::motion::apply(set) }
}));
}
if hover.is_some() || self.click.is_some() {
let views = node.all_views();
let interaction = crate::interact::Interaction::new(cx.mtm, hover, self.click.clone());
if self.click.is_some() {
let mut leaves = Vec::new();
node.leaf_views(&mut leaves);
let texts = leaves.into_iter().filter_map(|v| v.downcast::<objc2_app_kit::NSTextField>().ok()).collect();
interaction.set_views(views, self.label.clone(), texts);
}
let interaction: NativeView = objc2::rc::Retained::into_super(interaction);
Native::add_subview(&cx.container, &interaction);
node.decor.push(interaction);
node.meta.mark();
}
if let Some(font) = &self.font {
let ns = font.ns();
node.each_leaf(&mut |v, content, meta| {
if let Some(field) = v.downcast_ref::<objc2_app_kit::NSTextField>() {
field.setFont(Some(&ns));
content.set(None);
meta.mark();
}
});
}
if let Some(color) = self.color {
let mut fields = Vec::new();
let mut symbols = Vec::new();
node.each_leaf(&mut |v, _, _| {
if let Ok(f) = v.clone().downcast::<objc2_app_kit::NSTextField>() {
fields.push(f);
} else if let Ok(i) = v.clone().downcast::<objc2_app_kit::NSImageView>() {
symbols.push(i);
}
});
let set = move |c: crate::Color| {
let ns = c.ns();
fields.iter().for_each(|f| f.setTextColor(Some(&ns)));
symbols.iter().for_each(|i| i.setContentTintColor(Some(&ns)));
};
match color {
crate::Value::Fixed(c) => set(c),
color => node.own(Effect::new(move || set(color.get()))),
}
}
if let Some(value) = self.ax_value {
let mut targets: Vec<NativeView> = node.decor.iter().filter(|d| d.class().name().to_string_lossy() == "FerrokitInteraction").cloned().collect();
if targets.is_empty() {
node.leaf_views(&mut targets);
}
node.own(Effect::new(move || {
let v = objc2_foundation::NSString::from_str(&value.get());
for t in &targets {
unsafe { objc2_app_kit::NSAccessibility::setAccessibilityValue(&**t, Some(&v)) };
}
}));
}
if let Some(when) = self.disabled {
let mut leaves = Vec::new();
node.leaf_views(&mut leaves);
let controls: Vec<_> = leaves.into_iter().filter_map(|v| v.downcast::<objc2_app_kit::NSControl>().ok()).collect();
node.own(Effect::new(move || {
let enabled = !when.get();
for c in &controls {
c.setEnabled(enabled);
}
}));
}
if let Some(tip) = &self.tooltip {
let tip = objc2_foundation::NSString::from_str(tip);
let mut leaves = Vec::new();
node.leaf_views(&mut leaves);
for v in leaves.iter().chain(node.decor.iter().filter(|d| d.class().name().to_string_lossy() == "FerrokitInteraction")) {
v.setToolTip(Some(&tip));
}
}
if let Some(id) = self.matched {
crate::motion::matched_entering(&id, node.all_views());
node.matched = Some(id);
}
if let Some(t) = self.transition {
node.transition = Some(t);
if crate::motion::animating() {
crate::motion::enter(node.all_views(), t, self.opacity.unwrap_or(1.0));
}
}
if let Some(items) = self.menu {
let mut leaves = Vec::new();
node.leaf_views(&mut leaves);
for t in Native::set_context_menu(cx.mtm, &leaves, items) {
node.keep(t);
}
}
if let Some(label) = self.label.as_ref().filter(|_| self.click.is_none()) {
let mut leaves = Vec::new();
node.leaf_views(&mut leaves);
for v in leaves {
Native::set_accessibility_label(&v, label);
}
}
{
let mut r = node.meta.responds.borrow_mut();
r.commands.extend(self.responds.commands);
r.values.extend(self.responds.values);
}
if let Some(spec) = self.popover {
let mut leaves = Vec::new();
node.leaf_views(&mut leaves);
if let Some(anchor) = leaves.into_iter().next() {
crate::popover::attach(&mut node, anchor, spec);
}
}
if let Some(when) = self.hidden {
node = hide_when(node, when);
}
node
}
}
fn hide_when(node: Node, when: crate::Value<bool>) -> Node {
let children = Rc::new(RefCell::new(Vec::new()));
let mut group = Node::new(Kind::Group(children.clone()));
node.meta.set_parent(&group.meta);
children.borrow_mut().push(node);
let meta = group.meta.clone();
let first = Cell::new(true);
group.own(Effect::new(move || {
let hide = when.get();
if meta.hidden.get() == hide && !first.get() {
return;
}
let initial = first.replace(false);
if !initial || hide {
set_hidden(&meta, &children, hide);
}
}));
group
}
fn set_hidden(meta: &Rc<Meta>, children: &RefCell<Vec<Node>>, hide: bool) {
meta.hidden.set(hide);
if hide {
let views: Vec<NativeView> = children.borrow().iter().flat_map(Node::all_views).filter(|v| !v.isHidden()).collect();
views.iter().for_each(|v| v.setHidden(true));
meta.hid.borrow_mut().extend(views);
} else {
let views = std::mem::take(&mut *meta.hid.borrow_mut());
let mut up = meta.parent();
while let Some(m) = up {
if m.hidden.get() {
m.hid.borrow_mut().extend(views);
return;
}
up = m.parent();
}
views.iter().for_each(|v| v.setHidden(false));
}
meta.dirty.set(false);
meta.mark();
invalidate_layout();
}
fn follow_background(node: &mut Node, color: Option<Rc<dyn Fn() -> crate::Color>>) {
let Some(color) = color else { return };
let Some(surface) = node.decor.iter().rev().find_map(|d| d.clone().downcast::<crate::surface::Surface>().ok()) else { return };
let first = Cell::new(true);
node.own(Effect::new(move || {
let c = color();
if first.replace(false) {
return; }
let surface = surface.clone();
crate::motion::apply(move || surface.set_background(c));
}));
}
fn wrap(node: Node) -> Node {
Node::new(Kind::Stack { axis: Axis::Vertical, spacing: 0.0, align: Some(Align::Center), children: vec![node] })
}
fn add_surface(node: Node, mut look: crate::surface::Look, cx: &Cx) -> Node {
let mut node = if node.decor.is_empty() { node } else { wrap(node) };
let mut layers = Vec::new();
if let Some(b) = look.backdrop.take() {
layers.push(crate::material::backdrop(cx.mtm, b, look.radius));
}
if look != (crate::surface::Look { radius: look.radius, ..Default::default() }) || layers.is_empty() {
layers.push(objc2::rc::Retained::into_super(crate::surface::Surface::new(cx.mtm, look)));
}
let views = node.all_views();
let subviews = cx.container.subviews();
let lowest = subviews.iter().find(|s| views.iter().any(|v| objc2::rc::Retained::as_ptr(v) == objc2::rc::Retained::as_ptr(s)));
for layer in layers {
match &lowest {
Some(lowest) => cx.container.addSubview_positioned_relativeTo(&layer, objc2_app_kit::NSWindowOrderingMode::Below, Some(lowest)),
None => Native::add_subview(&cx.container, &layer),
}
node.decor.push(layer);
}
node.meta.mark();
node
}
pub trait Views {
fn into_views(self) -> Vec<AnyView>;
}
impl Views for Vec<AnyView> {
fn into_views(self) -> Vec<AnyView> {
self
}
}
impl<V: View> Views for V {
fn into_views(self) -> Vec<AnyView> {
vec![AnyView::new(self)]
}
}
macro_rules! tuple_views {
($($v:ident),+) => {
impl<$($v: View),+> Views for ($($v,)+) {
#[allow(non_snake_case)]
fn into_views(self) -> Vec<AnyView> {
let ($($v,)+) = self;
vec![$(AnyView::new($v)),+]
}
}
};
}
tuple_views!(A);
tuple_views!(A, B);
tuple_views!(A, B, C);
tuple_views!(A, B, C, D);
tuple_views!(A, B, C, D, E);
tuple_views!(A, B, C, D, E, F);
tuple_views!(A, B, C, D, E, F, G);
tuple_views!(A, B, C, D, E, F, G, H);
tuple_views!(A, B, C, D, E, F, G, H, I);
tuple_views!(A, B, C, D, E, F, G, H, I, J);
pub struct Stack {
axis: Axis,
spacing: f64,
align: Option<Align>,
children: Vec<AnyView>,
}
impl Stack {
pub fn alignment(mut self, align: Align) -> Self {
self.align = Some(align);
self
}
pub fn spacing(mut self, points: f64) -> Self {
self.spacing = points;
self
}
}
impl View for Stack {
fn build(self, cx: &mut Cx) -> Node {
let children = self.children.into_iter().map(|c| c.build_node(&mut cx.child())).collect();
Node::new(Kind::Stack { axis: self.axis, spacing: self.spacing, align: self.align, children })
}
}
pub fn vstack(children: impl Views) -> Stack {
Stack { axis: Axis::Vertical, spacing: 8.0, align: None, children: children.into_views() }
}
pub fn hstack(children: impl Views) -> Stack {
Stack { axis: Axis::Horizontal, spacing: 8.0, align: None, children: children.into_views() }
}
pub struct Layers {
align: (Align, Align),
children: Vec<AnyView>,
}
impl Layers {
pub fn alignment(mut self, horizontal: Align, vertical: Align) -> Self {
self.align = (horizontal, vertical);
self
}
}
impl View for Layers {
fn build(self, cx: &mut Cx) -> Node {
let children = self.children.into_iter().map(|c| c.build_node(&mut cx.child())).collect();
Node::new(Kind::Layers { align: self.align, children })
}
}
pub fn zstack(children: impl Views) -> Layers {
Layers { align: (Align::Center, Align::Center), children: children.into_views() }
}
pub struct Grid {
spacing: (f64, f64),
rows: Vec<Vec<AnyView>>,
align: Vec<Align>,
}
impl Grid {
pub fn align_column(mut self, column: usize, align: Align) -> Self {
if self.align.len() <= column {
self.align.resize(column + 1, Align::Start);
}
self.align[column] = align;
self
}
pub fn spacing(mut self, columns: f64, rows: f64) -> Self {
self.spacing = (columns, rows);
self
}
}
impl View for Grid {
fn build(self, cx: &mut Cx) -> Node {
let rows = self.rows.into_iter().map(|r| r.into_iter().map(|c| c.build_node(&mut cx.child())).collect()).collect();
Node::new(Kind::Grid { spacing: self.spacing, rows, align: self.align })
}
}
pub fn grid(rows: impl IntoIterator<Item = impl Views>) -> Grid {
Grid { spacing: (8.0, 8.0), rows: rows.into_iter().map(Views::into_views).collect(), align: Vec::new() }
}
pub struct Watch(Box<dyn FnMut()>);
impl View for Watch {
fn build(self, _cx: &mut Cx) -> Node {
let mut node = Node::new(Kind::Group(Rc::default()));
node.own(Effect::new(self.0));
node
}
}
pub fn watch(f: impl FnMut() + 'static) -> Watch {
Watch(Box::new(f))
}
pub struct Spacer;
impl View for Spacer {
fn build(self, _cx: &mut Cx) -> Node {
Node::new(Kind::Spacer)
}
}
pub fn spacer() -> Spacer {
Spacer
}
pub struct Dynamic(Box<dyn Fn() -> AnyView>);
impl View for Dynamic {
fn build(self, cx: &mut Cx) -> Node {
let children: Rc<RefCell<Vec<Node>>> = Rc::default();
let mut node = Node::new(Kind::Group(children.clone()));
let meta = node.meta.clone();
let container = cx.container.clone();
let f = self.0;
node.own(Effect::new(move || {
let owner = Owner::new();
let view = owner.with(&f);
untrack(|| {
let current = children.borrow().first().and_then(|n| n.id);
if view.id.is_some() && view.id == current {
return;
}
let mut new = owner.with(|| view.build_node(&mut Cx::new(container.clone())));
new.owner = Some(owner);
new.meta.set_parent(&meta);
*children.borrow_mut() = vec![new];
meta.mark();
});
}));
node
}
}
pub fn dynamic<V: View>(f: impl Fn() -> V + 'static) -> Dynamic {
Dynamic(Box::new(move || {
let v = f();
let any: Box<dyn std::any::Any> = Box::new(v);
match any.downcast::<AnyView>() {
Ok(a) => *a,
Err(v) => AnyView::new(*v.downcast::<V>().expect("view type")),
}
}))
}
pub trait Identifiable {
type Id: Hash + Eq + Clone + 'static;
fn id(&self) -> Self::Id;
}
pub struct ForEach(Box<dyn FnOnce(&mut Cx) -> Node>);
impl View for ForEach {
fn build(self, cx: &mut Cx) -> Node {
(self.0)(cx)
}
}
pub fn for_each<T, V>(items: impl Fn() -> Vec<T> + 'static, row: impl Fn(T) -> V + 'static) -> ForEach
where
T: Identifiable + 'static,
V: View,
{
ForEach(Box::new(move |cx| {
let children: Rc<RefCell<Vec<Node>>> = Rc::default();
let keys: Rc<RefCell<Vec<T::Id>>> = Rc::default();
let mut node = Node::new(Kind::Group(children.clone()));
let meta = node.meta.clone();
let container = cx.container.clone();
node.own(Effect::new(move || {
let items = items();
untrack(|| {
let mut old: HashMap<T::Id, Node> =
keys.borrow_mut().drain(..).zip(children.borrow_mut().drain(..)).collect();
let mut new_keys = Vec::with_capacity(items.len());
let mut new_nodes = Vec::with_capacity(items.len());
for item in items {
let key = item.id();
let n = match old.remove(&key) {
Some(n) => n,
None => {
let n = Node::build_owned(AnyView::new(row(item)), &mut Cx::new(container.clone()));
n.meta.set_parent(&meta);
n
}
};
new_keys.push(key);
new_nodes.push(n);
}
drop(old); *keys.borrow_mut() = new_keys;
*children.borrow_mut() = new_nodes;
meta.mark();
});
}));
node
}))
}