Skip to main content

pax_std/forms/
photo_picker.rs

1use pax_engine::api::LocalProperty;
2use pax_engine::pax;
3use pax_message::{AnyCreatePatch, PhotoPickerPatch};
4use pax_runtime::api::{borrow, borrow_mut, use_RefCell, Layer, NodeContext, Property};
5use pax_runtime::{
6    BaseInstance, ExpandedNode, InstanceFlags, InstanceNode, InstantiationArgs, RuntimeContext,
7};
8use std::rc::Rc;
9use_RefCell!();
10
11use crate::common::{native_surface_opacity, patch_if_needed};
12
13/// Source requested when opening a `PhotoPicker`.
14#[pax]
15#[derive(PartialEq)]
16#[engine_import_path("pax_engine")]
17pub enum PhotoPickerSource {
18    /// Let the user choose existing images from the platform photo/file picker.
19    #[default]
20    Library,
21    /// Request camera capture where the current platform supports it.
22    Camera,
23}
24
25impl PhotoPickerSource {
26    fn as_message(&self) -> String {
27        match self {
28            PhotoPickerSource::Library => "library",
29            PhotoPickerSource::Camera => "camera",
30        }
31        .to_string()
32    }
33}
34
35/// Opens the platform photo picker when its slotted content is activated.
36///
37/// `PhotoPicker` renders its children as the visible affordance and layers a
38/// transparent native hit target over them. Increment `trigger` to request a
39/// programmatic open; on the web, direct user activation of the picker element is
40/// the most reliable way to satisfy browser file-picker requirements.
41#[pax]
42#[engine_import_path("pax_engine")]
43#[inlined(
44    <PhotoPickerInput
45        width=100%
46        height=100%
47        trigger={self.trigger}
48        source={self.source}
49        allow_multiple={self.allow_multiple}
50        accept={self.accept}
51        include_bytes={self.include_bytes}
52        max_bytes_per_photo={self.max_bytes_per_photo}
53    />
54    for i in 0..self._projected_children_count {
55        slot(i)
56    }
57
58    @settings {
59        @mount: on_mount
60    }
61)]
62#[custom(Default)]
63pub struct PhotoPicker {
64    /// Incrementing request value. Returned as `request_id` in `photo_picker_change`.
65    pub trigger: Property<u64>,
66    /// Requested platform source.
67    pub source: Property<PhotoPickerSource>,
68    /// Whether multiple images may be selected.
69    pub allow_multiple: Property<bool>,
70    /// Accepted MIME/file filter. Web uses this as the input `accept` value.
71    pub accept: Property<String>,
72    /// Whether the chassis should copy bytes into the event when practical.
73    pub include_bytes: Property<bool>,
74    /// Maximum copied/read bytes per selected photo. Larger photos report a size-limit status.
75    pub max_bytes_per_photo: Property<u64>,
76    // Number of slotted children to render.
77    pub _projected_children_count: Property<usize>,
78}
79
80impl Default for PhotoPicker {
81    fn default() -> Self {
82        Self {
83            trigger: Property::new(0),
84            source: Property::new(PhotoPickerSource::Library),
85            allow_multiple: Property::new(true),
86            accept: Property::new("image/*".to_string()),
87            include_bytes: Property::new(true),
88            max_bytes_per_photo: Property::new(25 * 1024 * 1024),
89            _projected_children_count: Property::new(0),
90        }
91    }
92}
93
94impl PhotoPicker {
95    // Mirrors slot count for the generated inline template.
96    pub fn on_mount(&mut self, ctx: &NodeContext) {
97        let projected_children_count = ctx.projected_children_count.clone();
98        let deps = [projected_children_count.untyped()];
99        self._projected_children_count
100            .replace_with(LocalProperty::computed(
101                move || projected_children_count.get(),
102                &deps,
103            ));
104    }
105}
106
107#[doc(hidden)]
108#[pax]
109#[engine_import_path("pax_engine")]
110#[primitive("pax_std::forms::photo_picker::PhotoPickerInputInstance")]
111#[custom(Default)]
112pub struct PhotoPickerInput {
113    /// Incrementing request value. Returned as `request_id` in `photo_picker_change`.
114    pub trigger: Property<u64>,
115    /// Requested platform source.
116    pub source: Property<PhotoPickerSource>,
117    /// Whether multiple images may be selected.
118    pub allow_multiple: Property<bool>,
119    /// Accepted MIME/file filter. Web uses this as the input `accept` value.
120    pub accept: Property<String>,
121    /// Whether the chassis should copy bytes into the event when practical.
122    pub include_bytes: Property<bool>,
123    /// Maximum copied/read bytes per selected photo. Larger photos report a size-limit status.
124    pub max_bytes_per_photo: Property<u64>,
125}
126
127impl Default for PhotoPickerInput {
128    fn default() -> Self {
129        Self {
130            trigger: Property::new(0),
131            source: Property::new(PhotoPickerSource::Library),
132            allow_multiple: Property::new(true),
133            accept: Property::new("image/*".to_string()),
134            include_bytes: Property::new(true),
135            max_bytes_per_photo: Property::new(25 * 1024 * 1024),
136        }
137    }
138}
139
140// Runtime instance backing the native `<PhotoPickerInput>` overlay.
141pub struct PhotoPickerInputInstance {
142    base: BaseInstance,
143}
144
145impl InstanceNode for PhotoPickerInputInstance {
146    fn instantiate(args: InstantiationArgs) -> Rc<Self>
147    where
148        Self: Sized,
149    {
150        Rc::new(Self {
151            base: BaseInstance::new(
152                args,
153                InstanceFlags {
154                    invisible_to_slot: false,
155                    invisible_to_raycasting: false,
156                    layer: Layer::Native,
157                    is_component: false,
158                    is_slot: false,
159                },
160            ),
161        })
162    }
163
164    fn handle_mount(
165        self: Rc<Self>,
166        expanded_node: &Rc<ExpandedNode>,
167        context: &Rc<RuntimeContext>,
168    ) {
169        let id = expanded_node.id.to_u32();
170        context.enqueue_native_message(pax_message::NativeMessage::PhotoPickerCreate(
171            AnyCreatePatch {
172                id,
173                parent_frame: expanded_node.parent_frame.get().map(|v| v.to_u32()),
174                render_layer_id: 0,
175            },
176        ));
177
178        let weak_self_ref = Rc::downgrade(expanded_node);
179        let context = Rc::clone(context);
180        let last_patch = Rc::new(RefCell::new(PhotoPickerPatch {
181            id,
182            ..Default::default()
183        }));
184
185        let deps: Vec<_> = borrow!(expanded_node.properties_scope)
186            .values()
187            .cloned()
188            .map(|v| v.get_untyped_property().clone())
189            .chain([
190                expanded_node.transform_and_bounds.untyped(),
191                expanded_node.computed_opacity.untyped(),
192                expanded_node.occlusion.untyped(),
193            ])
194            .collect();
195        expanded_node
196            .changed_listener
197            .replace_with(LocalProperty::computed(
198                move || {
199                    let Some(expanded_node) = weak_self_ref.upgrade() else {
200                        return;
201                    };
202                    let mut old_state = borrow_mut!(last_patch);
203
204                    let mut patch = PhotoPickerPatch {
205                        id,
206                        ..Default::default()
207                    };
208                    expanded_node.with_properties_unwrapped(|properties: &mut PhotoPickerInput| {
209                        let computed_tab = expanded_node.transform_and_bounds.get();
210                        let (width, height) = computed_tab.bounds;
211                        let updates = [
212                            patch_if_needed(
213                                &mut old_state.trigger,
214                                &mut patch.trigger,
215                                properties.trigger.local().get(),
216                            ),
217                            patch_if_needed(
218                                &mut old_state.source,
219                                &mut patch.source,
220                                properties.source.local().get().as_message(),
221                            ),
222                            patch_if_needed(
223                                &mut old_state.allow_multiple,
224                                &mut patch.allow_multiple,
225                                properties.allow_multiple.local().get(),
226                            ),
227                            patch_if_needed(
228                                &mut old_state.accept,
229                                &mut patch.accept,
230                                properties.accept.local().get(),
231                            ),
232                            patch_if_needed(
233                                &mut old_state.include_bytes,
234                                &mut patch.include_bytes,
235                                properties.include_bytes.local().get(),
236                            ),
237                            patch_if_needed(
238                                &mut old_state.max_bytes_per_photo,
239                                &mut patch.max_bytes_per_photo,
240                                properties.max_bytes_per_photo.local().get(),
241                            ),
242                            patch_if_needed(&mut old_state.size_x, &mut patch.size_x, width),
243                            patch_if_needed(&mut old_state.size_y, &mut patch.size_y, height),
244                            patch_if_needed(
245                                &mut old_state.parent_frame,
246                                &mut patch.parent_frame,
247                                expanded_node.parent_frame.get().map(|v| v.to_u32()),
248                            ),
249                            patch_if_needed(
250                                &mut old_state.z_index,
251                                &mut patch.z_index,
252                                expanded_node.occlusion.get().z_index,
253                            ),
254                            patch_if_needed(
255                                &mut old_state.transform,
256                                &mut patch.transform,
257                                computed_tab.transform.coeffs().to_vec(),
258                            ),
259                            patch_if_needed(
260                                &mut old_state.opacity,
261                                &mut patch.opacity,
262                                native_surface_opacity(&expanded_node, &context),
263                            ),
264                        ];
265                        if updates.into_iter().any(|v| v) {
266                            context.enqueue_native_message(
267                                pax_message::NativeMessage::PhotoPickerUpdate(patch),
268                            );
269                        }
270                    });
271                },
272                &deps,
273            ));
274    }
275
276    fn handle_unmount(&self, expanded_node: &Rc<ExpandedNode>, context: &Rc<RuntimeContext>) {
277        let id = expanded_node.id.to_u32();
278        expanded_node
279            .changed_listener
280            .replace_with(LocalProperty::default());
281        context.enqueue_native_message(pax_message::NativeMessage::PhotoPickerDelete(id));
282    }
283
284    fn base(&self) -> &BaseInstance {
285        &self.base
286    }
287
288    fn resolve_debug(
289        &self,
290        f: &mut std::fmt::Formatter,
291        _expanded_node: Option<&ExpandedNode>,
292    ) -> std::fmt::Result {
293        f.debug_struct("PhotoPickerInput").finish_non_exhaustive()
294    }
295}