Skip to main content

mitsuami_core/
custom.rs

1//! Custom widgets: one platform-free definition, rendered natively on each
2//! platform or drawn with the [`Canvas`] API.
3//!
4//! - [`CustomWidget`]: the shared part. Props, events, semantics, and what
5//!   accessibility actions mean.
6//! - [`Drawn`]: the drawn tier. Measure, draw and hit-test in shared code;
7//!   runs everywhere, and stands in for the widget in headless tests.
8//! - The composed tier ([`Renderer::composed`]): built from the built-in
9//!   widgets, for widgets the [`Canvas`] can't draw (text, editing).
10//! - A native render per platform, e.g. `mitsuami_appkit::NativeRender`.
11//! - [`Render`]: says which render each platform uses. Using a widget
12//!   requires it, so a platform with no render doesn't compile.
13//!
14//! A widget unique to one platform is native there. Elsewhere it's built
15//! ad hoc from the platform's widgets, the way that platform's apps build
16//! it ([`Renderer::ad_hoc`]), or drawn, or composed; [`Renderer::is_native`]
17//! says which.
18
19use std::fmt;
20use std::rc::Rc;
21
22use mitsuami_reactive::{IntoValue, Value};
23
24use crate::a11y::{A11yAction, A11yProps};
25use crate::any_value::{AnyValue, Opaque};
26use crate::backend::{MeasureRequest, PlatformMetrics};
27use crate::command::{PointerEvent, UiEvent};
28use crate::draw::{Canvas, DisplayList};
29use crate::element::{Element, ElementBuilder};
30use crate::geometry::Size;
31use crate::ui::Ui;
32use crate::view::{AnyView, View};
33use crate::widget::{NodeId, Prop, WidgetKind};
34
35/// The shared, platform-free definition of a custom widget.
36///
37/// Its functions answer from their arguments alone. [`a11y`](Self::a11y),
38/// [`Drawn::measure`] and [`Drawn::draw`] run while the `Ui` holds its
39/// tree (building the accessibility tree, laying out, drawing), so one
40/// that reaches a `Ui` (builds nodes, sets props, commits, reads a query)
41/// panics with a `RefCell` borrow error. [`action`](Self::action) and
42/// [`Drawn::pointer`] run with the tree free, but their job is to return
43/// an event, which the app handles in [`Custom::on_event`].
44pub trait CustomWidget: Sized + 'static {
45    /// Shown in trees, logs and snapshots.
46    const NAME: &'static str;
47    type Props: Clone + PartialEq + fmt::Debug + 'static;
48    type Event: Clone + PartialEq + fmt::Debug + 'static;
49
50    /// Semantics, shared by every render. Apps can still override the
51    /// label and description where they use the widget.
52    fn a11y(props: &Self::Props) -> A11yProps;
53
54    /// What an accessibility action (increment, set value, …) means for
55    /// this widget. Used unless the native render performs it itself.
56    fn action(props: &Self::Props, action: &A11yAction) -> Option<Self::Event> {
57        let _ = (props, action);
58        None
59    }
60}
61
62/// The drawn tier: measured, drawn and hit-tested in shared code.
63pub trait Drawn: CustomWidget {
64    /// Intrinsic size, like a backend measures a native control.
65    fn measure(props: &Self::Props, request: &MeasureRequest, metrics: &PlatformMetrics) -> Size;
66
67    /// Draws into `canvas`, sized to the widget's frame. Called again
68    /// whenever the props, the size or the platform metrics change.
69    fn draw(props: &Self::Props, canvas: &mut Canvas);
70
71    /// What a pointer event at `event.position` (widget coordinates) means.
72    fn pointer(props: &Self::Props, size: Size, event: &PointerEvent) -> Option<Self::Event> {
73        let _ = (props, size, event);
74        None
75    }
76}
77
78/// Which render this platform uses. Implement it once, choosing per
79/// platform with `platform!`:
80///
81/// ```ignore
82/// impl Render for Rating {
83///     fn renderer() -> Renderer<Self> {
84///         platform! {
85///             macos => mitsuami::appkit::native::<Self>().with_drawn(),
86///             _ => Renderer::drawn(),
87///         }
88///     }
89/// }
90/// ```
91pub trait Render: CustomWidget {
92    fn renderer() -> Renderer<Self>;
93}
94
95/// A widget's renders on the current platform: native, drawn or composed.
96/// The first one present is used: native, then drawn, then composed. The
97/// others stay available (for headless tests, `.drawn()`, `.composed()`).
98pub struct Renderer<W: CustomWidget> {
99    native: Option<Opaque>,
100    /// The native render is the platform's own control, not built ad hoc.
101    platform_control: bool,
102    drawn: Option<DrawnFns>,
103    composed: Option<ComposeFn<W>>,
104}
105
106/// Builds the composed render from the widget's props and a way to emit
107/// its events.
108type ComposeFn<W> = Rc<dyn Fn(Composed<W>) -> AnyView>;
109
110/// What a composed render gets: the props (reactive), a way to emit the
111/// widget's events, and the accessible label the app gave the widget.
112pub struct Composed<W: CustomWidget> {
113    props: Rc<dyn Fn() -> W::Props>,
114    emit: Rc<dyn Fn(W::Event)>,
115    label: Option<String>,
116}
117
118impl<W: CustomWidget> Clone for Composed<W> {
119    fn clone(&self) -> Self {
120        Composed { props: self.props.clone(), emit: self.emit.clone(), label: self.label.clone() }
121    }
122}
123
124impl<W: CustomWidget> Composed<W> {
125    /// The current props. Reading them in a reactive closure tracks them.
126    pub fn props(&self) -> W::Props {
127        (self.props)()
128    }
129
130    /// Sends an event to the widget's `on_event` handlers. Call it from the
131    /// built-in widgets' handlers (a click, a submit).
132    pub fn emit(&self, event: W::Event) {
133        (self.emit)(event)
134    }
135
136    /// The accessible label the app gave the widget: put it on the control
137    /// that stands for the widget, so it's found the same way.
138    pub fn label(&self) -> Option<String> {
139        self.label.clone()
140    }
141}
142
143impl<W: CustomWidget> Renderer<W> {
144    /// Draws the widget with its [`Drawn`] implementation.
145    pub fn drawn() -> Renderer<W>
146    where
147        W: Drawn,
148    {
149        Renderer { native: None, platform_control: false, drawn: Some(DrawnFns::of::<W>()), composed: None }
150    }
151
152    /// For backend crates: a native render that is the platform's own
153    /// control, in whatever form the backend understands. Apps use the
154    /// backend's constructor instead.
155    pub fn native(render: Opaque) -> Renderer<W> {
156        Renderer { native: Some(render), platform_control: true, drawn: None, composed: None }
157    }
158
159    /// For backend crates: a render built ad hoc from the platform's widgets,
160    /// where the platform has no such control. It's rendered like a native
161    /// one, but [`is_native`](Renderer::is_native) says no.
162    pub fn ad_hoc(render: Opaque) -> Renderer<W> {
163        Renderer { native: Some(render), platform_control: false, drawn: None, composed: None }
164    }
165
166    /// Keeps the drawn render too: headless tests lay the widget out with
167    /// it, and `Custom::drawn` can pick it.
168    pub fn with_drawn(mut self) -> Renderer<W>
169    where
170        W: Drawn,
171    {
172        self.drawn = Some(DrawnFns::of::<W>());
173        self
174    }
175
176    /// Composes the widget from built-in widgets: the tier for widgets the
177    /// canvas can't draw.
178    pub fn composed<V: View>(compose: impl Fn(Composed<W>) -> V + 'static) -> Renderer<W> {
179        Renderer {
180            native: None,
181            platform_control: false,
182            drawn: None,
183            composed: Some(Rc::new(move |c| AnyView::new(compose(c)))),
184        }
185    }
186
187    /// Keeps a composed render too, for `Custom::composed`.
188    pub fn with_composed<V: View>(mut self, compose: impl Fn(Composed<W>) -> V + 'static) -> Renderer<W> {
189        self.composed = Some(Rc::new(move |c| AnyView::new(compose(c))));
190        self
191    }
192
193    /// Whether the widget is the platform's own control here (rather than
194    /// built ad hoc, drawn or composed as a stand-in).
195    pub fn is_native(&self) -> bool {
196        self.native.is_some() && self.platform_control
197    }
198}
199
200/// The drawn tier, type-erased.
201#[derive(Clone, Copy)]
202struct DrawnFns {
203    measure: fn(&AnyValue, &MeasureRequest, &PlatformMetrics) -> Size,
204    draw: fn(&AnyValue, &mut Canvas),
205    pointer: fn(&AnyValue, Size, &PointerEvent) -> Option<AnyValue>,
206}
207
208impl DrawnFns {
209    fn of<W: Drawn>() -> DrawnFns {
210        DrawnFns {
211            measure: |props, request, metrics| W::measure(props_of::<W>(props), request, metrics),
212            draw: |props, canvas| W::draw(props_of::<W>(props), canvas),
213            pointer: |props, size, event| W::pointer(props_of::<W>(props), size, event).map(AnyValue::new),
214        }
215    }
216}
217
218fn props_of<W: CustomWidget>(props: &AnyValue) -> &W::Props {
219    props.downcast_ref().unwrap_or_else(|| panic!("{}: props of another type: {props:?}", W::NAME))
220}
221
222/// Everything about one custom widget instance that is fixed at build time.
223struct Definition {
224    name: &'static str,
225    a11y: fn(&AnyValue) -> A11yProps,
226    action: fn(&AnyValue, &A11yAction) -> Option<AnyValue>,
227    native: Option<Opaque>,
228    drawn: Option<DrawnFns>,
229    /// Draw it even where a native render exists.
230    force_drawn: bool,
231}
232
233/// The props of a custom widget, as carried by [`Prop::Custom`]: the value
234/// plus the widget's type-erased definition (semantics and renders).
235#[derive(Clone)]
236pub struct CustomProps {
237    props: AnyValue,
238    definition: Rc<Definition>,
239}
240
241impl CustomProps {
242    pub fn name(&self) -> &'static str {
243        self.definition.name
244    }
245
246    pub fn props(&self) -> &AnyValue {
247        &self.props
248    }
249
250    pub fn get<T: 'static>(&self) -> Option<&T> {
251        self.props.downcast_ref()
252    }
253
254    /// The same widget with other props, e.g. read back from a native view.
255    pub fn with_props(&self, props: AnyValue) -> CustomProps {
256        CustomProps { props, definition: self.definition.clone() }
257    }
258
259    /// Whether the widget is drawn (by the core's display list) rather than
260    /// rendered natively.
261    pub fn is_drawn(&self) -> bool {
262        self.definition.drawn.is_some() && (self.definition.force_drawn || self.definition.native.is_none())
263    }
264
265    /// The native render, unless the widget is drawn.
266    pub fn native(&self) -> Option<&Opaque> {
267        if self.is_drawn() { None } else { self.definition.native.as_ref() }
268    }
269
270    pub fn a11y(&self) -> A11yProps {
271        (self.definition.a11y)(&self.props)
272    }
273
274    /// The event an accessibility action stands for, if any.
275    pub fn action(&self, action: &A11yAction) -> Option<AnyValue> {
276        (self.definition.action)(&self.props, action)
277    }
278
279    /// Size from the drawn render, if the widget has one.
280    pub fn measure_drawn(&self, request: &MeasureRequest, metrics: &PlatformMetrics) -> Option<Size> {
281        self.definition.drawn.map(|d| (d.measure)(&self.props, request, metrics))
282    }
283
284    pub fn draw(&self, size: Size, metrics: &PlatformMetrics) -> Option<DisplayList> {
285        let drawn = self.definition.drawn?;
286        let mut canvas = Canvas::new(size, metrics);
287        (drawn.draw)(&self.props, &mut canvas);
288        Some(canvas.finish())
289    }
290
291    pub fn pointer(&self, size: Size, event: &PointerEvent) -> Option<AnyValue> {
292        self.definition.drawn.and_then(|d| (d.pointer)(&self.props, size, event))
293    }
294}
295
296impl PartialEq for CustomProps {
297    fn eq(&self, other: &CustomProps) -> bool {
298        self.props == other.props && self.name() == other.name() && self.is_drawn() == other.is_drawn()
299    }
300}
301
302impl fmt::Debug for CustomProps {
303    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
304        write!(f, "{:?}", self.props)?;
305        if self.is_drawn() {
306            f.write_str(" (drawn)")?;
307        }
308        Ok(())
309    }
310}
311
312/// A custom widget in the view tree: `Custom::<Rating>::new(props)`, or
313/// `Rating::view(props)` through [`CustomView`].
314///
315/// `P` is the props: `Value<W::Props>`, or `()` for a `<Rating …>` tag in
316/// `view!` whose `props=…` isn't set yet. Only a widget with props is a
317/// [`View`].
318pub struct Custom<W: CustomWidget, P = Value<<W as CustomWidget>::Props>> {
319    element: Element,
320    props: P,
321    renderer: Renderer<W>,
322    force_drawn: bool,
323    force_composed: bool,
324}
325
326impl<W: Render> Custom<W> {
327    /// Props are usually reactive: `move || RatingProps { value: rating.get(), .. }`.
328    pub fn new(props: impl IntoValue<W::Props>) -> Custom<W> {
329        Custom {
330            element: Element::new(WidgetKind::Custom(W::NAME)),
331            props: props.into_value(),
332            renderer: W::renderer(),
333            force_drawn: false,
334            force_composed: false,
335        }
336    }
337}
338
339impl<W: CustomWidget, P> Custom<W, P> {
340    /// Sets the props; usually reactive: `move || RatingProps { … }`.
341    pub fn props(self, props: impl IntoValue<W::Props>) -> Custom<W> {
342        let Custom { element, props: _, renderer, force_drawn, force_composed } = self;
343        Custom { element, props: props.into_value(), renderer, force_drawn, force_composed }
344    }
345
346    /// Uses the drawn render even where a native one exists.
347    pub fn drawn(mut self) -> Custom<W, P>
348    where
349        W: Drawn,
350    {
351        self.renderer.drawn = Some(DrawnFns::of::<W>());
352        self.force_drawn = true;
353        self
354    }
355
356    /// Uses the composed render even where another one exists. Panics at
357    /// build time if the widget has none.
358    pub fn composed(mut self) -> Custom<W, P> {
359        self.force_composed = true;
360        self
361    }
362
363    /// Called with each event the widget emits.
364    pub fn on_event(mut self, handler: impl Fn(&W::Event) + 'static) -> Custom<W, P> {
365        self.element.on(move |event| {
366            if let UiEvent::Custom(value) = event
367                && let Some(event) = value.downcast_ref::<W::Event>()
368            {
369                handler(event);
370            }
371        });
372        self
373    }
374}
375
376impl<W: CustomWidget, P> ElementBuilder for Custom<W, P> {
377    fn element(&mut self) -> &mut Element {
378        &mut self.element
379    }
380}
381
382impl<W: CustomWidget> View for Custom<W> {
383    fn build(self, ui: &Ui) -> NodeId {
384        let Custom { mut element, props, renderer, force_drawn, force_composed } = self;
385        let composed = force_composed || (!force_drawn && renderer.native.is_none() && renderer.drawn.is_none());
386        if composed {
387            let compose = renderer.composed.unwrap_or_else(|| panic!("{}: no composed render", W::NAME));
388            return build_composed(ui, element, props, compose);
389        }
390        let definition = Rc::new(Definition {
391            name: W::NAME,
392            a11y: |props| W::a11y(props_of::<W>(props)),
393            action: |props, action| W::action(props_of::<W>(props), action).map(AnyValue::new),
394            native: renderer.native,
395            drawn: renderer.drawn,
396            force_drawn,
397        });
398        element.prop(props, move |props| {
399            Prop::Custom(CustomProps { props: AnyValue::new(props), definition: definition.clone() })
400        });
401        element.build(ui)
402    }
403}
404
405/// The composed tier: a plain container around what the render builds. The
406/// app's accessible label goes to the render (onto the control that stands
407/// for the widget); styles, test id and handlers stay on the container.
408fn build_composed<W: CustomWidget>(
409    ui: &Ui,
410    mut element: Element,
411    props: Value<W::Props>,
412    compose: ComposeFn<W>,
413) -> NodeId {
414    element.kind = WidgetKind::Container;
415    let label = element.a11y.label.take();
416    let props: Rc<dyn Fn() -> W::Props> = match props {
417        Value::Static(props) => Rc::new(move || props.clone()),
418        Value::Dynamic(props) => props,
419    };
420    // Events go to the container's handlers, the widget's `on_event` ones.
421    let node: Rc<std::cell::Cell<Option<NodeId>>> = Rc::default();
422    let (target, weak) = (node.clone(), ui.downgrade());
423    let emit = Rc::new(move |event: W::Event| {
424        if let (Some(id), Some(ui)) = (target.get(), weak.upgrade()) {
425            ui.events().emit(id, UiEvent::Custom(AnyValue::new(event)));
426        }
427    });
428    element.add_children(compose(Composed { props, emit, label }));
429    let id = element.build(ui);
430    node.set(Some(id));
431    id
432}
433
434/// `Rating::view(props)`: shorthand for `Custom::<Rating>::new(props)`.
435pub trait CustomView: Render {
436    fn view(props: impl IntoValue<Self::Props>) -> Custom<Self> {
437        Custom::new(props)
438    }
439
440    /// `<Rating props=… @event=…/>` in `view!`: the widget before its props.
441    #[doc(hidden)]
442    fn __tag() -> Custom<Self, ()> {
443        Custom {
444            element: Element::new(WidgetKind::Custom(Self::NAME)),
445            props: (),
446            renderer: Self::renderer(),
447            force_drawn: false,
448            force_composed: false,
449        }
450    }
451}
452
453impl<W: Render> CustomView for W {}