mitsuami_core/tweak.rs
1//! `Tweak`: raw platform settings for a built-in widget.
2
3use std::marker::PhantomData;
4
5use mitsuami_reactive::Value;
6
7use crate::any_value::Opaque;
8use crate::element::Element;
9use crate::widget::Prop;
10
11/// Sends the settings to an element, as a prop.
12type SendFn = Box<dyn FnOnce(&mut Element)>;
13
14/// Raw platform settings for a built-in widget `W`: the escape hatch past
15/// its semantic props, for what only one platform has. Each backend makes
16/// them with its `tweak` (or `tweak_with`), which gets the native control
17/// itself; pick one per platform with `platform!`:
18///
19/// ```ignore
20/// use mitsuami::{appkit, gtk};
21///
22/// Button::new("Share").native(platform! {
23/// macos => appkit::tweak(|b: &appkit::objc2_app_kit::NSButton| {
24/// b.setControlSize(appkit::objc2_app_kit::NSControlSize::Large)
25/// }),
26/// gtk => gtk::tweak(|b: >k::gtk::Button| b.add_css_class("circular")),
27/// _ => Tweak::none(),
28/// })
29/// ```
30///
31/// A tweak runs after the widget's other props, and again whenever they
32/// change, so what it sets wins; keep it idempotent. Headless tests don't
33/// run it.
34pub struct Tweak<W> {
35 send: Option<SendFn>,
36 widget: PhantomData<fn() -> W>,
37}
38
39impl<W> Tweak<W> {
40 /// No settings: for platforms the app doesn't tweak.
41 pub fn none() -> Tweak<W> {
42 Tweak { send: None, widget: PhantomData }
43 }
44
45 /// For backends: settings made from a value, in the backend's own form,
46 /// and made again whenever a dynamic value changes.
47 pub fn new<T: Clone + 'static>(value: Value<T>, settings: impl Fn(T) -> Opaque + 'static) -> Tweak<W> {
48 let send = move |element: &mut Element| element.prop(value, move |value| Prop::Tweak(settings(value)));
49 Tweak { send: Some(Box::new(send)), widget: PhantomData }
50 }
51
52 /// For widgets: sends the settings as `Prop::Tweak`.
53 pub fn apply(self, element: &mut Element) {
54 if let Some(send) = self.send {
55 send(element);
56 }
57 }
58}