zng/widget.rs
1//! Widget info, builder and base, UI node and list.
2//!
3//! The [`Wgt!`](struct@Wgt) widget is a blank widget that entirely shaped by properties.
4//!
5//! ```
6//! use zng::prelude::*;
7//! # let _scope = APP.defaults();
8//!
9//! # let _ =
10//! Wgt! {
11//! id = "sun";
12//!
13//! widget::background_gradient = {
14//! axis: 0.deg(),
15//! stops: color::gradient::stops![hex!(#ff5226), hex!(#ffc926)],
16//! };
17//! layout::size = 100;
18//! widget::corner_radius = 100;
19//! layout::align = layout::Align::BOTTOM;
20//!
21//! #[easing(2.secs())]
22//! layout::y = 100;
23//! when *#widget::is_inited {
24//! layout::y = -30;
25//! }
26//! }
27//! # ;
28//! ```
29//!
30//! To learn more about the widget macros syntax see [`widget_set!`].
31//!
32//! To learn more about how widgets are declared see [`widget`].
33//!
34//! To learn more about how properties are declared see [`property`].
35//!
36//! # Full API
37//!
38//! See [`zng_app::widget`] for the full API.
39
40pub use zng_app::widget::base::{HitTestMode, NonWidgetBase, PARALLEL_VAR, Parallel, WidgetBase, WidgetExt, WidgetImpl};
41
42pub use zng_app::widget::{WIDGET, WidgetId, WidgetUpdateMode, widget_impl, widget_set};
43
44pub use zng_app::widget::border::{
45 BORDER, BorderSide, BorderSides, BorderStyle, CornerRadius, CornerRadiusFit, LineOrientation, LineStyle,
46};
47pub use zng_app::widget::info::Visibility;
48pub use zng_app::widget::node::ZIndex;
49
50pub use zng_app::render::RepeatMode;
51
52pub use zng_wgt::{
53 EDITORS, EditorRequestArgs, IS_MOBILE_VAR, OnNodeOpArgs, WeakWidgetFn, Wgt, WidgetFn, auto_hide, border, border_align, border_over,
54 clip_to_bounds, corner_radius, corner_radius_fit, enabled, hit_test_mode, inline, interactive, is_collapsed, is_disabled, is_enabled,
55 is_hidden, is_hit_testable, is_inited, is_mobile, is_visible, modal, modal_included, modal_includes, on_block, on_blocked_changed,
56 on_collapse, on_deinit, on_disable, on_enable, on_enabled_changed, on_hide, on_info_init, on_init, on_interactivity_changed, on_move,
57 on_node_op, on_pre_block, on_pre_blocked_changed, on_pre_collapse, on_pre_deinit, on_pre_disable, on_pre_enable,
58 on_pre_enabled_changed, on_pre_hide, on_pre_init, on_pre_interactivity_changed, on_pre_move, on_pre_node_op, on_pre_show,
59 on_pre_transform_changed, on_pre_unblock, on_pre_update, on_pre_vis_disable, on_pre_vis_enable, on_pre_vis_enabled_changed,
60 on_pre_visibility_changed, on_show, on_transform_changed, on_unblock, on_update, on_vis_disable, on_vis_enable, on_vis_enabled_changed,
61 on_visibility_changed, parallel, visibility, wgt_fn, z_index,
62};
63
64#[cfg(feature = "image")]
65pub use zng_wgt_image::border::{BorderRepeats, border_img, border_img_fill, border_img_repeat};
66
67pub use zng_wgt_fill::{
68 background, background_color, background_conic, background_fn, background_gradient, background_radial, foreground, foreground_color,
69 foreground_conic, foreground_fn, foreground_gradient, foreground_highlight, foreground_radial,
70};
71
72/// Widget and property builder types.
73///
74/// # Examples
75///
76/// The example declares a new widget type, `ShowProperties!`, that inherits from `Text!` and display what properties
77/// are set on itself by accessing the [`WidgetBuilder`] at two points. First call is directly in the `widget_intrinsic` that
78/// is called after inherited intrinsics, but before the instance properties are set. Second call is in a build action that is called when
79/// the widget starts building, after the instance properties are set.
80///
81/// [`WidgetBuilder`]: builder::WidgetBuilder
82///
83/// ```
84/// mod widgets {
85/// use std::fmt::Write as _;
86/// use zng::prelude_wgt::*;
87///
88/// #[widget($crate::widgets::ShowProperties)]
89/// pub struct ShowProperties(zng::text::Text);
90///
91/// impl ShowProperties {
92/// fn widget_intrinsic(&mut self) {
93/// let txt = var(Txt::from(""));
94/// widget_set! {
95/// self;
96/// txt = txt.clone();
97/// }
98///
99/// let builder = self.widget_builder();
100///
101/// let mut t = Txt::from("Properties set by default:\n");
102/// for p in builder.properties() {
103/// writeln!(&mut t, "• {}", p.args.property().name).unwrap();
104/// }
105///
106/// builder.push_build_action(move |builder| {
107/// writeln!(&mut t, "\nAll properties set:").unwrap();
108/// for p in builder.properties() {
109/// writeln!(&mut t, "• {}", p.args.property().name).unwrap();
110/// }
111/// txt.set(t.clone());
112/// });
113/// }
114/// }
115/// }
116///
117/// # fn main() {
118/// # let _scope = zng::APP.defaults();
119/// # let _ =
120/// widgets::ShowProperties! {
121/// font_size = 20;
122/// }
123/// # ;
124/// # }
125/// ```
126///
127/// # Full API
128///
129/// See [`zng_app::widget::builder`] for the full API.
130pub mod builder {
131 pub use zng_app::widget::builder::{
132 AnyWhenArcWidgetHandlerBuilder, ArcWidgetHandler, BuilderProperty, BuilderPropertyMut, BuilderPropertyRef, Importance, InputKind,
133 NestGroup, NestPosition, PropertyArgs, PropertyBuildAction, PropertyBuildActionArgs, PropertyBuildActions,
134 PropertyBuildActionsWhenData, PropertyId, PropertyInfo, PropertyInput, PropertyInputTypes, PropertyNewArgs, SourceLocation,
135 WhenBuildAction, WhenInfo, WhenInput, WhenInputMember, WhenInputVar, WidgetBuilder, WidgetBuilderProperties, WidgetBuilding,
136 WidgetType, property_args, property_id, property_info, property_input_types, source_location, widget_type,
137 };
138}
139
140/// Widget info tree and info builder.
141///
142/// # Examples
143///
144/// The example declares a new info state for widgets and a property that sets the new state. The new state is then used
145/// in a widget.
146///
147/// ```
148/// mod custom {
149/// use zng::prelude_wgt::*;
150///
151/// static_id! {
152/// static ref STATE_ID: StateId<bool>;
153/// }
154///
155/// #[property(CONTEXT)]
156/// pub fn flag_state(child: impl UiNode, state: impl IntoVar<bool>) -> impl UiNode {
157/// let state = state.into_var();
158/// match_node(child, move |_, op| match op {
159/// UiNodeOp::Init => {
160/// WIDGET.sub_var_info(&state);
161/// }
162/// UiNodeOp::Info { info } => {
163/// info.set_meta(*STATE_ID, state.get());
164/// }
165/// _ => {}
166/// })
167/// }
168///
169/// pub trait StateExt {
170/// fn state(&self) -> Option<bool>;
171/// }
172/// impl StateExt for WidgetInfo {
173/// fn state(&self) -> Option<bool> {
174/// self.meta().get_clone(*STATE_ID)
175/// }
176/// }
177/// }
178///
179/// # fn main() {
180/// # use zng::prelude::*;
181/// # let _scope = APP.defaults();
182/// # let _ =
183/// Wgt! {
184/// custom::flag_state = true;
185/// widget::on_info_init = hn!(|_| {
186/// use custom::StateExt as _;
187/// let info = WIDGET.info();
188/// println!("state: {:?}", info.state());
189/// });
190/// }
191/// # ;
192/// # }
193/// ```
194pub mod info {
195 pub use zng_app::widget::info::{
196 HitInfo, HitTestInfo, INTERACTIVITY_CHANGED_EVENT, InlineSegmentInfo, InteractionPath, Interactivity, InteractivityChangedArgs,
197 InteractivityFilterArgs, ParallelBuilder, RelativeHitZ, TRANSFORM_CHANGED_EVENT, TransformChangedArgs, TreeFilter,
198 VISIBILITY_CHANGED_EVENT, VisibilityChangedArgs, WIDGET_INFO_CHANGED_EVENT, WidgetBorderInfo, WidgetBoundsInfo,
199 WidgetDescendantsRange, WidgetInfo, WidgetInfoBuilder, WidgetInfoChangedArgs, WidgetInfoMeta, WidgetInfoTree, WidgetInfoTreeStats,
200 WidgetInlineInfo, WidgetInlineMeasure, WidgetPath, iter,
201 };
202
203 /// Accessibility metadata types.
204 pub mod access {
205 pub use zng_app::widget::info::access::{AccessBuildArgs, WidgetAccessInfo, WidgetAccessInfoBuilder};
206 }
207
208 /// Helper types for inspecting an UI tree.
209 pub mod inspector {
210 pub use zng_app::widget::inspector::{
211 InspectPropertyPattern, InspectWidgetPattern, InspectorActualVars, InspectorInfo, InstanceItem, WidgetInfoInspectorExt,
212 };
213 }
214}
215
216/// Widget node types, [`UiNode`], [`UiNodeList`] and others.
217///
218/// [`UiNode`]: crate::prelude::UiNode
219/// [`UiNodeList`]: crate::prelude::UiNodeList
220pub mod node {
221 pub use zng_app::widget::node::{
222 AdoptiveChildNode, AdoptiveNode, ArcNode, ArcNodeList, BoxedUiNode, BoxedUiNodeList, DefaultPanelListData, EditableUiNodeList,
223 EditableUiNodeListRef, FillUiNode, MatchNodeChild, MatchNodeChildren, MatchWidgetChild, NilUiNode, OffsetUiListObserver, PanelList,
224 PanelListData, PanelListRange, SORTING_LIST, SortingList, UiNode, UiNodeList, UiNodeListChain, UiNodeListChainImpl,
225 UiNodeListObserver, UiNodeOp, UiNodeOpMethod, UiVec, WeakNode, WeakNodeList, WhenUiNodeBuilder, WhenUiNodeListBuilder, Z_INDEX,
226 extend_widget, match_node, match_node_leaf, match_node_list, match_node_typed, match_widget, ui_vec,
227 };
228
229 pub use zng_wgt::node::{
230 bind_state, bind_state_init, border_node, event_state, event_state2, event_state3, event_state4, fill_node, interactive_node,
231 list_presenter, presenter, presenter_opt, widget_state_get_state, widget_state_is_state, with_context_blend, with_context_local,
232 with_context_local_init, with_context_var, with_context_var_init, with_index_len_node, with_index_node, with_rev_index_node,
233 with_widget_state, with_widget_state_modify,
234 };
235}
236
237/// Expands a struct to a widget struct and macro.
238///
239/// Each widget is a struct and macro pair of the same name that builds a custom widget using [`WidgetBuilder`]. Widgets
240/// *inherit* from one other widget and can also inherit multiple mix-ins. Widgets can have intrinsic nodes, default properties
241/// and can build to a custom output type.
242///
243/// Properties can be strongly associated with the widget using the `#[property(.., widget_impl(Widget))]` directive, existing properties
244/// can be implemented for the widget using the [`widget_impl!`] macro.
245///
246/// # Attribute
247///
248/// The widget attribute must be placed in a `struct Name(Parent);` declaration, only struct following the exact pattern are allowed,
249/// different struct syntaxes will generate a compile error.
250///
251/// The attribute requires one argument, it must be a macro style `$crate` path to the widget struct, this is used in the generated macro
252/// to find the struct during instantiation. The path must be to the *public* path to the struct, that is, the same path that will be used
253/// to import the widget. After the required widget path [custom rules](#custom-rules) for the generated macro can be declared.
254///
255/// ```
256/// # fn main() { }
257/// use zng::prelude_wgt::*;
258///
259/// /// Minimal widget.
260/// #[widget($crate::Foo)]
261/// pub struct Foo(WidgetBase);
262/// ```
263///
264/// # Inherit
265///
266/// The widget struct field must be the parent widget type. All widgets inherit from another or the
267/// [`WidgetBase`], the parent widgets intrinsic properties and nodes are all included in the new widget. The intrinsic
268/// properties are included by deref, the new widget will dereference to the parent widget, during widget build auto-deref will select
269/// the property methods first, this mechanism even allows for property overrides.
270///
271/// # Intrinsic
272///
273/// The widget struct can define a method `widget_intrinsic` that includes custom build actions in the [`WidgetBuilder`], this special
274/// method will be called once for the widget. The same method is also called for the inherited widgets.
275///
276/// ```
277/// # fn main() { }
278/// use zng::prelude_wgt::*;
279///
280/// #[widget($crate::Foo)]
281/// pub struct Foo(WidgetBase);
282///
283/// impl Foo {
284/// fn widget_intrinsic(&mut self) {
285/// self.widget_builder().push_build_action(|b| {
286/// // push_intrinsic, capture_var.
287/// });
288/// }
289/// }
290/// ```
291///
292/// The example above demonstrates the intrinsic method used to [`push_build_action`]. This is the primary mechanism for widgets to define their
293/// own behavior that does not depend on properties. Note that the widget inherits from [`WidgetBase`], during instantiation
294/// of `Foo!` the base `widget_intrinsic` is called first, then the `Foo!` `widget_intrinsic` is called.
295///
296/// The method does not need to be `pub`, and it is not required.
297///
298/// # Build
299///
300/// The widget struct can define a method that builds the final widget instance.
301///
302/// ```
303/// # fn main() { }
304/// use zng::prelude_wgt::*;
305///
306/// #[widget($crate::Foo)]
307/// pub struct Foo(WidgetBase);
308///
309/// impl Foo {
310/// /// Custom build.
311/// pub fn widget_build(&mut self) -> impl UiNode + use<> {
312/// println!("on build!");
313/// WidgetBase::widget_build(self)
314/// }
315/// }
316/// ```
317///
318/// The build method must have the same visibility as the widget, and can define its own
319/// return type, this is the widget instance type. If the build method is not defined the inherited parent build method is used.
320///
321/// Unlike the [intrinsic](#intrinsic) method, the widget only has one `widget_build`, if defined it overrides the parent
322/// `widget_build`. Most widgets don't define their own build, leaving it to be inherited from [`WidgetBase`]. The base instance type
323/// is an opaque `impl UiNode`.
324///
325/// Normal widgets must implement [`UiNode`], otherwise they cannot be used as child of other widgets.
326/// The widget outer-node also must implement the widget context, to ensure that the widget is correctly placed in the UI tree.
327/// Note that you can still use the parent type build implementation, so even if you need
328/// to run code on build or define a custom type you don't need to deref to the parent type to build.
329///
330/// # Defaults
331///
332/// The [`widget_set!`] macro can be used inside `widget_intrinsic` to set properties and when conditions that are applied on the widget by default,
333/// if not overridden by derived widgets or the widget instance. During the call to `widget_intrinsic` the `self.importance()` value is
334/// [`Importance::WIDGET`], after it is changed to [`Importance::INSTANCE`], so just by setting properties in `widget_intrinsic` they
335/// will have less importance allowing for the override mechanism to replace them.
336///
337/// # Impl Properties
338///
339/// The [`widget_impl!`] macro can be used inside a `impl WgtIdent { }` block to strongly associate a property with the widget,
340/// and the [`property`] attribute has a `widget_impl(WgtIdent)` directive that also strongly associates a property with the widget.
341///
342/// These two mechanisms can be used to define properties for the widget, the impl properties don't need to be imported and are
343/// always selected over other properties of the same name. They also appear in the widget documentation and can have a distinct
344/// visual in IDEs as they are represented by immutable methods while standalone properties are represented by mutable trait methods.
345///
346/// As a general rule only properties that are captured by the widget, or only work with the widget, or have an special meaning in the widget
347/// are implemented like this, standalone properties that can be used in any widget are not implemented.
348///
349/// # Generated Macro
350///
351/// The generated widget macro has the same syntax as [`widget_set!`], except that is also starts the widget and builds it at the end.
352///
353/// This widget macro call:
354///
355/// ```
356/// # use zng::prelude_wgt::*;
357/// # #[widget($crate::Foo)]
358/// # pub struct Foo(WidgetBase);
359/// #
360/// # fn main() {
361/// let wgt = Foo! {
362/// id = "foo";
363/// };
364/// # }
365/// ```
366///
367/// Expands to this:
368///
369/// ```
370/// # use zng::prelude_wgt::*;
371/// # #[widget($crate::Foo)]
372/// # pub struct Foo(WidgetBase);
373/// #
374/// # fn main() {
375/// let wgt = {
376/// let mut wgt = Foo::widget_new();
377/// widget_set! {
378/// &mut wgt;
379/// id = "foo";
380/// }
381/// wgt.widget_build()
382/// };
383/// # }
384/// ```
385///
386/// #### Custom Rules
387///
388/// You can declare custom rules for the widget macro, this can be used to declare custom shorthand syntax for the widget.
389///
390/// The custom rules are declared inside braces after the widget path in the widget attribute. The syntax is similar to `macro_rules!`
391/// rules, but the expanded tokens are the direct input of the normal widget expansion.
392///
393/// ```txt
394/// (<rule>) => { <init> };
395/// ```
396///
397/// The `<rule>` is any macro pattern rule, the `<init>` is the normal widget init code that the rule expands to.
398///
399/// Note that custom rules are not inherited, they apply only to the declaring widget macro, inherited widgets must replicate
400/// the rules if desired.
401///
402/// Example of a widget that declares a shorthand syntax to implicitly set the `id` property:
403///
404/// ```
405/// use zng::prelude_wgt::*;
406///
407/// #[widget($crate::Foo {
408/// ($id:expr) => {
409/// id = $id;
410/// };
411/// })]
412/// pub struct Foo(WidgetBase);
413///
414/// # fn main() {
415/// let wgt = Foo!("foo");
416/// # }
417/// ```
418///
419/// The macro instance above is equivalent to:
420///
421/// ```
422/// # use zng::prelude_wgt::*;
423/// # #[widget($crate::Foo)]
424/// # pub struct Foo(WidgetBase);
425/// #
426/// # fn main() {
427/// let wgt = Foo! {
428/// id = "foo";
429/// };
430/// # }
431/// ```
432///
433/// #### Limitations
434///
435/// The expanded tokens can only be a recursive input for the same widget macro, you can't expand to a different widget.
436///
437/// Some rules are intercepted by the default widget rules:
438///
439/// * `$(#[$attr:meta])* $($property:ident)::+ = $($rest:tt)*`, blocks all custom `$ident = $tt*` patterns.
440/// * `$(#[$attr:meta])* when $($rest:tt)*`, blocks all custom `when $tt*` patterns.
441///
442/// Note that the default single property shorthand syntax is not blocked, for example `Text!(font_size)` will match
443/// the custom shorthand rule and try to set the `txt` with the `font_size` variable, without the shorthand it would create a widget without
444/// `txt` that sets `font_size`. So a custom rule `$p:expr` is only recommended for widgets that have a property of central importance.
445///
446/// # Widget Type
447///
448/// A public associated function `widget_type` is also generated for the widget, it returns a [`WidgetType`] instance that describes the
449/// widget type. Note that this is not the widget instance type, only the struct and macro type. If compiled with the `"inspector"` feature
450/// the type is also available in the widget info.
451///
452/// # See Also
453///
454/// See the [`WidgetBase`], [`WidgetBuilder`], [`WidgetBuilding`], [`NestGroup`] and [`Importance`] for more details.
455///
456/// [`WidgetBuilder`]: builder::WidgetBuilder
457/// [`WidgetType`]: builder::WidgetType
458/// [`WidgetBuilding`]: builder::WidgetBuilding
459/// [`NestGroup`]: builder::NestGroup
460/// [`Importance`]: builder::Importance
461/// [`push_build_action`]: builder::WidgetBuilder::push_build_action
462/// [`UiNode`]: node::UiNode
463/// [`WidgetBase`]: struct@WidgetBase
464/// [`Importance::WIDGET`]: builder::Importance::WIDGET
465/// [`Importance::INSTANCE`]: builder::Importance::INSTANCE
466///
467/// <script>
468/// // hide re-exported docs
469/// let me = document.currentScript;
470/// document.addEventListener("DOMContentLoaded", function() {
471/// while(me.nextElementSibling !== null) {
472/// me.nextElementSibling.remove();
473/// }
474/// });
475/// </script>
476pub use zng_app::widget::widget;
477
478/// Expands a struct to a widget mix-in.
479///
480/// Widget mix-ins can be inserted on a widgets inheritance chain, but they cannot be instantiated directly. Unlike
481/// the full widgets it defines its parent as a generic type, that must be filled with a real widget when used.
482///
483/// By convention mix-ins have the suffix `Mix` and the generic parent is named `P`. The `P` must not have any generic bounds
484/// in the declaration, the expansion will bound it to [`WidgetImpl`].
485///
486/// # Examples
487///
488/// ```
489/// # fn main() { }
490/// use zng::prelude_wgt::*;
491///
492/// /// Make a widget capable of receiving keyboard focus.
493/// #[widget_mixin]
494/// pub struct FocusableMix<P>(P);
495/// impl<P: WidgetImpl> FocusableMix<P> {
496/// fn widget_intrinsic(&mut self) {
497/// widget_set! {
498/// self;
499/// focusable = true;
500/// }
501/// }
502///
503/// widget_impl! {
504/// /// If the widget can receive focus, enabled by default.
505/// pub zng::focus::focusable(enabled: impl IntoVar<bool>);
506/// }
507/// }
508///
509/// /// Foo is focusable.
510/// #[widget($crate::Foo)]
511/// pub struct Foo(FocusableMix<WidgetBase>);
512/// ```
513///
514/// The example above declares a mix-in `FocusableMix<P>` and a widget `Foo`, the mix-in is used as a parent of the widget, only
515/// the `Foo! { }` widget can be instantiated, and it will have the strongly associated property `focusable` from the mix-in.
516///
517/// All widget `impl` items can be declared in a mix-in, including the `fn widget_build(&mut self) -> T`. Multiple mix-ins can be inherited
518/// by nesting the types in a full widget `Foo(AMix<BMix<Base>>)`. Mix-ins cannot inherit from other mix-ins.
519///
520/// <script>
521/// // hide re-exported docs
522/// let me = document.currentScript;
523/// document.addEventListener("DOMContentLoaded", function() {
524/// while(me.nextElementSibling !== null) {
525/// me.nextElementSibling.remove();
526/// }
527/// });
528/// </script>
529pub use zng_app::widget::widget_mixin;
530
531/// Expands a property assign to include an easing animation.
532///
533/// The attribute generates a [property build action] that applies [`Var::easing`] to the final variable inputs of the property.
534///
535/// # Arguments
536///
537/// The attribute takes one required argument and one optional that matches the [`Var::easing`]
538/// parameters. The required first arg is the duration, the second arg is an easing function, if not present the [`easing::linear`] is used.
539///
540/// Some items are auto-imported in each argument scope, [`TimeUnits`] for the first arg and the [`easing`] functions
541/// for the second. This enables syntax like `#[easing(300.ms(), expo)]`.
542///
543/// ## Unset
544///
545/// An alternative argument `unset` can be used instead to remove animations set by the inherited context or styles.
546///
547/// [`TimeUnits`]: zng::layout::TimeUnits
548/// [`easing`]: mod@zng::var::animation::easing
549/// [`easing::linear`]: zng::var::animation::easing::linear
550/// [property build action]: crate::widget::builder::WidgetBuilder::push_property_build_action
551/// [`Var::easing`]: crate::var::Var::easing
552///
553/// ## When
554///
555/// The attribute can also be set in `when` assigns, in this case the easing will be applied when the condition is active, so
556/// only the transition to the `true` value is animated using the conditional easing.
557///
558/// Note that you can't `unset` easing in when conditions, but you can set it to `0.ms()`, if all easing set for a property are `0`
559/// no easing variable is generated, in contexts that actually have animation the `when`` value will be set immediately,
560/// by a zero sized animation.
561///
562/// # Examples
563///
564/// The example demonstrates setting and removing easing animations.
565///
566/// ```
567/// # use zng::prelude_wgt::*;
568/// # #[widget($crate::Foo)] pub struct Foo(WidgetBase);
569/// # #[property(FILL, default(colors::BLACK))]
570/// # pub fn background_color(child: impl UiNode, color: impl IntoVar<Rgba>) -> impl UiNode {
571/// # child
572/// # }
573/// # #[property(LAYOUT, default(0))]
574/// # pub fn margin(child: impl UiNode, color: impl IntoVar<SideOffsets>) -> impl UiNode {
575/// # child
576/// # }
577/// # fn main() {
578/// Foo! {
579/// #[easing(300.ms(), expo)] // set/override the easing.
580/// background_color = colors::RED;
581///
582/// #[easing(unset)] // remove easing set by style or widget defaults.
583/// margin = 0;
584/// }
585/// # ; }
586/// ```
587///
588/// # Limitations
589///
590/// The attribute only works in properties that only have variable inputs of types that are [`Transitionable`], if the attribute
591/// is set in a property that does not match this a cryptic type error occurs, with a mention of `easing_property_input_Transitionable`.
592///
593/// <script>
594/// // hide re-exported docs
595/// let me = document.currentScript;
596/// document.addEventListener("DOMContentLoaded", function() {
597/// while(me.nextElementSibling !== null) {
598/// me.nextElementSibling.remove();
599/// }
600/// });
601/// </script>
602///
603/// [`Transitionable`]: crate::var::animation::Transitionable
604pub use zng_app::widget::easing;
605
606/// Expands a function to a widget property.
607///
608/// Property functions take one [`UiNode`] child input and one or more other inputs and produces an [`UiNode`] that implements
609/// the property feature.
610///
611/// The attribute expansion does not modify the function, it can still be used as a function directly. Some
612/// properties are implemented by calling other property functions to generate a derived effect.
613///
614/// The attribute expansion generates a hidden trait of the same name and visibility, the trait is implemented for widget builders,
615/// the widget macros use this to set the property. Because it has the same name it is imported together with the property
616/// function, in practice this only matters in doc links where you must use the `fn@` disambiguator.
617///
618/// # Attribute
619///
620/// The property attribute has one required argument and three optional.
621///
622/// #### Nest Group
623///
624/// The first argument is the property [`NestGroup`]. The group defines the overall nest position
625/// of the property, for example, `LAYOUT` properties always wrap `FILL` properties. This is important as widgets are open and any combination
626/// of properties may end-up instantiated in the same widget.
627///
628/// ```
629/// # fn main() { }
630/// use zng::prelude_wgt::*;
631///
632/// #[property(LAYOUT)]
633/// pub fn align(child: impl UiNode, align: impl IntoVar<Align>) -> impl UiNode {
634/// // ..
635/// # child
636/// }
637/// ```
638///
639/// The nest group can be tweaked, by adding or subtracting integers, in the example bellow both properties are in the `SIZE` group,
640/// but `size` is always inside `max_size`.
641///
642/// ```
643/// # fn main() { }
644/// use zng::prelude_wgt::*;
645///
646/// #[property(SIZE+1)]
647/// pub fn size(child: impl UiNode, size: impl IntoVar<Size>) -> impl UiNode {
648/// // ..
649/// # child
650/// }
651///
652/// #[property(SIZE)]
653/// pub fn max_size(child: impl UiNode, size: impl IntoVar<Size>) -> impl UiNode {
654/// // ..
655/// # child
656/// }
657/// ```
658///
659/// #### Default
660///
661/// The next argument is an optional `default(args..)`. It defines the value to use when the property must be instantiated and no value was provided.
662/// The defaults should cause the property to behave as if it is not set, as the default value will be used in widgets that only set the
663/// property in `when` blocks.
664///
665/// ```
666/// # fn main() { }
667/// use zng::prelude_wgt::*;
668///
669/// #[property(FILL, default(rgba(0, 0, 0, 0)))]
670/// pub fn background_color(child: impl UiNode, color: impl IntoVar<Rgba>) -> impl UiNode {
671/// // ..
672/// # child
673/// }
674/// ```
675///
676/// In the example above the `background_color` defines a transparent color as the default, so if the background color is only set in a `when`
677/// block if will only be visible when it is active.
678///
679/// For properties with multiple inputs the default args may be defined in a comma separated list of params, `default(dft0, ..)`.
680///
681/// #### Impl For
682///
683/// The last argument is an optional `impl(<widget-type>)`, it strongly associates
684/// the property with a widget, users can set this property on the widget without needing to import the property.
685///
686/// Note that this makes the property have priority over all others of the same name, only a derived widget can override
687/// with another strongly associated property.
688///
689/// Note that you can also use the [`widget_impl!`] in widget declarations to implement existing properties for a widget.
690///
691/// #### Capture
692///
693/// After the nest group and before default the `, capture, ` value indicates that the property is capture-only. This flag
694/// changes how the property must be declared, the first argument is a property input and the function can have only one input,
695/// no return type is allowed and the function body must be empty, unused input warnings are suppressed by the expanded code.
696///
697/// Capture-only properties must be captured by a widget and implemented as part of the widget's intrinsics, the reason for
698/// a property function is purely to define the property signature and metadata, the capture-only property function can also
699/// be used to set a property dynamically, such as in a style widget that is applied on the actual widget that captures the property.
700///
701/// A documentation sections explaining capture-only properties is generated for the property, it is also tagged differently in the functions list.
702///
703/// ```
704/// # fn main() { }
705/// use zng::prelude_wgt::*;
706///
707/// /// Children property, must be captured by panel widgets.
708/// #[property(CONTEXT, capture)]
709/// pub fn children(children: impl UiNodeList) { }
710/// ```
711///
712/// # Args
713///
714/// The property function requires at least two args, the first is the child node and the other(s) the input values. The
715/// number and type of inputs is validated at compile time, the types are limited and are identified and validated by their
716/// token name, so you cannot use renamed types.
717///
718/// #### Child
719///
720/// The first function arg must be of type `impl UiNode`, it represents the child node and the property node must
721/// delegate to it so that the UI tree functions correctly. The type must be an `impl` generic, a full path to [`UiNode`]
722/// is allowed, but no import renames as the proc-macro attribute can only use tokens to identify the type.
723///
724/// #### Inputs
725///
726/// The second arg and optional other args define the property inputs. When a property is assigned in a widget only these inputs
727/// are defined by the user, the child arg is provided by the widget builder. Property inputs are limited, and must be identifiable
728/// by their token name alone. The types are validated at compile time, they must be declared using `impl` generics,
729/// a full path to the generic traits is allowed, but no import renames.
730///
731/// #### Input Types
732///
733/// These are the allowed input types:
734///
735/// ##### `impl IntoVar<T>`
736///
737/// The most common type, accepts any value that can be converted [`IntoVar<T>`], usually the property defines the `T`, but it can be generic.
738/// The property node must respond to var updates. The input kind is [`InputKind::Var`]. No auto-default is generated for this type, property
739/// implementation should provide a default value that causes the property to behave as if it was not set.
740///
741/// The input can be read in `when` expressions and can be assigned in `when` blocks.
742///
743/// ##### `impl IntoValue<T>`
744///
745/// Accepts any value that can be converted [`IntoValue<T>`] that does not change, usually the property
746/// defines the `T`, but it can be generic. The input kind is [`InputKind::Value`]. No auto-default is generated for this type.
747///
748/// The input can be read in `when` expressions, but cannot be assigned in `when` blocks.
749///
750/// ##### `impl UiNode`
751///
752/// This input accepts another [`UiNode`], the implementation must handle it like it handles the child node, delegating all methods. The
753/// input kind is [`InputKind::UiNode`]. The [`NilUiNode`] is used as the default value if no other is provided.
754///
755/// The input cannot be read in `when` expressions, but can be assigned in `when` blocks.
756///
757/// ##### `impl UiNodeList`
758///
759/// This input accepts an [`UiNodeList`], the implementation must handle it like it handles the child node, delegating all methods. The
760/// input kind is [`InputKind::UiNodeList`]. An empty list is used as the default value if no other is provided.
761///
762/// The input cannot be read in `when` expressions, but can be assigned in `when` blocks.
763///
764/// ##### `impl WidgetHandler<A>`
765///
766/// This input accepts any [`WidgetHandler<A>`] for the argument type `A`, usually the property defines the `A`, but it can be generic.
767/// The input kind is [`InputKind::WidgetHandler`]. A no-op handler is used for the default if no other is provided.
768///
769/// Event handler properties usually have the `on_` name prefix. You can use the [`event_property!`] macro to generate standard event properties.
770///
771/// The input cannot be read in `when` expressions, but can be assigned in `when` blocks.
772///
773/// # Getter Properties
774///
775/// Most properties with var inputs are *setters*, that is the inputs affect the widget. Some properties
776/// can be *getters*, detecting widget state and setting it on the *input* variable. These properties are usually named with
777/// a prefix that indicates their input is actually for getting state, the prefixes `is_` and `has_` mark a property with
778/// a single `bool` input that reads a widget state, the prefix `get_` and `actual_` marks a property that reads a non-boolean state from
779/// the widget.
780///
781/// Getter properties are configured with a default read-write variable, so that they can be used in `when` expressions directly,
782/// for example, `when *#is_pressed`, the `is_pressed` property has a `default(var(false))`, so it automatically initializes
783/// with a read-write variable that is used in the when condition. The property attribute generates defaults automatically
784/// based on the prefix, the default is `var(T::default())`, this can be overwritten just by setting the default,
785/// it is not possible to declare a getter property without default.
786///
787/// Note that if a property is used in `when` condition without being set and without default value the when block is discarded on
788/// widget build. If you are implementing a getter property that is not named using the prefixes listed above you must set `default(var(T::default())`.
789///
790/// # Generics
791///
792/// Apart from the `impl` generics of inputs and child, there is some support for named generic types, only one named generic is allowed
793/// for inputs `impl IntoVar<T>`, `impl IntoValue<T>` and `impl WidgetHandler<A>`.
794///
795/// # Output
796///
797/// The property output type must be any type that implements [`UiNode`], usually an opaque type `impl UiNode` is used. The property
798/// node can be anything, as long as it delegates to the child node, see [`match_node`] or [`ui_node`] about implementing a node.
799///
800/// Some common property patterns have helper functions, for example, to setup a context var you can use the [`with_context_var`] function.
801///
802/// # More Details
803///
804/// See [`property_id!`] and [`property_args!`] for more details about what kind of meta-code is generated for properties.
805///
806/// [`NestGroup`]: crate::widget::builder::NestGroup
807/// [`property_id!`]: crate::widget::builder::property_id
808/// [`property_args!`]: crate::widget::builder::property_args
809/// [`ui_node`]: macro@ui_node
810/// [`match_node`]: crate::widget::node::match_node
811/// [`with_context_var`]: crate::widget::node::with_context_var
812/// [`VarValue`]: crate::var::VarValue
813/// [`IntoValue<T>`]: crate::var::IntoValue
814/// [`IntoVar<T>`]: crate::var::IntoVar
815/// [`WidgetHandler<A>`]: crate::handler::WidgetHandler
816/// [`UiNode`]: crate::widget::node::UiNode
817/// [`UiNodeList`]: crate::widget::node::UiNodeList
818/// [`NilUiNode`]: crate::widget::node::NilUiNode
819/// [`InputKind::Var`]: crate::widget::builder::InputKind::Var
820/// [`InputKind::Value`]: crate::widget::builder::InputKind::Value
821/// [`InputKind::UiNode`]: crate::widget::builder::InputKind::UiNode
822/// [`InputKind::UiNodeList`]: crate::widget::builder::InputKind::UiNodeList
823/// [`InputKind::WidgetHandler`]: crate::widget::builder::InputKind::WidgetHandler
824/// [`event_property!`]: crate::event::event_property
825///
826/// <script>
827/// // hide re-exported docs
828/// let me = document.currentScript;
829/// document.addEventListener("DOMContentLoaded", function() {
830/// while(me.nextElementSibling !== null) {
831/// me.nextElementSibling.remove();
832/// }
833/// });
834/// </script>
835pub use zng_app::widget::property;
836
837/// Expands an impl block into an [`UiNode`] trait implementation.
838///
839/// Missing [`UiNode`] methods are generated by this macro. The generation is configured in the macro arguments.
840/// The arguments can be a single keyword, a delegate or an entire struct declaration.
841///
842/// The general idea is you implement only the methods required by your node and configure this macro to generate the methods
843/// that are just boilerplate UI tree propagation, and in [new node](#new-node) mode var and event handlers can be inited automatically
844/// as well.
845///
846/// # Delegate to single `impl UiNode`
847///
848/// If your node contains a single child node, you can configure the attribute
849/// to delegate the method calls for the child node.
850///
851/// ```
852/// # fn main() { }
853/// use zng::prelude_wgt::*;
854///
855/// struct MyNode<C> {
856/// child: C
857/// }
858/// #[ui_node(delegate = &mut self.child)]
859/// impl<C: UiNode> UiNode for MyNode<C> { }
860/// ```
861///
862/// If the child node is in a field named `child` you can use this shorthand to the same effect:
863///
864/// ```
865/// # fn main() { }
866/// # use zng::prelude_wgt::*;
867/// # struct MyNode<C> { child: C }
868/// #[ui_node(child)]
869/// impl<C: UiNode> UiNode for MyNode<C> { }
870/// ```
871///
872/// The generated code simply calls the same [`UiNode`] method in the child.
873///
874/// # Delegate to a `impl UiNodeList`
875///
876/// If your node contains multiple children nodes in a type that implements [`UiNodeList`],
877/// you can configure the attribute to delegate to the equivalent list methods.
878///
879/// ```
880/// # fn main() { }
881/// use zng::prelude_wgt::*;
882///
883/// struct MyNode<L> {
884/// children: L
885/// }
886/// #[ui_node(delegate_list = &mut self.children)]
887/// impl<L: UiNodeList> UiNode for MyNode<L> { }
888/// ```
889///
890/// If the children list is a member named `children` you can use this shorthand to the same effect:
891///
892/// ```
893/// # fn main() { }
894/// # use zng::prelude_wgt::*;
895/// # struct MyNode<L> { children: L }
896/// #[ui_node(children)]
897/// impl<L: UiNodeList> UiNode for MyNode<L> { }
898/// ```
899///
900/// The generated code simply calls the equivalent [`UiNodeList`] method in the list.
901/// That is the same method name with the `_all` prefix. So `UiNode::init` maps to `UiNodeList::init_all` and so on.
902///
903/// ## Don't Delegate
904///
905/// If your node does not have any child nodes you can configure the attribute to generate empty missing methods.
906///
907/// ```
908/// # fn main() { }
909/// # use zng::prelude_wgt::*;
910/// # struct MyNode { }
911/// #[ui_node(none)]
912/// impl UiNode for MyNode { }
913/// ```
914///
915/// The generated [`measure`] and [`layout`] code returns the fill size.
916///
917/// The other generated methods are empty.
918///
919/// # Validation
920///
921/// If delegation is configured but no delegation occurs in the manually implemented methods
922/// you get the error ``"auto impl delegates call to `{}` but this manual impl does not"``.
923///
924/// To disable this error use `#[allow_(zng::missing_delegate)]` in the method or in the `impl` block. The
925/// error is also not shown if the method body contains a call to the [`todo!()`] macro.
926///
927/// The [`measure`] method is an exception to this and will not show the error, its ideal implementation
928/// is one where the entire sub-tree is skipped from the computation.
929///
930/// # Mixing Methods
931///
932/// You can use the same `impl` block to define [`UiNode`] methods and
933/// associated methods by using this attribute in a `impl` block without trait. The [`UiNode`]
934/// methods must be tagged with the `#[UiNode]` pseudo-attribute.
935///
936/// ```
937/// # fn main() { }
938/// # use zng::prelude_wgt::*;
939/// # struct MyNode { child: BoxedUiNode }
940/// #[ui_node(child)]
941/// impl MyNode {
942/// fn do_the_thing(&mut self) {
943/// // ..
944/// }
945///
946/// #[UiNode]
947/// fn init(&mut self) {
948/// self.child.init();
949/// self.do_the_thing();
950/// }
951///
952/// #[UiNode]
953/// fn update(&mut self, updates: &WidgetUpdates) {
954/// self.child.update(updates);
955/// self.do_the_thing();
956/// }
957/// }
958/// ```
959///
960/// The above code expands to two `impl` blocks, one with the associated method and the other with
961/// the [`UiNode`] implementation.
962///
963/// This is particularly useful for nodes that have a large amount of generic constraints, you just type them once.
964///
965/// # New Node
966///
967/// In all the usage seen so far you must declare the `struct` type and the generic bounds to
968/// make it work in the `impl` block, and any var or event in it needs to be subscribed manually. You can
969/// avoid this extra boilerplate by declaring the node `struct` as an arg for the macro.
970///
971/// ```
972/// # fn main() { }
973/// # use zng::prelude_wgt::*;
974/// fn my_widget_node(child: impl UiNode, number: impl IntoVar<u32>) -> impl UiNode {
975/// #[ui_node(struct MyNode {
976/// child: impl UiNode,
977/// #[var] number: impl Var<u32>,
978/// })]
979/// impl UiNode for MyNode {
980/// fn update(&mut self, updates: &WidgetUpdates) {
981/// self.child.update(updates);
982/// if let Some(n) = self.number.get_new() {
983/// println!("new number: {n}");
984/// }
985/// }
986/// }
987/// MyNode {
988/// child,
989/// number: number.into_var(),
990/// }
991/// }
992/// ```
993///
994/// In the example above the `MyNode` struct is declared with two generic params: `T_child` and `T_var`, the unimplemented
995/// node methods are delegated to `child` because of the name, and the `number` var is subscribed automatically because of
996/// the `#[var]` pseudo attribute.
997///
998/// Note that you can also use [`node::match_node`] to declare *anonymous* nodes, most of the properties are implemented using
999/// this node instead of the `#[ui_node]` macro.
1000///
1001/// #### Generics
1002///
1003/// You can declare named generics in the `struct`, those are copied to the implement block, you can also have members with type
1004/// `impl Trait`, a named generic is generated for these, the generated name is `T_member`. You can use named generics in the `impl`
1005/// generics the same way as you would in a function.
1006///
1007/// #### Impl Block
1008///
1009/// The impl block cannot have any generics, they are added automatically, the `UiNode for` part is optional, like in the delegating
1010/// mode, if you omit the trait you must annotate each node method with the `#[UiNode]` pseudo attribute.
1011///
1012/// #### Delegation
1013///
1014/// Delegation is limited to members named `child` or `children`, there is no way to declare a custom delegation in *new node*
1015/// mode. If no specially named member is present the `none` delegation is used.
1016///
1017/// #### Subscription
1018///
1019/// You can mark members with the `#[var]` or `#[event]` pseudo attributes to generate initialization code that subscribes the var or
1020/// event to the [`WIDGET`] context. The init code is placed in a method with signature `fn auto_subs(&mut self)`,
1021/// if you manually implement the `init` node method you must call `self.auto_subs();` in it, a compile time error is emitted if the call is missing.
1022///
1023/// #### Limitations
1024///
1025/// The new node type must be private, you cannot set visibility modifiers. The struct cannot have any attribute set on it, but you can
1026/// have attributes in members, the `#[cfg]` attribute is copied to generated generics. The `impl Trait` auto-generics only works for
1027/// the entire type of a generic, you cannot declare a type `Vec<impl Debug>` for example.
1028///
1029/// [`UiNode`]: crate::widget::node::UiNode
1030/// [`UiNodeList`]: crate::widget::node::UiNodeList
1031/// [`measure`]: crate::widget::node::UiNode::measure
1032/// [`layout`]: crate::widget::node::UiNode::layout
1033/// [`render`]: crate::widget::node::UiNode::render
1034/// [`WIDGET`]: crate::widget::WIDGET
1035///
1036/// <script>
1037/// // hide re-exported docs
1038/// let me = document.currentScript;
1039/// document.addEventListener("DOMContentLoaded", function() {
1040/// while(me.nextElementSibling !== null) {
1041/// me.nextElementSibling.remove();
1042/// }
1043/// });
1044/// </script>
1045pub use zng_app::widget::ui_node;