Skip to main content

gpui_form_runtime/
shape.rs

1//! Runtime storage policy used by `#[derive(GpuiForm)]`.
2//!
3//! Component shape construction, rendering, supported value types, and value
4//! binding are provided by `component-shape` and `component-shape-gpui`.
5
6pub use component_shape::{
7    ComponentCapabilities, ComponentPrototyping, ComponentShapeFor, ComponentShapeMetadata,
8    ComponentSuffix, McpInput, McpInputShape, McpPrimitiveKind, McpRangeBoundKind,
9    RenderCapability, ValueBindingCapability, ValueChange,
10    is_valid_component_suffix as is_valid_component_field_suffix,
11};
12pub use component_shape_gpui::{
13    DeclaredGpuiComponentShape, DefaultGpuiComponentShapeBuilder, GpuiComponentEventOf,
14    GpuiComponentRender, GpuiComponentShape, GpuiComponentShapeBuilder, GpuiComponentShapeFor,
15    GpuiComponentStateOf, GpuiComponentStateValueBinding, GpuiComponentValueBinding,
16    NoGpuiRenderComponent, build_component_shape, seed_value_binding_state, value_change,
17};
18
19/// Form storage policy for a GPUI component shape.
20///
21/// Implement this for shapes declared with
22/// `component_shape_gpui::component_shape!` or
23/// `#[derive(component_shape_gpui::GpuiComponentShape)]` when the shape should
24/// be consumable by `#[derive(GpuiForm)]`.
25pub trait GpuiFormComponentShapePolicy {
26    /// Shape-owned value-holder storage policy.
27    type ValueStoragePolicy: ComponentValueStoragePolicy;
28}
29
30mod sealed {
31    pub trait ValueStoragePolicy {}
32}
33
34/// Marker trait for a component shape's generated value-holder storage policy.
35pub trait ComponentValueStoragePolicy: sealed::ValueStoragePolicy {
36    /// Whether a missing generated value-holder value is invalid by default.
37    const REQUIRES_VALUE: bool;
38}
39
40/// Store non-optional source fields as `Option<T>` and treat `None` as missing.
41#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
42pub struct RequiredValueStorage;
43
44impl sealed::ValueStoragePolicy for RequiredValueStorage {}
45
46impl ComponentValueStoragePolicy for RequiredValueStorage {
47    const REQUIRES_VALUE: bool = true;
48}
49
50/// Store non-optional source fields directly as `T`.
51///
52/// Generated initialization requires an intent-scoped field default or a
53/// form-side `T` that implements [`Default`].
54#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
55pub struct DirectValueStorage;
56
57impl sealed::ValueStoragePolicy for DirectValueStorage {}
58
59impl ComponentValueStoragePolicy for DirectValueStorage {
60    const REQUIRES_VALUE: bool = false;
61}
62
63/// Storage behavior used by generated form value holders.
64///
65/// This lets `#[derive(GpuiForm)]` defer the `T` vs `Option<T>` choice to the
66/// component shape that owns the policy while emitting concrete holder
67/// conversion code.
68pub trait ValueStorage<T>: ComponentValueStoragePolicy {
69    /// Concrete generated value-holder field storage.
70    type Storage;
71
72    /// Construct storage from a present form value.
73    fn present(value: T) -> Self::Storage;
74
75    /// Construct storage from a present form value, allowing `RequiredValueStorage` to
76    /// encode a value equal to the declared default as missing.
77    fn present_unless_default(value: T, default: T) -> Self::Storage
78    where
79        T: PartialEq;
80
81    /// Convert storage into an output value, using `missing` only for policies
82    /// that can represent missing values.
83    fn map_into_value<Output, Present, Missing>(
84        storage: Self::Storage,
85        present: Present,
86        missing: Missing,
87    ) -> Output
88    where
89        Present: FnOnce(T) -> Output,
90        Missing: FnOnce() -> Output;
91
92    /// Fallible variant of [`ValueStorage::map_into_value`].
93    fn try_map_into_value<Output, Error, Present>(
94        storage: Self::Storage,
95        present: Present,
96        missing: Error,
97    ) -> Result<Output, Error>
98    where
99        Present: FnOnce(T) -> Output;
100
101    /// Clone and map a present value, returning `None` only for policies that
102    /// can represent missing values.
103    fn map_present_cloned<Output, Present>(
104        storage: &Self::Storage,
105        present: Present,
106    ) -> Option<Output>
107    where
108        T: Clone,
109        Present: FnOnce(T) -> Output;
110
111    /// Return whether storage contains a source value.
112    ///
113    /// Generated validation uses this to make shape-owned requiredness visible
114    /// to `validate()` without hard-coding whether the policy stores `Option<T>`
115    /// or `T`.
116    fn is_present(storage: &Self::Storage) -> bool;
117}
118
119/// Storage policies that can synthesize missing/default value-holder storage.
120#[diagnostic::on_unimplemented(
121    message = "gpui-form cannot synthesize direct storage for `{T}` with this component shape policy",
122    note = "add an intent-scoped `default = ...`, make `{T}` implement `Default`, or use `RequiredValueStorage` for the shape's form storage policy"
123)]
124pub trait DefaultValueStorage<T>: ValueStorage<T> {
125    /// Construct a missing/default value-holder field.
126    fn default_storage() -> Self::Storage;
127}
128
129/// Storage policies whose holder-to-model conversion cannot fail because the
130/// storage representation always contains a value.
131pub trait InfallibleValueStorage<T>: ValueStorage<T> {
132    /// Convert storage into an output value without a missing-value fallback.
133    fn map_into_value<Output, Present>(storage: Self::Storage, present: Present) -> Output
134    where
135        Present: FnOnce(T) -> Output;
136}
137
138impl<T> ValueStorage<T> for RequiredValueStorage {
139    type Storage = Option<T>;
140
141    fn present(value: T) -> Self::Storage {
142        Some(value)
143    }
144
145    fn present_unless_default(value: T, default: T) -> Self::Storage
146    where
147        T: PartialEq,
148    {
149        if value == default { None } else { Some(value) }
150    }
151
152    fn map_into_value<Output, Present, Missing>(
153        storage: Self::Storage,
154        present: Present,
155        missing: Missing,
156    ) -> Output
157    where
158        Present: FnOnce(T) -> Output,
159        Missing: FnOnce() -> Output,
160    {
161        match storage {
162            Some(value) => present(value),
163            None => missing(),
164        }
165    }
166
167    fn try_map_into_value<Output, Error, Present>(
168        storage: Self::Storage,
169        present: Present,
170        missing: Error,
171    ) -> Result<Output, Error>
172    where
173        Present: FnOnce(T) -> Output,
174    {
175        storage.map(present).ok_or(missing)
176    }
177
178    fn map_present_cloned<Output, Present>(
179        storage: &Self::Storage,
180        present: Present,
181    ) -> Option<Output>
182    where
183        T: Clone,
184        Present: FnOnce(T) -> Output,
185    {
186        storage.clone().map(present)
187    }
188
189    fn is_present(storage: &Self::Storage) -> bool {
190        storage.is_some()
191    }
192}
193
194impl<T> DefaultValueStorage<T> for RequiredValueStorage {
195    fn default_storage() -> Self::Storage {
196        None
197    }
198}
199
200impl<T> ValueStorage<T> for DirectValueStorage {
201    type Storage = T;
202
203    fn present(value: T) -> Self::Storage {
204        value
205    }
206
207    fn present_unless_default(value: T, _default: T) -> Self::Storage
208    where
209        T: PartialEq,
210    {
211        value
212    }
213
214    fn map_into_value<Output, Present, Missing>(
215        storage: Self::Storage,
216        present: Present,
217        _missing: Missing,
218    ) -> Output
219    where
220        Present: FnOnce(T) -> Output,
221        Missing: FnOnce() -> Output,
222    {
223        present(storage)
224    }
225
226    fn try_map_into_value<Output, Error, Present>(
227        storage: Self::Storage,
228        present: Present,
229        _missing: Error,
230    ) -> Result<Output, Error>
231    where
232        Present: FnOnce(T) -> Output,
233    {
234        Ok(present(storage))
235    }
236
237    fn map_present_cloned<Output, Present>(
238        storage: &Self::Storage,
239        present: Present,
240    ) -> Option<Output>
241    where
242        T: Clone,
243        Present: FnOnce(T) -> Output,
244    {
245        Some(present(storage.clone()))
246    }
247
248    fn is_present(_storage: &Self::Storage) -> bool {
249        true
250    }
251}
252
253impl<T: Default> DefaultValueStorage<T> for DirectValueStorage {
254    fn default_storage() -> Self::Storage {
255        T::default()
256    }
257}
258
259impl<T> InfallibleValueStorage<T> for DirectValueStorage {
260    fn map_into_value<Output, Present>(storage: Self::Storage, present: Present) -> Output
261    where
262        Present: FnOnce(T) -> Output,
263    {
264        present(storage)
265    }
266}
267
268#[cfg(test)]
269mod tests {
270    use super::{
271        ComponentPrototyping, ComponentValueStoragePolicy as _, DefaultValueStorage,
272        DirectValueStorage, InfallibleValueStorage, RequiredValueStorage, ValueStorage,
273        is_valid_component_field_suffix,
274    };
275
276    #[test]
277    fn component_field_suffix_validator_accepts_identifier_suffixes() {
278        assert!(is_valid_component_field_suffix("input"));
279        assert!(is_valid_component_field_suffix("_input"));
280        assert!(is_valid_component_field_suffix("input_2"));
281    }
282
283    #[test]
284    fn component_field_suffix_validator_rejects_non_identifier_suffixes() {
285        assert!(!is_valid_component_field_suffix(""));
286        assert!(!is_valid_component_field_suffix("_"));
287        assert!(!is_valid_component_field_suffix("2input"));
288        assert!(!is_valid_component_field_suffix("input-field"));
289    }
290
291    #[test]
292    #[should_panic(expected = "component suffix must be a non-empty ASCII identifier suffix")]
293    fn component_prototyping_rejects_invalid_field_suffixes() {
294        let _ = ComponentPrototyping::new().field_suffix("input-field");
295    }
296
297    #[test]
298    fn required_storage_preserves_presence_and_default_semantics() {
299        assert!(std::hint::black_box(RequiredValueStorage::REQUIRES_VALUE));
300        assert_eq!(
301            <RequiredValueStorage as ValueStorage<i32>>::present(7),
302            Some(7)
303        );
304        assert_eq!(
305            <RequiredValueStorage as ValueStorage<i32>>::present_unless_default(7, 7),
306            None
307        );
308        assert_eq!(
309            <RequiredValueStorage as ValueStorage<i32>>::present_unless_default(8, 7),
310            Some(8)
311        );
312        assert_eq!(
313            <RequiredValueStorage as DefaultValueStorage<i32>>::default_storage(),
314            None
315        );
316        assert!(<RequiredValueStorage as ValueStorage<i32>>::is_present(
317            &Some(1)
318        ));
319        assert!(!<RequiredValueStorage as ValueStorage<i32>>::is_present(
320            &None
321        ));
322    }
323
324    #[test]
325    fn required_storage_maps_present_and_missing_values() {
326        let present = <RequiredValueStorage as ValueStorage<i32>>::map_into_value(
327            Some(4),
328            |value| value * 2,
329            || 99,
330        );
331        let missing = <RequiredValueStorage as ValueStorage<i32>>::map_into_value(
332            None,
333            |value| value * 2,
334            || 99,
335        );
336        assert_eq!((present, missing), (8, 99));
337
338        assert_eq!(
339            <RequiredValueStorage as ValueStorage<i32>>::try_map_into_value(
340                Some(4),
341                |value| value * 2,
342                "missing"
343            ),
344            Ok(8)
345        );
346        assert_eq!(
347            <RequiredValueStorage as ValueStorage<i32>>::try_map_into_value(
348                None,
349                |value| value * 2,
350                "missing"
351            ),
352            Err("missing")
353        );
354        assert_eq!(
355            <RequiredValueStorage as ValueStorage<String>>::map_present_cloned(
356                &Some("form".to_owned()),
357                |value| value.len()
358            ),
359            Some(4)
360        );
361        assert_eq!(
362            <RequiredValueStorage as ValueStorage<String>>::map_present_cloned(&None, |value| {
363                value.len()
364            }),
365            None
366        );
367    }
368
369    #[test]
370    fn direct_storage_always_maps_a_present_value() {
371        assert!(!std::hint::black_box(DirectValueStorage::REQUIRES_VALUE));
372        assert_eq!(<DirectValueStorage as ValueStorage<i32>>::present(7), 7);
373        assert_eq!(
374            <DirectValueStorage as ValueStorage<i32>>::present_unless_default(7, 7),
375            7
376        );
377        assert_eq!(
378            <DirectValueStorage as DefaultValueStorage<i32>>::default_storage(),
379            0
380        );
381        assert!(<DirectValueStorage as ValueStorage<i32>>::is_present(&7));
382        assert_eq!(
383            <DirectValueStorage as ValueStorage<i32>>::map_into_value(4, |value| value * 2, || 99),
384            8
385        );
386        assert_eq!(
387            <DirectValueStorage as ValueStorage<i32>>::try_map_into_value(
388                4,
389                |value| value * 2,
390                "missing"
391            ),
392            Ok(8)
393        );
394        assert_eq!(
395            <DirectValueStorage as ValueStorage<String>>::map_present_cloned(
396                &"form".to_owned(),
397                |value| value.len()
398            ),
399            Some(4)
400        );
401        assert_eq!(
402            <DirectValueStorage as InfallibleValueStorage<i32>>::map_into_value(4, |value| value
403                * 2),
404            8
405        );
406    }
407}