use std::sync::Arc;
use super::{
Accessible, AnyElement, Interactive, IntoReactive,
builder::{ElNode, Element, IntoElement, IntoListener, Listener, ParentElement},
events::{
self, CaretEvent, Composition, HintReason, NativeEvent, OverlayPosition, Selection,
VideoInfo, VideoProgress, WebNavigation,
},
};
use crate::{
AudioSession, AutoCapitalize, AutoFill, Color, EventKind, HeaderSlot, Hsla, JsonValue,
KeyboardAppearance, KeyboardType, ModalAnimation, ModalPresentation, ModalProp, NativeProp,
OverlayProp, PasteBehavior, PasteEvent, Points, Prop, ResizeMode, ReturnKeyType, Rgba,
ScreenAnimation, ScreenProp, ScrollProp, SheetDetent, Size, StatusBarSetting, SubmitBehavior,
Tag, WebSource,
canvas::{
CanvasFont, CanvasGradient, CanvasImage, CanvasOp, CanvasTextAlign, CanvasTextBaseline,
Composite, Drawing, FillRule, LineCap, LineJoin, Num, Paint, Path, PathOp, ViewPaint,
},
geometry::{Bounds, Corners, Percentage, Point, Radians, ScaledPixels},
js::host::HostProps,
overlay::{Align, OverlayAnchor, Placement},
style::SvgPaint,
};
pub(crate) fn same_kind(a: &Prop, b: &Prop) -> bool {
match (a, b) {
(Prop::ComponentProp(a, _), Prop::ComponentProp(b, _)) => a == b,
(Prop::ComponentPropBinding(a, _), Prop::ComponentPropBinding(b, _)) => a == b,
(Prop::RustProp(a, _), Prop::RustProp(b, _)) => a == b,
_ => HostProps::same_kind(a, b),
}
}
pub(crate) fn reset(prop: &Prop) -> Option<Prop> {
match prop {
Prop::ComponentProp(name, _) => Some(Prop::ComponentProp(name.clone(), None)),
Prop::ComponentPropBinding(name, _) => Some(Prop::ComponentPropBinding(name.clone(), None)),
Prop::RustProp(name, _) => Some(Prop::RustProp(name, None)),
_ => HostProps::reset(prop),
}
}
pub(crate) fn set(node: &mut ElNode, prop: Prop) {
set_in(&mut node.attrs.props, prop);
}
crate::static_reactive!(Color: Color);
crate::static_reactive!(Hsla: Hsla, Rgba, Color);
crate::static_reactive!(crate::AccessibilityRole: crate::AccessibilityRole);
crate::static_reactive!(AutoCapitalize: AutoCapitalize);
crate::static_reactive!(AutoFill: AutoFill);
crate::static_reactive!(crate::HeaderSystemItem: crate::HeaderSystemItem);
crate::static_reactive!(crate::HeaderItem: crate::HeaderItem);
crate::static_reactive!(Vec<crate::HeaderItem>: Vec<crate::HeaderItem>);
crate::static_reactive!(super::header::HeaderItem: super::header::HeaderItem);
crate::static_reactive!(Vec<super::header::HeaderItem>: Vec<super::header::HeaderItem>);
crate::static_reactive!(Vec<super::desktop::MenuItem>: Vec<super::desktop::MenuItem>);
crate::static_reactive!(SheetDetent: SheetDetent);
crate::static_reactive!(Vec<SheetDetent>: Vec<SheetDetent>);
crate::static_reactive!(KeyboardAppearance: KeyboardAppearance);
crate::static_reactive!(KeyboardType: KeyboardType);
crate::static_reactive!(ModalAnimation: ModalAnimation);
crate::static_reactive!(ModalPresentation: ModalPresentation);
crate::static_reactive!(ResizeMode: ResizeMode);
crate::static_reactive!(ReturnKeyType: ReturnKeyType);
crate::static_reactive!(SubmitBehavior: SubmitBehavior);
crate::static_reactive!(PasteBehavior: PasteBehavior);
crate::static_reactive!(crate::EllipsizeMode: crate::EllipsizeMode);
crate::static_reactive!(JsonValue: JsonValue);
crate::static_reactive!(StatusBarSetting: StatusBarSetting, crate::StatusBarStyle);
crate::static_reactive!(Placement: Placement);
crate::static_reactive!(Align: Align);
pub(crate) fn set_in(props: &mut Vec<Prop>, prop: Prop) {
match props.iter_mut().find(|p| same_kind(p, &prop)) {
Some(p) => *p = prop,
None => props.push(prop),
}
}
pub(crate) fn bind_prop<T: 'static>(
node: &mut ElNode,
value: impl IntoReactive<T>,
prop: impl Fn(T) -> Prop + 'static,
) {
node.bind_attr(value, move |attrs, v| set_in(&mut attrs.props, prop(v)));
}
fn listen<T: ?Sized + ToOwned + 'static>(
node: &mut ElNode,
kind: EventKind,
listener: Listener<T>,
decode: events::Decode<T>,
) {
node.handlers.push((kind, events::typed(listener, decode)));
}
macro_rules! host_element {
($(#[$doc:meta])* $name:ident) => {
$(#[$doc])*
#[derive(Clone)]
pub struct $name(ElNode);
impl Element for $name {
fn node(&mut self) -> &mut ElNode {
&mut self.0
}
}
impl IntoElement for $name {
fn into_element(self) -> AnyElement {
AnyElement(self.0)
}
}
impl Accessible for $name {}
impl Interactive for $name {}
impl super::builder::IntoTooltip for $name {
fn apply_tooltip(self, node: &mut ElNode) {
self.into_element().apply_tooltip(node);
}
}
#[allow(dead_code)]
impl $name {
fn set(mut self, prop: Prop) -> Self {
set(&mut self.0, prop);
self
}
fn bind_prop<T: 'static>(
mut self,
value: impl IntoReactive<T>,
prop: impl Fn(T) -> Prop + 'static,
) -> Self {
bind_prop(&mut self.0, value, prop);
self
}
fn listen<T: ?Sized + ToOwned + 'static>(
mut self,
kind: EventKind,
listener: Listener<T>,
decode: events::Decode<T>,
) -> Self {
listen(&mut self.0, kind, listener, decode);
self
}
}
};
}
host_element! {
Input
}
host_element! {
Scroll
}
host_element! {
Stack
}
host_element! {
Screen
}
host_element! {
Modal
}
host_element! {
InputAccessoryView
}
host_element! {
CanvasView
}
host_element! {
Svg
}
host_element! {
ShaderView
}
host_element! {
WebView
}
host_element! {
Video
}
host_element! {
NativeView
}
host_element! {
Overlay
}
impl ParentElement for Overlay {}
impl ParentElement for ShaderView {}
impl ParentElement for Scroll {}
impl ParentElement for Stack {}
impl ParentElement for Screen {}
impl ParentElement for Modal {}
fn has_input_accessory() -> bool {
super::ambient::try_os().unwrap_or_default() == crate::platform::Os::Ios
}
impl ParentElement for InputAccessoryView {
fn child<M>(mut self, child: impl super::IntoChild<M>) -> Self {
if has_input_accessory() {
child.__push_into(&mut self.0.children);
}
self
}
fn children(mut self, children: impl IntoIterator<Item = impl IntoElement>) -> Self {
if has_input_accessory() {
self.0
.children
.extend(children.into_iter().map(|c| c.into_element().0));
}
self
}
}
pub fn overlay() -> Overlay {
Overlay(ElNode::new(Tag::Overlay))
}
pub fn input() -> Input {
Input(ElNode::new(Tag::Input))
}
pub fn scroll() -> Scroll {
Scroll(ElNode::new(Tag::Scroll))
}
#[doc(hidden)]
pub fn stack() -> Stack {
Stack(ElNode::new(Tag::Stack))
}
#[doc(hidden)]
pub fn screen() -> Screen {
let mut node = ElNode::new(Tag::Screen);
node.handlers.push((EventKind::Insets, Listener::noop()));
Screen(node)
}
#[doc(hidden)]
pub fn modal() -> Modal {
let mut node = ElNode::new(Tag::Modal);
node.handlers.push((EventKind::Insets, Listener::noop()));
Modal(node)
}
pub fn input_accessory_view(native_id: &str) -> InputAccessoryView {
let supported = has_input_accessory();
let tag = if supported {
Tag::InputAccessory
} else {
Tag::View
};
let mut node = ElNode::new(tag);
if supported {
set(&mut node, Prop::NativeId(Some(native_id.into())));
} else {
node.style.value(
crate::StyleKey::Display,
crate::PropertyValue::Display(taffy::Display::None),
);
}
InputAccessoryView(node)
}
pub fn canvas(painter: impl IntoReactive<Painter>) -> CanvasView {
let mut node = ElNode::new(Tag::Canvas);
node.bind_attr(painter, |attrs, painter: Painter| {
let r = attrs.rare_mut();
r.drawing = Some(Arc::new(painter.drawing));
r.bound = painter.nodes;
});
CanvasView(node)
}
crate::static_reactive!(Painter: Painter, Drawing);
pub fn svg(src: impl IntoReactive<super::ImageSrc>) -> Svg {
#[cfg(all(feature = "svg", not(target_arch = "wasm32")))]
{
let mut node = ElNode::new(Tag::Canvas);
let shown = svg_drawing(src);
node.bind_attr(
move || shown.get(),
|attrs, drawing: Option<Arc<crate::canvas::Drawing>>| {
if drawing.is_some() || attrs.rare.is_some() {
attrs.rare_mut().drawing = drawing;
}
},
);
Svg(node)
}
#[cfg(not(all(feature = "svg", not(target_arch = "wasm32"))))]
{
let mut node = ElNode::new(Tag::Image);
node.style.value(
crate::StyleKey::ObjectFit,
crate::PropertyValue::ObjectFit(Some(ResizeMode::Contain)),
);
node.bind_attr(src, |attrs, src| attrs.rare_mut().src = Some(src));
set(
&mut node,
Prop::Image(crate::ImageProp::SvgCurrentColor(true)),
);
Svg(node)
}
}
#[cfg(all(feature = "svg", not(target_arch = "wasm32")))]
fn svg_drawing(
src: impl IntoReactive<super::ImageSrc>,
) -> super::reactive::Signal<Option<Arc<Drawing>>> {
use super::reactive::{SignalEquals, render_effect, signal_with, stored, untracked};
let src = src.into_reactive();
let shown = signal_with(None::<Arc<Drawing>>, SignalEquals::Never);
let lease = stored(crate::image::Lease::none());
let task = stored(None::<super::Spawned<()>>);
render_effect(move || {
let src = match &src {
super::Reactive::Static(src) => src.clone(),
super::Reactive::Bound(f) => f(),
};
untracked(|| {
drop(task.replace(None));
let context = crate::image::loader::context();
let source = crate::ImageSource {
uri: src.uri.as_str().into(),
size: None,
scales: crate::ImageScales::NONE,
data: None,
}
.inline();
let Some(location) = context.locate(&source) else {
log::warn!("svg: unsupported source `{}`", source.uri);
shown.set(None);
lease.replace(crate::image::Lease::none());
return;
};
if let Some((drawing, held)) = crate::svg::drawings::now(&location) {
shown.set(Some(drawing));
lease.replace(held);
return;
}
let load = crate::svg::drawings::load(location, context);
task.replace(Some(super::spawn(async move {
let (drawing, held) = load.await;
shown.set(Some(drawing));
lease.replace(held);
})));
});
});
shown
}
pub fn shader() -> ShaderView {
ShaderView(ElNode::new(Tag::Shader))
}
pub fn shader_effect() -> ShaderView {
ShaderView(ElNode::new(Tag::ShaderEffect))
}
pub fn shader_transition() -> ShaderView {
ShaderView(ElNode::new(Tag::ShaderTransition))
}
pub fn screen_effect() -> ShaderView {
ShaderView(ElNode::new(Tag::ScreenEffect))
}
pub fn screen_transition() -> ShaderView {
ShaderView(ElNode::new(Tag::ScreenTransition))
}
crate::static_reactive!(crate::shader::Shader: crate::shader::Shader);
pub struct Uniform(UniformSource);
enum UniformSource {
Value(super::Reactive<crate::shader::UniformValue>),
Animated(super::AnimatedNode),
}
pub trait IntoUniform {
fn into_uniform(self) -> Uniform;
}
impl<T: IntoReactive<crate::shader::UniformValue>> IntoUniform for T {
fn into_uniform(self) -> Uniform {
Uniform(UniformSource::Value(self.into_reactive()))
}
}
impl IntoUniform for &super::AnimatedValue {
fn into_uniform(self) -> Uniform {
Uniform(UniformSource::Animated(super::Animated::animated_node(
self,
)))
}
}
impl IntoUniform for &super::AnimatedNode {
fn into_uniform(self) -> Uniform {
Uniform(UniformSource::Animated(*self))
}
}
crate::static_reactive!(
crate::shader::UniformValue: crate::shader::UniformValue,
f32,
i32,
Color,
Hsla,
[f32; 2],
[f32; 3],
[f32; 4],
Vec<crate::shader::UniformValue>
);
impl ShaderView {
pub fn source(self, shader: impl IntoReactive<crate::shader::Shader>) -> Self {
self.bind_prop(shader, |s| Prop::Shader(Some(s)))
}
pub fn uniform(mut self, name: &str, value: impl IntoUniform) -> Self {
let name: Arc<str> = name.into();
let value = match value.into_uniform().0 {
UniformSource::Value(value) => value,
UniformSource::Animated(node) => {
let value = match node.live() {
Some(node) => {
let id = node.id();
self.0.attrs.rare_mut().bound.push(node);
crate::shader::UniformValue::Animated(id)
}
None => crate::shader::UniformValue::Number(0.0),
};
super::Reactive::Static(value)
}
};
self.0.bind_attr(value, move |attrs, value| {
let mut uniforms = attrs
.props
.iter()
.find_map(|p| match p {
Prop::Uniforms(u) => Some(u.clone()),
_ => None,
})
.unwrap_or_default();
match uniforms.0.iter_mut().find(|(n, _)| *n == name) {
Some(entry) => entry.1 = value,
None => uniforms.0.push((name.clone(), value)),
}
set_in(&mut attrs.props, Prop::Uniforms(uniforms));
});
self
}
pub fn paused(self, paused: impl IntoReactive<bool>) -> Self {
self.bind_prop(paused, Prop::ShaderPaused)
}
pub fn progress(self, progress: impl IntoReactive<Percentage>) -> Self {
self.bind_prop(progress, |p| {
Prop::ShaderProgress(crate::shader::ShaderProgress::Number(p))
})
}
pub fn animated_progress(mut self, value: &impl super::Animated) -> Self {
let progress = match value.animated_node().live() {
Some(node) => {
let id = node.id();
self.0.attrs.rare_mut().bound.push(node);
crate::shader::ShaderProgress::Animated(id)
}
None => crate::shader::ShaderProgress::Number(Percentage(0.0)),
};
self.set(Prop::ShaderProgress(progress))
}
pub fn max_sample_offset(self, offset: Points) -> Self {
self.set(Prop::MaxSampleOffset(offset))
}
pub fn value(self, value: impl IntoReactive<crate::shader::TransitionKey>) -> Self {
self.bind_prop(value, |v| Prop::TransitionValue(Some(v)))
}
pub fn duration(self, duration: std::time::Duration) -> Self {
self.set(Prop::TransitionDuration(Some(
duration.as_secs_f32() * 1000.0,
)))
}
pub fn fallback(self, fallback: crate::TransitionFallback) -> Self {
self.set(Prop::TransitionFallback(fallback))
}
}
crate::static_reactive!(crate::shader::TransitionKey: crate::shader::TransitionKey);
pub fn web_view(url: impl IntoReactive<String>) -> WebView {
WebView(ElNode::new(Tag::WebView)).bind_prop(url, |url: String| {
Prop::Native(NativeProp::Source(WebSource::Uri(url.into())))
})
}
pub fn web_view_html(html: impl IntoReactive<String>, base_url: Option<&str>) -> WebView {
WebView(ElNode::new(Tag::WebView)).html(html, base_url)
}
pub fn video(url: impl IntoReactive<String>) -> Video {
Video(ElNode::new(Tag::Video)).bind_prop(url, |url: String| {
Prop::Native(NativeProp::Source(WebSource::Uri(url.into())))
})
}
pub fn native(name: &str) -> NativeView {
NativeView(ElNode::new(Tag::Native)).set(Prop::Component(name.into()))
}
impl Input {
pub fn value(self, text: impl IntoReactive<String>) -> Self {
self.bind_prop(text, |text: String| Prop::Value(text))
}
pub fn default_value(self, text: impl IntoReactive<String>) -> Self {
self.bind_prop(text, |text: String| Prop::DefaultValue(text))
}
pub fn placeholder(self, text: impl IntoReactive<String>) -> Self {
self.bind_prop(text, |text: String| Prop::Placeholder(text))
}
pub fn placeholder_color(self, color: impl IntoReactive<Hsla>) -> Self {
self.bind_prop(color, |color: Hsla| {
Prop::PlaceholderColor(Some(color.into()))
})
}
pub fn selection_color(self, color: impl IntoReactive<Hsla>) -> Self {
self.bind_prop(color, |color: Hsla| {
Prop::SelectionColor(Some(color.into()))
})
}
pub fn caret_color(self, color: impl IntoReactive<Hsla>) -> Self {
self.bind_prop(color, |color: Hsla| Prop::CaretColor(Some(color.into())))
}
pub fn masked(self, secure: impl IntoReactive<bool>) -> Self {
self.bind_prop(secure, |secure: bool| Prop::Secure(secure))
}
pub fn keyboard_type(self, kind: impl IntoReactive<KeyboardType>) -> Self {
self.bind_prop(kind, |kind: KeyboardType| Prop::KeyboardType(kind))
}
pub fn keyboard_appearance(self, appearance: impl IntoReactive<KeyboardAppearance>) -> Self {
self.bind_prop(appearance, |appearance: KeyboardAppearance| {
Prop::KeyboardAppearance(appearance)
})
}
pub fn return_key_type(self, kind: impl IntoReactive<ReturnKeyType>) -> Self {
self.bind_prop(kind, |kind: ReturnKeyType| Prop::ReturnKeyType(kind))
}
pub fn auto_capitalize(self, mode: impl IntoReactive<AutoCapitalize>) -> Self {
self.bind_prop(mode, |mode: AutoCapitalize| Prop::AutoCapitalize(mode))
}
pub fn auto_correct(self, on: impl IntoReactive<bool>) -> Self {
self.bind_prop(on, |on: bool| Prop::AutoCorrect(on))
}
pub fn auto_fill(self, kind: impl IntoReactive<AutoFill>) -> Self {
self.bind_prop(kind, |kind: AutoFill| Prop::AutoFill(kind))
}
pub fn multiline(self, multiline: impl IntoReactive<bool>) -> Self {
self.bind_prop(multiline, |multiline: bool| Prop::Multiline(multiline))
}
pub fn scrollbar(self, shows: impl IntoReactive<bool>) -> Self {
self.bind_prop(shows, |shows: bool| Prop::Scrollbar(shows.into()))
}
pub fn max_length(self, length: impl IntoReactive<u32>) -> Self {
self.bind_prop(length, |length: u32| Prop::MaxLength(Some(length)))
}
pub fn readonly(self, readonly: impl IntoReactive<bool>) -> Self {
self.bind_prop(readonly, |readonly: bool| Prop::Readonly(readonly))
}
pub fn submit_behavior(self, behavior: impl IntoReactive<SubmitBehavior>) -> Self {
self.bind_prop(behavior, |behavior: SubmitBehavior| {
Prop::SubmitBehavior(Some(behavior))
})
}
pub fn paste_behavior(self, behavior: impl IntoReactive<PasteBehavior>) -> Self {
self.bind_prop(behavior, Prop::PasteBehavior)
}
pub fn on_paste<M>(self, listener: impl IntoListener<PasteEvent, M>) -> Self {
self.listen(EventKind::Paste, listener.into_listener(), events::paste)
}
pub fn auto_focus(self, focus: impl IntoReactive<bool>) -> Self {
self.bind_prop(focus, |focus: bool| Prop::AutoFocus(focus))
}
pub fn caret(self, caret: impl IntoReactive<bool>) -> Self {
self.bind_prop(caret, |caret: bool| Prop::Caret(caret))
}
pub fn input_accessory(self, native_id: impl IntoReactive<String>) -> Self {
self.bind_prop(native_id, |id: String| {
Prop::InputAccessoryViewId(Some(id.into()))
})
}
pub fn selected_range(self, range: impl IntoReactive<(u32, u32)>) -> Self {
self.bind_prop(range, |(start, end): (u32, u32)| {
Prop::Selection(start, end)
})
}
pub fn on_change<M>(self, listener: impl IntoListener<str, M>) -> Self {
self.listen(
EventKind::ChangeText,
listener.into_listener(),
events::text,
)
}
pub fn on_submit<M>(self, listener: impl IntoListener<str, M>) -> Self {
self.listen(
EventKind::SubmitEditing,
listener.into_listener(),
events::text,
)
}
pub fn on_selection_change<M>(self, listener: impl IntoListener<Selection, M>) -> Self {
self.listen(
EventKind::SelectionChange,
listener.into_listener(),
events::selection,
)
}
pub fn on_caret_move<M>(self, listener: impl IntoListener<CaretEvent, M>) -> Self {
self.listen(
EventKind::CaretMove,
listener.into_listener(),
events::caret,
)
}
pub fn on_key_press<M>(self, listener: impl IntoListener<str, M>) -> Self {
self.listen(EventKind::KeyPress, listener.into_listener(), events::key)
}
pub fn on_composition_change<M>(self, listener: impl IntoListener<Composition, M>) -> Self {
self.listen(
EventKind::CompositionChange,
listener.into_listener(),
events::composition,
)
}
pub fn on_content_size_change<M>(self, listener: impl IntoListener<Size<Points>, M>) -> Self {
self.listen(
EventKind::ContentSizeChange,
listener.into_listener(),
events::size,
)
}
}
impl Scroll {
pub fn horizontal(self) -> Self {
self.set(Prop::Horizontal(true))
}
pub fn scrollbar(self, shows: impl IntoReactive<bool>) -> Self {
self.bind_prop(shows, |shows: bool| Prop::Scrollbar(shows.into()))
}
pub fn zoom_range(self, min: f32, max: f32) -> Self {
self.set(Prop::Scroll(ScrollProp::MinZoom(min)))
.set(Prop::Scroll(ScrollProp::MaxZoom(max)))
}
pub fn zoom(self, scale: impl IntoReactive<f32>) -> Self {
self.bind_prop(scale, |scale: f32| Prop::Scroll(ScrollProp::Zoom(scale)))
}
pub fn bounces_zoom(self, bounces: impl IntoReactive<bool>) -> Self {
self.bind_prop(bounces, |bounces: bool| {
Prop::Scroll(ScrollProp::BouncesZoom(bounces))
})
}
pub fn zoomable(self, enabled: impl IntoReactive<bool>) -> Self {
self.bind_prop(enabled, |enabled: bool| {
Prop::Scroll(ScrollProp::Pinch(enabled))
})
}
pub fn center_content(self, center: impl IntoReactive<bool>) -> Self {
self.bind_prop(center, |center: bool| {
Prop::Scroll(ScrollProp::CenterContent(center))
})
}
}
impl super::Scrollable for Scroll {}
impl Screen {
fn header_item(mut self, slot: HeaderSlot, key: &'static str, item: impl IntoElement) -> Self {
let mut node = ElNode::new(Tag::HeaderItem);
node.key = Some(key.into());
set(&mut node, Prop::HeaderSlot(slot));
node.children.push(item.into_element().0);
self.0.children.push(node);
self
}
pub fn title(self, title: impl IntoReactive<super::SharedString>) -> Self {
self.bind_prop(title, |t| {
Prop::Screen(ScreenProp::Title(Some(Arc::from(t.as_str()))))
})
}
pub fn header_visible(self, shown: impl IntoReactive<bool>) -> Self {
self.bind_prop(shown, |v| Prop::Screen(ScreenProp::HeaderVisible(v)))
}
pub fn hides_bottom_bar_when_pushed(self, hides: impl IntoReactive<bool>) -> Self {
self.bind_prop(hides, |v| {
Prop::Screen(ScreenProp::HidesBottomBarWhenPushed(v))
})
}
pub fn supported_orientations(
self,
orientations: impl IntoIterator<Item = Orientation>,
) -> Self {
let bits = orientations.into_iter().fold(0, |bits, o| bits | o.bits());
self.set(Prop::Screen(ScreenProp::Orientations(bits)))
}
pub fn header_large_title(self, large: impl IntoReactive<bool>) -> Self {
self.bind_prop(large, |v| Prop::Screen(ScreenProp::HeaderLargeTitle(v)))
}
pub fn header_transparent(self, transparent: impl IntoReactive<bool>) -> Self {
self.bind_prop(transparent, |v| {
Prop::Screen(ScreenProp::HeaderTransparent(v))
})
}
pub fn header_style(mut self, style: impl IntoReactive<super::Style>) -> Self {
let style = match style.into_reactive() {
super::Reactive::Static(s) if s.1.is_bound() => {
super::Reactive::Bound(std::rc::Rc::new(move || s.clone()))
}
style => style,
};
self.0.bind_attr(style, |a, s: super::Style| {
set_in(&mut a.props, Prop::HeaderStyle(s.0));
if !s.1.is_empty() {
let typed = s.1.resolved();
let list = (!typed.is_empty()).then(|| std::rc::Rc::new(typed.lower()));
set_in(&mut a.props, Prop::HeaderClassList(list));
}
});
self
}
pub fn header_style_with(
self,
f: impl Fn(super::StyleRefinement) -> super::StyleRefinement + 'static,
) -> Self {
let list = move || {
let style = f(super::StyleRefinement::default()).resolved();
(!style.is_empty()).then(|| std::rc::Rc::new(style.lower()))
};
self.bind_prop(super::Reactive::Bound(std::rc::Rc::new(list)), |list| {
Prop::HeaderClassList(list)
})
}
pub fn header_back_title(self, title: impl IntoReactive<super::SharedString>) -> Self {
self.bind_prop(title, |t| {
Prop::Screen(ScreenProp::HeaderBackTitle(Some(Arc::from(t.as_str()))))
})
}
pub fn header_right_system_item(
self,
item: impl IntoReactive<crate::HeaderSystemItem>,
) -> Self {
self.bind_prop(item, |item| {
Prop::Screen(ScreenProp::HeaderRightSystemItem(Some(item)))
})
}
pub fn header_left_system_item(self, item: impl IntoReactive<crate::HeaderSystemItem>) -> Self {
self.bind_prop(item, |item| {
Prop::Screen(ScreenProp::HeaderLeftSystemItem(Some(item)))
})
}
pub fn header_right_symbol(self, name: impl IntoReactive<super::SharedString>) -> Self {
self.bind_prop(name, |n| {
Prop::Screen(ScreenProp::HeaderRightSymbol(Some(Arc::from(n.as_str()))))
})
}
pub fn header_left_symbol(self, name: impl IntoReactive<super::SharedString>) -> Self {
self.bind_prop(name, |n| {
Prop::Screen(ScreenProp::HeaderLeftSymbol(Some(Arc::from(n.as_str()))))
})
}
pub fn header_right_items(
self,
items: impl IntoReactive<Vec<super::header::HeaderItem>>,
) -> Self {
self.bind_prop(items, |items| {
Prop::Screen(ScreenProp::HeaderRightItems(super::header::register(items)))
})
}
pub fn header_back_visible(self, visible: impl IntoReactive<bool>) -> Self {
self.bind_prop(visible, |v| Prop::Screen(ScreenProp::HeaderBackVisible(v)))
}
pub fn pop_on_swipe(self, enabled: impl IntoReactive<bool>) -> Self {
self.bind_prop(enabled, |v| Prop::Screen(ScreenProp::PopOnSwipe(v)))
}
pub fn pop_on_back(self, pop: impl IntoReactive<bool>) -> Self {
self.bind_prop(pop, |v| Prop::Screen(ScreenProp::PopOnBack(v)))
}
pub fn animation(self, animation: impl IntoReactive<ScreenAnimation>) -> Self {
self.bind_prop(animation, |a| Prop::Screen(ScreenProp::Animation(a)))
}
pub fn transition_shader(
self,
shader: impl IntoReactive<Option<crate::shader::TransitionShader>>,
) -> Self {
self.bind_prop(shader, |s: Option<crate::shader::TransitionShader>| {
Prop::TransitionShader(s.map(Into::into))
})
}
pub fn status_bar(self, setting: impl IntoReactive<StatusBarSetting>) -> Self {
self.bind_prop(setting, |s| Prop::Screen(ScreenProp::StatusBar(Some(s))))
}
pub fn header_left(self, item: impl IntoElement) -> Self {
self.header_item(HeaderSlot::Left, "header-left", item)
}
pub fn header_right(self, item: impl IntoElement) -> Self {
self.header_item(HeaderSlot::Right, "header-right", item)
}
pub fn header_title(self, item: impl IntoElement) -> Self {
self.header_item(HeaderSlot::Title, "header-title", item)
}
pub fn header(self, item: impl IntoElement) -> Self {
self.header_item(HeaderSlot::Header, "header", item)
}
pub fn on_dismiss<M>(self, listener: impl IntoListener<(), M>) -> Self {
self.listen(EventKind::Dismiss, listener.into_listener(), events::unit)
}
pub fn on_back_press<M>(self, listener: impl IntoListener<(), M>) -> Self {
self.listen(
EventKind::BackRequest,
listener.into_listener(),
events::unit,
)
}
}
impl Overlay {
pub fn anchor(self, anchor: &super::ElementRef) -> Self {
let anchor = *anchor;
self.bind_prop(
move || match anchor.node() {
Some(id) => OverlayAnchor::Node(id),
None => OverlayAnchor::None,
},
|a| Prop::Overlay(OverlayProp::Anchor(a)),
)
}
pub fn cover(self, cover: &super::ElementRef, shown: impl Fn() -> bool + 'static) -> Self {
let cover = *cover;
self.bind_prop(
move || if shown() { cover.node() } else { None },
|id| Prop::Overlay(OverlayProp::Cover(id)),
)
}
pub fn anchor_beside(self, anchor: &super::ElementRef, edges: &super::ElementRef) -> Self {
let (anchor, edges) = (*anchor, *edges);
self.bind_prop(
move || match (anchor.node(), edges.node()) {
(Some(node), Some(edges)) => OverlayAnchor::Beside { node, edges },
(Some(id), None) => OverlayAnchor::Node(id),
_ => OverlayAnchor::None,
},
|a| Prop::Overlay(OverlayProp::Anchor(a)),
)
}
pub fn anchor_content(self, anchor: &super::ElementRef) -> Self {
let anchor = *anchor;
self.bind_prop(
move || match anchor.node() {
Some(id) => OverlayAnchor::Content(id),
None => OverlayAnchor::None,
},
|a| Prop::Overlay(OverlayProp::Anchor(a)),
)
}
pub fn anchor_point(self, point: impl IntoReactive<Point<Points>>) -> Self {
self.bind_prop(point, |p| {
Prop::Overlay(OverlayProp::Anchor(OverlayAnchor::Point(p)))
})
}
pub fn anchor_bounds(self, bounds: impl IntoReactive<Bounds<Points>>) -> Self {
self.bind_prop(bounds, |b| {
Prop::Overlay(OverlayProp::Anchor(OverlayAnchor::Bounds(b)))
})
}
pub fn anchor_to(self, anchor: impl IntoReactive<OverlayAnchor>) -> Self {
self.bind_prop(anchor, |a| Prop::Overlay(OverlayProp::Anchor(a)))
}
pub fn placement(self, placement: impl IntoReactive<Placement>) -> Self {
self.bind_prop(placement, |p| Prop::Overlay(OverlayProp::Placement(p)))
}
pub fn align(self, align: impl IntoReactive<Align>) -> Self {
self.bind_prop(align, |a| Prop::Overlay(OverlayProp::Align(a)))
}
pub fn offset(self, offset: impl IntoReactive<Points>) -> Self {
self.bind_prop(offset, |o| Prop::Overlay(OverlayProp::Offset(o)))
}
pub fn margin(self, margin: impl IntoReactive<Points>) -> Self {
self.bind_prop(margin, |m| Prop::Overlay(OverlayProp::Margin(m)))
}
pub fn on_press_outside<M>(self, listener: impl IntoListener<Point<Points>, M>) -> Self {
self.listen(
EventKind::PressOutside,
listener.into_listener(),
events::page_point,
)
}
pub fn on_cancel<M>(self, listener: impl IntoListener<(), M>) -> Self {
self.listen(EventKind::Cancel, listener.into_listener(), events::unit)
}
pub fn hint(self, delay: impl IntoReactive<std::time::Duration>) -> Self {
self.bind_prop(delay, |d| Prop::Overlay(OverlayProp::Hint(Some(d))))
}
pub fn hint_open(self, open: impl IntoReactive<Option<bool>>) -> Self {
self.bind_prop(open, |o| Prop::Overlay(OverlayProp::Open(o)))
}
pub fn on_hint_show<M>(self, listener: impl IntoListener<HintReason, M>) -> Self {
self.listen(
EventKind::Show,
listener.into_listener(),
events::hint_reason,
)
}
pub fn on_hint_hide<M>(self, listener: impl IntoListener<HintReason, M>) -> Self {
self.listen(
EventKind::Dismiss,
listener.into_listener(),
events::hint_reason,
)
}
pub fn on_position<M>(self, listener: impl IntoListener<OverlayPosition, M>) -> Self {
self.listen(
EventKind::Position,
listener.into_listener(),
events::overlay_position,
)
}
}
impl Modal {
pub fn animation(self, animation: impl IntoReactive<ModalAnimation>) -> Self {
self.bind_prop(animation, |animation: ModalAnimation| {
Prop::Modal(ModalProp::Animation(animation))
})
}
pub fn transition_shader(
self,
shader: impl IntoReactive<Option<crate::shader::TransitionShader>>,
) -> Self {
self.bind_prop(shader, |s: Option<crate::shader::TransitionShader>| {
Prop::TransitionShader(s.map(Into::into))
})
}
pub fn presentation(self, presentation: impl IntoReactive<ModalPresentation>) -> Self {
self.bind_prop(presentation, |presentation: ModalPresentation| {
Prop::Modal(ModalProp::Presentation(presentation))
})
}
pub fn status_bar(self, setting: impl IntoReactive<StatusBarSetting>) -> Self {
self.bind_prop(setting, |s| Prop::Screen(ScreenProp::StatusBar(Some(s))))
}
pub fn status_bar_translucent(self, translucent: impl IntoReactive<bool>) -> Self {
self.bind_prop(translucent, |translucent: bool| {
Prop::Modal(ModalProp::StatusBarTranslucent(translucent))
})
}
pub fn supported_orientations(
self,
orientations: impl IntoIterator<Item = Orientation>,
) -> Self {
let bits = orientations.into_iter().fold(0, |bits, o| bits | o.bits());
self.set(Prop::Modal(ModalProp::Orientations(bits)))
}
pub fn close_on_escape(self, close: impl IntoReactive<bool>) -> Self {
self.bind_prop(close, |v: bool| Prop::Modal(ModalProp::CloseOnEscape(v)))
}
pub fn close_on_backdrop_press(self, close: impl IntoReactive<bool>) -> Self {
self.bind_prop(close, |v: bool| {
Prop::Modal(ModalProp::CloseOnBackdropPress(v))
})
}
pub fn close_on_swipe(self, close: impl IntoReactive<bool>) -> Self {
self.bind_prop(close, |v: bool| Prop::Modal(ModalProp::CloseOnSwipe(v)))
}
pub fn detents(self, detents: impl IntoReactive<Vec<SheetDetent>>) -> Self {
self.bind_prop(detents, |v: Vec<SheetDetent>| {
Prop::Modal(ModalProp::Detents(v))
})
}
pub fn detent(self, detent: impl IntoReactive<Option<SheetDetent>>) -> Self {
self.bind_prop(detent, |v: Option<SheetDetent>| {
Prop::Modal(ModalProp::Detent(v))
})
}
pub fn default_detent(self, detent: impl IntoReactive<Option<SheetDetent>>) -> Self {
self.bind_prop(detent, |v: Option<SheetDetent>| {
Prop::Modal(ModalProp::DefaultDetent(v))
})
}
pub fn grabber(self, grabber: impl IntoReactive<bool>) -> Self {
self.bind_prop(grabber, |v: bool| Prop::Modal(ModalProp::Grabber(v)))
}
pub fn largest_undimmed_detent(self, detent: impl IntoReactive<Option<SheetDetent>>) -> Self {
self.bind_prop(detent, |v: Option<SheetDetent>| {
Prop::Modal(ModalProp::LargestUndimmedDetent(v))
})
}
pub fn on_detent_change<M>(self, listener: impl IntoListener<SheetDetent, M>) -> Self {
self.listen(
EventKind::DetentChange,
listener.into_listener(),
events::sheet_detent,
)
}
pub fn on_cancel<M>(self, listener: impl IntoListener<(), M>) -> Self {
self.listen(
EventKind::RequestClose,
listener.into_listener(),
events::unit,
)
}
pub fn on_open<M>(self, listener: impl IntoListener<(), M>) -> Self {
self.listen(EventKind::Show, listener.into_listener(), events::unit)
}
pub fn on_close<M>(self, listener: impl IntoListener<(), M>) -> Self {
self.listen(EventKind::Dismiss, listener.into_listener(), events::unit)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Orientation {
Portrait,
PortraitUpsideDown,
Landscape,
LandscapeLeft,
LandscapeRight,
}
impl Orientation {
fn bits(self) -> u8 {
use crate::ModalConfig as M;
match self {
Orientation::Portrait => M::PORTRAIT,
Orientation::PortraitUpsideDown => M::PORTRAIT_UPSIDE_DOWN,
Orientation::Landscape => M::LANDSCAPE_LEFT | M::LANDSCAPE_RIGHT,
Orientation::LandscapeLeft => M::LANDSCAPE_LEFT,
Orientation::LandscapeRight => M::LANDSCAPE_RIGHT,
}
}
}
impl WebView {
pub fn html(self, html: impl IntoReactive<String>, base_url: Option<&str>) -> Self {
let base_url: Option<Arc<str>> = base_url.map(Into::into);
self.bind_prop(html, move |html: String| {
Prop::Native(NativeProp::Source(WebSource::Html {
html: html.into(),
base_url: base_url.clone(),
}))
})
}
pub fn injected_java_script(self, script: impl IntoReactive<String>) -> Self {
self.bind_prop(script, |script: String| {
Prop::Native(NativeProp::InjectedJavaScript(Some(script.into())))
})
}
pub fn injected_java_script_before_content(self, script: impl IntoReactive<String>) -> Self {
self.bind_prop(script, |script: String| {
Prop::Native(NativeProp::InjectedJavaScriptBefore(Some(script.into())))
})
}
pub fn user_agent(self, agent: impl IntoReactive<String>) -> Self {
self.bind_prop(agent, |agent: String| {
Prop::Native(NativeProp::UserAgent(Some(agent.into())))
})
}
pub fn scrollable(self, enabled: impl IntoReactive<bool>) -> Self {
self.bind_prop(enabled, |enabled: bool| {
Prop::Native(NativeProp::Scrollable(enabled))
})
}
pub fn java_script_enabled(self, enabled: impl IntoReactive<bool>) -> Self {
self.bind_prop(enabled, |enabled: bool| {
Prop::Native(NativeProp::JavaScriptEnabled(enabled))
})
}
pub fn back_forward_gestures(self, enabled: impl IntoReactive<bool>) -> Self {
self.bind_prop(enabled, |enabled: bool| {
Prop::Native(NativeProp::BackForwardGestures(enabled))
})
}
pub fn incognito(self, incognito: bool) -> Self {
self.set(Prop::Native(NativeProp::Incognito(incognito)))
}
pub fn url_scheme(
self,
scheme: &str,
handler: impl Fn(crate::web_resource::WebResourceRequest) + Send + Sync + 'static,
) -> Self {
let scheme = match crate::web_resource::WebUrlScheme::new(scheme, handler) {
Ok(scheme) => scheme,
Err(e) => {
log::warn!(target: "js", "web view: {e}");
return self;
}
};
let mut schemes = self
.0
.attrs
.props
.iter()
.find_map(|p| match p {
Prop::Native(NativeProp::UrlSchemes(list)) => Some(list.clone()),
_ => None,
})
.unwrap_or_default();
schemes.retain(|s| s.scheme() != scheme.scheme());
schemes.push(scheme);
self.set(Prop::Native(NativeProp::UrlSchemes(schemes)))
}
pub fn on_load_start<M>(self, listener: impl IntoListener<WebNavigation, M>) -> Self {
self.listen(
EventKind::LoadStart,
listener.into_listener(),
events::navigation,
)
}
pub fn on_load<M>(self, listener: impl IntoListener<WebNavigation, M>) -> Self {
self.listen(
EventKind::Load,
listener.into_listener(),
events::navigation,
)
}
pub fn on_error<M>(self, listener: impl IntoListener<str, M>) -> Self {
self.listen(EventKind::Error, listener.into_listener(), events::message)
}
pub fn on_unavailable<M>(self, listener: impl IntoListener<str, M>) -> Self {
self.listen(
EventKind::Error,
listener.into_listener(),
events::unavailable,
)
}
pub fn on_process_terminated<M>(self, listener: impl IntoListener<str, M>) -> Self {
self.listen(
EventKind::Error,
listener.into_listener(),
events::terminated,
)
}
pub fn on_message<M>(self, listener: impl IntoListener<str, M>) -> Self {
self.listen(EventKind::Message, listener.into_listener(), events::data)
}
pub fn on_navigation_state_change<M>(
self,
listener: impl IntoListener<WebNavigation, M>,
) -> Self {
self.listen(
EventKind::NavigationStateChange,
listener.into_listener(),
events::navigation,
)
}
pub fn on_download<M>(
self,
listener: impl IntoListener<crate::webview::WebDownload, M>,
) -> Self {
self.listen(
EventKind::Download,
listener.into_listener(),
events::web_download,
)
.set(Prop::Native(NativeProp::DeferDownloads(true)))
}
pub fn on_download_pending<M>(
self,
listener: impl IntoListener<crate::webview::WebDownloadPending, M>,
) -> Self {
self.listen(
EventKind::DownloadPending,
listener.into_listener(),
events::web_download_pending,
)
.set(Prop::Native(NativeProp::DeferDownloads(true)))
}
}
impl Video {
pub fn paused(self, paused: impl IntoReactive<bool>) -> Self {
self.bind_prop(paused, |paused: bool| {
Prop::Native(NativeProp::Paused(paused))
})
}
pub fn muted(self, muted: impl IntoReactive<bool>) -> Self {
self.bind_prop(muted, |muted: bool| Prop::Native(NativeProp::Muted(muted)))
}
pub fn volume(self, volume: impl IntoReactive<f32>) -> Self {
self.bind_prop(volume, |volume: f32| {
Prop::Native(NativeProp::Volume(volume))
})
}
pub fn rate(self, rate: impl IntoReactive<f32>) -> Self {
self.bind_prop(rate, |rate: f32| Prop::Native(NativeProp::Rate(rate)))
}
pub fn repeat(self, repeat: impl IntoReactive<bool>) -> Self {
self.bind_prop(repeat, |repeat: bool| {
Prop::Native(NativeProp::Repeat(repeat))
})
}
pub fn controls(self, controls: impl IntoReactive<bool>) -> Self {
self.bind_prop(controls, |controls: bool| {
Prop::Native(NativeProp::Controls(controls))
})
}
pub fn progress_interval(self, ms: impl IntoReactive<f32>) -> Self {
self.bind_prop(ms, |ms: f32| Prop::Native(NativeProp::ProgressInterval(ms)))
}
pub fn audio_session(self, session: impl IntoReactive<AudioSession>) -> Self {
self.bind_prop(session, |session: AudioSession| {
Prop::Native(NativeProp::AudioSession(session))
})
}
pub fn on_load_start<M>(self, listener: impl IntoListener<(), M>) -> Self {
self.listen(EventKind::LoadStart, listener.into_listener(), events::unit)
}
pub fn on_load<M>(self, listener: impl IntoListener<VideoInfo, M>) -> Self {
self.listen(EventKind::Load, listener.into_listener(), events::video)
}
pub fn on_progress<M>(self, listener: impl IntoListener<VideoProgress, M>) -> Self {
self.listen(
EventKind::Progress,
listener.into_listener(),
events::progress,
)
}
pub fn on_end<M>(self, listener: impl IntoListener<(), M>) -> Self {
self.listen(EventKind::End, listener.into_listener(), events::unit)
}
pub fn on_buffer<M>(self, listener: impl IntoListener<bool, M>) -> Self {
self.listen(
EventKind::Buffer,
listener.into_listener(),
events::buffering,
)
}
pub fn on_error<M>(self, listener: impl IntoListener<str, M>) -> Self {
self.listen(EventKind::Error, listener.into_listener(), events::message)
}
}
impl NativeView {
pub fn prop(self, name: &str, value: impl IntoReactive<JsonValue>) -> Self {
let name: Arc<str> = name.into();
self.bind_prop(value, move |value| {
Prop::ComponentProp(name.clone(), Some(value))
})
}
pub fn bind_animated_prop(mut self, name: &str, value: &impl super::Animated) -> Self {
if let Some(node) = value.animated_node().live() {
set(
&mut self.0,
Prop::ComponentPropBinding(name.into(), Some(node.id())),
);
self.0.attrs.rare_mut().bound.push(node);
}
self
}
pub fn on_native_event<M>(self, listener: impl IntoListener<NativeEvent, M>) -> Self {
self.listen(
EventKind::NativeEvent,
listener.into_listener(),
events::native,
)
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct CanvasArg(pub(crate) CanvasArgKind);
#[derive(Debug, Clone, PartialEq)]
pub(crate) enum CanvasArgKind {
Const(f32),
Node(super::LiveNode),
}
impl From<f32> for CanvasArg {
fn from(n: f32) -> Self {
Self(CanvasArgKind::Const(n))
}
}
impl From<Points> for CanvasArg {
fn from(n: Points) -> Self {
Self(CanvasArgKind::Const(n.0))
}
}
impl From<Radians> for CanvasArg {
fn from(n: Radians) -> Self {
Self(CanvasArgKind::Const(n.0))
}
}
impl<A: super::Animated> From<&A> for CanvasArg {
fn from(a: &A) -> Self {
Self(match a.animated_node().live() {
Some(node) => CanvasArgKind::Node(node),
None => CanvasArgKind::Const(0.0),
})
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct CanvasPaint(CanvasPaintKind);
#[derive(Debug, Clone, PartialEq)]
enum CanvasPaintKind {
Color(Color),
Gradient(Arc<CanvasGradient>),
Node(super::LiveNode),
}
impl From<Color> for CanvasPaint {
fn from(color: Color) -> Self {
Self(CanvasPaintKind::Color(color))
}
}
impl From<Hsla> for CanvasPaint {
fn from(color: Hsla) -> Self {
Color::from(color).into()
}
}
impl From<Rgba> for CanvasPaint {
fn from(color: Rgba) -> Self {
Color::from(color).into()
}
}
impl From<CanvasGradient> for CanvasPaint {
fn from(gradient: CanvasGradient) -> Self {
Self(CanvasPaintKind::Gradient(Arc::new(gradient)))
}
}
impl From<Arc<CanvasGradient>> for CanvasPaint {
fn from(gradient: Arc<CanvasGradient>) -> Self {
Self(CanvasPaintKind::Gradient(gradient))
}
}
impl<A: super::Animated> From<&A> for CanvasPaint {
fn from(a: &A) -> Self {
Self(match a.animated_node().live() {
Some(node) => CanvasPaintKind::Node(node),
None => CanvasPaintKind::Color(Color::TRANSPARENT),
})
}
}
#[derive(Debug, Clone, Default)]
pub struct Painter {
drawing: Drawing,
nodes: Vec<super::LiveNode>,
}
impl Painter {
pub fn new() -> Self {
Self::default()
}
pub fn finish(self) -> Drawing {
self.drawing
}
pub fn render(
self,
size: Size<Points>,
options: crate::canvas::render::RenderOptions,
) -> crate::element::Answer<Result<Vec<u8>, crate::element::JsError>> {
crate::element::ambient::render_canvas(crate::canvas::render::RenderRequest {
drawing: self.drawing,
size,
scale: options.scale,
format: options.format,
})
}
pub fn num(&mut self, value: impl Into<CanvasArg>) -> Num {
match value.into().0 {
CanvasArgKind::Const(n) => Num::Const(n),
CanvasArgKind::Node(node) => Num::Slot(self.slot(node)),
}
}
pub fn paint(&mut self, paint: impl Into<CanvasPaint>) -> Paint {
match paint.into().0 {
CanvasPaintKind::Color(color) => Paint::Color(color),
CanvasPaintKind::Gradient(gradient) => Paint::Gradient(gradient),
CanvasPaintKind::Node(node) => Paint::Slot(self.slot(node)),
}
}
fn slot(&mut self, node: super::LiveNode) -> u16 {
let slot = self.drawing.slot(node.id());
self.nodes.push(node);
slot
}
pub fn node(mut self, node: crate::canvas::CanvasNode) -> Self {
self.drawing.nodes.push(node);
self
}
pub fn op(mut self, op: CanvasOp) -> Self {
self.drawing.ops.push(op);
self
}
fn path(self, op: PathOp) -> Self {
self.op(CanvasOp::Path(op))
}
pub fn is_point_in_path(&self, point: Point<Points>, rule: FillRule) -> bool {
crate::canvas::point_in_path(&self.drawing.ops, None, rule, point, |_| 0.0)
}
pub fn is_point_in_stroke(&self, point: Point<Points>) -> bool {
crate::canvas::point_in_stroke(&self.drawing.ops, None, point, |_| 0.0)
}
pub fn path_contains(&self, path: &Path, point: Point<Points>, rule: FillRule) -> bool {
crate::canvas::point_in_path(&self.drawing.ops, Some(path), rule, point, |_| 0.0)
}
pub fn stroke_contains(&self, path: &Path, point: Point<Points>) -> bool {
crate::canvas::point_in_stroke(&self.drawing.ops, Some(path), point, |_| 0.0)
}
pub fn save(self) -> Self {
self.op(CanvasOp::Save)
}
pub fn restore(self) -> Self {
self.op(CanvasOp::Restore)
}
pub fn translate(mut self, x: impl Into<CanvasArg>, y: impl Into<CanvasArg>) -> Self {
let (x, y) = (self.num(x), self.num(y));
self.op(CanvasOp::Translate(x, y))
}
pub fn scale(mut self, x: impl Into<CanvasArg>, y: impl Into<CanvasArg>) -> Self {
let (x, y) = (self.num(x), self.num(y));
self.op(CanvasOp::Scale(x, y))
}
pub fn rotate(mut self, angle: impl Into<CanvasArg>) -> Self {
let a = self.num(angle);
self.op(CanvasOp::Rotate(a))
}
pub fn transform(mut self, m: [impl Into<CanvasArg>; 6]) -> Self {
let m = m.map(|n| self.num(n));
self.op(CanvasOp::Transform(m))
}
pub fn set_transform(mut self, m: [impl Into<CanvasArg>; 6]) -> Self {
let m = m.map(|n| self.num(n));
self.op(CanvasOp::SetTransform(m))
}
pub fn reset_transform(self) -> Self {
self.set_transform([1.0, 0.0, 0.0, 1.0, 0.0, 0.0])
}
pub fn begin_path(self) -> Self {
self.op(CanvasOp::BeginPath)
}
pub fn move_to(mut self, x: impl Into<CanvasArg>, y: impl Into<CanvasArg>) -> Self {
let (x, y) = (self.num(x), self.num(y));
self.path(PathOp::MoveTo(x, y))
}
pub fn line_to(mut self, x: impl Into<CanvasArg>, y: impl Into<CanvasArg>) -> Self {
let (x, y) = (self.num(x), self.num(y));
self.path(PathOp::LineTo(x, y))
}
pub fn quadratic_curve_to(self, control: Point<Points>, to: Point<Points>) -> Self {
let c = |v: Points| Num::Const(v.0);
self.path(PathOp::QuadTo([
c(control.x),
c(control.y),
c(to.x),
c(to.y),
]))
}
pub fn bezier_curve_to(self, c1: Point<Points>, c2: Point<Points>, to: Point<Points>) -> Self {
let c = |v: Points| Num::Const(v.0);
self.path(PathOp::CubicTo([
c(c1.x),
c(c1.y),
c(c2.x),
c(c2.y),
c(to.x),
c(to.y),
]))
}
pub fn arc(
self,
x: impl Into<CanvasArg>,
y: impl Into<CanvasArg>,
radius: impl Into<CanvasArg>,
start: impl Into<CanvasArg>,
end: impl Into<CanvasArg>,
) -> Self {
self.arc_in(x, y, radius, start, end, false)
}
pub fn arc_counterclockwise(
self,
x: impl Into<CanvasArg>,
y: impl Into<CanvasArg>,
radius: impl Into<CanvasArg>,
start: impl Into<CanvasArg>,
end: impl Into<CanvasArg>,
) -> Self {
self.arc_in(x, y, radius, start, end, true)
}
fn arc_in(
mut self,
x: impl Into<CanvasArg>,
y: impl Into<CanvasArg>,
radius: impl Into<CanvasArg>,
start: impl Into<CanvasArg>,
end: impl Into<CanvasArg>,
ccw: bool,
) -> Self {
let (x, y, radius, start, end) = (
self.num(x),
self.num(y),
self.num(radius),
self.num(start),
self.num(end),
);
self.path(PathOp::Arc {
x,
y,
radius,
start,
end,
ccw,
})
}
pub fn arc_to(self, p1: Point<Points>, p2: Point<Points>, radius: Points) -> Self {
let c = |v: Points| Num::Const(v.0);
self.path(PathOp::ArcTo([
c(p1.x),
c(p1.y),
c(p2.x),
c(p2.y),
c(radius),
]))
}
pub fn ellipse(
self,
center: Point<Points>,
radii: Size<Points>,
rotation: Radians,
start: Radians,
end: Radians,
counterclockwise: bool,
) -> Self {
let c = Num::Const;
self.path(PathOp::Ellipse {
geometry: [
c(center.x.0),
c(center.y.0),
c(radii.width.0),
c(radii.height.0),
c(rotation.0),
],
start: c(start.0),
end: c(end.0),
ccw: counterclockwise,
})
}
pub fn rect(self, rect: Bounds<Points>) -> Self {
self.path(PathOp::Rect(nums(rect)))
}
pub fn round_rect(self, rect: Bounds<Points>, radius: Points) -> Self {
self.round_rect_corners(rect, Corners::all(radius))
}
pub fn round_rect_corners(self, rect: Bounds<Points>, radii: Corners<Points>) -> Self {
let c = |v: Points| Num::Const(v.0);
self.path(PathOp::RoundRect(
nums(rect),
[
c(radii.top_left),
c(radii.top_right),
c(radii.bottom_right),
c(radii.bottom_left),
],
))
}
pub fn close_path(self) -> Self {
self.path(PathOp::Close)
}
pub fn fill(self) -> Self {
self.fill_with(FillRule::NonZero)
}
pub fn fill_with(self, rule: FillRule) -> Self {
self.op(CanvasOp::Fill(None, rule))
}
pub fn fill_path(self, path: &Path, rule: FillRule) -> Self {
self.op(CanvasOp::Fill(Some(path.clone()), rule))
}
pub fn fill_svg(self, data: &str) -> Self {
self.fill_path(&crate::canvas::svg_path(data), FillRule::NonZero)
}
pub fn stroke(self) -> Self {
self.op(CanvasOp::Stroke(None))
}
pub fn stroke_path(self, path: &Path) -> Self {
self.op(CanvasOp::Stroke(Some(path.clone())))
}
pub fn stroke_svg(self, data: &str) -> Self {
self.stroke_path(&crate::canvas::svg_path(data))
}
pub fn clip(self) -> Self {
self.clip_with(FillRule::NonZero)
}
pub fn clip_with(self, rule: FillRule) -> Self {
self.op(CanvasOp::Clip(None, rule))
}
pub fn clip_path(self, path: &Path, rule: FillRule) -> Self {
self.op(CanvasOp::Clip(Some(path.clone()), rule))
}
pub fn fill_rect(
mut self,
x: impl Into<CanvasArg>,
y: impl Into<CanvasArg>,
w: impl Into<CanvasArg>,
h: impl Into<CanvasArg>,
) -> Self {
let (x, y, w, h) = (self.num(x), self.num(y), self.num(w), self.num(h));
self.op(CanvasOp::FillRect([x, y, w, h]))
}
pub fn stroke_rect(self, rect: Bounds<Points>) -> Self {
self.op(CanvasOp::StrokeRect(nums(rect)))
}
pub fn clear_rect(self, rect: Bounds<Points>) -> Self {
self.op(CanvasOp::ClearRect(nums(rect)))
}
pub fn fill_color(self, color: impl Into<Hsla>) -> Self {
self.fill_style(color.into())
}
pub fn stroke_color(self, color: impl Into<Hsla>) -> Self {
self.stroke_style(color.into())
}
pub fn fill_style(mut self, paint: impl Into<CanvasPaint>) -> Self {
let paint = self.paint(paint);
self.op(CanvasOp::FillStyle(paint))
}
pub fn fill_style_from_view(self, initial: SvgPaint) -> Self {
self.view_paint(
ViewPaint::Fill(initial),
CanvasOp::FillStyle(Paint::Color(Color::TRANSPARENT)),
)
}
pub fn stroke_style_from_view(self, initial: SvgPaint) -> Self {
self.view_paint(
ViewPaint::Stroke(initial),
CanvasOp::StrokeStyle(Paint::Color(Color::TRANSPARENT)),
)
}
pub fn line_width_from_view(self) -> Self {
self.view_paint(ViewPaint::StrokeWidth, CanvasOp::LineWidth(Num::Const(1.0)))
}
pub fn line_dash_from_view(self) -> Self {
self.view_paint(
ViewPaint::StrokeDasharray,
CanvasOp::LineDash(Arc::from([])),
)
}
pub fn fill_background_from_view(self, area: Bounds<Points>) -> Self {
self.view_paint(
ViewPaint::Background {
area,
rule: FillRule::NonZero,
},
CanvasOp::Fill(None, FillRule::NonZero),
)
}
fn view_paint(mut self, view: ViewPaint, placeholder: CanvasOp) -> Self {
let at = self.drawing.ops.len() as u32;
self.drawing.view_paints.push((at, view));
self.op(placeholder)
}
pub fn stroke_style(mut self, paint: impl Into<CanvasPaint>) -> Self {
let paint = self.paint(paint);
self.op(CanvasOp::StrokeStyle(paint))
}
pub fn line_width(mut self, width: impl Into<CanvasArg>) -> Self {
let w = self.num(width);
self.op(CanvasOp::LineWidth(w))
}
pub fn line_cap(self, cap: LineCap) -> Self {
self.op(CanvasOp::LineCap(cap))
}
pub fn line_join(self, join: LineJoin) -> Self {
self.op(CanvasOp::LineJoin(join))
}
pub fn miter_limit(self, limit: f32) -> Self {
self.op(CanvasOp::MiterLimit(limit.max(1.0)))
}
pub fn line_dash(self, segments: &[Points]) -> Self {
self.op(CanvasOp::LineDash(segments.into()))
}
pub fn line_dash_offset(mut self, offset: impl Into<CanvasArg>) -> Self {
let o = self.num(offset);
self.op(CanvasOp::LineDashOffset(o))
}
pub fn global_alpha(mut self, alpha: impl Into<CanvasArg>) -> Self {
let a = self.num(alpha);
self.op(CanvasOp::GlobalAlpha(a))
}
pub fn composite(self, composite: Composite) -> Self {
self.op(CanvasOp::Composite(composite))
}
pub fn shadow(self, color: impl Into<Hsla>, blur: Points, offset: Point<Points>) -> Self {
self.op(CanvasOp::ShadowColor(Color::from(color.into())))
.op(CanvasOp::ShadowBlur(blur.max(Points::ZERO)))
.op(CanvasOp::ShadowOffset(offset))
}
pub fn font(self, font: &str) -> Self {
match CanvasFont::parse(font) {
Some(font) => self.op(CanvasOp::Font(font)),
None => self,
}
}
pub fn font_variant_numeric(self, numeric: crate::style::FontVariant) -> Self {
self.op(CanvasOp::FontVariantNumeric(crate::style::FontVariant(
numeric.0 & !crate::style::FontVariant::SMALL_CAPS,
)))
}
pub fn text_align(self, align: CanvasTextAlign) -> Self {
self.op(CanvasOp::TextAlign(align))
}
pub fn text_baseline(self, baseline: CanvasTextBaseline) -> Self {
self.op(CanvasOp::TextBaseline(baseline))
}
pub fn fill_text(self, text: &str, x: impl Into<CanvasArg>, y: impl Into<CanvasArg>) -> Self {
self.text(text, x, y, None, false)
}
pub fn fill_text_max_width(
self,
text: &str,
x: impl Into<CanvasArg>,
y: impl Into<CanvasArg>,
max_width: Points,
) -> Self {
self.text(text, x, y, Some(max_width), false)
}
pub fn stroke_text(self, text: &str, x: impl Into<CanvasArg>, y: impl Into<CanvasArg>) -> Self {
self.text(text, x, y, None, true)
}
pub fn stroke_text_max_width(
self,
text: &str,
x: impl Into<CanvasArg>,
y: impl Into<CanvasArg>,
max_width: Points,
) -> Self {
self.text(text, x, y, Some(max_width), true)
}
fn text(
mut self,
text: &str,
x: impl Into<CanvasArg>,
y: impl Into<CanvasArg>,
max_width: Option<Points>,
stroke: bool,
) -> Self {
let (text, x, y) = (text.into(), self.num(x), self.num(y));
self.op(if stroke {
CanvasOp::StrokeText {
text,
x,
y,
max_width,
}
} else {
CanvasOp::FillText {
text,
x,
y,
max_width,
}
})
}
pub fn draw_image(self, uri: &str, dest: Bounds<Points>) -> Self {
self.draw_image_part(uri, None, dest)
}
pub fn draw_image_part(
self,
uri: &str,
source: Option<Bounds<ScaledPixels>>,
dest: Bounds<Points>,
) -> Self {
self.op(CanvasOp::DrawImage {
image: CanvasImage { uri: uri.into() },
source,
dest: nums(dest),
})
}
}
fn nums(rect: Bounds<Points>) -> [Num; 4] {
[
rect.origin.x,
rect.origin.y,
rect.size.width,
rect.size.height,
]
.map(|v| Num::Const(v.0))
}
impl From<Drawing> for Painter {
fn from(drawing: Drawing) -> Self {
Self {
drawing,
nodes: Vec::new(),
}
}
}
crate::static_reactive!(ScreenAnimation: ScreenAnimation);
impl IntoReactive<Option<crate::shader::TransitionShader>> for crate::shader::TransitionShader {
fn into_reactive(self) -> super::Reactive<Option<crate::shader::TransitionShader>> {
super::Reactive::Static(Some(self))
}
}
impl IntoReactive<Option<crate::MacOsBackdrop>> for crate::MacOsBackdrop {
fn into_reactive(self) -> super::Reactive<Option<crate::MacOsBackdrop>> {
super::Reactive::Static(Some(self))
}
}
impl IntoReactive<Option<crate::WindowsBackdrop>> for crate::WindowsBackdrop {
fn into_reactive(self) -> super::Reactive<Option<crate::WindowsBackdrop>> {
super::Reactive::Static(Some(self))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
element::{
AnimatedValue,
reactive::{Runtime, create_root, signal},
},
shader::{ShaderUniforms, UniformValue},
};
fn uniforms(attrs: &super::super::builder::Attrs) -> ShaderUniforms {
attrs
.props
.iter()
.find_map(|p| match p {
Prop::Uniforms(u) => Some(u.clone()),
_ => None,
})
.unwrap_or_default()
}
fn released(executor: &super::super::task::Executor) -> usize {
executor
.take_actions()
.into_iter()
.filter(|a| {
matches!(
a,
super::super::task::Action::Animation(
crate::animation::AnimationOp::Release { .. }
)
)
})
.count()
}
fn value(u: &ShaderUniforms, name: &str) -> Option<UniformValue> {
u.0.iter()
.find(|(n, _)| &**n == name)
.map(|(_, v)| v.clone())
}
#[test]
fn screens_and_modals_take_a_transition_shader() {
let runtime = Runtime::default();
let _entered = runtime.enter();
let source = "struct Uniforms { edge: f32 }\n\
fn shade(uv: vec2f) -> vec4f {\n \
return select(sample_from(uv), sample_to(uv), uv.x < nsh.progress * uniforms.edge);\n}\n";
let shader = crate::shader::Shader::compile(source).expect("compiles");
let wipe = crate::shader::TransitionShader::new(shader)
.uniform("edge", 1.0_f32)
.duration(std::time::Duration::from_millis(400));
let expected = crate::shader::NavShaderSpec {
source: source.into(),
uniforms: ShaderUniforms(vec![("edge".into(), UniformValue::Number(1.0))]),
duration: Some(400.0),
};
let spec = |attrs: &super::super::builder::Attrs| {
attrs.props.iter().find_map(|p| match p {
Prop::TransitionShader(s) => Some(s.clone()),
_ => None,
})
};
let page = screen().transition_shader(wipe.clone()).0;
assert_eq!(spec(&page.resolved_attrs()), Some(Some(expected.clone())));
let dialog = modal().transition_shader(wipe.clone()).0;
assert_eq!(spec(&dialog.resolved_attrs()), Some(Some(expected.clone())));
let on = signal(true);
let bound = screen()
.transition_shader(move || on.get().then(|| wipe.clone()))
.0;
assert_eq!(spec(&bound.resolved_attrs()), Some(Some(expected)));
on.set(false);
assert_eq!(spec(&bound.resolved_attrs()), Some(None));
}
#[test]
fn uniform_takes_static_bound_and_animated_values() {
let runtime = Runtime::default();
let _entered = runtime.enter();
let executor = std::rc::Rc::new(super::super::task::Executor::default());
let (value_owner, wave) = create_root(|| AnimatedValue::new(&executor, 0.0));
let speed = signal(1.0_f32);
let view = shader()
.uniform("center", [0.5_f32, 0.5])
.uniform("wave", &wave)
.uniform("speed", move || speed.get());
let node = view.0;
let set = uniforms(&node.attrs);
assert_eq!(
value(&set, "center"),
Some(UniformValue::List(vec![
UniformValue::Number(0.5),
UniformValue::Number(0.5)
]))
);
let id = wave.node().live().expect("live").id();
assert_eq!(value(&set, "wave"), Some(UniformValue::Animated(id)));
assert_eq!(
node.attrs.bound().len(),
1,
"the element holds the animated node"
);
assert_eq!(
value(&set, "speed"),
None,
"a bound one is applied when resolved"
);
assert_eq!(
value(&uniforms(&node.resolved_attrs()), "speed"),
Some(UniformValue::Number(1.0))
);
speed.set(2.0);
assert_eq!(
value(&uniforms(&node.resolved_attrs()), "speed"),
Some(UniformValue::Number(2.0))
);
value_owner.dispose();
assert_eq!(released(&executor), 0, "the view keeps the animated node");
drop(node);
assert_eq!(released(&executor), 1, "and lets it go with the view");
}
#[test]
fn a_later_uniform_replaces_one_of_the_same_name() {
let view = shader().uniform("speed", 1.0_f32).uniform("speed", 3.0_f32);
let set = uniforms(&view.0.attrs);
assert_eq!(set.0.len(), 1);
assert_eq!(value(&set, "speed"), Some(UniformValue::Number(3.0)));
}
#[test]
fn web_view_url_scheme_builder_collects_schemes() {
let web = web_view_html("<img src=\"a:1\">", None)
.url_scheme("a", |request| request.fail())
.url_scheme("b", |request| request.fail())
.url_scheme("A", |request| request.fail())
.url_scheme("https", |request| request.fail());
let schemes: Vec<String> = web
.0
.attrs
.props
.iter()
.find_map(|p| match p {
Prop::Native(NativeProp::UrlSchemes(list)) => {
Some(list.iter().map(|s| s.scheme().to_owned()).collect())
}
_ => None,
})
.unwrap();
assert_eq!(schemes, ["b", "a"]);
}
}