gpui-form-runtime 0.8.0

Runtime contracts referenced by gpui-form generated code.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
//! Runtime storage policy used by `#[derive(GpuiForm)]`.
//!
//! Component shape construction, rendering, supported value types, and value
//! binding are provided by `component-shape` and `component-shape-gpui`.

pub use component_shape::{
    ComponentCapabilities, ComponentPrototyping, ComponentShapeFor, ComponentShapeMetadata,
    ComponentSuffix, McpInput, McpInputShape, McpPrimitiveKind, McpRangeBoundKind,
    RenderCapability, ValueBindingCapability, ValueChange,
    is_valid_component_suffix as is_valid_component_field_suffix,
};
pub use component_shape_gpui::{
    DeclaredGpuiComponentShape, DefaultGpuiComponentShapeBuilder, GpuiComponentEventOf,
    GpuiComponentRender, GpuiComponentShape, GpuiComponentShapeBuilder, GpuiComponentShapeFor,
    GpuiComponentStateOf, GpuiComponentStateValueBinding, GpuiComponentValueBinding,
    NoGpuiRenderComponent, build_component_shape, seed_value_binding_state, value_change,
};

/// Form storage policy for a GPUI component shape.
///
/// Implement this for shapes declared with
/// `component_shape_gpui::component_shape!` or
/// `#[derive(component_shape_gpui::GpuiComponentShape)]` when the shape should
/// be consumable by `#[derive(GpuiForm)]`.
pub trait GpuiFormComponentShapePolicy {
    /// Shape-owned value-holder storage policy.
    type ValueStoragePolicy: ComponentValueStoragePolicy;
}

mod sealed {
    pub trait ValueStoragePolicy {}
}

/// Marker trait for a component shape's generated value-holder storage policy.
pub trait ComponentValueStoragePolicy: sealed::ValueStoragePolicy {
    /// Whether a missing generated value-holder value is invalid by default.
    const REQUIRES_VALUE: bool;
}

/// Store non-optional source fields as `Option<T>` and treat `None` as missing.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct RequiredValueStorage;

impl sealed::ValueStoragePolicy for RequiredValueStorage {}

impl ComponentValueStoragePolicy for RequiredValueStorage {
    const REQUIRES_VALUE: bool = true;
}

/// Store non-optional source fields directly as `T`.
///
/// Generated initialization requires an intent-scoped field default or a
/// form-side `T` that implements [`Default`].
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct DirectValueStorage;

impl sealed::ValueStoragePolicy for DirectValueStorage {}

impl ComponentValueStoragePolicy for DirectValueStorage {
    const REQUIRES_VALUE: bool = false;
}

/// Storage behavior used by generated form value holders.
///
/// This lets `#[derive(GpuiForm)]` defer the `T` vs `Option<T>` choice to the
/// component shape that owns the policy while emitting concrete holder
/// conversion code.
pub trait ValueStorage<T>: ComponentValueStoragePolicy {
    /// Concrete generated value-holder field storage.
    type Storage;

    /// Construct storage from a present form value.
    fn present(value: T) -> Self::Storage;

    /// Construct storage from a present form value, allowing `RequiredValueStorage` to
    /// encode a value equal to the declared default as missing.
    fn present_unless_default(value: T, default: T) -> Self::Storage
    where
        T: PartialEq;

    /// Convert storage into an output value, using `missing` only for policies
    /// that can represent missing values.
    fn map_into_value<Output, Present, Missing>(
        storage: Self::Storage,
        present: Present,
        missing: Missing,
    ) -> Output
    where
        Present: FnOnce(T) -> Output,
        Missing: FnOnce() -> Output;

    /// Fallible variant of [`ValueStorage::map_into_value`].
    fn try_map_into_value<Output, Error, Present>(
        storage: Self::Storage,
        present: Present,
        missing: Error,
    ) -> Result<Output, Error>
    where
        Present: FnOnce(T) -> Output;

    /// Clone and map a present value, returning `None` only for policies that
    /// can represent missing values.
    fn map_present_cloned<Output, Present>(
        storage: &Self::Storage,
        present: Present,
    ) -> Option<Output>
    where
        T: Clone,
        Present: FnOnce(T) -> Output;

    /// Return whether storage contains a source value.
    ///
    /// Generated validation uses this to make shape-owned requiredness visible
    /// to `validate()` without hard-coding whether the policy stores `Option<T>`
    /// or `T`.
    fn is_present(storage: &Self::Storage) -> bool;
}

/// Storage policies that can synthesize missing/default value-holder storage.
#[diagnostic::on_unimplemented(
    message = "gpui-form cannot synthesize direct storage for `{T}` with this component shape policy",
    note = "add an intent-scoped `default = ...`, make `{T}` implement `Default`, or use `RequiredValueStorage` for the shape's form storage policy"
)]
pub trait DefaultValueStorage<T>: ValueStorage<T> {
    /// Construct a missing/default value-holder field.
    fn default_storage() -> Self::Storage;
}

/// Storage policies whose holder-to-model conversion cannot fail because the
/// storage representation always contains a value.
pub trait InfallibleValueStorage<T>: ValueStorage<T> {
    /// Convert storage into an output value without a missing-value fallback.
    fn map_into_value<Output, Present>(storage: Self::Storage, present: Present) -> Output
    where
        Present: FnOnce(T) -> Output;
}

impl<T> ValueStorage<T> for RequiredValueStorage {
    type Storage = Option<T>;

    fn present(value: T) -> Self::Storage {
        Some(value)
    }

    fn present_unless_default(value: T, default: T) -> Self::Storage
    where
        T: PartialEq,
    {
        if value == default { None } else { Some(value) }
    }

    fn map_into_value<Output, Present, Missing>(
        storage: Self::Storage,
        present: Present,
        missing: Missing,
    ) -> Output
    where
        Present: FnOnce(T) -> Output,
        Missing: FnOnce() -> Output,
    {
        match storage {
            Some(value) => present(value),
            None => missing(),
        }
    }

    fn try_map_into_value<Output, Error, Present>(
        storage: Self::Storage,
        present: Present,
        missing: Error,
    ) -> Result<Output, Error>
    where
        Present: FnOnce(T) -> Output,
    {
        storage.map(present).ok_or(missing)
    }

    fn map_present_cloned<Output, Present>(
        storage: &Self::Storage,
        present: Present,
    ) -> Option<Output>
    where
        T: Clone,
        Present: FnOnce(T) -> Output,
    {
        storage.clone().map(present)
    }

    fn is_present(storage: &Self::Storage) -> bool {
        storage.is_some()
    }
}

impl<T> DefaultValueStorage<T> for RequiredValueStorage {
    fn default_storage() -> Self::Storage {
        None
    }
}

impl<T> ValueStorage<T> for DirectValueStorage {
    type Storage = T;

    fn present(value: T) -> Self::Storage {
        value
    }

    fn present_unless_default(value: T, _default: T) -> Self::Storage
    where
        T: PartialEq,
    {
        value
    }

    fn map_into_value<Output, Present, Missing>(
        storage: Self::Storage,
        present: Present,
        _missing: Missing,
    ) -> Output
    where
        Present: FnOnce(T) -> Output,
        Missing: FnOnce() -> Output,
    {
        present(storage)
    }

    fn try_map_into_value<Output, Error, Present>(
        storage: Self::Storage,
        present: Present,
        _missing: Error,
    ) -> Result<Output, Error>
    where
        Present: FnOnce(T) -> Output,
    {
        Ok(present(storage))
    }

    fn map_present_cloned<Output, Present>(
        storage: &Self::Storage,
        present: Present,
    ) -> Option<Output>
    where
        T: Clone,
        Present: FnOnce(T) -> Output,
    {
        Some(present(storage.clone()))
    }

    fn is_present(_storage: &Self::Storage) -> bool {
        true
    }
}

impl<T: Default> DefaultValueStorage<T> for DirectValueStorage {
    fn default_storage() -> Self::Storage {
        T::default()
    }
}

impl<T> InfallibleValueStorage<T> for DirectValueStorage {
    fn map_into_value<Output, Present>(storage: Self::Storage, present: Present) -> Output
    where
        Present: FnOnce(T) -> Output,
    {
        present(storage)
    }
}

#[cfg(test)]
mod tests {
    use super::{
        ComponentPrototyping, ComponentValueStoragePolicy as _, DefaultValueStorage,
        DirectValueStorage, InfallibleValueStorage, RequiredValueStorage, ValueStorage,
        is_valid_component_field_suffix,
    };

    #[test]
    fn component_field_suffix_validator_accepts_identifier_suffixes() {
        assert!(is_valid_component_field_suffix("input"));
        assert!(is_valid_component_field_suffix("_input"));
        assert!(is_valid_component_field_suffix("input_2"));
    }

    #[test]
    fn component_field_suffix_validator_rejects_non_identifier_suffixes() {
        assert!(!is_valid_component_field_suffix(""));
        assert!(!is_valid_component_field_suffix("_"));
        assert!(!is_valid_component_field_suffix("2input"));
        assert!(!is_valid_component_field_suffix("input-field"));
    }

    #[test]
    #[should_panic(expected = "component suffix must be a non-empty ASCII identifier suffix")]
    fn component_prototyping_rejects_invalid_field_suffixes() {
        let _ = ComponentPrototyping::new().field_suffix("input-field");
    }

    #[test]
    fn required_storage_preserves_presence_and_default_semantics() {
        assert!(std::hint::black_box(RequiredValueStorage::REQUIRES_VALUE));
        assert_eq!(
            <RequiredValueStorage as ValueStorage<i32>>::present(7),
            Some(7)
        );
        assert_eq!(
            <RequiredValueStorage as ValueStorage<i32>>::present_unless_default(7, 7),
            None
        );
        assert_eq!(
            <RequiredValueStorage as ValueStorage<i32>>::present_unless_default(8, 7),
            Some(8)
        );
        assert_eq!(
            <RequiredValueStorage as DefaultValueStorage<i32>>::default_storage(),
            None
        );
        assert!(<RequiredValueStorage as ValueStorage<i32>>::is_present(
            &Some(1)
        ));
        assert!(!<RequiredValueStorage as ValueStorage<i32>>::is_present(
            &None
        ));
    }

    #[test]
    fn required_storage_maps_present_and_missing_values() {
        let present = <RequiredValueStorage as ValueStorage<i32>>::map_into_value(
            Some(4),
            |value| value * 2,
            || 99,
        );
        let missing = <RequiredValueStorage as ValueStorage<i32>>::map_into_value(
            None,
            |value| value * 2,
            || 99,
        );
        assert_eq!((present, missing), (8, 99));

        assert_eq!(
            <RequiredValueStorage as ValueStorage<i32>>::try_map_into_value(
                Some(4),
                |value| value * 2,
                "missing"
            ),
            Ok(8)
        );
        assert_eq!(
            <RequiredValueStorage as ValueStorage<i32>>::try_map_into_value(
                None,
                |value| value * 2,
                "missing"
            ),
            Err("missing")
        );
        assert_eq!(
            <RequiredValueStorage as ValueStorage<String>>::map_present_cloned(
                &Some("form".to_owned()),
                |value| value.len()
            ),
            Some(4)
        );
        assert_eq!(
            <RequiredValueStorage as ValueStorage<String>>::map_present_cloned(&None, |value| {
                value.len()
            }),
            None
        );
    }

    #[test]
    fn direct_storage_always_maps_a_present_value() {
        assert!(!std::hint::black_box(DirectValueStorage::REQUIRES_VALUE));
        assert_eq!(<DirectValueStorage as ValueStorage<i32>>::present(7), 7);
        assert_eq!(
            <DirectValueStorage as ValueStorage<i32>>::present_unless_default(7, 7),
            7
        );
        assert_eq!(
            <DirectValueStorage as DefaultValueStorage<i32>>::default_storage(),
            0
        );
        assert!(<DirectValueStorage as ValueStorage<i32>>::is_present(&7));
        assert_eq!(
            <DirectValueStorage as ValueStorage<i32>>::map_into_value(4, |value| value * 2, || 99),
            8
        );
        assert_eq!(
            <DirectValueStorage as ValueStorage<i32>>::try_map_into_value(
                4,
                |value| value * 2,
                "missing"
            ),
            Ok(8)
        );
        assert_eq!(
            <DirectValueStorage as ValueStorage<String>>::map_present_cloned(
                &"form".to_owned(),
                |value| value.len()
            ),
            Some(4)
        );
        assert_eq!(
            <DirectValueStorage as InfallibleValueStorage<i32>>::map_into_value(4, |value| value
                * 2),
            8
        );
    }
}